content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.samples.apps.nowinandroid.core.data.model
import com.google.samples.apps.nowinandroid.core.database.model.AuthorEntity
import com.google.samples.apps.nowinandroid.core.database.model.NewsResourceAuthorCrossRef
import com.google.samples.apps.nowinandroid.core.database.model.NewsResourceEntity
import com.google.samples.apps.nowinandroid.core.database.model.NewsResourceTopicCrossRef
import com.google.samples.apps.nowinandroid.core.database.model.TopicEntity
import com.google.samples.apps.nowinandroid.core.network.model.NetworkNewsResource
import com.google.samples.apps.nowinandroid.core.network.model.NetworkNewsResourceExpanded
fun NetworkNewsResource.asEntity() = NewsResourceEntity(
id = id,
title = title,
content = content,
url = url,
headerImageUrl = headerImageUrl,
publishDate = publishDate,
type = type,
)
fun NetworkNewsResourceExpanded.asEntity() = NewsResourceEntity(
id = id,
title = title,
content = content,
url = url,
headerImageUrl = headerImageUrl,
publishDate = publishDate,
type = type,
)
/**
* A shell [AuthorEntity] to fulfill the foreign key constraint when inserting
* a [NewsResourceEntity] into the DB
*/
fun NetworkNewsResource.authorEntityShells() =
authors.map { authorId ->
AuthorEntity(
id = authorId,
name = "",
imageUrl = "",
twitter = "",
mediumPage = "",
bio = "",
)
}
/**
* A shell [TopicEntity] to fulfill the foreign key constraint when inserting
* a [NewsResourceEntity] into the DB
*/
fun NetworkNewsResource.topicEntityShells() =
topics.map { topicId ->
TopicEntity(
id = topicId,
name = "",
url = "",
imageUrl = "",
shortDescription = "",
longDescription = "",
)
}
fun NetworkNewsResource.topicCrossReferences(): List<NewsResourceTopicCrossRef> =
topics.map { topicId ->
NewsResourceTopicCrossRef(
newsResourceId = id,
topicId = topicId
)
}
fun NetworkNewsResource.authorCrossReferences(): List<NewsResourceAuthorCrossRef> =
authors.map { authorId ->
NewsResourceAuthorCrossRef(
newsResourceId = id,
authorId = authorId
)
}
| core/data/src/main/java/com/google/samples/apps/nowinandroid/core/data/model/NewsResource.kt | 2993929994 |
package org.example.myapp.web.api
import org.avaje.metric.*
import org.example.extension.loggerFor
import javax.inject.Inject
import javax.inject.Singleton
import javax.ws.rs.Consumes
import javax.ws.rs.GET
import javax.ws.rs.Path
import javax.ws.rs.Produces
import javax.ws.rs.PathParam
import javax.ws.rs.core.MediaType
/**
* Controls metrics.
*/
@Singleton
@Path("/metric")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class MetricResource {
private val logger = loggerFor(javaClass)
private val metricEvents: MetricWebSocket
@Inject
constructor(metricEvents: MetricWebSocket) {
this.metricEvents = metricEvents
}
/**
* Return all the timing metrics.
*/
@GET
@Path("/allTiming/{match}")
fun allTiming(@PathParam("match") match: String): MutableList<TimingMetricInfo>? {
return MetricManager.getAllTimingMetrics(match)
}
/**
* Return all the timing metrics that are active 'request timing'.
*/
@GET
@Path("/requestTiming/{match}")
fun collecting(@PathParam("match") match: String): MutableList<TimingMetricInfo>? {
return MetricManager.getRequestTimingMetrics(match)
}
/**
* Set the number of request timings to collect on the timing metrics that match the matchExpression.
*
* @param matchExpression the expression using '*' wildcard to match timing metrics
* @param count the number of requests to collect per request timing on
*/
@GET
@Path("/collectUsingMatch/{matchExpression}/{count}")
fun setCollection(@PathParam("matchExpression") matchExpression: String,
@PathParam("count") count: Int): MutableList<TimingMetricInfo>? {
logger.info("set collect {} using matchExpression {}", count, matchExpression)
return MetricManager.setRequestTimingCollectionUsingMatch(matchExpression, count);
}
/**
* Collect request timing on a specific timing metric based on the className and methodName.
*/
@GET
@Path("/collect/{className}/{methodName}")
@Produces(MediaType.TEXT_PLAIN)
fun setCollection(@PathParam("className") className: String,
@PathParam("methodName") methodName: String): String {
logger.info("set collect 8 on {}.{}", className, methodName)
val clazz = Class.forName(className);
val success = MetricManager.setRequestTimingCollection(clazz, methodName, 6);
return if (success) "done" else "not found"
}
/**
* Test endpoint to broadcast a message to webSocket listeners.
*/
@GET
@Path("/broadcast/{message}")
fun testBroadcast(@PathParam("message") message: String): Int {
return metricEvents.broadcast(message)
}
} | src/main/java/org/example/myapp/web/api/MetricResource.kt | 449923405 |
package <%= appPackage %>.features.base
/**
* Every presenter in the app must either implement this interface or extend BasePresenter
* indicating the MvpView type that wants to be attached with.
*/
interface Presenter<in V : MvpView> {
fun attachView(mvpView: V)
fun detachView()
}
| templates/androidstarters-kotlin/app/src/main/java/io/mvpstarter/sample/features/base/Presenter.kt | 2378695337 |
/*
* The MIT License (MIT)
* Copyright (c) 2018 DataRank, Inc.
*
* 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.simplymeasured.elasticsearch.plugins.tempest.balancer
import org.eclipse.collections.api.RichIterable
import org.eclipse.collections.api.list.ListIterable
import org.eclipse.collections.api.map.MapIterable
import org.eclipse.collections.api.multimap.Multimap
import org.eclipse.collections.impl.factory.Lists
import org.eclipse.collections.impl.list.mutable.FastList
import org.eclipse.collections.impl.tuple.Tuples
import org.eclipse.collections.impl.utility.LazyIterate
import org.elasticsearch.cluster.metadata.IndexMetaData
import org.elasticsearch.cluster.metadata.MetaData
import org.elasticsearch.common.component.AbstractComponent
import org.elasticsearch.common.inject.Inject
import org.elasticsearch.common.logging.Loggers
import org.elasticsearch.common.settings.Settings
import java.util.regex.Pattern
import java.util.regex.PatternSyntaxException
import javax.swing.UIManager.put
/**
* Partition indexes into groups based on a user defined regular expression
*/
open class IndexGroupPartitioner
@Inject constructor(settings: Settings) : AbstractComponent(settings) {
private var indexPatterns: ListIterable<Pattern> = Lists.immutable.of(safeCompile(".*"))
// commas aren't perfect here since they can legally be defined in regexes but it seems reasonable for now;
// perhaps there is a more generic way to define groups
var indexGroupPatternSetting: String = ".*"
set (value) {
field = value
indexPatterns = field
.split(",")
.mapNotNull { safeCompile(it) }
.let { Lists.mutable.ofAll(it) }
.apply { this.add(safeCompile(".*")) }
.toImmutable()
}
private fun safeCompile(it: String): Pattern? {
return try {
Pattern.compile(it)
} catch(e: PatternSyntaxException) {
logger.warn("failed to compile group pattern ${it}")
null
}
}
fun partition(metadata: MetaData): RichIterable<RichIterable<IndexMetaData>> = FastList
.newWithNValues(indexPatterns.size()) { Lists.mutable.empty<IndexMetaData>() }
.apply { metadata.forEach { this[determineGroupNumber(it.index)].add(it) } }
.let { it as RichIterable<RichIterable<IndexMetaData>> }
fun patternMapping(metadata: MetaData) : Multimap<String, String> = LazyIterate
.adapt(metadata)
.collect { it.index }
.groupBy { indexPatterns[determineGroupNumber(it)].toString() }
private fun determineGroupNumber(indexName: String): Int {
return indexPatterns.indexOfFirst { it.matcher(indexName).matches() }
}
} | src/main/java/com/simplymeasured/elasticsearch/plugins/tempest/balancer/IndexGroupPartitioner.kt | 1309224793 |
package com.github.plombardi89.kocean.model
import com.eclipsesource.json.JsonObject
private fun <T> ModelFactory<T>.readMetaAndLinksData(json: JsonObject): Pair<Meta, Links> {
return Pair(Meta(json.get("meta").asObject()), Links(json.get("links").asObject()))
}
| src/main/kotlin/com/github/plombardi89/kocean/model/ModelExtensions.kt | 1891203105 |
package com.eden.orchid.impl.themes.menus
import com.eden.common.util.EdenUtils
import com.eden.orchid.api.OrchidContext
import com.eden.orchid.api.options.annotations.Description
import com.eden.orchid.api.options.annotations.Option
import com.eden.orchid.api.theme.menus.MenuItem
import com.eden.orchid.api.theme.menus.OrchidMenuFactory
import com.eden.orchid.api.theme.pages.OrchidPage
import java.util.ArrayList
@Description("A divider between sections of the menu, optionally with a title.", name = "Divider")
class DividerMenuItem : OrchidMenuFactory("separator") {
@Option
@Description("An optional title for this divider, to create a contextual section within the menu.")
lateinit var title: String
override fun getMenuItems(
context: OrchidContext,
page: OrchidPage
): List<MenuItem> {
val menuItems = ArrayList<MenuItem>()
if (!EdenUtils.isEmpty(title)) {
menuItems.add(
MenuItem.Builder(context)
.title(title)
.separator(true)
.build()
)
} else {
menuItems.add(
MenuItem.Builder(context)
.separator(true)
.build()
)
}
return menuItems
}
}
| OrchidCore/src/main/kotlin/com/eden/orchid/impl/themes/menus/DividerMenuItem.kt | 3897707839 |
package com.eden.orchid.api.options.archetypes
import com.caseyjbrooks.clog.Clog
import com.eden.common.util.EdenUtils
import com.eden.orchid.api.OrchidContext
import com.eden.orchid.api.options.OptionArchetype
import com.eden.orchid.api.options.annotations.Description
import com.eden.orchid.api.resources.resourcesource.LocalResourceSource
import com.eden.orchid.api.theme.assets.AssetPage
import com.eden.orchid.utilities.OrchidUtils
import javax.inject.Inject
@Description(
value = "Allows this asset to have configurations from data files in the archetype key's directory. " +
"This is especially useful for binary asset files which cannot have Front Matter. Additional asset configs " +
"come from a data file at the same path as the asset itself, but in the archetype key's directory.",
name = "Asset Config"
)
class AssetMetadataArchetype
@Inject
constructor(
private val context: OrchidContext
) : OptionArchetype {
override fun getOptions(target: Any, archetypeKey: String): Map<String, Any?>? {
var data: Map<String, Any?>? = null
if (target is AssetPage) {
val metadataFilename = Clog.format(
"{}/{}/{}",
OrchidUtils.normalizePath(archetypeKey),
OrchidUtils.normalizePath(target.resource.reference.originalPath),
OrchidUtils.normalizePath(target.resource.reference.originalFileName)
)
if (!EdenUtils.isEmpty(metadataFilename)) {
data = context.getDataResourceSource(LocalResourceSource).getDatafile(context, metadataFilename)
}
}
return data
}
}
| OrchidCore/src/main/kotlin/com/eden/orchid/api/options/archetypes/AssetMetadataArchetype.kt | 3393700661 |
package test
fun <caret>foo() {} | plugins/kotlin/idea/tests/testData/refactoring/move/kotlin/moveTopLevelDeclarations/misc/facadeClassChangeInTheSamePackage/before/source/foo.kt | 835010815 |
// 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.java.configurationStore
import com.intellij.ProjectTopics
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.EDT
import com.intellij.openapi.application.ex.PathManagerEx
import com.intellij.openapi.application.runWriteActionAndWait
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ModuleRootEvent
import com.intellij.openapi.roots.ModuleRootListener
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.roots.impl.libraries.LibraryEx
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar
import com.intellij.openapi.util.Computable
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.testFramework.ApplicationRule
import com.intellij.testFramework.DisposableRule
import com.intellij.testFramework.TemporaryDirectory
import com.intellij.testFramework.loadProjectAndCheckResults
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.idea.maven.utils.library.RepositoryLibraryProperties
import org.junit.ClassRule
import org.junit.Rule
import org.junit.Test
import java.nio.file.Path
import java.nio.file.Paths
import java.util.function.Consumer
class LoadProjectTest {
companion object {
@JvmField
@ClassRule
val appRule = ApplicationRule()
}
@JvmField
@Rule
val tempDirectory = TemporaryDirectory()
@JvmField
@Rule
val disposable = DisposableRule()
@Test
fun `load single module`() = runBlocking {
loadProjectAndCheckResults("single-module") { project ->
val module = ModuleManager.getInstance(project).modules.single()
assertThat(module.name).isEqualTo("foo")
assertThat(module.moduleTypeName).isEqualTo("EMPTY_MODULE")
}
}
@Test
fun `load module with group`() = runBlocking {
loadProjectAndCheckResults("module-in-group") { project ->
val module = ModuleManager.getInstance(project).modules.single()
assertThat(module.name).isEqualTo("foo")
assertThat(module.moduleTypeName).isEqualTo("EMPTY_MODULE")
assertThat(ModuleManager.getInstance(project).getModuleGroupPath(module)).containsExactly("group")
}
}
@Test
fun `load detached module`() = runBlocking {
loadProjectAndCheckResults("detached-module") { project ->
val fooModule = ModuleManager.getInstance(project).modules.single()
assertThat(fooModule.name).isEqualTo("foo")
val barModule = withContext(Dispatchers.EDT) {
ApplicationManager.getApplication().runWriteAction(Computable {
ModuleManager.getInstance(project).loadModule(Path.of("${project.basePath}/bar/bar.iml"))
})
}
assertThat(barModule.name).isEqualTo("bar")
assertThat(barModule.moduleTypeName).isEqualTo("EMPTY_MODULE")
assertThat(ModuleManager.getInstance(project).modules).containsExactlyInAnyOrder(fooModule, barModule)
}
}
@Test
fun `load detached module via modifiable model`() = runBlocking {
loadProjectAndCheckResults("detached-module") { project ->
val fooModule = ModuleManager.getInstance(project).modules.single()
assertThat(fooModule.name).isEqualTo("foo")
runWriteActionAndWait {
val model = ModuleManager.getInstance(project).getModifiableModel()
model.loadModule("${project.basePath}/bar/bar.iml")
model.commit()
}
val barModule = ModuleManager.getInstance(project).findModuleByName("bar")
assertThat(barModule).isNotNull
assertThat(barModule!!.moduleTypeName).isEqualTo("EMPTY_MODULE")
assertThat(ModuleManager.getInstance(project).modules).containsExactlyInAnyOrder(fooModule, barModule)
}
}
@Test
fun `load single library`() = runBlocking {
loadProjectAndCheckResults("single-library") { project ->
assertThat(ModuleManager.getInstance(project).modules).isEmpty()
val library = LibraryTablesRegistrar.getInstance().getLibraryTable(project).libraries.single()
assertThat(library.name).isEqualTo("foo")
val rootUrl = library.getUrls(OrderRootType.CLASSES).single()
assertThat(rootUrl).isEqualTo(VfsUtilCore.pathToUrl("${project.basePath}/lib/classes"))
}
}
@Test
fun `load module and library`() = runBlocking {
loadProjectAndCheckResults("module-and-library", beforeOpen = { project ->
//this emulates listener declared in plugin.xml, it's registered before the project is loaded
project.messageBus.connect().subscribe(ProjectTopics.PROJECT_ROOTS, object : ModuleRootListener {
override fun rootsChanged(event: ModuleRootEvent) {
val library = LibraryTablesRegistrar.getInstance().getLibraryTable(project).libraries.single()
assertThat(library.name).isEqualTo("foo")
}
})
}) { project ->
val fooModule = ModuleManager.getInstance(project).modules.single()
assertThat(fooModule.name).isEqualTo("foo")
val library = LibraryTablesRegistrar.getInstance().getLibraryTable(project).libraries.single()
assertThat(library.name).isEqualTo("foo")
val rootUrl = library.getUrls(OrderRootType.CLASSES).single()
assertThat(rootUrl).isEqualTo(VfsUtilCore.pathToUrl("${project.basePath}/lib/classes"))
}
}
private val Library.properties: RepositoryLibraryProperties
get() = (this as LibraryEx).properties as RepositoryLibraryProperties
@Test
fun `load repository libraries`() = runBlocking {
val projectPath = Paths.get(PathManagerEx.getCommunityHomePath()).resolve("jps/model-serialization/testData/repositoryLibraries")
loadProjectAndCheckResults(listOf(projectPath), tempDirectory) { project ->
assertThat(ModuleManager.getInstance(project).modules).isEmpty()
val libraries = LibraryTablesRegistrar.getInstance().getLibraryTable(project).libraries.sortedBy { it.name }
assertThat(libraries).hasSize(3)
val (plain, withExcluded, withoutTransitive) = libraries
assertThat(plain.name).isEqualTo("plain")
assertThat(plain.properties.groupId).isEqualTo("junit")
assertThat(plain.properties.artifactId).isEqualTo("junit")
assertThat(plain.properties.version).isEqualTo("3.8.1")
assertThat(plain.properties.isIncludeTransitiveDependencies).isTrue()
assertThat(plain.properties.excludedDependencies).isEmpty()
assertThat(withExcluded.name).isEqualTo("with-excluded-dependencies")
assertThat(withExcluded.properties.isIncludeTransitiveDependencies).isTrue()
assertThat(withExcluded.properties.excludedDependencies).containsExactly("org.apache.httpcomponents:httpclient")
assertThat(withoutTransitive.name).isEqualTo("without-transitive-dependencies")
assertThat(withoutTransitive.properties.isIncludeTransitiveDependencies).isFalse()
assertThat(withoutTransitive.properties.excludedDependencies).isEmpty()
}
}
private suspend fun loadProjectAndCheckResults(testDataDirName: String, beforeOpen: Consumer<Project>? = null, checkProject: suspend (Project) -> Unit) {
val testDataRoot = Path.of(PathManagerEx.getCommunityHomePath()).resolve("java/java-tests/testData/configurationStore")
return loadProjectAndCheckResults(projectPaths = listOf(element = testDataRoot.resolve(testDataDirName)),
tempDirectory = tempDirectory,
beforeOpen = beforeOpen,
checkProject = checkProject)
}
}
| java/java-tests/testSrc/com/intellij/java/configurationStore/LoadProjectTest.kt | 297698516 |
// 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.configurationStore
import com.intellij.openapi.components.PathMacroManager
import com.intellij.openapi.components.PathMacroSubstitutor
import com.intellij.openapi.components.TrackingPathMacroSubstitutor
import org.jetbrains.annotations.ApiStatus
internal fun PathMacroManager?.createTrackingSubstitutor(): TrackingPathMacroSubstitutorImpl? = if (this == null) null else TrackingPathMacroSubstitutorImpl(this)
@ApiStatus.Internal
class TrackingPathMacroSubstitutorImpl(internal val macroManager: PathMacroManager) : PathMacroSubstitutor by macroManager, TrackingPathMacroSubstitutor {
private val lock = Object()
private val macroToComponentNames = HashMap<String, MutableSet<String>>()
private val componentNameToMacros = HashMap<String, MutableSet<String>>()
override fun reset() {
synchronized(lock) {
macroToComponentNames.clear()
componentNameToMacros.clear()
}
}
override fun hashCode() = macroManager.expandMacroMap.hashCode()
override fun invalidateUnknownMacros(macros: Set<String>) {
synchronized(lock) {
for (macro in macros) {
val componentNames = macroToComponentNames.remove(macro) ?: continue
for (component in componentNames) {
componentNameToMacros.remove(component)
}
}
}
}
override fun getComponents(macros: Collection<String>): Set<String> {
synchronized(lock) {
val result = HashSet<String>()
for (macro in macros) {
result.addAll(macroToComponentNames.get(macro) ?: continue)
}
return result
}
}
override fun getUnknownMacros(componentName: String?): Set<String> {
return synchronized(lock) {
if (componentName == null) {
macroToComponentNames.keys
}
else {
componentNameToMacros.get(componentName) ?: emptySet()
}
}
}
override fun addUnknownMacros(componentName: String, unknownMacros: Collection<String>) {
if (unknownMacros.isEmpty()) {
return
}
LOG.info("Registering unknown macros ${unknownMacros.joinToString(", ")} in component $componentName")
synchronized(lock) {
for (unknownMacro in unknownMacros) {
macroToComponentNames.computeIfAbsent(unknownMacro, { HashSet() }).add(componentName)
}
componentNameToMacros.computeIfAbsent(componentName, { HashSet() }).addAll(unknownMacros)
}
}
}
| platform/configuration-store-impl/src/TrackingPathMacroSubstitutorImpl.kt | 3829362715 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.wm.impl.customFrameDecorations.header.titleLabel
import com.intellij.ide.RecentProjectsManager
import com.intellij.ide.RecentProjectsManagerBase
import com.intellij.ide.lightEdit.LightEdit
import com.intellij.ide.ui.UISettings
import com.intellij.ide.ui.UISettingsListener
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.ProjectManagerListener
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.registry.RegistryValue
import com.intellij.openapi.util.registry.RegistryValueListener
import com.intellij.openapi.wm.impl.customFrameDecorations.header.title.CustomHeaderTitle
import com.intellij.ui.awt.RelativeRectangle
import com.intellij.util.ui.JBUI.CurrentTheme.CustomFrameDecorations
import java.awt.Rectangle
import java.beans.PropertyChangeListener
import javax.swing.JComponent
import javax.swing.JFrame
internal open class CustomDecorationPath(val frame: JFrame) : SelectedEditorFilePath(frame), CustomHeaderTitle {
companion object {
fun createInstance(frame: JFrame): CustomDecorationPath = CustomDecorationPath(frame)
fun createMainInstance(frame: JFrame): CustomDecorationPath = MainCustomDecorationPath(frame)
}
private val projectManagerListener = object : ProjectManagerListener {
override fun projectOpened(project: Project) {
checkOpenedProjects()
}
override fun projectClosed(project: Project) {
checkOpenedProjects()
}
}
private fun checkOpenedProjects() {
val currentProject = project ?: return
val manager = RecentProjectsManager.getInstance() as RecentProjectsManagerBase
val currentPath = manager.getProjectPath(currentProject) ?: return
val currentName = manager.getProjectName(currentPath)
val sameNameInRecent = manager.getRecentPaths().any {
currentPath != it && currentName == manager.getProjectName(it)
}
val sameNameInOpen = ProjectManager.getInstance().openProjects.any {
val path = manager.getProjectPath(it) ?: return@any false
val name = manager.getProjectName(path)
currentPath != path && currentName == name
}
multipleSameNamed = sameNameInRecent || sameNameInOpen
}
private val titleChangeListener = PropertyChangeListener {
updateProjectPath()
}
override fun getCustomTitle(): String? {
if (LightEdit.owns(project)) {
return frame.title
}
return null
}
override fun setActive(value: Boolean) {
val color = if (value) CustomFrameDecorations.titlePaneInfoForeground() else CustomFrameDecorations.titlePaneInactiveInfoForeground()
view.foreground = color
}
override fun getBoundList(): List<RelativeRectangle> {
return if (!toolTipNeeded) {
emptyList()
}
else {
val hitTestSpots = ArrayList<RelativeRectangle>()
hitTestSpots.addAll(getMouseInsetList(label))
hitTestSpots
}
}
override fun installListeners() {
super.installListeners()
frame.addPropertyChangeListener("title", titleChangeListener)
}
override fun addAdditionalListeners(disp: Disposable) {
super.addAdditionalListeners(disp)
project?.let {
val busConnection = ApplicationManager.getApplication().messageBus.connect(disp)
busConnection.subscribe(ProjectManager.TOPIC, projectManagerListener)
busConnection.subscribe(UISettingsListener.TOPIC, UISettingsListener { checkTabPlacement() })
checkTabPlacement()
checkOpenedProjects()
}
}
private fun checkTabPlacement() {
classPathNeeded = UISettings.getInstance().editorTabPlacement == 0
}
override fun unInstallListeners() {
super.unInstallListeners()
frame.removePropertyChangeListener(titleChangeListener)
}
private fun getMouseInsetList(view: JComponent, mouseInsets: Int = 1): List<RelativeRectangle> {
return listOf(
RelativeRectangle(view, Rectangle(0, 0, mouseInsets, view.height)),
RelativeRectangle(view, Rectangle(0, 0, view.width, mouseInsets)),
RelativeRectangle(view,
Rectangle(0, view.height - mouseInsets, view.width, mouseInsets)),
RelativeRectangle(view,
Rectangle(view.width - mouseInsets, 0, mouseInsets, view.height))
)
}
}
private class MainCustomDecorationPath(frame: JFrame) : CustomDecorationPath(frame) {
private val classKey = "ide.borderless.tab.caption.in.title"
private val registryListener = object : RegistryValueListener {
override fun afterValueChanged(value: RegistryValue) {
updatePaths()
}
}
override val captionInTitle: Boolean
get() = Registry.get(classKey).asBoolean()
override fun addAdditionalListeners(disp: Disposable) {
super.addAdditionalListeners(disp)
Registry.get(classKey).addListener(registryListener, disp)
}
} | platform/platform-impl/src/com/intellij/openapi/wm/impl/customFrameDecorations/header/titleLabel/CustomDecorationPath.kt | 285911443 |
package test
class MemberExtension {
fun funMe(p: Int) {}
}
fun MemberExtension./*rename*/funMe(p: String) {} | plugins/kotlin/idea/tests/testData/refactoring/rename/automaticRenamerOverloadsExtensionAndMember/before/test/test.kt | 516600520 |
// 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.editor.wordSelection
import com.intellij.codeInsight.editorActions.ExtendWordSelectionHandlerBase
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.psi.KtReturnExpression
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.startOffset
class KotlinLabeledReturnSelectioner : ExtendWordSelectionHandlerBase() {
override fun canSelect(e: PsiElement) = e is KtReturnExpression
override fun select(e: PsiElement, editorText: CharSequence, cursorOffset: Int, editor: Editor): List<TextRange>? {
if (e !is KtReturnExpression) return null
val labelQualifier = e.labelQualifier ?: return null
return listOf(TextRange(e.startOffset, labelQualifier.endOffset))
}
} | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/editor/wordSelection/KotlinLabeledReturnSelectioner.kt | 3125145507 |
// 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.execution.junit
import com.intellij.lang.properties.codeInspection.unused.UnusedPropertyInspection
import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase
class JUnitPlatformPropertiesTest : LightJavaCodeInsightFixtureTestCase() {
override fun setUp() {
super.setUp()
// define property source class
myFixture.addClass("""
package org.junit.jupiter.engine;
public final class Constants {
public static final String DEACTIVATE_CONDITIONS_PATTERN_PROPERTY_NAME = "junit.jupiter.conditions.deactivate";
public static final String DEACTIVATE_ALL_CONDITIONS_PATTERN = "*";
public static final String DEFAULT_DISPLAY_NAME_GENERATOR_PROPERTY_NAME = "junit.jupiter.displayname.generator.default";
public static final String EXTENSIONS_AUTODETECTION_ENABLED_PROPERTY_NAME = "junit.jupiter.extensions.autodetection.enabled";
public static final String DEFAULT_TEST_INSTANCE_LIFECYCLE_PROPERTY_NAME = "junit.jupiter.testinstance.lifecycle.default";
public static final String PARALLEL_EXECUTION_ENABLED_PROPERTY_NAME = "junit.jupiter.execution.parallel.enabled";
public static final String DEFAULT_PARALLEL_EXECUTION_MODE = "junit.jupiter.execution.parallel.mode.default";
}
""".trimIndent())
}
fun testImplicitUsage() {
myFixture.enableInspections(UnusedPropertyInspection::class.java)
myFixture.configureByText("junit-platform.properties", """
junit.jupiter.displayname.generator.default = {index}
<warning descr="Unused property">junit.unknown</warning> = unknown
""".trimIndent())
myFixture.checkHighlighting()
}
fun testCompletion() {
myFixture.configureByText("junit-platform.properties", """
junit.jupiter.<caret>
""".trimIndent())
myFixture.testCompletionVariants("junit-platform.properties",
"junit.jupiter.conditions.deactivate",
"junit.jupiter.displayname.generator.default",
"junit.jupiter.execution.parallel.enabled",
"junit.jupiter.extensions.autodetection.enabled",
"junit.jupiter.testinstance.lifecycle.default",
"junit.jupiter.execution.parallel.mode.default")
}
} | plugins/junit/test/com/intellij/execution/junit/JUnitPlatformPropertiesTest.kt | 3937319335 |
// 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.ide.konan
import com.intellij.extapi.psi.PsiFileBase
import com.intellij.lang.*
import com.intellij.lexer.FlexAdapter
import com.intellij.lexer.Lexer
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors
import com.intellij.openapi.editor.HighlighterColors
import com.intellij.openapi.fileTypes.*
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.*
import com.intellij.psi.tree.*
import javax.swing.Icon
import java.io.Reader
import org.jetbrains.kotlin.ide.konan.psi.*
import org.jetbrains.kotlin.idea.KotlinIcons
const val KOTLIN_NATIVE_DEFINITIONS_FILE_EXTENSION = "def"
const val KOTLIN_NATIVE_DEFINITIONS_ID = "KND"
val KOTLIN_NATIVE_DEFINITIONS_DESCRIPTION get() = KotlinNativeBundle.message("kotlin.native.definitions.description")
object NativeDefinitionsFileType : LanguageFileType(NativeDefinitionsLanguage.INSTANCE) {
override fun getName(): String = "Kotlin/Native Def"
override fun getDescription(): String = KOTLIN_NATIVE_DEFINITIONS_DESCRIPTION
override fun getDefaultExtension(): String = KOTLIN_NATIVE_DEFINITIONS_FILE_EXTENSION
override fun getIcon(): Icon = KotlinIcons.NATIVE
}
class NativeDefinitionsLanguage private constructor() : Language(KOTLIN_NATIVE_DEFINITIONS_ID) {
companion object {
val INSTANCE = NativeDefinitionsLanguage()
}
override fun getDisplayName(): String = KotlinNativeBundle.message("kotlin.native.definitions.short")
}
class NativeDefinitionsFile(viewProvider: FileViewProvider) : PsiFileBase(viewProvider, NativeDefinitionsLanguage.INSTANCE) {
override fun getFileType(): FileType = NativeDefinitionsFileType
override fun toString(): String = KOTLIN_NATIVE_DEFINITIONS_DESCRIPTION
override fun getIcon(flags: Int): Icon? = super.getIcon(flags)
}
class NativeDefinitionsLexerAdapter : FlexAdapter(NativeDefinitionsLexer(null as Reader?))
private object NativeDefinitionsTokenSets {
val COMMENTS: TokenSet = TokenSet.create(NativeDefinitionsTypes.COMMENT)
}
class NativeDefinitionsParserDefinition : ParserDefinition {
private val FILE = IFileElementType(NativeDefinitionsLanguage.INSTANCE)
override fun getWhitespaceTokens(): TokenSet = TokenSet.WHITE_SPACE
override fun getCommentTokens(): TokenSet = NativeDefinitionsTokenSets.COMMENTS
override fun getStringLiteralElements(): TokenSet = TokenSet.EMPTY
override fun getFileNodeType(): IFileElementType = FILE
override fun createLexer(project: Project): Lexer = NativeDefinitionsLexerAdapter()
override fun createParser(project: Project): PsiParser = NativeDefinitionsParser()
override fun createFile(viewProvider: FileViewProvider): PsiFile = NativeDefinitionsFile(viewProvider)
override fun createElement(node: ASTNode): PsiElement = NativeDefinitionsTypes.Factory.createElement(node)
override fun spaceExistenceTypeBetweenTokens(left: ASTNode?, right: ASTNode?): ParserDefinition.SpaceRequirements =
ParserDefinition.SpaceRequirements.MAY
}
class CLanguageInjector : LanguageInjector {
private val cLanguage = Language.findLanguageByID("ObjectiveC")
override fun getLanguagesToInject(host: PsiLanguageInjectionHost, registrar: InjectedLanguagePlaces) {
if (!host.isValid) return
if (host is NativeDefinitionsCodeImpl && cLanguage != null) {
val range = host.getTextRange().shiftLeft(host.startOffsetInParent)
registrar.addPlace(cLanguage, range, null, null)
}
}
}
object NativeDefinitionsSyntaxHighlighter : SyntaxHighlighterBase() {
override fun getTokenHighlights(tokenType: IElementType?): Array<TextAttributesKey> =
when (tokenType) {
TokenType.BAD_CHARACTER -> BAD_CHAR_KEYS
NativeDefinitionsTypes.COMMENT -> COMMENT_KEYS
NativeDefinitionsTypes.DELIM -> COMMENT_KEYS
NativeDefinitionsTypes.SEPARATOR -> OPERATOR_KEYS
NativeDefinitionsTypes.UNKNOWN_KEY -> BAD_CHAR_KEYS
NativeDefinitionsTypes.UNKNOWN_PLATFORM -> BAD_CHAR_KEYS
NativeDefinitionsTypes.VALUE -> VALUE_KEYS
// known properties
NativeDefinitionsTypes.COMPILER_OPTS -> KNOWN_PROPERTIES_KEYS
NativeDefinitionsTypes.DEPENDS -> KNOWN_PROPERTIES_KEYS
NativeDefinitionsTypes.DISABLE_DESIGNATED_INITIALIZER_CHECKS -> KNOWN_PROPERTIES_KEYS
NativeDefinitionsTypes.ENTRY_POINT -> KNOWN_PROPERTIES_KEYS
NativeDefinitionsTypes.EXCLUDE_DEPENDENT_MODULES -> KNOWN_PROPERTIES_KEYS
NativeDefinitionsTypes.EXCLUDE_SYSTEM_LIBS -> KNOWN_PROPERTIES_KEYS
NativeDefinitionsTypes.EXCLUDED_FUNCTIONS -> KNOWN_PROPERTIES_KEYS
NativeDefinitionsTypes.EXCLUDED_MACROS -> KNOWN_PROPERTIES_KEYS
NativeDefinitionsTypes.EXPORT_FORWARD_DECLARATIONS -> KNOWN_PROPERTIES_KEYS
NativeDefinitionsTypes.HEADERS -> KNOWN_PROPERTIES_KEYS
NativeDefinitionsTypes.HEADER_FILTER -> KNOWN_PROPERTIES_KEYS
NativeDefinitionsTypes.LANGUAGE -> KNOWN_PROPERTIES_KEYS
NativeDefinitionsTypes.LIBRARY_PATHS -> KNOWN_PROPERTIES_KEYS
NativeDefinitionsTypes.LINKER -> KNOWN_PROPERTIES_KEYS
NativeDefinitionsTypes.LINKER_OPTS -> KNOWN_PROPERTIES_KEYS
NativeDefinitionsTypes.MODULES -> KNOWN_PROPERTIES_KEYS
NativeDefinitionsTypes.NON_STRICT_ENUMS -> KNOWN_PROPERTIES_KEYS
NativeDefinitionsTypes.NO_STRING_CONVERSION -> KNOWN_PROPERTIES_KEYS
NativeDefinitionsTypes.PACKAGE -> KNOWN_PROPERTIES_KEYS
NativeDefinitionsTypes.STATIC_LIBRARIES -> KNOWN_PROPERTIES_KEYS
NativeDefinitionsTypes.STRICT_ENUMS -> KNOWN_PROPERTIES_KEYS
// known extensions
NativeDefinitionsTypes.ANDROID -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.ANDROID_X64 -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.ANDROID_X86 -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.ANDROID_ARM32 -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.ANDROID_ARM64 -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.ARM32 -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.ARM64 -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.IOS -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.IOS_ARM32 -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.IOS_ARM64 -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.IOS_X64 -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.LINUX -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.LINUX_ARM32_HFP -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.LINUX_MIPS32 -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.LINUX_MIPSEL32 -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.LINUX_X64 -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.MACOS_X64 -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.MINGW -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.MINGW_X64 -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.MIPS32 -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.MIPSEL32 -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.OSX -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.TVOS -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.TVOS_ARM64 -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.TVOS_X64 -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.WASM -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.WASM32 -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.WATCHOS -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.WATCHOS_ARM32 -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.WATCHOS_ARM64 -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.WATCHOS_X64 -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.WATCHOS_X86 -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.X64 -> KNOWN_EXTENSIONS_KEYS
else -> EMPTY_KEYS
}
override fun getHighlightingLexer(): Lexer = NativeDefinitionsLexerAdapter()
private fun createKeys(externalName: String, key: TextAttributesKey): Array<TextAttributesKey> {
return arrayOf(TextAttributesKey.createTextAttributesKey(externalName, key))
}
private val BAD_CHAR_KEYS = createKeys("Unknown key", HighlighterColors.BAD_CHARACTER)
private val COMMENT_KEYS = createKeys("Comment", DefaultLanguageHighlighterColors.LINE_COMMENT)
private val EMPTY_KEYS = emptyArray<TextAttributesKey>()
private val KNOWN_EXTENSIONS_KEYS = createKeys("Known extension", DefaultLanguageHighlighterColors.LABEL)
private val KNOWN_PROPERTIES_KEYS = createKeys("Known property", DefaultLanguageHighlighterColors.KEYWORD)
private val OPERATOR_KEYS = createKeys("Operator", DefaultLanguageHighlighterColors.OPERATION_SIGN)
private val VALUE_KEYS = createKeys("Value", DefaultLanguageHighlighterColors.STRING)
}
class NativeDefinitionsSyntaxHighlighterFactory : SyntaxHighlighterFactory() {
override fun getSyntaxHighlighter(project: Project?, virtualFile: VirtualFile?): SyntaxHighlighter =
NativeDefinitionsSyntaxHighlighter
} | plugins/kotlin/native/src/org/jetbrains/kotlin/ide/konan/NativeDefinitions.kt | 3436708763 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package git4idea.index.ui
import com.intellij.dvcs.ui.RepositoryChangesBrowserNode
import com.intellij.icons.AllIcons
import com.intellij.ide.DataManager
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.ex.ActionUtil
import com.intellij.openapi.actionSystem.ex.ActionUtil.performActionDumbAwareWithCallbacks
import com.intellij.openapi.components.service
import com.intellij.openapi.progress.util.ProgressWindow
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Splitter
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vcs.AbstractVcsHelper
import com.intellij.openapi.vcs.VcsBundle
import com.intellij.openapi.vcs.changes.ChangeListListener
import com.intellij.openapi.vcs.changes.ChangeListManagerImpl
import com.intellij.openapi.vcs.changes.ChangesViewManager.createTextStatusFactory
import com.intellij.openapi.vcs.changes.EditorTabDiffPreviewManager
import com.intellij.openapi.vcs.changes.InclusionListener
import com.intellij.openapi.vcs.changes.ui.*
import com.intellij.openapi.vcs.changes.ui.ChangesGroupingSupport.Companion.REPOSITORY_GROUPING
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.ui.*
import com.intellij.ui.ScrollPaneFactory.createScrollPane
import com.intellij.ui.components.panels.Wrapper
import com.intellij.ui.switcher.QuickActionProvider
import com.intellij.util.EditSourceOnDoubleClickHandler
import com.intellij.util.EventDispatcher
import com.intellij.util.OpenSourceUtil
import com.intellij.util.Processor
import com.intellij.util.concurrency.annotations.RequiresEdt
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.JBUI.Borders.empty
import com.intellij.util.ui.JBUI.Panels.simplePanel
import com.intellij.util.ui.ProportionKey
import com.intellij.util.ui.ThreeStateCheckBox
import com.intellij.util.ui.TwoKeySplitter
import com.intellij.util.ui.tree.TreeUtil
import com.intellij.vcs.commit.CommitStatusPanel
import com.intellij.vcs.commit.CommitWorkflowListener
import com.intellij.vcs.commit.EditedCommitNode
import com.intellij.vcs.log.runInEdt
import com.intellij.vcs.log.runInEdtAsync
import com.intellij.vcs.log.ui.frame.ProgressStripe
import git4idea.GitVcs
import git4idea.conflicts.GitConflictsUtil.canShowMergeWindow
import git4idea.conflicts.GitConflictsUtil.showMergeWindow
import git4idea.conflicts.GitMergeHandler
import git4idea.i18n.GitBundle.message
import git4idea.index.GitStageCommitWorkflow
import git4idea.index.GitStageCommitWorkflowHandler
import git4idea.index.GitStageTracker
import git4idea.index.GitStageTrackerListener
import git4idea.index.actions.GitAddOperation
import git4idea.index.actions.GitResetOperation
import git4idea.index.actions.StagingAreaOperation
import git4idea.index.actions.performStageOperation
import git4idea.merge.GitDefaultMergeDialogCustomizer
import git4idea.repo.GitConflict
import git4idea.repo.GitRepository
import git4idea.repo.GitRepositoryManager
import git4idea.status.GitRefreshListener
import org.jetbrains.annotations.NonNls
import java.awt.BorderLayout
import java.awt.event.InputEvent
import java.beans.PropertyChangeListener
import java.util.*
import javax.swing.JPanel
internal class GitStagePanel(private val tracker: GitStageTracker,
isVertical: Boolean,
isEditorDiffPreview: Boolean,
disposableParent: Disposable,
private val activate: () -> Unit) :
JPanel(BorderLayout()), DataProvider, Disposable {
private val project = tracker.project
private val disposableFlag = Disposer.newCheckedDisposable()
private val _tree: MyChangesTree
val tree: ChangesTree get() = _tree
private val progressStripe: ProgressStripe
private val toolbar: ActionToolbar
private val commitPanel: GitStageCommitPanel
private val changesStatusPanel: Wrapper
private val treeMessageSplitter: Splitter
private val commitDiffSplitter: OnePixelSplitter
private val commitWorkflowHandler: GitStageCommitWorkflowHandler
private var diffPreviewProcessor: GitStageDiffPreview? = null
private var editorTabPreview: GitStageEditorDiffPreview? = null
private val state: GitStageTracker.State
get() = tracker.state
private var hasPendingUpdates = false
internal val commitMessage get() = commitPanel.commitMessage
init {
_tree = MyChangesTree(project)
commitPanel = GitStageCommitPanel(project)
commitPanel.commitActionsPanel.isCommitButtonDefault = {
!commitPanel.commitProgressUi.isDumbMode &&
IdeFocusManager.getInstance(project).getFocusedDescendantFor(this) != null
}
commitPanel.commitActionsPanel.createActions().forEach { it.registerCustomShortcutSet(this, this) }
commitPanel.addEditedCommitListener(_tree::editedCommitChanged, this)
commitPanel.setIncludedRoots(_tree.getIncludedRoots())
_tree.addIncludedRootsListener(object : IncludedRootsListener {
override fun includedRootsChanged() {
commitPanel.setIncludedRoots(_tree.getIncludedRoots())
}
}, this)
commitWorkflowHandler = GitStageCommitWorkflowHandler(GitStageCommitWorkflow(project), commitPanel)
Disposer.register(this, commitPanel)
val toolbarGroup = DefaultActionGroup()
toolbarGroup.add(ActionManager.getInstance().getAction("Git.Stage.Toolbar"))
toolbarGroup.addAll(TreeActionsToolbarPanel.createTreeActions(tree))
toolbar = ActionManager.getInstance().createActionToolbar(GIT_STAGE_PANEL_PLACE, toolbarGroup, true)
toolbar.targetComponent = tree
PopupHandler.installPopupMenu(tree, "Git.Stage.Tree.Menu", "Git.Stage.Tree.Menu")
val statusPanel = CommitStatusPanel(commitPanel).apply {
border = empty(0, 1, 0, 6)
background = tree.background
addToLeft(commitPanel.toolbar.component)
}
val sideBorder = if (ExperimentalUI.isNewUI()) SideBorder.NONE else SideBorder.TOP
val treePanel = simplePanel(createScrollPane(tree, sideBorder)).addToBottom(statusPanel)
progressStripe = ProgressStripe(treePanel, this, ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS)
val treePanelWithToolbar = JPanel(BorderLayout())
treePanelWithToolbar.add(toolbar.component, BorderLayout.NORTH)
treePanelWithToolbar.add(progressStripe, BorderLayout.CENTER)
treeMessageSplitter = TwoKeySplitter(true, ProportionKey("git.stage.tree.message.splitter", 0.7f,
"git.stage.tree.message.splitter.horizontal", 0.5f))
treeMessageSplitter.firstComponent = treePanelWithToolbar
treeMessageSplitter.secondComponent = commitPanel
changesStatusPanel = Wrapper()
changesStatusPanel.minimumSize = JBUI.emptySize()
commitDiffSplitter = OnePixelSplitter("git.stage.commit.diff.splitter", 0.5f)
commitDiffSplitter.firstComponent = treeMessageSplitter
add(commitDiffSplitter, BorderLayout.CENTER)
add(changesStatusPanel, BorderLayout.SOUTH)
updateLayout(isVertical, isEditorDiffPreview, forceDiffPreview = true)
tracker.addListener(MyGitStageTrackerListener(), this)
val busConnection = project.messageBus.connect(this)
busConnection.subscribe(GitRefreshListener.TOPIC, MyGitChangeProviderListener())
busConnection.subscribe(ChangeListListener.TOPIC, MyChangeListListener())
commitWorkflowHandler.workflow.addListener(MyCommitWorkflowListener(), this)
if (isRefreshInProgress()) {
tree.setEmptyText(message("stage.loading.status"))
progressStripe.startLoadingImmediately()
}
updateChangesStatusPanel()
Disposer.register(disposableParent, this)
Disposer.register(this, disposableFlag)
runInEdtAsync(disposableFlag) { update() }
}
private fun isRefreshInProgress(): Boolean {
if (GitVcs.getInstance(project).changeProvider!!.isRefreshInProgress) return true
return GitRepositoryManager.getInstance(project).repositories.any {
it.untrackedFilesHolder.isInUpdateMode ||
it.ignoredFilesHolder.isInUpdateMode()
}
}
private fun updateChangesStatusPanel() {
val manager = ChangeListManagerImpl.getInstanceImpl(project)
val factory = manager.updateException?.let { createTextStatusFactory(VcsBundle.message("error.updating.changes", it.message), true) }
?: manager.additionalUpdateInfo
changesStatusPanel.setContent(factory?.create())
}
@RequiresEdt
fun update() {
if (commitWorkflowHandler.workflow.isExecuting) {
hasPendingUpdates = true
return
}
tree.rebuildTree()
commitPanel.setTrackerState(state)
commitWorkflowHandler.state = state
}
override fun getData(dataId: String): Any? {
if (QuickActionProvider.KEY.`is`(dataId)) return toolbar
if (EditorTabDiffPreviewManager.EDITOR_TAB_DIFF_PREVIEW.`is`(dataId)) return editorTabPreview
return null
}
fun updateLayout(isVertical: Boolean, canUseEditorDiffPreview: Boolean, forceDiffPreview: Boolean = false) {
val isEditorDiffPreview = canUseEditorDiffPreview || isVertical
val isMessageSplitterVertical = isVertical || !isEditorDiffPreview
if (treeMessageSplitter.orientation != isMessageSplitterVertical) {
treeMessageSplitter.orientation = isMessageSplitterVertical
}
setDiffPreviewInEditor(isEditorDiffPreview, forceDiffPreview)
}
private fun setDiffPreviewInEditor(isInEditor: Boolean, force: Boolean = false) {
if (disposableFlag.isDisposed) return
if (!force && (isInEditor == (editorTabPreview != null))) return
if (diffPreviewProcessor != null) Disposer.dispose(diffPreviewProcessor!!)
diffPreviewProcessor = GitStageDiffPreview(project, _tree, tracker, isInEditor, this)
diffPreviewProcessor!!.getToolbarWrapper().setVerticalSizeReferent(toolbar.component)
if (isInEditor) {
editorTabPreview = GitStageEditorDiffPreview(diffPreviewProcessor!!, tree).apply { setup() }
commitDiffSplitter.secondComponent = null
}
else {
editorTabPreview = null
commitDiffSplitter.secondComponent = diffPreviewProcessor!!.component
}
}
private fun GitStageEditorDiffPreview.setup() {
escapeHandler = Runnable {
closePreview()
activate()
}
installSelectionHandler(tree, false)
installNextDiffActionOn(this@GitStagePanel)
tree.putClientProperty(ExpandableItemsHandler.IGNORE_ITEM_SELECTION, true)
}
override fun dispose() {
}
private inner class MyChangesTree(project: Project) : GitStageTree(project, project.service<GitStageUiSettingsImpl>(),
this@GitStagePanel) {
override val state
get() = [email protected]
override val ignoredFilePaths
get() = [email protected]
override val operations: List<StagingAreaOperation> = listOf(GitAddOperation, GitResetOperation)
private val includedRootsListeners = EventDispatcher.create(IncludedRootsListener::class.java)
init {
isShowCheckboxes = true
setInclusionModel(GitStageRootInclusionModel(project, tracker, this@GitStagePanel))
groupingSupport.addPropertyChangeListener(PropertyChangeListener {
includedRootsListeners.multicaster.includedRootsChanged()
})
inclusionModel.addInclusionListener(object : InclusionListener {
override fun inclusionChanged() {
includedRootsListeners.multicaster.includedRootsChanged()
}
})
tracker.addListener(object : GitStageTrackerListener {
override fun update() {
includedRootsListeners.multicaster.includedRootsChanged()
}
}, this@GitStagePanel)
doubleClickHandler = Processor { e ->
if (EditSourceOnDoubleClickHandler.isToggleEvent(this, e)) return@Processor false
processDoubleClickOrEnter(e, true)
true
}
enterKeyHandler = Processor { e ->
processDoubleClickOrEnter(e, false)
true
}
}
private fun processDoubleClickOrEnter(e: InputEvent?, isDoubleClick: Boolean) {
val dataContext = DataManager.getInstance().getDataContext(tree)
val mergeAction = ActionManager.getInstance().getAction("Git.Stage.Merge")
val event = AnActionEvent.createFromAnAction(mergeAction, e, ActionPlaces.UNKNOWN, dataContext)
if (ActionUtil.lastUpdateAndCheckDumb(mergeAction, event, true)) {
performActionDumbAwareWithCallbacks(mergeAction, event)
return
}
if (editorTabPreview?.processDoubleClickOrEnter(isDoubleClick) == true) return
OpenSourceUtil.openSourcesFrom(dataContext, true)
}
fun editedCommitChanged() {
rebuildTree()
commitPanel.editedCommit?.let {
val node = TreeUtil.findNodeWithObject(root, it)
node?.let { expandPath(TreeUtil.getPathFromRoot(node)) }
}
}
override fun customizeTreeModel(builder: TreeModelBuilder) {
super.customizeTreeModel(builder)
commitPanel.editedCommit?.let {
val commitNode = EditedCommitNode(it)
builder.insertSubtreeRoot(commitNode)
builder.insertChanges(it.commit.changes, commitNode)
}
}
override fun performStageOperation(nodes: List<GitFileStatusNode>, operation: StagingAreaOperation) {
performStageOperation(project, nodes, operation)
}
override fun getDndOperation(targetKind: NodeKind): StagingAreaOperation? {
return when (targetKind) {
NodeKind.STAGED -> GitAddOperation
NodeKind.UNSTAGED -> GitResetOperation
else -> null
}
}
override fun showMergeDialog(conflictedFiles: List<VirtualFile>) {
AbstractVcsHelper.getInstance(project).showMergeDialog(conflictedFiles)
}
override fun createHoverIcon(node: ChangesBrowserGitFileStatusNode): HoverIcon? {
val conflict = node.conflict ?: return null
val mergeHandler = createMergeHandler(project)
if (!canShowMergeWindow(project, mergeHandler, conflict)) return null
return GitStageMergeHoverIcon(mergeHandler, conflict)
}
fun getIncludedRoots(): Collection<VirtualFile> {
if (!isInclusionEnabled()) return state.allRoots
return inclusionModel.getInclusion().mapNotNull { (it as? GitRepository)?.root }
}
fun addIncludedRootsListener(listener: IncludedRootsListener, disposable: Disposable) {
includedRootsListeners.addListener(listener, disposable)
}
private fun isInclusionEnabled(): Boolean {
return state.rootStates.size > 1 && state.stagedRoots.size > 1 &&
groupingSupport.isAvailable(REPOSITORY_GROUPING) &&
groupingSupport[REPOSITORY_GROUPING]
}
override fun isInclusionEnabled(node: ChangesBrowserNode<*>): Boolean {
return isInclusionEnabled() && node is RepositoryChangesBrowserNode && isUnderKind(node, NodeKind.STAGED)
}
override fun isInclusionVisible(node: ChangesBrowserNode<*>): Boolean = isInclusionEnabled(node)
override fun getIncludableUserObjects(treeModelData: VcsTreeModelData): List<Any> {
return treeModelData
.iterateRawNodes()
.filter { node -> isIncludable(node) }
.map { node -> node.userObject }
.toList()
}
override fun getNodeStatus(node: ChangesBrowserNode<*>): ThreeStateCheckBox.State {
return inclusionModel.getInclusionState(node.userObject)
}
private fun isUnderKind(node: ChangesBrowserNode<*>, nodeKind: NodeKind): Boolean {
val nodePath = node.path ?: return false
return (nodePath.find { it is MyKindNode } as? MyKindNode)?.kind == nodeKind
}
override fun installGroupingSupport(): ChangesGroupingSupport {
val result = ChangesGroupingSupport(project, this, false)
if (PropertiesComponent.getInstance(project).getList(GROUPING_PROPERTY_NAME) == null) {
val oldGroupingKeys = (PropertiesComponent.getInstance(project).getList(GROUPING_KEYS) ?: DEFAULT_GROUPING_KEYS).toMutableSet()
oldGroupingKeys.add(REPOSITORY_GROUPING)
PropertiesComponent.getInstance(project).setList(GROUPING_PROPERTY_NAME, oldGroupingKeys.toList())
}
installGroupingSupport(this, result, GROUPING_PROPERTY_NAME, DEFAULT_GROUPING_KEYS + REPOSITORY_GROUPING)
return result
}
private inner class GitStageMergeHoverIcon(private val handler: GitMergeHandler, private val conflict: GitConflict) :
HoverIcon(AllIcons.Vcs.Merge, message("changes.view.merge.action.text")) {
override fun invokeAction(node: ChangesBrowserNode<*>) {
showMergeWindow(project, handler, listOf(conflict))
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as GitStageMergeHoverIcon
if (conflict != other.conflict) return false
return true
}
override fun hashCode(): Int {
return conflict.hashCode()
}
}
}
interface IncludedRootsListener : EventListener {
fun includedRootsChanged()
}
private inner class MyGitStageTrackerListener : GitStageTrackerListener {
override fun update() {
[email protected]()
}
}
private inner class MyGitChangeProviderListener : GitRefreshListener {
override fun progressStarted() {
runInEdt(disposableFlag) {
updateProgressState()
}
}
override fun progressStopped() {
runInEdt(disposableFlag) {
updateProgressState()
}
}
private fun updateProgressState() {
if (isRefreshInProgress()) {
tree.setEmptyText(message("stage.loading.status"))
progressStripe.startLoading()
}
else {
progressStripe.stopLoading()
tree.setEmptyText("")
}
}
}
private inner class MyChangeListListener : ChangeListListener {
override fun changeListUpdateDone() {
runInEdt(disposableFlag) {
updateChangesStatusPanel()
}
}
}
private inner class MyCommitWorkflowListener : CommitWorkflowListener {
override fun executionEnded() {
if (hasPendingUpdates) {
hasPendingUpdates = false
update()
}
}
}
companion object {
@NonNls
private const val GROUPING_PROPERTY_NAME = "GitStage.ChangesTree.GroupingKeys"
private const val GIT_STAGE_PANEL_PLACE = "GitStagePanelPlace"
}
}
internal fun createMergeHandler(project: Project) = GitMergeHandler(project, GitDefaultMergeDialogCustomizer(project))
| plugins/git4idea/src/git4idea/index/ui/GitStagePanel.kt | 3128272437 |
package com.xiasuhuei321.gankkotlin.data
import io.objectbox.annotation.Entity
import io.objectbox.annotation.Id
/**
* Created by xiasuhuei321 on 2018/8/22.
* author:luo
* e-mail:[email protected]
*/
data class GankData<T>(private val error: Boolean, var results: T? = null) {
fun isSuccess() = !error
}
@Entity
data class Data(val _id: String, val createdAt: String, val desc: String,
val publishedAt: String, val source: String, val type: String,
val url: String, val used: Boolean, val who: String, @Id var id: Long = 0)
// 数据比较操蛋,偷懒就这么写了
data class Daily(val Android: List<Data>, val iOS: List<Data>, val 休息视频: List<Data>, val 拓展资源: List<Data>, val 福利: List<Data>) | app/src/main/java/com/xiasuhuei321/gankkotlin/data/ResponseDTO.kt | 3006395577 |
/*
* Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.client.engine.winhttp.internal
import io.ktor.client.call.*
import io.ktor.client.engine.*
import io.ktor.client.request.*
import io.ktor.http.*
import io.ktor.http.content.*
import io.ktor.util.*
import io.ktor.utils.io.*
import io.ktor.utils.io.core.*
import io.ktor.utils.io.pool.*
import kotlinx.atomicfu.*
import kotlinx.cinterop.*
import kotlinx.coroutines.*
import kotlin.collections.MutableMap
import kotlin.collections.mutableMapOf
import kotlin.collections.set
import kotlin.coroutines.*
@OptIn(InternalAPI::class)
internal class WinHttpRequestProducer(
private val request: WinHttpRequest,
private val data: HttpRequestData
) {
private val closed = atomic(false)
private val chunked: Boolean = request.chunkedMode == WinHttpChunkedMode.Enabled && !data.isUpgradeRequest()
fun getHeaders(): Map<String, String> {
val headers = data.headersToMap()
if (chunked) {
headers[HttpHeaders.TransferEncoding] = "chunked"
}
return headers
}
suspend fun writeBody() {
if (closed.value) return
val requestBody = data.body.toByteChannel()
if (requestBody != null) {
val readBuffer = ByteArrayPool.borrow()
try {
if (chunked) {
writeChunkedBody(requestBody, readBuffer)
} else {
writeRegularBody(requestBody, readBuffer)
}
} finally {
ByteArrayPool.recycle(readBuffer)
}
}
}
private suspend fun writeChunkedBody(requestBody: ByteReadChannel, readBuffer: ByteArray) {
while (true) {
val readBytes = requestBody.readAvailable(readBuffer).takeIf { it > 0 } ?: break
writeBodyChunk(readBuffer, readBytes)
}
chunkTerminator.usePinned { src ->
request.writeData(src, chunkTerminator.size)
}
}
private suspend fun writeBodyChunk(readBuffer: ByteArray, length: Int) {
// Write chunk length
val chunkStart = "${length.toString(16)}\r\n".toByteArray()
chunkStart.usePinned { src ->
request.writeData(src, chunkStart.size)
}
// Write chunk data
readBuffer.usePinned { src ->
request.writeData(src, length)
}
// Write chunk ending
chunkEnd.usePinned { src ->
request.writeData(src, chunkEnd.size)
}
}
private suspend fun writeRegularBody(requestBody: ByteReadChannel, readBuffer: ByteArray) {
while (true) {
val readBytes = requestBody.readAvailable(readBuffer).takeIf { it > 0 } ?: break
readBuffer.usePinned { src ->
request.writeData(src, readBytes)
}
}
}
private fun HttpRequestData.headersToMap(): MutableMap<String, String> {
val result = mutableMapOf<String, String>()
mergeHeaders(headers, body) { key, value ->
result[key] = value
}
return result
}
private suspend fun OutgoingContent.toByteChannel(): ByteReadChannel? = when (this) {
is OutgoingContent.ByteArrayContent -> ByteReadChannel(bytes())
is OutgoingContent.WriteChannelContent -> GlobalScope.writer(coroutineContext) {
writeTo(channel)
}.channel
is OutgoingContent.ReadChannelContent -> readFrom()
is OutgoingContent.NoContent -> null
else -> throw UnsupportedContentTypeException(this)
}
companion object {
private val chunkEnd = "\r\n".toByteArray()
private val chunkTerminator = "0\r\n\r\n".toByteArray()
}
}
| ktor-client/ktor-client-winhttp/windows/src/io/ktor/client/engine/winhttp/internal/WinHttpRequestProducer.kt | 2659153879 |
package com.airbnb.lottie.samples
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.browser.customtabs.CustomTabsIntent
import androidx.core.net.toUri
import androidx.fragment.app.Fragment
import com.airbnb.lottie.samples.databinding.MainActivityBinding
import com.airbnb.lottie.samples.utils.viewBinding
class MainActivity : AppCompatActivity() {
private val binding: MainActivityBinding by viewBinding()
override fun onCreate(savedInstanceState: Bundle?) {
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true)
super.onCreate(savedInstanceState)
binding.bottomNavigation.setOnItemSelectedListener listener@{ item ->
when (item.itemId) {
R.id.showcase -> showFragment(ShowcaseFragment())
R.id.preview -> showFragment(PreviewFragment())
R.id.lottiefiles -> showFragment(LottiefilesFragment())
R.id.learn -> showShowcase()
}
true
}
if (savedInstanceState == null) {
showFragment(ShowcaseFragment())
}
}
private fun showShowcase() {
val intent = CustomTabsIntent.Builder().build()
intent.launchUrl(this, "http://airbnb.io/lottie/#/android".toUri())
}
private fun showFragment(fragment: Fragment) {
supportFragmentManager.beginTransaction()
.replace(R.id.content, fragment)
.commit()
}
}
| sample/src/main/kotlin/com/airbnb/lottie/samples/MainActivity.kt | 214635812 |
package com.aswiatek.pricecomparator.buisinesslogic.screenmodes
import com.aswiatek.pricecomparator.buisinesslogic.Mode
class ModeGetter {
private val mModes: MutableMap<Mode, ScreenMode> = mutableMapOf()
fun get(mode: Mode): ScreenMode =
mModes.getOrPut(mode) {
when (mode) {
Mode.CurrentQuantity -> CurrentQuantityMode(this)
Mode.CurrentPrice -> CurrentPriceMode(this)
Mode.TargetQuantity -> TargetQuantityMode(this)
else -> EmptyMode()
}
}
} | PriceComparator/app/src/main/java/com/aswiatek/pricecomparator/buisinesslogic/screenmodes/ModeGetter.kt | 2260822081 |
/*
* 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 EXT_image_drm_format_modifier = "EXTImageDrmFormatModifier".nativeClassVK("EXT_image_drm_format_modifier", type = "device", postfix = "EXT") {
documentation =
"""
This extension provides the ability to use <em>DRM format modifiers</em> with images, enabling Vulkan to better integrate with the Linux ecosystem of graphics, video, and display APIs.
Its functionality closely overlaps with {@code EGL_EXT_image_dma_buf_import_modifiers}<sup><a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#VK_EXT_image_drm_format_modifier-fn2">2</a></sup> and {@code EGL_MESA_image_dma_buf_export}<sup><a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#VK_EXT_image_drm_format_modifier-fn3">3</a></sup>. Unlike the EGL extensions, this extension does not require the use of a specific handle type (such as a dma_buf) for external memory and provides more explicit control of image creation.
<h5>Introduction to DRM Format Modifiers</h5>
A <em>DRM format modifier</em> is a 64-bit, vendor-prefixed, semi-opaque unsigned integer. Most <em>modifiers</em> represent a concrete, vendor-specific tiling format for images. Some exceptions are {@code DRM_FORMAT_MOD_LINEAR} (which is not vendor-specific); {@code DRM_FORMAT_MOD_NONE} (which is an alias of {@code DRM_FORMAT_MOD_LINEAR} due to historical accident); and {@code DRM_FORMAT_MOD_INVALID} (which does not represent a tiling format). The <em>modifier’s</em> vendor prefix consists of the 8 most significant bits. The canonical list of <em>modifiers</em> and vendor prefixes is found in <a target="_blank" href="https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/include/uapi/drm/drm_fourcc.h">{@code drm_fourcc.h}</a> in the Linux kernel source. The other dominant source of <em>modifiers</em> are vendor kernel trees.
One goal of <em>modifiers</em> in the Linux ecosystem is to enumerate for each vendor a reasonably sized set of tiling formats that are appropriate for images shared across processes, APIs, and/or devices, where each participating component may possibly be from different vendors. A non-goal is to enumerate all tiling formats supported by all vendors. Some tiling formats used internally by vendors are inappropriate for sharing; no <em>modifiers</em> should be assigned to such tiling formats.
Modifier values typically do not <em>describe</em> memory layouts. More precisely, a <em>modifier</em>'s lower 56 bits usually have no structure. Instead, modifiers <em>name</em> memory layouts; they name a small set of vendor-preferred layouts for image sharing. As a consequence, in each vendor namespace the modifier values are often sequentially allocated starting at 1.
Each <em>modifier</em> is usually supported by a single vendor and its name matches the pattern {@code {VENDOR}_FORMAT_MOD_*} or {@code DRM_FORMAT_MOD_{VENDOR}_*}. Examples are {@code I915_FORMAT_MOD_X_TILED} and {@code DRM_FORMAT_MOD_BROADCOM_VC4_T_TILED}. An exception is {@code DRM_FORMAT_MOD_LINEAR}, which is supported by most vendors.
Many APIs in Linux use <em>modifiers</em> to negotiate and specify the memory layout of shared images. For example, a Wayland compositor and Wayland client may, by relaying <em>modifiers</em> over the Wayland protocol {@code zwp_linux_dmabuf_v1}, negotiate a vendor-specific tiling format for a shared {@code wl_buffer}. The client may allocate the underlying memory for the {@code wl_buffer} with GBM, providing the chosen <em>modifier</em> to {@code gbm_bo_create_with_modifiers}. The client may then import the {@code wl_buffer} into Vulkan for producing image content, providing the resource’s dma_buf to ##VkImportMemoryFdInfoKHR and its <em>modifier</em> to ##VkImageDrmFormatModifierExplicitCreateInfoEXT. The compositor may then import the {@code wl_buffer} into OpenGL for sampling, providing the resource’s dma_buf and <em>modifier</em> to {@code eglCreateImage}. The compositor may also bypass OpenGL and submit the {@code wl_buffer} directly to the kernel’s display API, providing the dma_buf and <em>modifier</em> through {@code drm_mode_fb_cmd2}.
<h5>Format Translation</h5>
<em>Modifier</em>-capable APIs often pair <em>modifiers</em> with DRM formats, which are defined in <a target="_blank" href="https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/include/uapi/drm/drm_fourcc.h">{@code drm_fourcc.h}</a>. However, {@code VK_EXT_image_drm_format_modifier} uses {@code VkFormat} instead of DRM formats. The application must convert between {@code VkFormat} and DRM format when it sends or receives a DRM format to or from an external API.
The mapping from {@code VkFormat} to DRM format is lossy. Therefore, when receiving a DRM format from an external API, often the application must use information from the external API to accurately map the DRM format to a {@code VkFormat}. For example, DRM formats do not distinguish between RGB and sRGB (as of 2018-03-28); external information is required to identify the image’s colorspace.
The mapping between {@code VkFormat} and DRM format is also incomplete. For some DRM formats there exist no corresponding Vulkan format, and for some Vulkan formats there exist no corresponding DRM format.
<h5>Usage Patterns</h5>
Three primary usage patterns are intended for this extension:
<ul>
<li>
<b>Negotiation.</b> The application negotiates with <em>modifier</em>-aware, external components to determine sets of image creation parameters supported among all components.
In the Linux ecosystem, the negotiation usually assumes the image is a 2D, single-sampled, non-mipmapped, non-array image; this extension permits that assumption but does not require it. The result of the negotiation usually resembles a set of tuples such as <em>(drmFormat, drmFormatModifier)</em>, where each participating component supports all tuples in the set.
Many details of this negotiation - such as the protocol used during negotiation, the set of image creation parameters expressible in the protocol, and how the protocol chooses which process and which API will create the image - are outside the scope of this specification.
In this extension, #GetPhysicalDeviceFormatProperties2() with ##VkDrmFormatModifierPropertiesListEXT serves a primary role during the negotiation, and #GetPhysicalDeviceImageFormatProperties2() with ##VkPhysicalDeviceImageDrmFormatModifierInfoEXT serves a secondary role.
</li>
<li>
<b>Import.</b> The application imports an image with a <em>modifier</em>.
In this pattern, the application receives from an external source the image’s memory and its creation parameters, which are often the result of the negotiation described above. Some image creation parameters are implicitly defined by the external source; for example, #IMAGE_TYPE_2D is often assumed. Some image creation parameters are usually explicit, such as the image’s {@code format}, {@code drmFormatModifier}, and {@code extent}; and each plane’s {@code offset} and {@code rowPitch}.
Before creating the image, the application first verifies that the physical device supports the received creation parameters by querying #GetPhysicalDeviceFormatProperties2() with ##VkDrmFormatModifierPropertiesListEXT and #GetPhysicalDeviceImageFormatProperties2() with ##VkPhysicalDeviceImageDrmFormatModifierInfoEXT. Then the application creates the image by chaining ##VkImageDrmFormatModifierExplicitCreateInfoEXT and ##VkExternalMemoryImageCreateInfo onto ##VkImageCreateInfo.
</li>
<li>
<b>Export.</b> The application creates an image and allocates its memory. Then the application exports to <em>modifier</em>-aware consumers the image’s memory handles; its creation parameters; its <em>modifier</em>; and the <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#VkSubresourceLayout">{@code offset}</a>, <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#VkSubresourceLayout">{@code size}</a>, and <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#VkSubresourceLayout">{@code rowPitch}</a> of each <em>memory plane</em>.
In this pattern, the Vulkan device is the authority for the image; it is the allocator of the image’s memory and the decider of the image’s creation parameters. When choosing the image’s creation parameters, the application usually chooses a tuple <em>(format, drmFormatModifier)</em> from the result of the negotiation described above. The negotiation’s result often contains multiple tuples that share the same format but differ in their <em>modifier</em>. In this case, the application should defer the choice of the image’s <em>modifier</em> to the Vulkan implementation by providing all such <em>modifiers</em> to ##VkImageDrmFormatModifierListCreateInfoEXT{@code ::pDrmFormatModifiers}; and the implementation should choose from {@code pDrmFormatModifiers} the optimal <em>modifier</em> in consideration with the other image parameters.
The application creates the image by chaining ##VkImageDrmFormatModifierListCreateInfoEXT and ##VkExternalMemoryImageCreateInfo onto ##VkImageCreateInfo. The protocol and APIs by which the application will share the image with external consumers will likely determine the value of ##VkExternalMemoryImageCreateInfo{@code ::handleTypes}. The implementation chooses for the image an optimal <em>modifier</em> from ##VkImageDrmFormatModifierListCreateInfoEXT{@code ::pDrmFormatModifiers}. The application then queries the implementation-chosen <em>modifier</em> with #GetImageDrmFormatModifierPropertiesEXT(), and queries the memory layout of each plane with #GetImageSubresourceLayout().
The application then allocates the image’s memory with ##VkMemoryAllocateInfo, adding chained extending structures for external memory; binds it to the image; and exports the memory, for example, with #GetMemoryFdKHR().
Finally, the application sends the image’s creation parameters, its <em>modifier</em>, its per-plane memory layout, and the exported memory handle to the external consumers. The details of how the application transmits this information to external consumers is outside the scope of this specification.
</li>
</ul>
<h5>Prior Art</h5>
Extension {@code EGL_EXT_image_dma_buf_import}<sup><a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#VK_EXT_image_drm_format_modifier-fn1">1</a></sup> introduced the ability to create an {@code EGLImage} by importing for each plane a dma_buf, offset, and row pitch.
Later, extension {@code EGL_EXT_image_dma_buf_import_modifiers}<sup><a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#VK_EXT_image_drm_format_modifier-fn2">2</a></sup> introduced the ability to query which combination of formats and <em>modifiers</em> the implementation supports and to specify <em>modifiers</em> during creation of the {@code EGLImage}.
Extension {@code EGL_MESA_image_dma_buf_export}<sup><a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#VK_EXT_image_drm_format_modifier-fn3">3</a></sup> is the inverse of {@code EGL_EXT_image_dma_buf_import_modifiers}.
The Linux kernel modesetting API (KMS), when configuring the display’s framebuffer with {@code struct drm_mode_fb_cmd2}<sup><a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#VK_EXT_image_drm_format_modifier-fn4">4</a></sup>, allows one to specify the frambuffer’s <em>modifier</em> as well as a per-plane memory handle, offset, and row pitch.
GBM, a graphics buffer manager for Linux, allows creation of a {@code gbm_bo} (that is, a graphics <em>buffer object</em>) by importing data similar to that in {@code EGL_EXT_image_dma_buf_import_modifiers}<sup><a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#VK_EXT_image_drm_format_modifier-fn1">1</a></sup>; and symmetrically allows exporting the same data from the {@code gbm_bo}. See the references to <em>modifier</em> and <em>plane</em> in {@code gbm.h}<sup><a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#VK_EXT_image_drm_format_modifier-fn5">5</a></sup>.
<h5>VK_EXT_image_drm_format_modifier</h5>
<dl>
<dt><b>Name String</b></dt>
<dd>{@code VK_EXT_image_drm_format_modifier}</dd>
<dt><b>Extension Type</b></dt>
<dd>Device extension</dd>
<dt><b>Registered Extension Number</b></dt>
<dd>159</dd>
<dt><b>Revision</b></dt>
<dd>2</dd>
<dt><b>Extension and Version Dependencies</b></dt>
<dd><ul>
<li>Requires support for Vulkan 1.0</li>
<li>Requires {@link KHRBindMemory2 VK_KHR_bind_memory2} to be enabled for any device-level functionality</li>
<li>Requires {@link KHRGetPhysicalDeviceProperties2 VK_KHR_get_physical_device_properties2} to be enabled for any device-level functionality</li>
<li>Requires {@link KHRImageFormatList VK_KHR_image_format_list} to be enabled for any device-level functionality</li>
<li>Requires {@link KHRSamplerYcbcrConversion VK_KHR_sampler_ycbcr_conversion} to be enabled for any device-level functionality</li>
</ul></dd>
<dt><b>Contact</b></dt>
<dd><ul>
<li>Chad Versace <a target="_blank" href="https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_EXT_image_drm_format_modifier]%20@chadversary%250A*Here%20describe%20the%20issue%20or%20question%20you%20have%20about%20the%20VK_EXT_image_drm_format_modifier%20extension*">chadversary</a></li>
</ul></dd>
</dl>
<h5>Other Extension Metadata</h5>
<dl>
<dt><b>Last Modified Date</b></dt>
<dd>2021-09-30</dd>
<dt><b>IP Status</b></dt>
<dd>No known IP claims.</dd>
<dt><b>Contributors</b></dt>
<dd><ul>
<li>Antoine Labour, Google</li>
<li>Bas Nieuwenhuizen, Google</li>
<li>Chad Versace, Google</li>
<li>James Jones, NVIDIA</li>
<li>Jason Ekstrand, Intel</li>
<li>Jőrg Wagner, ARM</li>
<li>Kristian Høgsberg Kristensen, Google</li>
<li>Ray Smith, ARM</li>
</ul></dd>
</dl>
"""
IntConstant(
"The extension specification version.",
"EXT_IMAGE_DRM_FORMAT_MODIFIER_SPEC_VERSION".."2"
)
StringConstant(
"The extension name.",
"EXT_IMAGE_DRM_FORMAT_MODIFIER_EXTENSION_NAME".."VK_EXT_image_drm_format_modifier"
)
EnumConstant(
"Extends {@code VkResult}.",
"ERROR_INVALID_DRM_FORMAT_MODIFIER_PLANE_LAYOUT_EXT".."-1000158000"
)
EnumConstant(
"Extends {@code VkStructureType}.",
"STRUCTURE_TYPE_DRM_FORMAT_MODIFIER_PROPERTIES_LIST_EXT".."1000158000",
"STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_DRM_FORMAT_MODIFIER_INFO_EXT".."1000158002",
"STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_LIST_CREATE_INFO_EXT".."1000158003",
"STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_EXPLICIT_CREATE_INFO_EXT".."1000158004",
"STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_PROPERTIES_EXT".."1000158005"
)
EnumConstant(
"Extends {@code VkImageTiling}.",
"IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT".."1000158000"
)
EnumConstant(
"Extends {@code VkImageAspectFlagBits}.",
"IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT".enum(0x00000080),
"IMAGE_ASPECT_MEMORY_PLANE_1_BIT_EXT".enum(0x00000100),
"IMAGE_ASPECT_MEMORY_PLANE_2_BIT_EXT".enum(0x00000200),
"IMAGE_ASPECT_MEMORY_PLANE_3_BIT_EXT".enum(0x00000400)
)
EnumConstant(
"Extends {@code VkStructureType}.",
"STRUCTURE_TYPE_DRM_FORMAT_MODIFIER_PROPERTIES_LIST_2_EXT".."1000158006"
)
VkResult(
"GetImageDrmFormatModifierPropertiesEXT",
"""
Returns an image’s DRM format modifier.
<h5>C Specification</h5>
If an image was created with #IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT, then the image has a <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#glossary-drm-format-modifier">Linux DRM format modifier</a>. To query the <em>modifier</em>, call:
<pre><code>
VkResult vkGetImageDrmFormatModifierPropertiesEXT(
VkDevice device,
VkImage image,
VkImageDrmFormatModifierPropertiesEXT* pProperties);</code></pre>
<h5>Valid Usage</h5>
<ul>
<li>{@code image} <b>must</b> have been created with {@link VkImageCreateInfo tiling} equal to #IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT</li>
</ul>
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code device} <b>must</b> be a valid {@code VkDevice} handle</li>
<li>{@code image} <b>must</b> be a valid {@code VkImage} handle</li>
<li>{@code pProperties} <b>must</b> be a valid pointer to a ##VkImageDrmFormatModifierPropertiesEXT structure</li>
<li>{@code image} <b>must</b> have been created, allocated, or retrieved from {@code device}</li>
</ul>
<h5>Return Codes</h5>
<dl>
<dt>On success, this command returns</dt>
<dd><ul>
<li>#SUCCESS</li>
</ul></dd>
<dt>On failure, this command returns</dt>
<dd><ul>
<li>#ERROR_OUT_OF_HOST_MEMORY</li>
</ul></dd>
</dl>
<h5>See Also</h5>
##VkImageDrmFormatModifierPropertiesEXT
""",
VkDevice("device", "the logical device that owns the image."),
VkImage("image", "the queried image."),
VkImageDrmFormatModifierPropertiesEXT.p("pProperties", "a pointer to a ##VkImageDrmFormatModifierPropertiesEXT structure in which properties of the image’s <em>DRM format modifier</em> are returned.")
)
} | modules/lwjgl/vulkan/src/templates/kotlin/vulkan/templates/EXT_image_drm_format_modifier.kt | 4257136130 |
/*
* Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker 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.
*
* Loop Habit Tracker 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 org.isoron.uhabits.core.models
data class PaletteColor(val paletteIndex: Int) {
fun toCsvColor(): String {
return arrayOf(
"#D32F2F", // 0 red
"#E64A19", // 1 deep orange
"#F57C00", // 2 orange
"#FF8F00", // 3 amber
"#F9A825", // 4 yellow
"#AFB42B", // 5 lime
"#7CB342", // 6 light green
"#388E3C", // 7 green
"#00897B", // 8 teal
"#00ACC1", // 9 cyan
"#039BE5", // 10 light blue
"#1976D2", // 11 blue
"#303F9F", // 12 indigo
"#5E35B1", // 13 deep purple
"#8E24AA", // 14 purple
"#D81B60", // 15 pink
"#5D4037", // 16 brown
"#303030", // 17 dark grey
"#757575", // 18 grey
"#aaaaaa" // 19 light grey
)[paletteIndex]
}
fun compareTo(other: PaletteColor): Int {
return paletteIndex.compareTo(other.paletteIndex)
}
}
| uhabits-core/src/jvmMain/java/org/isoron/uhabits/core/models/PaletteColor.kt | 236315660 |
/*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.arch.handlers.internal
import org.hisp.dhis.android.core.common.CoreObject
internal interface LinkHandler<S, O : CoreObject> {
@JvmSuppressWildcards
fun handleMany(masterUid: String, slaves: Collection<S>?, transformer: (S) -> O)
fun resetAllLinks()
}
| core/src/main/java/org/hisp/dhis/android/core/arch/handlers/internal/LinkHandler.kt | 229972906 |
// 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
import com.intellij.lexer.Lexer
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.application.ex.PathManagerEx
import com.intellij.testFramework.LexerTestCase
import org.editorconfig.language.lexer.EditorConfigLexerAdapter
// 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.
class EditorConfigLexerTest : LexerTestCase() {
override fun createLexer(): Lexer = EditorConfigLexerAdapter()
override fun getDirPath() =
"${PathManagerEx.getCommunityHomePath()}/plugins/editorconfig/testSrc/org/editorconfig/language/lexer/"
.substring(PathManager.getHomePath().length)
fun testEmpty() = doTest()
fun testComment() = doTest()
fun testKeyValuePair() = doTest()
fun testSimpleSection() = doTest()
fun testCharClassSection() = doTest()
fun testVariantSection() = doTest()
fun testComplexSection() = doTest()
fun testWhitespacedComplexSection() = doTest()
fun testWhitespacedKeyValuePair() = doTest()
fun testQualifiedName() = doTest()
private fun doTest() =
doFileTest("editorconfig")
}
| plugins/editorconfig/test/org/editorconfig/language/EditorConfigLexerTest.kt | 2542420684 |
// 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.github.pullrequest.ui
import com.intellij.ide.CopyProvider
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.actionSystem.DataProvider
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.ide.CopyPasteManager
import com.intellij.openapi.util.Disposer
import com.intellij.ui.ListUtil
import com.intellij.ui.ScrollingUtil
import com.intellij.ui.components.JBList
import com.intellij.util.text.DateFormatUtil
import com.intellij.util.ui.*
import icons.GithubIcons
import net.miginfocom.layout.CC
import net.miginfocom.layout.LC
import net.miginfocom.swing.MigLayout
import org.jetbrains.plugins.github.api.data.GithubIssueState
import org.jetbrains.plugins.github.api.data.GithubSearchedIssue
import org.jetbrains.plugins.github.pullrequest.avatars.CachingGithubAvatarIconsProvider
import org.jetbrains.plugins.github.util.GithubUIUtil
import java.awt.Component
import java.awt.FlowLayout
import java.awt.datatransfer.StringSelection
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import javax.swing.*
internal class GithubPullRequestsList(private val copyPasteManager: CopyPasteManager,
avatarIconsProviderFactory: CachingGithubAvatarIconsProvider.Factory,
model: ListModel<GithubSearchedIssue>)
: JBList<GithubSearchedIssue>(model), CopyProvider, DataProvider, Disposable {
private val avatarIconSize = JBValue.UIInteger("Github.PullRequests.List.Assignee.Avatar.Size", 20)
private val avatarIconsProvider = avatarIconsProviderFactory.create(avatarIconSize, this)
init {
selectionModel.selectionMode = ListSelectionModel.SINGLE_SELECTION
addMouseListener(RightClickSelectionListener())
val renderer = PullRequestsListCellRenderer()
cellRenderer = renderer
UIUtil.putClientProperty(this, UIUtil.NOT_IN_HIERARCHY_COMPONENTS, listOf(renderer))
ScrollingUtil.installActions(this)
Disposer.register(this, avatarIconsProvider)
}
override fun getToolTipText(event: MouseEvent): String? {
val childComponent = ListUtil.getDeepestRendererChildComponentAt(this, event.point)
if (childComponent !is JComponent) return null
return childComponent.toolTipText
}
override fun performCopy(dataContext: DataContext) {
if (selectedIndex < 0) return
val selection = model.getElementAt(selectedIndex)
copyPasteManager.setContents(StringSelection("#${selection.number} ${selection.title}"))
}
override fun isCopyEnabled(dataContext: DataContext) = !isSelectionEmpty
override fun isCopyVisible(dataContext: DataContext) = false
override fun getData(dataId: String) = if (PlatformDataKeys.COPY_PROVIDER.`is`(dataId)) this else null
override fun dispose() {}
private inner class PullRequestsListCellRenderer : ListCellRenderer<GithubSearchedIssue>, JPanel() {
private val stateIcon = JLabel()
private val title = JLabel()
private val info = JLabel()
private val labels = JPanel(FlowLayout(FlowLayout.LEFT, 4, 0))
private val assignees = JPanel().apply {
layout = BoxLayout(this, BoxLayout.X_AXIS)
}
init {
border = JBUI.Borders.empty(5, 8)
layout = MigLayout(LC().gridGap("0", "0")
.insets("0", "0", "0", "0")
.fillX())
add(stateIcon, CC()
.gapAfter("${JBUI.scale(5)}px"))
add(title, CC()
.minWidth("0px"))
add(labels, CC()
.growX()
.pushX())
add(assignees, CC()
.spanY(2)
.wrap())
add(info, CC()
.minWidth("0px")
.skip(1)
.spanX(2))
}
override fun getListCellRendererComponent(list: JList<out GithubSearchedIssue>,
value: GithubSearchedIssue,
index: Int,
isSelected: Boolean,
cellHasFocus: Boolean): Component {
UIUtil.setBackgroundRecursively(this, GithubUIUtil.List.WithTallRow.background(list, isSelected))
val primaryTextColor = GithubUIUtil.List.WithTallRow.foreground(list, isSelected)
val secondaryTextColor = GithubUIUtil.List.WithTallRow.secondaryForeground(list, isSelected)
stateIcon.apply {
icon = if (value.state == GithubIssueState.open) GithubIcons.PullRequestOpen else GithubIcons.PullRequestClosed
}
title.apply {
text = value.title
foreground = primaryTextColor
}
info.apply {
text = "#${value.number} ${value.user.login} on ${DateFormatUtil.formatDate(value.createdAt)}"
foreground = secondaryTextColor
}
labels.apply {
removeAll()
for (label in value.labels) add(GithubUIUtil.createIssueLabelLabel(label))
}
assignees.apply {
removeAll()
for (assignee in value.assignees) {
if (componentCount != 0) {
add(Box.createRigidArea(JBDimension(UIUtil.DEFAULT_HGAP, 0)))
}
add(JLabel().apply {
icon = assignee.let { avatarIconsProvider.getIcon(it) }
toolTipText = assignee.login
})
}
}
return this
}
}
private inner class RightClickSelectionListener : MouseAdapter() {
override fun mousePressed(e: MouseEvent) {
if (JBSwingUtilities.isRightMouseButton(e)) {
val row = locationToIndex(e.point)
if (row != -1) selectionModel.setSelectionInterval(row, row)
}
}
}
} | plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/GithubPullRequestsList.kt | 3333386218 |
// WITH_STDLIB
// AFTER-WARNING: Parameter 'value' is never used
class FooException : Exception()
class Test {
var setter: String = ""
set(value) = <caret>throw FooException()
} | plugins/kotlin/idea/tests/testData/intentions/addThrowsAnnotation/inSetter.kt | 4166802707 |
package com.tungnui.abccomputer.models
/**
* Created by thanh on 28/10/2017.
*/
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
data class LineItem (
@SerializedName("id")
@Expose
var id: Int? = null,
@SerializedName("name")
@Expose
var name: String? = null,
@SerializedName("product_id")
@Expose
var productId: Int? = null,
@SerializedName("variation_id")
@Expose
var variationId: Int? = null,
@SerializedName("quantity")
@Expose
var quantity: Int? = null,
@SerializedName("tax_class")
@Expose
var taxClass: String? = null,
@SerializedName("subtotal")
@Expose
var subtotal: String? = null,
@SerializedName("subtotal_tax")
@Expose
var subtotalTax: String? = null,
@SerializedName("total")
@Expose
var total: String? = null,
@SerializedName("total_tax")
@Expose
var totalTax: String? = null,
@SerializedName("taxes")
@Expose
var taxes: List<Any>? = null,
@SerializedName("meta_data")
@Expose
var metaData: List<Any>? = null,
@SerializedName("sku")
@Expose
var sku: String? = null,
@SerializedName("price")
@Expose
var price: String? = null
) | app/src/main/java/com/tungnui/abccomputer/models/LineItem.kt | 1432412562 |
// snippet-sourcedescription:[DeleteApiKey.kt demonstrates how to delete a unique key.]
// snippet-keyword:[AWS SDK for Kotlin]
// snippet-service:[AWS AppSync]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.example.appsync
// snippet-start:[appsync.kotlin.del_ds.import]
import aws.sdk.kotlin.services.appsync.AppSyncClient
import aws.sdk.kotlin.services.appsync.model.DeleteDataSourceRequest
import kotlin.system.exitProcess
// snippet-end:[appsync.kotlin.del_ds.import]
/**
* Before running this Kotlin code example, set up your development environment, including your credentials.
*
* For more information, see the following documentation topic:
*
* https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html
*/
suspend fun main(args: Array<String>) {
val usage = """
Usage:
<apiId> <keyId>
Where:
apiId - The Id of the API. (You can get this value from the AWS Management Console.)
keyId - The Id of the key to delete.
"""
if (args.size != 2) {
println(usage)
exitProcess(1)
}
val apiId = args[0]
val dsName = args[1]
deleteDS(apiId, dsName)
}
// snippet-start:[appsync.kotlin.del_ds.main]
suspend fun deleteDS(apiIdVal: String?, dsName: String?) {
val request = DeleteDataSourceRequest {
apiId = apiIdVal
name = dsName
}
AppSyncClient { region = "us-east-1" }.use { appClient ->
appClient.deleteDataSource(request)
println("The data source was deleted.")
}
}
// snippet-end:[appsync.kotlin.del_ds.main]
| kotlin/services/appsync/src/main/kotlin/com/example/appsync/DeleteDataSource.kt | 2592208116 |
public class HasFields {
companion object {
const val constField = "taint"
lateinit var lateinitField: String
@JvmField val jvmFieldAnnotatedField = "taint"
}
fun doLateInit() {
lateinitField = "taint"
}
}
| java/ql/integration-tests/all-platforms/kotlin/kotlin_java_static_fields/hasFields.kt | 1001002381 |
package com.elpassion.mainframerplugin.common
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.project.Project
@State(name = "StateProvider", storages = arrayOf(Storage("mainframer_state.xml")))
class StateProvider : PersistentStateComponent<StateProvider.State> {
var isTurnOn: Boolean
get() = myState.isTurnOn
set(value) = with(myState) {
isTurnOn = value
}
override fun loadState(state: State) {
isTurnOn = state.isTurnOn
}
override fun getState(): State = myState
private val myState = State()
class State {
var isTurnOn = true
}
companion object {
fun getInstance(project: Project): StateProvider = ServiceManager.getService(project, StateProvider::class.java)
}
} | src/main/kotlin/com/elpassion/mainframerplugin/common/StateProvider.kt | 3646679499 |
package ua.com.lavi.komock.model
import org.eclipse.jetty.util.resource.Resource
import java.io.ByteArrayInputStream
import java.io.File
import java.io.InputStream
import java.net.URL
import java.nio.channels.ReadableByteChannel
/**
* Created by Oleksandr Loushkin
*/
class ByteResource(private val content: ByteArray) : Resource() {
override fun isContainedIn(resource: Resource): Boolean {
return false
}
override fun close() {
// nothing to close
}
override fun exists(): Boolean {
return true
}
override fun isDirectory(): Boolean {
return false
}
override fun lastModified(): Long {
return 0
}
override fun length(): Long {
return 0
}
override fun getURL(): URL? {
return null
}
override fun getFile(): File? {
return null
}
override fun getName(): String? {
return null
}
override fun getInputStream(): InputStream {
return ByteArrayInputStream(content)
}
override fun getReadableByteChannel(): ReadableByteChannel? {
return null
}
override fun delete(): Boolean {
return false
}
override fun renameTo(dest: Resource): Boolean {
return false
}
override fun list(): Array<String> {
return arrayOf("")
}
override fun addPath(path: String): Resource? {
return null
}
}
| komock-core/src/main/kotlin/ua/com/lavi/komock/model/ByteResource.kt | 2226332446 |
// COMPILER_ARGUMENTS: -XXLanguage:+TrailingCommas
// PROBLEM: none
fun a(i: Int, b: Boolean,)<caret> = Unit | plugins/kotlin/idea/tests/testData/inspectionsLocal/trailingComma/removeComma4.kt | 424387675 |
// 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.configuration
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.Extensions
import com.intellij.openapi.module.Module
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.modules
import com.intellij.openapi.roots.DependencyScope
import com.intellij.openapi.roots.LibraryOrderEntry
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.roots.impl.libraries.LibraryEx
import com.intellij.openapi.roots.libraries.PersistentLibraryKind
import com.intellij.openapi.util.ThrowableComputable
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.search.DelegatingGlobalSearchScope
import com.intellij.psi.search.FileTypeIndex
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.util.concurrency.annotations.RequiresBackgroundThread
import com.intellij.util.indexing.DumbModeAccessType
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.base.platforms.KotlinJavaScriptLibraryKind
import org.jetbrains.kotlin.idea.base.platforms.LibraryEffectiveKindProvider
import org.jetbrains.kotlin.idea.base.projectStructure.*
import org.jetbrains.kotlin.idea.base.util.projectScope
import org.jetbrains.kotlin.idea.compiler.configuration.IdeKotlinVersion
import org.jetbrains.kotlin.idea.core.KotlinPluginDisposable
import org.jetbrains.kotlin.idea.core.syncNonBlockingReadAction
import org.jetbrains.kotlin.idea.projectConfiguration.KotlinProjectConfigurationBundle
import org.jetbrains.kotlin.idea.projectConfiguration.RepositoryDescription
import org.jetbrains.kotlin.idea.projectConfiguration.KotlinNotConfiguredSuppressedModulesState
import org.jetbrains.kotlin.idea.util.application.isDispatchThread
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.idea.vfilefinder.IdeVirtualFileFinder
import org.jetbrains.kotlin.idea.vfilefinder.KotlinJavaScriptMetaFileIndex
import org.jetbrains.kotlin.idea.vfilefinder.hasSomethingInPackage
import org.jetbrains.kotlin.name.FqName
private val LOG = Logger.getInstance("#org.jetbrains.kotlin.idea.configuration.ConfigureKotlinInProjectUtils")
val LAST_SNAPSHOT_VERSION: IdeKotlinVersion = IdeKotlinVersion.get("1.5.255-SNAPSHOT")
val SNAPSHOT_REPOSITORY = RepositoryDescription(
"sonatype.oss.snapshots",
"Sonatype OSS Snapshot Repository",
"https://oss.sonatype.org/content/repositories/snapshots",
null,
isSnapshot = true
)
val DEFAULT_GRADLE_PLUGIN_REPOSITORY = RepositoryDescription(
"default.gradle.plugins",
"Default Gradle Plugin Repository",
"https://plugins.gradle.org/m2/",
null,
isSnapshot = false
)
fun devRepository(version: IdeKotlinVersion) = RepositoryDescription(
"teamcity.kotlin.dev",
"Teamcity Repository of Kotlin Development Builds",
"https://teamcity.jetbrains.com/guestAuth/app/rest/builds/buildType:(id:Kotlin_KotlinPublic_Aggregate),number:${version.rawVersion},branch:(default:any)/artifacts/content/maven",
null,
isSnapshot = false
)
const val MAVEN_CENTRAL = "mavenCentral()"
const val JCENTER = "jcenter()"
const val KOTLIN_GROUP_ID = "org.jetbrains.kotlin"
fun isRepositoryConfigured(repositoriesBlockText: String): Boolean =
repositoriesBlockText.contains(MAVEN_CENTRAL) || repositoriesBlockText.contains(JCENTER)
fun DependencyScope.toGradleCompileScope(isAndroidModule: Boolean) = when (this) {
DependencyScope.COMPILE -> "implementation"
// TODO: We should add testCompile or androidTestCompile
DependencyScope.TEST -> if (isAndroidModule) "implementation" else "testImplementation"
DependencyScope.RUNTIME -> "runtime"
DependencyScope.PROVIDED -> "implementation"
else -> "implementation"
}
fun RepositoryDescription.toGroovyRepositorySnippet() = "maven { url '$url' }"
/**
* This syntax has been released in kotlin-dsl-0.11.1 release and in Gradle 4.2-RC1 release.
*
* We already require Gradle distribution of higher version (see `checkGradleCompatibility` function),
* so it is safe to use this syntax everywhere.
*/
fun RepositoryDescription.toKotlinRepositorySnippet() = "maven(\"$url\")"
fun getRepositoryForVersion(version: IdeKotlinVersion): RepositoryDescription? = when {
version.isSnapshot -> SNAPSHOT_REPOSITORY
version.isDev -> devRepository(version)
else -> null
}
fun isModuleConfigured(moduleSourceRootGroup: ModuleSourceRootGroup): Boolean {
return allConfigurators().any {
it.getStatus(moduleSourceRootGroup) == ConfigureKotlinStatus.CONFIGURED
}
}
/**
* Returns a list of modules which contain sources in Kotlin.
* Note that this method is expensive and should not be called more often than strictly necessary.
*
* DO NOT CALL THIS ON AWT THREAD
*/
@RequiresBackgroundThread
fun getModulesWithKotlinFiles(project: Project, modulesWithKotlinFacets: List<Module>? = null): Collection<Module> {
if (!isUnitTestMode() && isDispatchThread()) {
LOG.error("getModulesWithKotlinFiles could be a heavy operation and should not be call on AWT thread")
}
fun <T> nonBlockingReadActionSync(block: () -> T): T {
return ReadAction.nonBlocking(block)
.expireWith(KotlinPluginDisposable.getInstance(project))
.executeSynchronously()
}
val projectScope = project.projectScope()
// nothing to configure if there is no Kotlin files in entire project
val anyKotlinFileInProject = nonBlockingReadActionSync {
FileTypeIndex.containsFileOfType(KotlinFileType.INSTANCE, projectScope)
}
if (!anyKotlinFileInProject) {
return emptyList()
}
val projectFileIndex = ProjectFileIndex.getInstance(project)
val modules =
if (modulesWithKotlinFacets.isNullOrEmpty()) {
val kotlinFiles = nonBlockingReadActionSync {
FileTypeIndex.getFiles(KotlinFileType.INSTANCE, projectScope)
}
kotlinFiles.mapNotNullTo(mutableSetOf()) { ktFile: VirtualFile ->
if (projectFileIndex.isInSourceContent(ktFile)) {
projectFileIndex.getModuleForFile(ktFile)
} else null
}
} else {
// filter modules with Kotlin facet AND have at least a single Kotlin file in them
nonBlockingReadActionSync {
modulesWithKotlinFacets.filterTo(mutableSetOf()) { module ->
if (module.isDisposed) return@filterTo false
FileTypeIndex.containsFileOfType(KotlinFileType.INSTANCE, module.moduleScope)
}
}
}
return modules
}
/**
* Returns a list of modules which contain sources in Kotlin, grouped by base module.
* Note that this method is expensive and should not be called more often than strictly necessary.
*/
fun getConfigurableModulesWithKotlinFiles(project: Project): List<ModuleSourceRootGroup> {
val modules = getModulesWithKotlinFiles(project)
if (modules.isEmpty()) return emptyList()
return ModuleSourceRootMap(project).groupByBaseModules(modules)
}
fun showConfigureKotlinNotificationIfNeeded(module: Module) {
val action: () -> Unit = {
val moduleGroup = module.toModuleGroup()
if (isNotConfiguredNotificationRequired(moduleGroup)) {
ConfigureKotlinNotificationManager.notify(module.project)
}
}
val dumbService = DumbService.getInstance(module.project)
if (dumbService.isDumb) {
dumbService.smartInvokeLater { action() }
} else {
action()
}
}
fun isNotConfiguredNotificationRequired(moduleGroup: ModuleSourceRootGroup): Boolean {
return KotlinNotConfiguredSuppressedModulesState.shouldSuggestConfiguration(moduleGroup.baseModule)
&& !isModuleConfigured(moduleGroup)
}
fun getAbleToRunConfigurators(project: Project): Collection<KotlinProjectConfigurator> {
val modules = getConfigurableModules(project)
return allConfigurators().filter { configurator ->
modules.any { configurator.getStatus(it) == ConfigureKotlinStatus.CAN_BE_CONFIGURED }
}
}
fun getConfigurableModules(project: Project): List<ModuleSourceRootGroup> {
return getConfigurableModulesWithKotlinFiles(project).ifEmpty {
ModuleSourceRootMap(project).groupByBaseModules(project.modules.asList())
}
}
fun getAbleToRunConfigurators(module: Module): Collection<KotlinProjectConfigurator> {
val moduleGroup = module.toModuleGroup()
return allConfigurators().filter {
it.getStatus(moduleGroup) == ConfigureKotlinStatus.CAN_BE_CONFIGURED
}
}
fun getConfiguratorByName(name: String): KotlinProjectConfigurator? {
return allConfigurators().firstOrNull { it.name == name }
}
fun allConfigurators(): Array<KotlinProjectConfigurator> {
@Suppress("DEPRECATION")
return Extensions.getExtensions(KotlinProjectConfigurator.EP_NAME)
}
fun getCanBeConfiguredModules(project: Project, configurator: KotlinProjectConfigurator): List<Module> {
val projectModules = project.modules.asList()
val result = mutableListOf<Module>()
val progressIndicator = ProgressManager.getGlobalProgressIndicator()
for ((index, module) in ModuleSourceRootMap(project).groupByBaseModules(projectModules).withIndex()) {
if (!isUnitTestMode()) {
progressIndicator?.let {
it.checkCanceled()
it.fraction = index * 1.0 / projectModules.size
it.text2 = KotlinProjectConfigurationBundle.message("lookup.module.0.configuration.progress.text", module.baseModule.name)
}
}
if (configurator.canConfigure(module)) {
result.add(module.baseModule)
}
}
return result
}
private fun KotlinProjectConfigurator.canConfigure(moduleSourceRootGroup: ModuleSourceRootGroup) =
getStatus(moduleSourceRootGroup) == ConfigureKotlinStatus.CAN_BE_CONFIGURED &&
(allConfigurators().toList() - this).none { it.getStatus(moduleSourceRootGroup) == ConfigureKotlinStatus.CONFIGURED }
/**
* Returns a list of modules which contain sources in Kotlin and for which it's possible to run the given configurator.
* Note that this method is expensive and should not be called more often than strictly necessary.
*/
fun getCanBeConfiguredModulesWithKotlinFiles(project: Project, configurator: KotlinProjectConfigurator): List<Module> {
val modules = getConfigurableModulesWithKotlinFiles(project)
return modules.filter { configurator.getStatus(it) == ConfigureKotlinStatus.CAN_BE_CONFIGURED }.map { it.baseModule }
}
fun getConfigurationPossibilitiesForConfigureNotification(
project: Project,
excludeModules: Collection<Module> = emptyList()
): Pair<Collection<ModuleSourceRootGroup>, Collection<KotlinProjectConfigurator>> {
val modulesWithKotlinFiles = getConfigurableModulesWithKotlinFiles(project).exclude(excludeModules)
val configurators = allConfigurators()
val runnableConfigurators = mutableSetOf<KotlinProjectConfigurator>()
val configurableModules = mutableListOf<ModuleSourceRootGroup>()
// We need to return all modules for which at least one configurator is applicable, as well as all configurators which
// are applicable for at least one module. At the same time we want to call getStatus() only once for each module/configurator pair.
for (moduleSourceRootGroup in modulesWithKotlinFiles) {
var moduleCanBeConfigured = false
var moduleAlreadyConfigured = false
for (configurator in configurators) {
if (moduleCanBeConfigured && configurator in runnableConfigurators) continue
when (configurator.getStatus(moduleSourceRootGroup)) {
ConfigureKotlinStatus.CAN_BE_CONFIGURED -> {
moduleCanBeConfigured = true
runnableConfigurators.add(configurator)
}
ConfigureKotlinStatus.CONFIGURED -> moduleAlreadyConfigured = true
else -> {
}
}
}
if (moduleCanBeConfigured
&& !moduleAlreadyConfigured
&& KotlinNotConfiguredSuppressedModulesState.shouldSuggestConfiguration(moduleSourceRootGroup.baseModule)
) {
configurableModules.add(moduleSourceRootGroup)
}
}
return configurableModules to runnableConfigurators
}
fun findApplicableConfigurator(module: Module): KotlinProjectConfigurator {
val moduleGroup = module.toModuleGroup()
return allConfigurators().find { it.getStatus(moduleGroup) != ConfigureKotlinStatus.NON_APPLICABLE }
?: KotlinJavaModuleConfigurator.instance
}
fun hasAnyKotlinRuntimeInScope(module: Module): Boolean {
return syncNonBlockingReadAction(module.project) {
val scope = module.getModuleWithDependenciesAndLibrariesScope(true)
DumbModeAccessType.RELIABLE_DATA_ONLY.ignoreDumbMode(ThrowableComputable {
scope.hasKotlinJvmRuntime(module.project)
|| runReadAction { hasKotlinJsKjsmFile(LibraryKindSearchScope(module, scope, KotlinJavaScriptLibraryKind)) }
|| hasKotlinCommonRuntimeInScope(scope)
})
}
}
fun hasKotlinJvmRuntimeInScope(module: Module): Boolean {
return syncNonBlockingReadAction(module.project) {
val scope = module.getModuleWithDependenciesAndLibrariesScope(true)
DumbModeAccessType.RELIABLE_DATA_ONLY.ignoreDumbMode<Boolean, Throwable> {
scope.hasKotlinJvmRuntime(module.project)
}
}
}
fun hasKotlinJsRuntimeInScope(module: Module): Boolean {
return syncNonBlockingReadAction(module.project) {
val scope = module.getModuleWithDependenciesAndLibrariesScope(true)
runReadAction {
hasKotlinJsKjsmFile(LibraryKindSearchScope(module, scope, KotlinJavaScriptLibraryKind))
}
}
}
fun hasKotlinCommonRuntimeInScope(scope: GlobalSearchScope): Boolean {
return IdeVirtualFileFinder(scope).hasMetadataPackage(StandardNames.BUILT_INS_PACKAGE_FQ_NAME)
}
private val KOTLIN_JS_FQ_NAME = FqName("kotlin.js")
private fun hasKotlinJsKjsmFile(scope: GlobalSearchScope): Boolean {
return KotlinJavaScriptMetaFileIndex.hasSomethingInPackage(KOTLIN_JS_FQ_NAME, scope)
}
class LibraryKindSearchScope(
val module: Module,
baseScope: GlobalSearchScope,
private val libraryKind: PersistentLibraryKind<*>
) : DelegatingGlobalSearchScope(baseScope) {
override fun contains(file: VirtualFile): Boolean {
if (!super.contains(file)) return false
val orderEntry = ModuleRootManager.getInstance(module).fileIndex.getOrderEntryForFile(file)
if (orderEntry is LibraryOrderEntry) {
return LibraryEffectiveKindProvider.getInstance(module.project).getEffectiveKind(orderEntry.library as LibraryEx) == libraryKind
}
return true
}
} | plugins/kotlin/project-configuration/src/org/jetbrains/kotlin/idea/configuration/ConfigureKotlinInProjectUtils.kt | 2323623625 |
package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList
import kotlin.jvm.JvmName
import kotlin.jvm.JvmOverloads
import kotlin.jvm.JvmStatic
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.MutableEntityStorage
// ------------------------------ Persistent Id ---------------
data class NameId(private val name: String) : SymbolicEntityId<NamedEntity> {
override val presentableName: String
get() = name
override fun toString(): String = name
}
data class AnotherNameId(private val name: String) : SymbolicEntityId<NamedEntity> {
override val presentableName: String
get() = name
override fun toString(): String = name
}
data class ComposedId(val name: String, val link: NameId) : SymbolicEntityId<ComposedIdSoftRefEntity> {
override val presentableName: String
get() = "$name - ${link.presentableName}"
}
// ------------------------------ Entity With Persistent Id ------------------
interface NamedEntity : WorkspaceEntityWithSymbolicId {
val myName: String
val additionalProperty: String?
val children: List<@Child NamedChildEntity>
override val symbolicId: NameId
get() = NameId(myName)
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : NamedEntity, WorkspaceEntity.Builder<NamedEntity>, ObjBuilder<NamedEntity> {
override var entitySource: EntitySource
override var myName: String
override var additionalProperty: String?
override var children: List<NamedChildEntity>
}
companion object : Type<NamedEntity, Builder>() {
@JvmOverloads
@JvmStatic
@JvmName("create")
operator fun invoke(myName: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): NamedEntity {
val builder = builder()
builder.myName = myName
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: NamedEntity, modification: NamedEntity.Builder.() -> Unit) = modifyEntity(
NamedEntity.Builder::class.java, entity, modification)
//endregion
fun MutableEntityStorage.addNamedEntity(
name: String,
additionalProperty: String? = null,
source: EntitySource = MySource
): NamedEntity {
val namedEntity = NamedEntity(name, source) {
this.additionalProperty = additionalProperty
this.children = emptyList()
}
this.addEntity(namedEntity)
return namedEntity
}
//val NamedEntity.children: List<NamedChildEntity>
// get() = TODO()
// get() = referrers(NamedChildEntity::parent)
// ------------------------------ Child of entity with persistent id ------------------
interface NamedChildEntity : WorkspaceEntity {
val childProperty: String
val parentEntity: NamedEntity
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : NamedChildEntity, WorkspaceEntity.Builder<NamedChildEntity>, ObjBuilder<NamedChildEntity> {
override var entitySource: EntitySource
override var childProperty: String
override var parentEntity: NamedEntity
}
companion object : Type<NamedChildEntity, Builder>() {
@JvmOverloads
@JvmStatic
@JvmName("create")
operator fun invoke(childProperty: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): NamedChildEntity {
val builder = builder()
builder.childProperty = childProperty
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: NamedChildEntity, modification: NamedChildEntity.Builder.() -> Unit) = modifyEntity(
NamedChildEntity.Builder::class.java, entity, modification)
//endregion
fun MutableEntityStorage.addNamedChildEntity(
parentEntity: NamedEntity,
childProperty: String = "child",
source: EntitySource = MySource
): NamedChildEntity {
val namedChildEntity = NamedChildEntity(childProperty, source) {
this.parentEntity = parentEntity
}
this.addEntity(namedChildEntity)
return namedChildEntity
}
// ------------------------------ Entity with soft link --------------------
interface WithSoftLinkEntity : WorkspaceEntity {
val link: NameId
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : WithSoftLinkEntity, WorkspaceEntity.Builder<WithSoftLinkEntity>, ObjBuilder<WithSoftLinkEntity> {
override var entitySource: EntitySource
override var link: NameId
}
companion object : Type<WithSoftLinkEntity, Builder>() {
@JvmOverloads
@JvmStatic
@JvmName("create")
operator fun invoke(link: NameId, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): WithSoftLinkEntity {
val builder = builder()
builder.link = link
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: WithSoftLinkEntity, modification: WithSoftLinkEntity.Builder.() -> Unit) = modifyEntity(
WithSoftLinkEntity.Builder::class.java, entity, modification)
//endregion
fun MutableEntityStorage.addWithSoftLinkEntity(link: NameId, source: EntitySource = MySource): WithSoftLinkEntity {
val withSoftLinkEntity = WithSoftLinkEntity(link, source)
this.addEntity(withSoftLinkEntity)
return withSoftLinkEntity
}
interface ComposedLinkEntity : WorkspaceEntity {
val link: ComposedId
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : ComposedLinkEntity, WorkspaceEntity.Builder<ComposedLinkEntity>, ObjBuilder<ComposedLinkEntity> {
override var entitySource: EntitySource
override var link: ComposedId
}
companion object : Type<ComposedLinkEntity, Builder>() {
@JvmOverloads
@JvmStatic
@JvmName("create")
operator fun invoke(link: ComposedId, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ComposedLinkEntity {
val builder = builder()
builder.link = link
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: ComposedLinkEntity, modification: ComposedLinkEntity.Builder.() -> Unit) = modifyEntity(
ComposedLinkEntity.Builder::class.java, entity, modification)
//endregion
fun MutableEntityStorage.addComposedLinkEntity(link: ComposedId, source: EntitySource = MySource): ComposedLinkEntity {
val composedLinkEntity = ComposedLinkEntity(link, source)
this.addEntity(composedLinkEntity)
return composedLinkEntity
}
// ------------------------- Entity with SymbolicId and the list of soft links ------------------
interface WithListSoftLinksEntity : WorkspaceEntityWithSymbolicId {
val myName: String
val links: List<NameId>
override val symbolicId: AnotherNameId get() = AnotherNameId(myName)
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : WithListSoftLinksEntity, WorkspaceEntity.Builder<WithListSoftLinksEntity>, ObjBuilder<WithListSoftLinksEntity> {
override var entitySource: EntitySource
override var myName: String
override var links: MutableList<NameId>
}
companion object : Type<WithListSoftLinksEntity, Builder>() {
@JvmOverloads
@JvmStatic
@JvmName("create")
operator fun invoke(myName: String,
links: List<NameId>,
entitySource: EntitySource,
init: (Builder.() -> Unit)? = null): WithListSoftLinksEntity {
val builder = builder()
builder.myName = myName
builder.links = links.toMutableWorkspaceList()
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: WithListSoftLinksEntity,
modification: WithListSoftLinksEntity.Builder.() -> Unit) = modifyEntity(
WithListSoftLinksEntity.Builder::class.java, entity, modification)
//endregion
fun MutableEntityStorage.addWithListSoftLinksEntity(
name: String,
links: List<NameId>,
source: EntitySource = MySource
): WithListSoftLinksEntity {
val withListSoftLinksEntity = WithListSoftLinksEntity(name, links, source)
this.addEntity(withListSoftLinksEntity)
return withListSoftLinksEntity
}
// --------------------------- Entity with composed persistent id via soft reference ------------------
interface ComposedIdSoftRefEntity : WorkspaceEntityWithSymbolicId {
val myName: String
val link: NameId
override val symbolicId: ComposedId get() = ComposedId(myName, link)
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : ComposedIdSoftRefEntity, WorkspaceEntity.Builder<ComposedIdSoftRefEntity>, ObjBuilder<ComposedIdSoftRefEntity> {
override var entitySource: EntitySource
override var myName: String
override var link: NameId
}
companion object : Type<ComposedIdSoftRefEntity, Builder>() {
@JvmOverloads
@JvmStatic
@JvmName("create")
operator fun invoke(myName: String,
link: NameId,
entitySource: EntitySource,
init: (Builder.() -> Unit)? = null): ComposedIdSoftRefEntity {
val builder = builder()
builder.myName = myName
builder.link = link
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: ComposedIdSoftRefEntity,
modification: ComposedIdSoftRefEntity.Builder.() -> Unit) = modifyEntity(
ComposedIdSoftRefEntity.Builder::class.java, entity, modification)
//endregion
fun MutableEntityStorage.addComposedIdSoftRefEntity(
name: String,
link: NameId,
source: EntitySource = MySource
): ComposedIdSoftRefEntity {
val composedIdSoftRefEntity = ComposedIdSoftRefEntity(name, link, source)
this.addEntity(composedIdSoftRefEntity)
return composedIdSoftRefEntity
}
| platform/workspaceModel/storage/testEntities/testSrc/com/intellij/workspaceModel/storage/entities/test/api/WithSoftLinkEntityData.kt | 318154294 |
// 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.warmup
import com.intellij.openapi.extensions.ExtensionPointName
import org.jetbrains.annotations.ApiStatus
/**
* Allows to add a custom 'Project is built/compiled' event for warmup mode.
* All such events are awaited in warmup mode after all [ProjectIndexesWarmupSupport] were awaited.
*/
@ApiStatus.Internal
interface ProjectBuildWarmupSupport {
companion object {
var EP_NAME = ExtensionPointName<ProjectBuildWarmupSupport>("com.intellij.projectBuildWarmupSupport")
}
/**
* Builder ID which is used to customize a set of builders (implementations of [ProjectBuildWarmupSupport])
* which should be run. Customization can be made using environment variable IJ_WARMUP_BUILD_BUILDERS with semicolon separated builder ids
* ```
* IJ_WARMUP_BUILD_BUILDERS=PLATFORM;RIDER
* ```
* @see PlatformBuildWarmupSupport
*/
fun getBuilderId(): String
/**
* Start custom build process and return a future which is completed only when a custom build is finished
* @param rebuild indicates if rebuild should be done instead of ordinary build
*
* @return build status message
*/
suspend fun buildProject(rebuild: Boolean = false): String
} | platform/warmup/src/com/intellij/warmup/ProjectBuildWarmupSupport.kt | 4035175416 |
package org.camunda.community.process_test_coverage.spring_test.platform8
object CoverageTestProcessConstants {
const val PROCESS_DEFINITION_KEY = "process-test-coverage"
}
| extension/spring-test-platform-8/src/test/kotlin/org/camunda/community/process_test_coverage/spring_test/platform8/CoverageTestProcessConstants.kt | 63154515 |
// 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.intellij.build.impl.compilation
import com.intellij.diagnostic.telemetry.use
import com.intellij.diagnostic.telemetry.useWithScope
import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.io.Compressor
import io.opentelemetry.api.common.AttributeKey
import io.opentelemetry.api.common.Attributes
import io.opentelemetry.api.trace.Span
import okhttp3.Request
import okhttp3.RequestBody
import okio.BufferedSink
import okio.source
import org.jetbrains.intellij.build.*
import org.jetbrains.intellij.build.TraceManager.spanBuilder
import org.jetbrains.intellij.build.impl.compilation.cache.CommitsHistory
import org.jetbrains.intellij.build.impl.compilation.cache.SourcesStateProcessor
import org.jetbrains.intellij.build.io.moveFile
import org.jetbrains.intellij.build.io.retryWithExponentialBackOff
import org.jetbrains.intellij.build.io.zipWithCompression
import org.jetbrains.jps.cache.model.BuildTargetState
import org.jetbrains.jps.incremental.storage.ProjectStamps
import java.nio.file.Files
import java.nio.file.Path
import java.util.concurrent.ForkJoinTask
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
internal class PortableCompilationCacheUploader(
private val context: CompilationContext,
private val remoteCache: PortableCompilationCache.RemoteCache,
private val remoteGitUrl: String,
private val commitHash: String,
s3Folder: String,
private val uploadCompilationOutputsOnly: Boolean,
private val forcedUpload: Boolean,
) {
private val uploadedOutputCount = AtomicInteger()
private val sourcesStateProcessor = SourcesStateProcessor(context.compilationData.dataStorageRoot, context.classesOutputDirectory)
private val uploader = Uploader(remoteCache.uploadUrl, remoteCache.authHeader)
private val commitHistory = CommitsHistory(mapOf(remoteGitUrl to setOf(commitHash)))
private val s3Folder = Path.of(s3Folder)
init {
FileUtil.delete(this.s3Folder)
Files.createDirectories(this.s3Folder)
}
fun upload(messages: BuildMessages) {
if (!Files.exists(sourcesStateProcessor.sourceStateFile)) {
messages.warning("Compilation outputs doesn't contain source state file, " +
"please enable '${ProjectStamps.PORTABLE_CACHES_PROPERTY}' flag")
return
}
val start = System.nanoTime()
val tasks = mutableListOf<ForkJoinTask<*>>()
if (!uploadCompilationOutputsOnly) {
// Jps Caches upload is started first because of significant size
tasks.add(ForkJoinTask.adapt(::uploadJpsCaches))
}
val currentSourcesState = sourcesStateProcessor.parseSourcesStateFile()
uploadCompilationOutputs(currentSourcesState, uploader, tasks)
ForkJoinTask.invokeAll(tasks)
messages.reportStatisticValue("Compilation upload time, ms", (TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start).toString()))
val totalOutputs = (sourcesStateProcessor.getAllCompilationOutputs(currentSourcesState).size).toString()
messages.reportStatisticValue("Total outputs", totalOutputs)
messages.reportStatisticValue("Uploaded outputs", uploadedOutputCount.get().toString())
uploadMetadata()
uploadToS3()
}
private fun uploadToS3() {
spanBuilder("aws s3 sync").useWithScope {
context.messages.info(awsS3Cli("sync", "--no-progress", "--include", "*", "$s3Folder", "s3://intellij-jps-cache"))
println("##teamcity[setParameter name='jps.caches.aws.sync.skip' value='true']")
}
}
private fun uploadJpsCaches() {
val dataStorageRoot = context.compilationData.dataStorageRoot
val zipFile = dataStorageRoot.parent.resolve(commitHash)
Compressor.Zip(zipFile).use { zip ->
zip.addDirectory(dataStorageRoot)
}
val cachePath = "caches/$commitHash"
if (forcedUpload || !uploader.isExist(cachePath, true)) {
uploader.upload(cachePath, zipFile)
}
moveFile(zipFile, s3Folder.resolve(cachePath))
}
private fun uploadMetadata() {
val metadataPath = "metadata/$commitHash"
val sourceStateFile = sourcesStateProcessor.sourceStateFile
uploader.upload(metadataPath, sourceStateFile)
moveFile(sourceStateFile, s3Folder.resolve(metadataPath))
}
private fun uploadCompilationOutputs(currentSourcesState: Map<String, Map<String, BuildTargetState>>,
uploader: Uploader,
tasks: MutableList<ForkJoinTask<*>>): List<ForkJoinTask<*>> {
return sourcesStateProcessor.getAllCompilationOutputs(currentSourcesState).mapTo(tasks) { compilationOutput ->
ForkJoinTask.adapt {
val sourcePath = compilationOutput.remotePath
val outputFolder = Path.of(compilationOutput.path)
if (!Files.exists(outputFolder)) {
Span.current().addEvent("$outputFolder doesn't exist, was a respective module removed?")
return@adapt
}
val zipFile = context.paths.tempDir.resolve("compilation-output-zips").resolve(sourcePath)
zipWithCompression(zipFile, mapOf(outputFolder to ""))
if (forcedUpload || !uploader.isExist(sourcePath)) {
uploader.upload(sourcePath, zipFile)
uploadedOutputCount.incrementAndGet()
}
moveFile(zipFile, s3Folder.resolve(sourcePath))
}
}
}
/**
* Upload and publish file with commits history
*/
fun updateCommitHistory(commitHistory: CommitsHistory = this.commitHistory, overrideRemoteHistory: Boolean = false) {
for (commitHash in commitHistory.commitsForRemote(remoteGitUrl)) {
val cacheUploaded = uploader.isExist("caches/$commitHash")
val metadataUploaded = uploader.isExist("metadata/$commitHash")
if (!cacheUploaded && !metadataUploaded) {
val msg = "Unable to publish $commitHash due to missing caches/$commitHash and metadata/$commitHash. " +
"Probably caused by previous cleanup build."
if (overrideRemoteHistory) context.messages.error(msg) else context.messages.warning(msg)
return
}
check(cacheUploaded == metadataUploaded) {
"JPS Caches are uploaded: $cacheUploaded, metadata is uploaded: $metadataUploaded"
}
}
uploader.upload(path = CommitsHistory.JSON_FILE,
file = writeCommitHistory(if (overrideRemoteHistory) commitHistory else commitHistory.plus(remoteCommitHistory())))
}
private fun remoteCommitHistory(): CommitsHistory {
return if (uploader.isExist(CommitsHistory.JSON_FILE)) {
CommitsHistory(uploader.getAsString(CommitsHistory.JSON_FILE, remoteCache.authHeader))
}
else {
CommitsHistory(emptyMap())
}
}
private fun writeCommitHistory(commitHistory: CommitsHistory): Path {
val commitHistoryFile = s3Folder.resolve(CommitsHistory.JSON_FILE)
Files.createDirectories(commitHistoryFile.parent)
val json = commitHistory.toJson()
Files.writeString(commitHistoryFile, json)
Span.current().addEvent("write commit history", Attributes.of(AttributeKey.stringKey("data"), json))
return commitHistoryFile
}
}
private class Uploader(serverUrl: String, val authHeader: String) {
private val serverUrl = toUrlWithTrailingSlash(serverUrl)
fun upload(path: String, file: Path): Boolean {
val url = pathToUrl(path)
spanBuilder("upload").setAttribute("url", url).setAttribute("path", path).useWithScope {
check(Files.exists(file)) {
"The file $file does not exist"
}
retryWithExponentialBackOff {
httpClient.newCall(Request.Builder().url(url)
.header("Authorization", authHeader)
.put(object : RequestBody() {
override fun contentType() = MEDIA_TYPE_BINARY
override fun contentLength() = Files.size(file)
override fun writeTo(sink: BufferedSink) {
file.source().use(sink::writeAll)
}
}).build()).execute().useSuccessful {}
}
}
return true
}
fun isExist(path: String, logIfExists: Boolean = false): Boolean {
val url = pathToUrl(path)
spanBuilder("head").setAttribute("url", url).use { span ->
val code = retryWithExponentialBackOff {
httpClient.head(url, authHeader).use {
check(it.code == 200 || it.code == 404) {
"HEAD $url responded with unexpected ${it.code}"
}
it.code
}
}
if (code == 200) {
try {
/**
* FIXME dirty workaround for unreliable [serverUrl]
*/
httpClient.get(url, authHeader).use {
it.peekBody(byteCount = 1)
}
}
catch (ignored: Exception) {
return false
}
if (logIfExists) {
span.addEvent("File '$path' already exists on server, nothing to upload")
}
return true
}
}
return false
}
fun getAsString(path: String, authHeader: String) = retryWithExponentialBackOff {
httpClient.get(pathToUrl(path), authHeader).useSuccessful { it.body.string() }
}
private fun pathToUrl(path: String) = "$serverUrl${path.trimStart('/')}"
} | platform/build-scripts/src/org/jetbrains/intellij/build/impl/compilation/PortableCompilationCacheUploader.kt | 2767049593 |
package org.jetbrains.generator
import org.jetbrains.generator.grammar.Grammar
import org.jetbrains.generator.grammar.TokenDescription
import java.util.ArrayList
import org.jetbrains.generator.grammar.Rule
import org.jetbrains.generator.TokenType.*
import org.jetbrains.generator.grammar.Variant
import org.jetbrains.generator.grammar.RuleRef
import org.jetbrains.generator.grammar.NonFinalVariant
import org.jetbrains.generator.grammar.FinalVariant
/**
* Created by atsky on 11/7/14.
*/
class GrammarParser(val tokens : List<Token>) {
var current : Int = -1
fun parseGrammar( ) : Grammar? {
match("token")
match(OBRACE)
val tokens = parseTokens()
match(CBRACE)
val rules = parseRules()
return Grammar(tokens, rules)
}
fun text(): String {
return tokens[current].text
}
fun parseTokens( ) : List<TokenDescription> {
val list = ArrayList<TokenDescription>()
while (true) {
if (tryMatch(TokenType.STRING)) {
val tokenText = text()
list.add(TokenDescription(tokenText.substring(1, tokenText.length - 1), getNext()!!.text, true))
} else if (tryMatch(TokenType.ID)) {
val tokenText = text()
list.add(TokenDescription(tokenText, getNext()!!.text, false))
} else {
break
}
}
return list
}
fun match(text: String) {
getNext()
if (text() == text) {
throw RuntimeException()
}
}
fun match(expected: TokenType) : Token {
val next = getNext()
if (next == null || next.type != expected) {
throw ParserException(next, "${expected} expected, but ${next?.type}")
}
return next
}
fun tryMatch(type: TokenType): Boolean {
if (getNext()!!.type != type) {
current--
return false
}
return true
}
fun getNext(): Token? {
if (current < tokens.size) {
current++
return if (current < tokens.size) tokens[current] else null
} else {
return null
}
}
fun parseRules() : List<Rule> {
val list = ArrayList<Rule>()
while (!eof()) {
list.add(parseRule())
}
return list
}
fun parseRule() : Rule {
val name = match(ID).text
match(COLON)
val variants = ArrayList<Variant>()
while (true) {
variants.add(parseVariant())
if (!tryMatch(VBAR)) {
break
}
}
match(SEMICOLON)
return Rule(name, variants)
}
fun eof(): Boolean {
return current >= tokens.size - 1
}
fun parseVariant() : Variant {
val list = ArrayList<RuleRef>()
while (true) {
if (tryMatch(TokenType.STRING)) {
val t = text()
list.add(RuleRef(t.substring(1, t.length - 1), false))
} else if (tryMatch(TokenType.ID)) {
list.add(RuleRef(text(), true))
} else {
break
}
}
val name = if (tryMatch(OBRACE)) {
match(TokenType.ID)
val text = text()
match(CBRACE)
text
} else {
null
}
var variant : Variant = FinalVariant(name)
for (ref in list.reversed()) {
variant = NonFinalVariant(ref, listOf(variant))
}
return variant
}
} | generator/src/org/jetbrains/generator/GrammarParser.kt | 3820567569 |
package com.devtub.injekt.tooling
import kotlin.reflect.KClass
import kotlin.reflect.primaryConstructor
class Provider internal constructor(private val context: Context) {
private companion object {
fun shim(instance: Any): (Any?) -> Any = { instance }
fun shim(kClass: KClass<*>): (Any?) -> Any = { kClass.primaryConstructor!!.call() }
fun shim(factory: () -> Any): (Any?) -> Any = { factory() }
fun <A> shim(factory: (A) -> Any): (Any?) -> Any = { @Suppress("UNCHECKED_CAST") factory(it as A) }
}
val global by lazy { Context.global.provide }
val parent by lazy { context.parent!!.provide }
inline fun <reified T : Any> singleton(instance: T, tag: String? = null, override: Boolean = false) {
singleton(T::class, tag, instance, override)
}
inline fun <reified T : Any> singleton(implClass: KClass<out T>, tag: String? = null, override: Boolean = false) {
singleton(T::class, tag, implClass, override)
}
inline fun <reified T : Any> singleton(tag: String? = null, override: Boolean = false, noinline factory: () -> T) {
singleton(T::class, tag, factory, override)
}
inline fun <reified T : Any, A> singleton(tag: String? = null, override: Boolean = false, noinline factory: (A) -> T) {
singleton(T::class, tag, factory, override)
}
inline fun <reified T : Any> eager(implClass: KClass<out T>, tag: String? = null, override: Boolean = false) {
eager(T::class, tag, implClass, override)
}
inline fun <reified T : Any> eager(tag: String? = null, override: Boolean = false, noinline factory: () -> T) {
eager(T::class, tag, factory, override)
}
inline fun <reified T : Any> thread(implClass: KClass<out T>, tag: String? = null, override: Boolean = false) {
thread(T::class, tag, implClass, override)
}
inline fun <reified T : Any> thread(tag: String? = null, override: Boolean = false, noinline factory: () -> T) {
thread(T::class, tag, factory, override)
}
inline fun <reified T : Any, A> thread(tag: String? = null, override: Boolean = false, noinline factory: (A) -> T) {
thread(T::class, tag, factory, override)
}
inline fun <reified T : Any> factory(implClass: KClass<out T>, tag: String? = null, override: Boolean = false) {
factory(T::class, tag, implClass, override)
}
inline fun <reified T : Any> factory(tag: String? = null, override: Boolean = false, noinline factory: () -> T) {
factory(T::class, tag, factory, override)
}
inline fun <reified T : Any, A> factory(tag: String? = null, override: Boolean = false, noinline factory: (A) -> T) {
factory(T::class, tag, factory, override)
}
fun <T : Any> singleton(kClass: KClass<T>, tag: String?, instance: T, override: Boolean) {
context.provide(ProviderData(kClass, tag, ProviderScope.APPLICATION, shim(instance), false, false), override)
}
fun <T : Any> singleton(kClass: KClass<T>, tag: String?, implClass: KClass<out T>, override: Boolean) {
context.provide(ProviderData(kClass, tag, ProviderScope.APPLICATION, shim(implClass), false, false), override)
}
fun <T : Any> singleton(kClass: KClass<T>, tag: String?, factory: () -> T, override: Boolean) {
context.provide(ProviderData(kClass, tag, ProviderScope.APPLICATION, shim(factory), false, false), override)
}
fun <T : Any, A> singleton(kClass: KClass<T>, tag: String?, factory: (A) -> T, override: Boolean) {
context.provide(ProviderData(kClass, tag, ProviderScope.APPLICATION, shim(factory), true, false), override)
}
fun <T : Any> eager(kClass: KClass<T>, tag: String?, implClass: KClass<out T>, override: Boolean) {
context.provide(ProviderData(kClass, tag, ProviderScope.APPLICATION, shim(implClass), false, true), override)
}
fun <T : Any> eager(kClass: KClass<T>, tag: String?, factory: () -> T, override: Boolean) {
context.provide(ProviderData(kClass, tag, ProviderScope.APPLICATION, shim(factory), false, true), override)
}
fun <T : Any> thread(kClass: KClass<T>, tag: String?, implClass: KClass<out T>, override: Boolean) {
context.provide(ProviderData(kClass, tag, ProviderScope.THREAD, shim(implClass), false, false), override)
}
fun <T : Any> thread(kClass: KClass<T>, tag: String?, factory: () -> T, override: Boolean) {
context.provide(ProviderData(kClass, tag, ProviderScope.THREAD, shim(factory), false, false), override)
}
fun <T : Any, A> thread(kClass: KClass<T>, tag: String?, factory: (A) -> T, override: Boolean) {
context.provide(ProviderData(kClass, tag, ProviderScope.THREAD, shim(factory), true, false), override)
}
fun <T : Any> factory(kClass: KClass<T>, tag: String?, implClass: KClass<out T>, override: Boolean) {
context.provide(ProviderData(kClass, tag, ProviderScope.INSTANCE, shim(implClass), false, false), override)
}
fun <T : Any> factory(kClass: KClass<T>, tag: String?, factory: () -> T, override: Boolean) {
context.provide(ProviderData(kClass, tag, ProviderScope.INSTANCE, shim(factory), false, false), override)
}
fun <T : Any, A> factory(kClass: KClass<T>, tag: String?, factory: (A) -> T, override: Boolean) {
context.provide(ProviderData(kClass, tag, ProviderScope.INSTANCE, shim(factory), true, false), override)
}
} | src/main/kotlin/com/devtub/injekt/tooling/Provider.kt | 4009197369 |
package graphics.scenery.tests.unit
import graphics.scenery.geometry.DummySpline
import graphics.scenery.proteins.Protein
import graphics.scenery.proteins.RibbonDiagram
import graphics.scenery.utils.LazyLogger
import org.biojava.nbio.structure.Group
import org.biojava.nbio.structure.secstruc.SecStrucElement
import org.joml.Vector3f
import org.junit.Test
import org.lwjgl.system.Platform
import kotlin.reflect.full.declaredMemberFunctions
import kotlin.reflect.jvm.isAccessible
import kotlin.test.assertEquals
import kotlin.test.assertNotEquals
import kotlin.test.assertTrue
/**
* This is the test for the RibbonCalculation, i.e. the pdb-support.
*
* @author Justin Buerger, [email protected]
*/
class RibbonDiagramTests {
private val logger by LazyLogger()
/**
* Tests coherence of curve size and number of residues.
*/
@Test
fun residueCountTest() {
logger.info("Tests coherence of curve size and number of residues.")
val plantProtein = Protein.fromID("3nir")
val plantRibbon = RibbonDiagram(plantProtein)
val dsspPlant = plantRibbon.callPrivateFunc("dssp")
val plantChains = plantProtein.getResidues()
var allPlantPoints = 0
plantChains.forEach {
if (dsspPlant is List<*>) {
@Suppress("UNCHECKED_CAST")
val guides =
RibbonDiagram.GuidePointCalculation.calculateGuidePoints(it, dsspPlant as List<SecStrucElement>)
val spline = plantRibbon.callPrivateFunc("ribbonSpline", guides) as DummySpline
allPlantPoints += spline.splinePoints().size
}
}
assertEquals(allPlantPoints, (46) * (10 + 1))
}
/**
* Tests number of subProteins.
*/
@Test
fun numberSubProteinsTest() {
logger.info("Tests number of subProteins.")
val plantProtein = Protein.fromID("3nir")
val plantRibbon = RibbonDiagram(plantProtein)
assertEquals(plantRibbon.children.size, 1)
val insectWing = Protein.fromID("2w49")
val insectWingRibbon = RibbonDiagram(insectWing)
assertEquals(insectWingRibbon.children.size, 36)
/*
val saccharomycesCerevisiae = Protein.fromID("6zqd")
val scRibbon = RibbonDiagram(saccharomycesCerevisiae)
assertEquals(scRibbon.children.size, 63)
*/
/*
val covid19 = Protein.fromID("6zcz")
val covidRibbon = RibbonDiagram(covid19)
assertEquals(covidRibbon.children.size, 4)
*/
val aspirin = Protein.fromID("6mqf")
val aspirinRibbon = RibbonDiagram(aspirin)
assertEquals(aspirinRibbon.children.size, 2)
val nucleosome = Protein.fromID("6y5e")
val nucRibbon = RibbonDiagram(nucleosome)
assertEquals(nucRibbon.children.size, 9)
}
/**
* Tests a lot of pdb structures and check that everyone of them yields a valid output.
* The comments refer to the chosen filter in the "SCIENTIFIC NAME OF SOURCE ORGANISM" category
* in the RCSB data base. These organisms as well as the pdb files have been chosen arbitrary.
* The null checks are there to satisfy the test structure- the test verifies in fact that no
* exception is thrown.
*/
@Test
fun testLotsOfProteins() {
val proteins = listOf(
"6l69", "3mbw", "4u1a", "5m9m", "6mzl", "6mp5", "2qd4", "6pe9",
"1ydk", "2rma", "3mdc", "2kne", "4tn7", "3mao", "5m8s", "6v2e",
"4giz", "3l2j", "4odq", "6slm", "2qho", "1zr0", "2ake", "2wx1",
"2mue", "2m0j", "1q5w", "3gj8", "3sui", "6pby", "2m0k", "1r4a",
"3fub", "6uku", "6v92", "2l2i", "1pyo", "4lcd", "6p9x", "6uun",
"6v80", "6v7z", "4grw", "3mc5", "3mbw", "4tkw", "4u0i", "3mas",
"6znn", "1ctp", /*"3j92",*/ "3jak", "1nb5", "3lk3", "1mdu", "3eks",
"2ebv", "4gbj", "6v4e", "6v4h", "4m8n", "4ia1", "3ei2", "2rh1",
"6ps3", "3v2y", "4pla", "3eml", "2seb", "2qej", "1d5m", "2wy8",
"4idj", "2vr3", "2win", "6urh", "3ua7", "3mrn", "4z0x", "2rhk",
"6pdx", "6urm", "2x4q", "1r0n", "2ff6", "4i7b", "3bs5", "5chl",
"5f84", "4uuz", "4v98", "4wsi", "4u68", "4aa1", "5jvs", "6hom",
"4xib", "4u0q", "6phf"
)
var max = 0L
val runtime = Runtime.getRuntime()
val onWindows = Platform.get() == Platform.WINDOWS
proteins.shuffled()/*.take(20)*/.forEach { pdbId ->
val protein = Protein.fromID(pdbId)
logger.info("Testing ${protein.structure.name} ...")
RibbonDiagram(protein)
val m = runtime.maxMemory()/1024/1024
val used = (runtime.totalMemory()-runtime.freeMemory())/1024/1024
val free = runtime.freeMemory()/1024/1024
logger.info("Memory use: $used MB, $free MB free $m MB max")
max = maxOf(used, max)
}
logger.info("Max use was $max MB")
}
/**
* Verifies that the boundingbox min and max vector don't become the null vector.
*/
@Test
fun testMaxBoundingBoxNoNullVector() {
//test min max don't become the null vector
val protein = Protein.fromID("2zzw")
val ribbon = RibbonDiagram(protein)
val bb = ribbon.getMaximumBoundingBox()
assertEquals(bb.n, ribbon)
assertNotEquals(bb.min, Vector3f(0f, 0f, 0f))
assertNotEquals(bb.max, Vector3f(0f, 0f, 0f))
}
/**
* Verifies that a BoundingBox for a ribbon can be created.
*/
@Test
fun testMaxBoundingBox() {
// check if the right BoundingBoc is created
val protein = Protein.fromID("5m9m")
val ribbon = RibbonDiagram(protein)
val bb = ribbon.getMaximumBoundingBox()
print(bb.max)
//We use ranges because the first and last guidePoint are created nondeterministically- but in the guaranteed range
assertTrue { 22.2 < bb.max.x && bb.max.x < 22.6 }
assertTrue { 33.6 < bb.max.y && 34 > bb.max.y }
assertTrue { 37.5 < bb.max.z && 37.9 > bb.max.z }
assertTrue { -31.3 < bb.min.x && -29.9 > bb.min.x }
assertTrue { -28.3 < bb.min.y && -27.9 > bb.min.y }
assertTrue { -36.8 < bb.min.z && -36.4 > bb.min.z }
}
@Test
fun testSplinePointsToResidueNumber() {
val protein = Protein.fromID("4u68")
val ribbon = RibbonDiagram(protein)
val residuesCount = ribbon.children.flatMap { chain -> chain.children }.flatMap { it.children }.size
val allResidues = protein.structure.chains.flatMap { it.atomGroups }.filter { it.hasAminoAtoms() }
assertEquals(residuesCount, allResidues.size)
}
//Inline function for the protein to access residues
private fun Protein.getResidues(): ArrayList<ArrayList<Group>> {
val proteins = ArrayList<ArrayList<Group>>(this.structure.chains.size)
this.structure.chains.forEach { chain ->
if (chain.isProtein) {
val aminoList = ArrayList<Group>(chain.atomGroups.size)
chain.atomGroups.forEach { group ->
if (group.hasAminoAtoms()) {
aminoList.add(group)
}
}
proteins.add(aminoList)
}
}
return proteins
}
//Inline function to access private function in the RibbonDiagram
private inline fun <reified T> T.callPrivateFunc(name: String, vararg args: Any?): Any? =
T::class
.declaredMemberFunctions
.firstOrNull { it.name == name }
?.apply { isAccessible = true }
?.call(this, *args)
}
| src/test/kotlin/graphics/scenery/tests/unit/RibbonDiagramTests.kt | 4049966779 |
/*
* Copyright (C) 2020 Square, Inc. and others.
*
* 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 okio
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec
import kotlin.random.Random
data class CipherAlgorithm(
val transformation: String,
val padding: Boolean,
val keyLength: Int,
val ivLength: Int? = null
) {
fun createCipherFactory(random: Random): CipherFactory {
val key = random.nextBytes(keyLength)
val secretKeySpec = SecretKeySpec(key, transformation.substringBefore('/'))
return if (ivLength == null) {
CipherFactory(transformation) { mode ->
init(mode, secretKeySpec)
}
} else {
val iv = random.nextBytes(ivLength)
val ivParameterSpec = IvParameterSpec(iv)
CipherFactory(transformation) { mode ->
init(mode, secretKeySpec, ivParameterSpec)
}
}
}
override fun toString() = transformation
companion object {
val BLOCK_CIPHER_ALGORITHMS
get() = listOf(
CipherAlgorithm("AES/CBC/NoPadding", false, 16, 16),
CipherAlgorithm("AES/CBC/PKCS5Padding", true, 16, 16),
CipherAlgorithm("AES/ECB/NoPadding", false, 16),
CipherAlgorithm("AES/ECB/PKCS5Padding", true, 16),
CipherAlgorithm("DES/CBC/NoPadding", false, 8, 8),
CipherAlgorithm("DES/CBC/PKCS5Padding", true, 8, 8),
CipherAlgorithm("DES/ECB/NoPadding", false, 8),
CipherAlgorithm("DES/ECB/PKCS5Padding", true, 8),
CipherAlgorithm("DESede/CBC/NoPadding", false, 24, 8),
CipherAlgorithm("DESede/CBC/PKCS5Padding", true, 24, 8),
CipherAlgorithm("DESede/ECB/NoPadding", false, 24),
CipherAlgorithm("DESede/ECB/PKCS5Padding", true, 24)
)
}
}
| okio/src/jvmTest/kotlin/okio/CipherAlgorithm.kt | 1196720080 |
package com.intellij.codeInspection.tests.java
import com.intellij.codeInspection.tests.JUnitRuleInspectionTestBase
import com.intellij.jvm.analysis.JvmAnalysisTestsUtil
class JavaJUnitRuleInspectionTest : JUnitRuleInspectionTestBase() {
override fun getTestDataPath() = JvmAnalysisTestsUtil.TEST_DATA_PROJECT_RELATIVE_BASE_PATH + "/codeInspection/junitrule"
fun `test @Rule highlighting`() {
myFixture.testHighlighting("RuleTest.java")
}
fun `test @Rule quickFixes`() {
val quickfixes = myFixture.getAllQuickFixes("RuleQfTest.java")
quickfixes.forEach { myFixture.launchAction(it) }
myFixture.checkResultByFile("RuleQfTest.after.java")
}
fun `test @ClassRule highlighting`() {
myFixture.testHighlighting("ClassRuleTest.java")
}
fun `test @ClassRule quickFixes`() {
val quickfixes = myFixture.getAllQuickFixes("ClassRuleQfTest.java")
quickfixes.forEach { myFixture.launchAction(it) }
myFixture.checkResultByFile("ClassRuleQfTest.after.java")
}
} | jvm/jvm-analysis-java-tests/testSrc/com/intellij/codeInspection/tests/java/JavaJUnitRuleInspectionTest.kt | 1886528199 |
// 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.ide.plugins
import com.intellij.diagnostic.PluginException
import com.intellij.ide.impl.ProjectUtil
import com.intellij.ide.plugins.cl.PluginClassLoader
import com.intellij.notification.Notification
import com.intellij.notification.NotificationType
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.Service
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.ExtensionNotApplicableException
import com.intellij.openapi.extensions.impl.ExtensionPointImpl
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.runModalTask
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.psi.stubs.StubElementTypeHolderEP
import com.intellij.serviceContainer.ComponentManagerImpl
import io.github.classgraph.AnnotationEnumValue
import io.github.classgraph.ClassGraph
import io.github.classgraph.ClassInfo
import java.util.function.BiConsumer
import kotlin.properties.Delegates.notNull
@Suppress("HardCodedStringLiteral")
private class CreateAllServicesAndExtensionsAction : AnAction("Create All Services And Extensions"), DumbAware {
companion object {
@JvmStatic
fun createAllServicesAndExtensions() {
val errors = mutableListOf<Throwable>()
runModalTask("Creating All Services And Extensions", cancellable = true) { indicator ->
val logger = logger<ComponentManagerImpl>()
val taskExecutor: (task: () -> Unit) -> Unit = { task ->
try {
task()
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: Throwable) {
logger.error(e)
errors.add(e)
}
}
// check first
checkExtensionPoint(StubElementTypeHolderEP.EP_NAME.point as ExtensionPointImpl<*>, taskExecutor)
checkContainer(ApplicationManager.getApplication() as ComponentManagerImpl, indicator, taskExecutor)
ProjectUtil.getOpenProjects().firstOrNull()?.let {
checkContainer(it as ComponentManagerImpl, indicator, taskExecutor)
}
indicator.text2 = "Checking light services..."
checkLightServices(taskExecutor)
}
// some errors are not thrown but logged
val message = (if (errors.isEmpty()) "No errors" else "${errors.size} errors were logged") + ". Check also that no logged errors."
Notification("Error Report", null, "", message, NotificationType.INFORMATION, null)
.notify(null)
}
}
override fun actionPerformed(e: AnActionEvent) {
createAllServicesAndExtensions()
}
}
@Suppress("ReplaceJavaStaticMethodWithKotlinAnalog")
private val badServices = java.util.Set.of(
"com.intellij.usageView.impl.UsageViewContentManagerImpl",
"com.jetbrains.python.scientific.figures.PyPlotToolWindow",
"org.jetbrains.plugins.grails.runner.GrailsConsole",
"com.intellij.analysis.pwa.analyser.PwaServiceImpl",
"com.intellij.analysis.pwa.view.toolwindow.PwaProblemsViewImpl",
)
@Suppress("HardCodedStringLiteral")
private fun checkContainer(container: ComponentManagerImpl, indicator: ProgressIndicator, taskExecutor: (task: () -> Unit) -> Unit) {
indicator.text2 = "Checking ${container.activityNamePrefix()}services..."
ComponentManagerImpl.createAllServices(container, badServices)
indicator.text2 = "Checking ${container.activityNamePrefix()}extensions..."
container.extensionArea.processExtensionPoints { extensionPoint ->
// requires read action
if (extensionPoint.name == "com.intellij.favoritesListProvider" || extensionPoint.name == "com.intellij.favoritesListProvider") {
return@processExtensionPoints
}
checkExtensionPoint(extensionPoint, taskExecutor)
}
}
private fun checkExtensionPoint(extensionPoint: ExtensionPointImpl<*>, taskExecutor: (task: () -> Unit) -> Unit) {
extensionPoint.processImplementations(false, BiConsumer { supplier, pluginDescriptor ->
var extensionClass: Class<out Any> by notNull()
taskExecutor {
extensionClass = extensionPoint.extensionClass
}
taskExecutor {
try {
val extension = supplier.get()
if (!extensionClass.isInstance(extension)) {
throw PluginException("Extension ${extension.javaClass.name} does not implement $extensionClass",
pluginDescriptor.pluginId)
}
}
catch (ignore: ExtensionNotApplicableException) {
}
}
})
taskExecutor {
extensionPoint.extensionList
}
}
private fun checkLightServices(taskExecutor: (task: () -> Unit) -> Unit) {
for (plugin in PluginManagerCore.getLoadedPlugins(null)) {
// we don't check classloader for sub descriptors because url set is the same
if (plugin.classLoader !is PluginClassLoader || plugin.pluginDependencies == null) {
continue
}
ClassGraph()
.enableAnnotationInfo()
.ignoreParentClassLoaders()
.overrideClassLoaders(plugin.classLoader)
.scan()
.use { scanResult ->
val lightServices = scanResult.getClassesWithAnnotation(Service::class.java.name)
for (lightService in lightServices) {
// not clear - from what classloader light service will be loaded in reality
val lightServiceClass = loadLightServiceClass(lightService, plugin)
val isProjectLevel: Boolean
val isAppLevel: Boolean
val annotationParameterValue = lightService.getAnnotationInfo(Service::class.java.name).parameterValues.find { it.name == "value" }
if (annotationParameterValue == null) {
isAppLevel = lightServiceClass.declaredConstructors.any { it.parameterCount == 0 }
isProjectLevel = lightServiceClass.declaredConstructors.any { it.parameterCount == 1 && it.parameterTypes.get(0) == Project::class.java }
}
else {
val list = annotationParameterValue.value as Array<*>
isAppLevel = list.any { v -> (v as AnnotationEnumValue).valueName == Service.Level.APP.name }
isProjectLevel = list.any { v -> (v as AnnotationEnumValue).valueName == Service.Level.PROJECT.name }
}
if (isAppLevel) {
taskExecutor {
ApplicationManager.getApplication().getService(lightServiceClass)
}
}
if (isProjectLevel) {
taskExecutor {
ProjectUtil.getOpenProjects().firstOrNull()?.getService(lightServiceClass)
}
}
}
}
}
}
private fun loadLightServiceClass(lightService: ClassInfo, mainDescriptor: IdeaPluginDescriptorImpl): Class<*> {
//
for (pluginDependency in mainDescriptor.pluginDependencies!!) {
val subPluginClassLoader = pluginDependency.subDescriptor?.classLoader as? PluginClassLoader ?: continue
val packagePrefix = subPluginClassLoader.packagePrefix ?: continue
if (lightService.name.startsWith(packagePrefix)) {
return subPluginClassLoader.loadClass(lightService.name, true)
}
}
for (pluginDependency in mainDescriptor.pluginDependencies!!) {
val subPluginClassLoader = pluginDependency.subDescriptor?.classLoader as? PluginClassLoader ?: continue
val clazz = subPluginClassLoader.loadClass(lightService.name, true)
if (clazz != null && clazz.classLoader === subPluginClassLoader) {
// light class is resolved from this sub plugin classloader - check successful
return clazz
}
}
// ok, or no plugin dependencies at all, or all are disabled, resolve from main
return (mainDescriptor.classLoader as PluginClassLoader).loadClass(lightService.name, true)
} | platform/platform-impl/src/com/intellij/ide/plugins/CreateAllServicesAndExtensionsAction.kt | 2665467610 |
package com.aemtools.refactoring.htl.rename
import com.aemtools.lang.util.htlAttributeName
import com.aemtools.lang.util.htlVariableName
import com.aemtools.lang.util.isHtlDeclarationAttribute
import com.aemtools.reference.common.reference.HtlPropertyAccessReference
import com.aemtools.reference.htl.reference.HtlDeclarationReference
import com.aemtools.reference.htl.reference.HtlListHelperReference
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.xml.XmlAttribute
import com.intellij.refactoring.listeners.RefactoringElementListener
import com.intellij.refactoring.rename.RenameDialog
import com.intellij.refactoring.rename.RenamePsiElementProcessor
import com.intellij.usageView.UsageInfo
import java.awt.GridBagConstraints
import javax.swing.JCheckBox
import javax.swing.JPanel
/**
* @author Dmytro Troynikov
*/
class HtlDeclarationAttributeRenameProcessor : RenamePsiElementProcessor() {
override fun canProcessElement(element: PsiElement): Boolean {
return element is XmlAttribute
&& element.isHtlDeclarationAttribute()
}
override fun renameElement(
element: PsiElement,
newName: String,
usages: Array<out UsageInfo>,
listener: RefactoringElementListener?) {
val attribute = element as? XmlAttribute
?: return
val htlAttributeName = attribute.htlAttributeName() ?: return
val newAttributeName = "$htlAttributeName.$newName"
attribute.name = newAttributeName
val htlDeclarationUsages: ArrayList<UsageInfo> = ArrayList()
val htlListHelperUsages: ArrayList<UsageInfo> = ArrayList()
val propertyAccessUsages: ArrayList<UsageInfo> = ArrayList()
usages.filterTo(htlDeclarationUsages, { it.reference is HtlDeclarationReference })
usages.filterTo(htlListHelperUsages, { it.reference is HtlListHelperReference })
usages.filterTo(propertyAccessUsages, { it.reference is HtlPropertyAccessReference })
htlListHelperUsages.forEach {
it.reference?.handleElementRename("${newName}List")
}
htlDeclarationUsages.forEach {
it.reference?.handleElementRename(newName)
}
propertyAccessUsages.forEach {
it.reference?.handleElementRename(newName)
}
listener?.elementRenamed(attribute)
}
override fun isInplaceRenameSupported(): Boolean {
return true
}
override fun createRenameDialog(project: Project,
element: PsiElement,
nameSuggestionContext: PsiElement?,
editor: Editor?): RenameDialog {
return HtlAttributeRenameDialog(project,
element,
nameSuggestionContext,
editor)
}
}
/**
* Htl attribute rename dialog.
*/
class HtlAttributeRenameDialog(project: Project,
element: PsiElement,
context: PsiElement?,
editor: Editor?)
: RenameDialog(project, element, context, editor) {
override fun hasPreviewButton(): Boolean = false
override fun isToSearchForTextOccurrencesForRename(): Boolean = false
override fun isToSearchInCommentsForRename(): Boolean = false
override fun createCheckboxes(panel: JPanel?, gbConstraints: GridBagConstraints?) {
super.createCheckboxes(panel, gbConstraints)
// hide checkboxes
panel?.let {
it.components.filter {
it is JCheckBox
}.forEach {
it.isVisible = false
}
}
}
override fun getSuggestedNames(): Array<String> {
val attribute = psiElement as? XmlAttribute
val name = attribute?.htlVariableName()
return arrayOf(name ?: "")
}
}
| aem-intellij-core/src/main/kotlin/com/aemtools/refactoring/htl/rename/HtlDeclarationAttributeRenameProcessor.kt | 2281871263 |
package ch.difty.scipamato.core.web.user
import ch.difty.scipamato.common.persistence.paging.matchPaginationContext
import ch.difty.scipamato.core.entity.User
import ch.difty.scipamato.core.entity.search.UserFilter
import ch.difty.scipamato.core.web.AbstractWicketTest
import io.mockk.confirmVerified
import io.mockk.every
import io.mockk.verify
import org.amshove.kluent.shouldBeEqualTo
import org.amshove.kluent.shouldBeFalse
import org.amshove.kluent.shouldBeTrue
import org.amshove.kluent.shouldNotBeEqualTo
import org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder
import org.apache.wicket.util.tester.WicketTester
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
internal class UserProviderTest : AbstractWicketTest() {
private val filter = UserFilter().apply { nameMask = "foo" }
private val entity = User()
private val entities = listOf(entity, entity, entity)
private lateinit var provider: UserProvider
@BeforeEach
fun setUp() {
WicketTester(application)
provider = UserProvider(filter)
provider.setService(userServiceMock)
}
@AfterEach
fun tearDown() {
confirmVerified(userServiceMock)
}
@Test
fun defaultFilterIsNewUserFilter() {
provider = UserProvider()
provider.filterState shouldBeEqualTo UserFilter()
}
@Test
fun nullFilterResultsInNewUserFilter() {
val p = UserProvider(null)
p.filterState shouldBeEqualTo UserFilter()
}
@Test
fun size() {
val size = 5
every { userServiceMock.countByFilter(filter) } returns size
provider.size() shouldBeEqualTo size.toLong()
verify { userServiceMock.countByFilter(filter) }
}
@Test
fun gettingModel_wrapsEntity() {
val model = provider.model(entity)
model.getObject() shouldBeEqualTo entity
}
@Test
fun gettingFilterState_returnsFilter() {
provider.filterState shouldBeEqualTo filter
}
@Test
fun settingFilterState() {
provider = UserProvider()
provider.filterState shouldNotBeEqualTo filter
provider.filterState = filter
provider.filterState shouldBeEqualTo filter
}
@Test
fun iterating_withNoRecords_returnsNoRecords() {
every { userServiceMock.findPageByFilter(any(), any()) } returns emptyList()
val it = provider.iterator(0, 3)
it.hasNext().shouldBeFalse()
verify { userServiceMock.findPageByFilter(any(), matchPaginationContext(0, 3, "userName: ASC")) }
}
@Test
fun iterating_throughFirst() {
every { userServiceMock.findPageByFilter(any(), any()) } returns entities
val it = provider.iterator(0, 3)
assertRecordsIn(it)
verify { userServiceMock.findPageByFilter(any(), matchPaginationContext(0, 3, "userName: ASC")) }
}
private fun assertRecordsIn(it: Iterator<User>) {
repeat(3) { _ ->
it.hasNext().shouldBeTrue()
it.next()
}
it.hasNext().shouldBeFalse()
}
@Test
fun iterating_throughSecondPage() {
every { userServiceMock.findPageByFilter(any(), any()) } returns entities
val it = provider.iterator(3, 3)
assertRecordsIn(it)
verify { userServiceMock.findPageByFilter(any(), matchPaginationContext(3, 3, "userName: ASC")) }
}
@Test
fun iterating_throughThirdPage() {
provider.setSort("title", SortOrder.DESCENDING)
every { userServiceMock.findPageByFilter(any(), any()) } returns entities
val it = provider.iterator(6, 3)
assertRecordsIn(it)
verify { userServiceMock.findPageByFilter(any(), matchPaginationContext(6, 3, "title: DESC")) }
}
}
| core/core-web/src/test/kotlin/ch/difty/scipamato/core/web/user/UserProviderTest.kt | 3486668369 |
/*
* Copyright 2018 New Vector Ltd
*
* 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.matrix.androidsdk.crypto.model.keys
import com.google.gson.annotations.SerializedName
/**
* Backup data for several keys in several rooms.
*/
class KeysBackupData {
// the keys are the room IDs, and the values are RoomKeysBackupData
@SerializedName("rooms")
var roomIdToRoomKeysBackupData: MutableMap<String, RoomKeysBackupData> = HashMap()
}
| matrix-sdk-crypto/src/main/java/org/matrix/androidsdk/crypto/model/keys/KeysBackupData.kt | 1237764164 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInspection.ex
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.InvalidDataException
import com.intellij.openapi.util.WriteExternalException
import com.intellij.profile.codeInspection.InspectionProjectProfileManager
import com.intellij.psi.PsiElement
import com.intellij.psi.search.scope.packageSet.NamedScope
import com.intellij.util.Consumer
open class InspectionProfileModifiableModel(val source: InspectionProfileImpl) : InspectionProfileImpl(source.name, source.myToolSupplier, source.profileManager, source.myBaseProfile, null) {
private var modified = false
init {
myUninitializedSettings.putAll(source.myUninitializedSettings)
isProjectLevel = source.isProjectLevel
myLockedProfile = source.myLockedProfile
copyFrom(source)
}
fun isChanged(): Boolean = modified || source.myLockedProfile != myLockedProfile
fun setModified(value: Boolean) {
modified = value
}
override fun resetToBase(toolId: String, scope: NamedScope?, project: Project) {
super.resetToBase(toolId, scope, project)
setModified(true)
}
override fun copyToolsConfigurations(project: Project?) {
copyToolsConfigurations(source, project)
}
override fun createTools(project: Project?) = source.getDefaultStates(project).map { it.tool }
private fun copyToolsConfigurations(profile: InspectionProfileImpl, project: Project?) {
try {
for (toolList in profile.myTools.values) {
val tools = myTools[toolList.shortName]!!
val defaultState = toolList.defaultState
tools.setDefaultState(copyToolSettings(defaultState.tool), defaultState.isEnabled, defaultState.level)
tools.removeAllScopes()
val nonDefaultToolStates = toolList.nonDefaultTools
if (nonDefaultToolStates != null) {
for (state in nonDefaultToolStates) {
val toolWrapper = copyToolSettings(state.tool)
val scope = state.getScope(project)
if (scope == null) {
tools.addTool(state.scopeName, toolWrapper, state.isEnabled, state.level)
}
else {
tools.addTool(scope, toolWrapper, state.isEnabled, state.level)
}
}
}
tools.isEnabled = toolList.isEnabled
}
}
catch (e: WriteExternalException) {
LOG.error(e)
}
catch (e: InvalidDataException) {
LOG.error(e)
}
}
fun isProperSetting(toolId: String): Boolean {
if (myBaseProfile != null) {
val tools = myBaseProfile.getToolsOrNull(toolId, null)
val currentTools = myTools[toolId]
return tools != currentTools
}
return false
}
fun isProperSetting(toolId: String, scope: NamedScope, project: Project): Boolean {
if (myBaseProfile != null) {
val baseDefaultWrapper = myBaseProfile.getToolsOrNull(toolId, null)?.defaultState?.tool
val actualWrapper = myTools[toolId]?.tools?.first { s -> scope == s.getScope(project) }?.tool
return baseDefaultWrapper != null && actualWrapper != null && ScopeToolState.areSettingsEqual(baseDefaultWrapper, actualWrapper)
}
return false
}
fun resetToBase(project: Project?) {
initInspectionTools(project)
copyToolsConfigurations(myBaseProfile, project)
myChangedToolNames = null
myUninitializedSettings.clear()
}
//invoke when isChanged() == true
fun commit() {
source.commit(this)
modified = false
}
fun resetToEmpty(project: Project) {
initInspectionTools(project)
for (toolWrapper in getInspectionTools(null)) {
setToolEnabled(toolWrapper.shortName, false, project, fireEvents = false)
}
}
private fun InspectionProfileImpl.commit(model: InspectionProfileImpl) {
name = model.name
description = model.description
isProjectLevel = model.isProjectLevel
myLockedProfile = model.myLockedProfile
myChangedToolNames = null
if (model.wasInitialized()) {
myTools = model.myTools
}
profileManager = model.profileManager
scopesOrder = model.scopesOrder
}
fun disableTool(toolShortName: String, element: PsiElement) {
getTools(toolShortName, element.project).disableTool(element)
}
override fun toString(): String = "$name (copy)"
}
fun modifyAndCommitProjectProfile(project: Project, action: Consumer<InspectionProfileModifiableModel>) {
InspectionProjectProfileManager.getInstance(project).currentProfile.edit { action.consume(this) }
}
inline fun InspectionProfileImpl.edit(task: InspectionProfileModifiableModel.() -> Unit) {
val model = InspectionProfileModifiableModel(this)
model.task()
model.commit()
profileManager.fireProfileChanged(this)
}
| platform/analysis-impl/src/com/intellij/codeInspection/ex/InspectionProfileModifiableModel.kt | 1217560695 |
// 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.debugger
import com.intellij.execution.console.LanguageConsoleView
import com.intellij.execution.process.ProcessHandler
import com.intellij.xdebugger.XDebugSessionListener
import com.jetbrains.python.console.PydevConsoleExecuteActionHandler
import com.jetbrains.python.console.pydev.ConsoleCommunication
class PydevDebugConsoleExecuteActionHandler(consoleView: LanguageConsoleView,
myProcessHandler: ProcessHandler,
consoleCommunication: ConsoleCommunication) : PydevConsoleExecuteActionHandler(consoleView, myProcessHandler, consoleCommunication), XDebugSessionListener {
override val consoleIsNotEnabledMessage: String
get() = "Pause the process to use command-line."
override fun sessionPaused() {
isEnabled = true
}
override fun sessionResumed() {
isEnabled = false
}
override fun sessionStopped() {
isEnabled = false
}
override fun stackFrameChanged() {
}
override fun beforeSessionResume() {
}
}
| python/src/com/jetbrains/python/debugger/PydevDebugConsoleExecuteActionHandler.kt | 1391999050 |
@file:Suppress("unused")
package com.agoda.kakao.tabs
import androidx.test.espresso.ViewAssertion
import com.agoda.kakao.common.assertions.BaseAssertions
import com.google.android.material.tabs.TabLayout
/**
* Provides assertions for TabLayout
*/
interface TabLayoutAssertions : BaseAssertions {
/**
* Checks if TabLayout have selected tab with given index
*
* @param index tab index to be checked
*/
fun isTabSelected(index: Int) {
view.check(ViewAssertion { view, notFoundException ->
if (view is TabLayout) {
if (view.selectedTabPosition != index) {
throw AssertionError(
"Expected selected item index is $index," +
" but actual is ${view.selectedTabPosition}"
)
}
} else {
notFoundException?.let { throw AssertionError(it) }
}
})
}
}
| kakao/src/main/kotlin/com/agoda/kakao/tabs/TabLayoutAssertions.kt | 2946273855 |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.api
data class GHRepositoryCoordinates(internal val serverPath: GithubServerPath, internal val repositoryPath: GHRepositoryPath) {
fun toUrl(): String {
return serverPath.toUrl() + "/" + repositoryPath
}
override fun toString(): String {
return "$serverPath/$repositoryPath"
}
}
| plugins/github/src/org/jetbrains/plugins/github/api/GHRepositoryCoordinates.kt | 2798120118 |
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.actions
import com.intellij.execution.ui.RunContentDescriptor
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.openapi.wm.ToolWindowId
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.xdebugger.XDebuggerManager
import com.jetbrains.python.console.*
import com.jetbrains.python.run.PythonRunConfiguration
object PyExecuteInConsole {
@JvmStatic
fun executeCodeInConsole(project: Project,
commandText: String?,
editor: Editor?,
canUseExistingConsole: Boolean,
canUseDebugConsole: Boolean,
requestFocusToConsole: Boolean,
config: PythonRunConfiguration?) {
var existingConsole: RunContentDescriptor? = null
var isDebug = false
var newConsoleListener: PydevConsoleRunner.ConsoleListener? = null
if (canUseExistingConsole) {
if (canUseDebugConsole) {
existingConsole = getCurrentDebugConsole(project)
}
if (existingConsole != null) {
isDebug = true
}
else {
val virtualFile = (editor as? EditorImpl)?.virtualFile
if (virtualFile != null && PyExecuteConsoleCustomizer.instance.isCustomDescriptorSupported(virtualFile)) {
val (descriptor, listener) = getCustomDescriptor(project, editor)
existingConsole = descriptor
newConsoleListener = listener
}
else {
existingConsole = getSelectedPythonConsole(project)
}
}
}
if (existingConsole != null) {
val console = existingConsole.executionConsole
(console as PyCodeExecutor).executeCode(commandText, editor)
val consoleView = showConsole(project, existingConsole, isDebug)
requestFocus(requestFocusToConsole, editor, consoleView)
}
else {
startNewConsoleInstance(project, commandText, config, newConsoleListener)
}
}
private fun getCustomDescriptor(project: Project, editor: Editor?): Pair<RunContentDescriptor?, PydevConsoleRunner.ConsoleListener?> {
val virtualFile = (editor as? EditorImpl)?.virtualFile ?: return Pair(null, null)
val executeCustomizer = PyExecuteConsoleCustomizer.instance
when (executeCustomizer.getCustomDescriptorType(virtualFile)) {
DescriptorType.NEW -> {
return Pair(null, createNewConsoleListener(project, executeCustomizer, virtualFile))
}
DescriptorType.EXISTING -> {
val console = executeCustomizer.getExistingDescriptor(virtualFile)
if (console != null && isAlive(console)) {
return Pair(console, null)
}
else {
return Pair(null, createNewConsoleListener(project, executeCustomizer, virtualFile))
}
}
else -> {
throw IllegalStateException("Custom descriptor for ${virtualFile} is null")
}
}
}
private fun createNewConsoleListener(project: Project, executeCustomizer: PyExecuteConsoleCustomizer,
virtualFile: VirtualFile): PydevConsoleRunner.ConsoleListener {
return PydevConsoleRunner.ConsoleListener { consoleView ->
val consoles = getAllRunningConsoles(project)
val newDescriptor = consoles.find { it.executionConsole === consoleView }
executeCustomizer.updateDescriptor(virtualFile, DescriptorType.EXISTING, newDescriptor)
}
}
private fun getCurrentDebugConsole(project: Project): RunContentDescriptor? {
XDebuggerManager.getInstance(project).currentSession?.let { currentSession ->
val descriptor = currentSession.runContentDescriptor
if (isAlive(descriptor)) {
return descriptor
}
}
return null
}
fun getAllRunningConsoles(project: Project?): List<RunContentDescriptor> {
val toolWindow = PythonConsoleToolWindow.getInstance(project!!)
return if (toolWindow != null && toolWindow.isInitialized) {
toolWindow.consoleContentDescriptors.filter { isAlive(it) }
}
else emptyList()
}
private fun getSelectedPythonConsole(project: Project): RunContentDescriptor? {
val toolWindow = PythonConsoleToolWindow.getInstance(project) ?: return null
if (!toolWindow.isInitialized) return null
val consoles = toolWindow.consoleContentDescriptors.filter { isAlive(it) }
return consoles.singleOrNull()
?: toolWindow.selectedContentDescriptor.takeIf { it in consoles }
?: consoles.firstOrNull()
}
fun isAlive(dom: RunContentDescriptor): Boolean {
val processHandler = dom.processHandler
return processHandler != null && !processHandler.isProcessTerminated
}
private fun startNewConsoleInstance(project: Project,
runFileText: String?,
config: PythonRunConfiguration?,
listener: PydevConsoleRunner.ConsoleListener?) {
val consoleRunnerFactory = PythonConsoleRunnerFactory.getInstance()
val runner = if (runFileText == null || config == null) {
consoleRunnerFactory.createConsoleRunner(project, null)
}
else {
consoleRunnerFactory.createConsoleRunnerWithFile(project, null, runFileText, config)
}
val toolWindow = PythonConsoleToolWindow.getInstance(project)
runner.addConsoleListener { consoleView ->
if (consoleView is PyCodeExecutor) {
(consoleView as PyCodeExecutor).executeCode(runFileText, null)
toolWindow?.toolWindow?.show(null)
}
}
if (listener != null) {
runner.addConsoleListener(listener)
}
runner.run(false)
}
private fun showConsole(project: Project,
descriptor: RunContentDescriptor,
isDebug: Boolean): PythonConsoleView? {
if (isDebug) {
val console = descriptor.executionConsole
val currentSession = XDebuggerManager.getInstance(project).currentSession
if (currentSession != null) {
ToolWindowManager.getInstance(project).getToolWindow(ToolWindowId.DEBUG)?.let { debugToolWindow ->
if (!debugToolWindow.isVisible) {
debugToolWindow.show()
}
}
// Select "Console" tab in case of Debug console
val contentManager = currentSession.ui.contentManager
contentManager.findContent("Console")?.let { content ->
contentManager.setSelectedContent(content)
}
return (console as PythonDebugLanguageConsoleView).pydevConsoleView
}
}
else {
PythonConsoleToolWindow.getInstance(project)?.toolWindow?.let { toolWindow ->
if (!toolWindow.isVisible) {
toolWindow.show(null)
}
val contentManager = toolWindow.contentManager
contentManager.findContent(PyExecuteConsoleCustomizer.instance.getDescriptorName(descriptor))?.let {
contentManager.setSelectedContent(it)
}
}
return descriptor.executionConsole as? PythonConsoleView
}
return null
}
private fun requestFocus(requestFocusToConsole: Boolean, editor: Editor?, consoleView: PythonConsoleView?) {
if (requestFocusToConsole) {
consoleView?.requestFocus()
}
else {
if (editor != null) {
IdeFocusManager.findInstance().requestFocus(editor.contentComponent, true)
}
}
}
} | python/src/com/jetbrains/python/actions/PyExecuteInConsole.kt | 568107961 |
/*
* This file is part of Blokada.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
* Copyright © 2021 Blocka AB. All rights reserved.
*
* @author Karol Gusak ([email protected])
*/
package ui.settings.leases
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.View.OnClickListener
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import model.Lease
import org.blokada.R
class LeasesAdapter(private val interaction: Interaction) :
ListAdapter<Lease, LeasesAdapter.LeaseViewHolder>(LeaseDC()) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = LeaseViewHolder(
LayoutInflater.from(parent.context)
.inflate(R.layout.item_lease, parent, false), interaction
)
override fun onBindViewHolder(holder: LeaseViewHolder, position: Int) =
holder.bind(getItem(position))
fun swapData(data: List<Lease>) {
submitList(data.toMutableList())
}
inner class LeaseViewHolder(
itemView: View,
private val interaction: Interaction
) : RecyclerView.ViewHolder(itemView), OnClickListener {
private val name: TextView = itemView.findViewById(R.id.lease_name)
private val deleteButton: View = itemView.findViewById(R.id.lease_delete)
private val thisDevice: View = itemView.findViewById(R.id.lease_thisdevice)
init {
deleteButton.setOnClickListener(this)
}
override fun onClick(v: View) {
if (adapterPosition == RecyclerView.NO_POSITION) return
val clicked = getItem(adapterPosition)
interaction.onDelete(clicked)
itemView.alpha = 0.5f
}
fun bind(item: Lease) = with(itemView) {
name.text = item.niceName()
if (interaction.isThisDevice(item)) {
thisDevice.visibility = View.VISIBLE
deleteButton.visibility = View.GONE
} else {
thisDevice.visibility = View.GONE
deleteButton.visibility = View.VISIBLE
}
}
}
interface Interaction {
fun onDelete(lease: Lease)
fun isThisDevice(lease: Lease): Boolean
}
private class LeaseDC : DiffUtil.ItemCallback<Lease>() {
override fun areItemsTheSame(
oldItem: Lease,
newItem: Lease
): Boolean {
return oldItem == newItem
}
override fun areContentsTheSame(
oldItem: Lease,
newItem: Lease
): Boolean {
return oldItem == newItem
}
}
} | android5/app/src/main/java/ui/settings/leases/LeasesAdapter.kt | 3763135473 |
package com.github.triplet.gradle.play.tasks
import com.github.triplet.gradle.androidpublisher.FakePlayPublisher
import com.github.triplet.gradle.androidpublisher.UploadInternalSharingArtifactResponse
import com.github.triplet.gradle.androidpublisher.newUploadInternalSharingArtifactResponse
import com.github.triplet.gradle.play.helpers.IntegrationTestBase
import com.github.triplet.gradle.play.helpers.SharedIntegrationTest.Companion.DEFAULT_TASK_VARIANT
import com.github.triplet.gradle.play.tasks.shared.ArtifactIntegrationTests
import com.github.triplet.gradle.play.tasks.shared.LifecycleIntegrationTests
import com.github.triplet.gradle.play.tasks.shared.PublishInternalSharingArtifactIntegrationTests
import com.google.common.truth.Truth.assertThat
import org.gradle.testkit.runner.BuildResult
import org.gradle.testkit.runner.TaskOutcome.SUCCESS
import org.junit.jupiter.api.Test
import java.io.File
class PublishInternalSharingApkIntegrationTest : IntegrationTestBase(), ArtifactIntegrationTests,
PublishInternalSharingArtifactIntegrationTests, LifecycleIntegrationTests {
override fun taskName(taskVariant: String) =
":upload${taskVariant.ifEmpty { DEFAULT_TASK_VARIANT }}PrivateApk"
override fun customArtifactName(name: String) = "$name.apk"
override fun assertCustomArtifactResults(result: BuildResult, executed: Boolean) {
assertThat(result.task(":packageRelease")).isNull()
if (executed) {
assertThat(result.output).contains("uploadInternalSharingApk(")
}
}
override fun outputFile() = "build/outputs/internal-sharing/apk/release"
@Test
fun `Builds apk on-the-fly by default`() {
val result = execute("", "uploadReleasePrivateApk")
result.requireTask(":packageRelease", outcome = SUCCESS)
assertThat(result.output).contains("uploadInternalSharingApk(")
assertThat(result.output).contains(".apk")
}
companion object {
@JvmStatic
fun installFactories() {
val publisher = object : FakePlayPublisher() {
override fun uploadInternalSharingApk(
apkFile: File,
): UploadInternalSharingArtifactResponse {
println("uploadInternalSharingApk($apkFile)")
return newUploadInternalSharingArtifactResponse(
"json-payload", "https://google.com")
}
}
publisher.install()
}
}
}
| play/plugin/src/test/kotlin/com/github/triplet/gradle/play/tasks/PublishInternalSharingApkIntegrationTest.kt | 84590965 |
import kotlin.test.*
import kotlin.comparisons.*
data class Item(val name: String, val rating: Int) : Comparable<Item> {
public override fun compareTo(other: Item): Int {
return compareValuesBy(this, other, { it.rating }, { it.name })
}
}
val v1 = Item("wine", 9)
val v2 = Item("beer", 10)
fun box() {
val comparator = compareBy<Item> { it.name }
val reversed = comparator.reversed()
assertEquals(comparator.compare(v2, v1), reversed.compare(v1, v2))
assertEquals(comparator, reversed.reversed())
}
| backend.native/tests/external/stdlib/OrderingTest/reversedComparator.kt | 1817607818 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.datastore.core
import kotlin.coroutines.CoroutineContext
import kotlinx.coroutines.CompletableDeferred
/** The actions for the actor. */
internal sealed class Message<T> {
abstract val lastState: State<T>?
/**
* Represents a read operation. If the data is already cached, this is a no-op. If data
* has not been cached, it triggers a new read to the specified dataChannel.
*/
class Read<T>(
override val lastState: State<T>?
) : Message<T>()
/** Represents an update operation. */
class Update<T>(
val transform: suspend (t: T) -> T,
/**
* Used to signal (un)successful completion of the update to the caller.
*/
val ack: CompletableDeferred<T>,
override val lastState: State<T>?,
val callerContext: CoroutineContext
) : Message<T>()
} | datastore/datastore-core/src/commonMain/kotlin/androidx/datastore/core/Message.kt | 3458978582 |
package abi44_0_0.host.exp.exponent.modules.api.screens
import android.content.Context
import androidx.appcompat.widget.Toolbar
// This class is used to store config closer to search bar
open class CustomToolbar(context: Context, val config: ScreenStackHeaderConfig) : Toolbar(context)
| android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/host/exp/exponent/modules/api/screens/CustomToolbar.kt | 2085506020 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.impl
import com.intellij.execution.ExecutionBundle
import com.intellij.execution.configurations.ConfigurationType
import com.intellij.openapi.actionSystem.ActionToolbarPosition
import com.intellij.openapi.project.Project
import com.intellij.ui.*
import com.intellij.ui.components.ActionLink
import com.intellij.ui.components.JBPanelWithEmptyText
import com.intellij.util.ui.JBDimension
import com.intellij.util.ui.JBUI
import java.awt.BorderLayout
import java.awt.event.MouseEvent
import javax.swing.JComponent
import javax.swing.JPanel
import javax.swing.tree.DefaultMutableTreeNode
open class ProjectRunConfigurationConfigurable(project: Project, runDialog: RunDialogBase? = null) : RunConfigurable(project, runDialog) {
override fun createLeftPanel(): JComponent {
if (project.isDefault) {
return ScrollPaneFactory.createScrollPane(tree)
}
val removeAction = MyRemoveAction()
toolbarDecorator = ToolbarDecorator.createDecorator(tree)
.setToolbarPosition(ActionToolbarPosition.TOP)
.setPanelBorder(JBUI.Borders.empty())
.setScrollPaneBorder(JBUI.Borders.empty())
.setAddAction(toolbarAddAction).setAddActionName(ExecutionBundle.message("add.new.run.configuration.action2.name"))
.setRemoveAction(removeAction).setRemoveActionUpdater(removeAction)
.setRemoveActionName(ExecutionBundle.message("remove.run.configuration.action.name"))
.addExtraAction(AnActionButton.fromAction(MyCopyAction()))
.addExtraAction(AnActionButton.fromAction(MySaveAction()))
.addExtraAction(AnActionButton.fromAction(MyCreateFolderAction()))
.addExtraAction(AnActionButton.fromAction(MySortFolderAction()))
.setMinimumSize(JBDimension(200, 200))
.setButtonComparator(ExecutionBundle.message("add.new.run.configuration.action2.name"),
ExecutionBundle.message("remove.run.configuration.action.name"),
ExecutionBundle.message("copy.configuration.action.name"),
ExecutionBundle.message("action.name.save.configuration"),
ExecutionBundle.message("run.configuration.edit.default.configuration.settings.text"),
ExecutionBundle.message("move.up.action.name"),
ExecutionBundle.message("move.down.action.name"),
ExecutionBundle.message("run.configuration.create.folder.text"))
.setForcedDnD()
val panel = JPanel(BorderLayout())
panel.background = JBColor.background()
panel.add(toolbarDecorator!!.createPanel(), BorderLayout.CENTER)
val actionLink = ActionLink(ExecutionBundle.message("edit.configuration.templates")) { showTemplatesDialog(project, selectedConfigurationType) }
actionLink.border = JBUI.Borders.empty(10)
actionLink.background = JBColor.background()
panel.add(actionLink, BorderLayout.SOUTH)
initTree()
return panel
}
override fun typeOrFactorySelected(userObject: Any) {
drawPressAddButtonMessage(userObject as ConfigurationType);
}
override fun addRunConfigurationsToModel(model: DefaultMutableTreeNode) {
for ((type, folderMap) in runManager.getConfigurationsGroupedByTypeAndFolder(true)) {
val typeNode = DefaultMutableTreeNode(type)
model.add(typeNode)
for ((folder, configurations) in folderMap.entries) {
val node: DefaultMutableTreeNode
if (folder == null) {
node = typeNode
}
else {
node = DefaultMutableTreeNode(folder)
typeNode.add(node)
}
for (it in configurations) {
node.add(DefaultMutableTreeNode(it))
}
}
}
}
override fun createTipPanelAboutAddingNewRunConfiguration(configurationType: ConfigurationType?): JComponent {
val messagePanel = JBPanelWithEmptyText()
messagePanel.emptyText.appendLine(ExecutionBundle.message("status.text.add.new.run.configuration"), SimpleTextAttributes.LINK_PLAIN_ATTRIBUTES) {
if (configurationType == null) {
toolbarAddAction.showAddPopup(true, it.source as MouseEvent)
}
else createNewConfiguration(configurationType.configurationFactories[0])
}.appendLine(ExecutionBundle.message("status.text.or.select.run.configuration.to.edit"), SimpleTextAttributes.GRAYED_ATTRIBUTES, null)
return messagePanel
}
} | platform/execution-impl/src/com/intellij/execution/impl/ProjectRunConfigurationConfigurable.kt | 978415805 |
// PROBLEM: none
fun test(n: Int): String {
return <caret>when {
n in 0..10 -> "small"
n >= 10 && n <= 100 -> "average"
n < 0 || n > 1000 -> "unknown"
else -> "big"
}
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/branched/introduceWhenSubject/whenWithNondivisibleConditions.kt | 1648811700 |
// ERROR: Type mismatch: inferred type is String but Charset was expected
// ERROR: Type mismatch: inferred type is String but Charset was expected
import java.nio.charset.Charset
import java.util.Locale
internal class A {
@Throws(Exception::class)
fun constructors() {
String()
// TODO: new String("original");
String(charArrayOf('a', 'b', 'c'))
String(charArrayOf('b', 'd'), 1, 1)
String(intArrayOf(32, 65, 127), 0, 3)
val bytes = byteArrayOf(32, 65, 100, 81)
val charset = Charset.forName("utf-8")
String(bytes)
String(bytes, charset)
String(bytes, 0, 2)
String(bytes, "utf-8")
String(bytes, 0, 2, "utf-8")
String(bytes, 0, 2, charset)
String(StringBuilder("content"))
String(StringBuffer("content"))
}
fun normalMethods() {
val s = "test string"
s.length
s.isEmpty()
s[1]
s.codePointAt(2)
s.codePointBefore(2)
s.codePointCount(0, s.length)
s.offsetByCodePoints(0, 4)
s.compareTo("test 2")
s.contains("seq")
s.contentEquals(StringBuilder(s))
s.contentEquals(StringBuffer(s))
s.endsWith("ng")
s.startsWith("te")
s.startsWith("st", 2)
s.indexOf("st")
s.indexOf("st", 5)
s.lastIndexOf("st")
s.lastIndexOf("st", 4)
s.indexOf('t')
s.indexOf('t', 5)
s.lastIndexOf('t')
s.lastIndexOf('t', 5)
s.substring(1)
s.substring(0, 4)
s.subSequence(0, 4)
s.replace('e', 'i')
s.replace("est", "oast")
s.intern()
s.lowercase(Locale.getDefault())
s.lowercase(Locale.FRENCH)
s.uppercase(Locale.getDefault())
s.uppercase(Locale.FRENCH)
s
s.toCharArray()
}
@Throws(Exception::class)
fun specialMethods() {
val s = "test string"
s == "test"
s.equals(
"tesT", ignoreCase = true
)
s.compareTo("Test", ignoreCase = true)
s.regionMatches(
0,
"TE",
0,
2, ignoreCase = true
)
s.regionMatches(0, "st", 1, 2)
s.replace("\\w+".toRegex(), "---")
.replaceFirst("([s-t])".toRegex(), "A$1")
useSplit(s.split("\\s+".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray())
useSplit(s.split("\\s+".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray())
useSplit(s.split("\\s+".toRegex()).toTypedArray())
useSplit(s.split("\\s+".toRegex(), limit = 2).toTypedArray())
val pattern = "\\s+"
useSplit(s.split(pattern.toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray())
val limit = 5
useSplit(s.split("\\s+".toRegex(), limit.coerceAtLeast(0)).toTypedArray())
useSplit(s.split("\\s+".toRegex(), (limit + 5).coerceAtLeast(0)).toTypedArray())
/* TODO
s.matches("\\w+");
*/s.trim { it <= ' ' }
"$s another"
s.toByteArray()
s.toByteArray(Charset.forName("utf-8"))
s.toByteArray(charset("utf-8"))
val chars = CharArray(10)
s.toCharArray(chars, 0, 1, 11)
}
fun staticMethods() {
1.toString()
1L.toString()
'a'.toString()
true.toString()
1.11f.toString()
3.14.toString()
Any().toString()
String.format(
Locale.FRENCH,
"Je ne mange pas %d jours",
6
)
String.format("Operation completed with %s", "success")
val chars = charArrayOf('a', 'b', 'c')
String(chars)
String(chars, 1, 2)
String(chars)
String(chars, 1, 2)
val order = java.lang.String.CASE_INSENSITIVE_ORDER
}
fun unsupportedMethods() {
val s = "test string"
/* TODO:
s.indexOf(32);
s.indexOf(32, 2);
s.lastIndexOf(32);
s.lastIndexOf(32, 2);
*/
}
fun useSplit(result: Array<String?>?) {}
}
| plugins/kotlin/j2k/new/tests/testData/newJ2k/methodCallExpression/stringMethods.kt | 1213003281 |
// 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.configuration
import org.jetbrains.kotlin.idea.framework.KotlinSdkType
import org.jetbrains.kotlin.idea.util.getProjectJdkTableSafe
import org.junit.Assert
import org.junit.internal.runners.JUnit38ClassRunner
import org.junit.runner.RunWith
// Do not add new tests here since application is initialized only once
@RunWith(JUnit38ClassRunner::class)
class AutoConfigureKotlinSdkOnStartupTest : AbstractConfigureKotlinInTempDirTest() {
fun testKotlinSdkAdded() {
Assert.assertTrue(getProjectJdkTableSafe().allJdks.any { it.sdkType is KotlinSdkType })
}
} | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/configuration/AutoConfigureKotlinSdkOnStartupTest.kt | 1918598420 |
package zielu.gittoolbox.extension.blame
import com.intellij.openapi.project.Project
internal interface InlineBlameAllowed {
fun isAllowed(project: Project): Boolean
}
| src/main/kotlin/zielu/gittoolbox/extension/blame/InlineBlameAllowed.kt | 436704704 |
package com.quran.recitation.presenter
import android.graphics.RectF
import android.widget.ImageView
import com.quran.data.model.AyahWord
import com.quran.data.model.selection.SelectionIndicator
import com.quran.recitation.presenter.RecitationPopupPresenter.PopupContainer
interface RecitationPopupPresenter : Presenter<PopupContainer> {
override fun bind(what: PopupContainer)
override fun unbind(what: PopupContainer)
interface PopupContainer {
fun getQuranPageImageView(page: Int): ImageView?
fun getSelectionBoundsForWord(page: Int, word: AyahWord): SelectionIndicator.SelectedItemPosition?
fun getBoundsForWord(word: AyahWord): List<RectF>?
}
}
| common/recitation/src/main/java/com/quran/recitation/presenter/RecitationPopupPresenter.kt | 3511194452 |
package com.habitrpg.android.habitica.ui.activities
import android.app.ProgressDialog
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.core.content.ContextCompat
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.data.UserRepository
import com.habitrpg.android.habitica.databinding.ActivityFixcharacterBinding
import com.habitrpg.android.habitica.helpers.RxErrorHandler
import com.habitrpg.android.habitica.models.user.Stats
import com.habitrpg.android.habitica.models.user.User
import com.habitrpg.android.habitica.modules.AppModule
import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper
import com.habitrpg.android.habitica.ui.views.settings.FixValuesEditText
import io.reactivex.functions.Action
import io.reactivex.functions.Consumer
import javax.inject.Inject
import javax.inject.Named
class FixCharacterValuesActivity: BaseActivity() {
private lateinit var binding: ActivityFixcharacterBinding
@Inject
lateinit var repository: UserRepository
@field:[Inject Named(AppModule.NAMED_USER_ID)]
lateinit var userId: String
override fun getLayoutResId(): Int = R.layout.activity_fixcharacter
override fun getContentView(): View {
binding = ActivityFixcharacterBinding.inflate(layoutInflater)
return binding.root
}
override fun injectActivity(component: UserComponent?) {
component?.inject(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setTitle(R.string.fix_character_values)
setupToolbar(binding.toolbar)
compositeSubscription.add(repository.getUser(userId).firstElement().subscribe(Consumer {
user = it
}, RxErrorHandler.handleEmptyError()))
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_save, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val id = item.itemId
if (id == R.id.action_save_changes) {
@Suppress("DEPRECATION")
val progressDialog = ProgressDialog.show(this, getString(R.string.saving), "")
val userInfo = HashMap<String, Any>()
userInfo["stats.hp"] = binding.healthEditText.getDoubleValue()
userInfo["stats.exp"] = binding.experienceEditText.getDoubleValue()
userInfo["stats.gp"] = binding.goldEditText.getDoubleValue()
userInfo["stats.mp"] = binding.manaEditText.getDoubleValue()
userInfo["stats.lvl"] = binding.levelEditText.getDoubleValue().toInt()
userInfo["achievements.streak"] = binding.streakEditText.getDoubleValue().toInt()
compositeSubscription.add(repository.updateUser(user, userInfo).subscribe(Consumer {}, RxErrorHandler.handleEmptyError(), Action {
progressDialog.dismiss()
finish()
}))
return true
}
return super.onOptionsItemSelected(item)
}
private var user: User? = null
set(value) {
field = value
if (value != null) {
updateFields(value)
}
}
private fun updateFields(user: User) {
val stats = user.stats ?: return
binding.healthEditText.text = stats.hp.toString()
binding.experienceEditText.text = stats.exp.toString()
binding.goldEditText.text = stats.gp.toString()
binding.manaEditText.text = stats.mp.toString()
binding.levelEditText.text = stats.lvl.toString()
binding.streakEditText.text = user.streakCount.toString()
when (stats.habitClass) {
Stats.WARRIOR -> {
binding.levelEditText.iconBackgroundColor = ContextCompat.getColor(this, R.color.red_500)
binding.levelEditText.setIconBitmap(HabiticaIconsHelper.imageOfWarriorLightBg())
}
Stats.MAGE -> {
binding.levelEditText.iconBackgroundColor = ContextCompat.getColor(this, R.color.blue_500)
binding.levelEditText.setIconBitmap(HabiticaIconsHelper.imageOfMageLightBg())
}
Stats.HEALER -> {
binding.levelEditText.iconBackgroundColor = ContextCompat.getColor(this, R.color.yellow_500)
binding.levelEditText.setIconBitmap(HabiticaIconsHelper.imageOfHealerLightBg())
}
Stats.ROGUE -> {
binding.levelEditText.iconBackgroundColor = ContextCompat.getColor(this, R.color.brand_500)
binding.levelEditText.setIconBitmap(HabiticaIconsHelper.imageOfRogueLightBg())
}
}
}
private fun FixValuesEditText.getDoubleValue(): Double {
val stringValue = this.text
return try {
stringValue.toDouble()
} catch (_: NumberFormatException) {
0.0
}
}
} | Habitica/src/main/java/com/habitrpg/android/habitica/ui/activities/FixCharacterValuesActivity.kt | 2156149544 |
package com.habitrpg.android.habitica.data
import com.habitrpg.android.habitica.models.FAQArticle
import io.reactivex.Flowable
import io.realm.RealmResults
interface FAQRepository : BaseRepository {
fun getArticles(): Flowable<RealmResults<FAQArticle>>
fun getArticle(position: Int): Flowable<FAQArticle>
}
| Habitica/src/main/java/com/habitrpg/android/habitica/data/FAQRepository.kt | 2235935002 |
package eu.vaadinonkotlin.vaadin.vokdb
import com.github.mvysny.dynatest.DynaTest
import com.github.mvysny.dynatest.expectList
import com.github.mvysny.karibudsl.v10.grid
import com.github.mvysny.kaributesting.v10.MockVaadin
import com.github.mvysny.kaributesting.v10._findAll
import com.github.mvysny.kaributesting.v10.getSuggestions
import com.github.mvysny.kaributesting.v10.setUserInput
import com.github.vokorm.dataloader.SqlDataLoader
import com.github.vokorm.dataloader.dataLoader
import com.vaadin.flow.component.UI
import com.vaadin.flow.component.combobox.ComboBox
import com.vaadin.flow.component.grid.Grid
import kotlin.test.expect
class DataProvidersTest : DynaTest({
group("API test: populating components with data providers") {
usingH2Database()
beforeEach { MockVaadin.setup() }
afterEach { MockVaadin.tearDown() }
group("combobox") {
// test that the EntityDataProvider and SqlDataProviders are compatible with Vaadin ComboBox
// since ComboBox emits String as a filter (it emits whatever the user typed into the ComboBox).
test("entity data provider") {
(0..10).forEach { Person(null, "foo $it", it).save() }
val dp = Person.dataLoader
val cb = ComboBox<Person>().apply {
setItemLabelGenerator { it.personName }
setItems(dp.withStringFilterOn(Person::personName))
}
expect((0..10).map { "foo $it" }) { cb.getSuggestions() }
cb.setUserInput("foo 1")
expectList("foo 1", "foo 10") { cb.getSuggestions() }
}
// tests that the EntityDataProvider and SqlDataProviders are compatible with Vaadin ComboBox
// since ComboBox emits String as a filter (it emits whatever the user typed into the ComboBox).
test("sql data provider") {
(0..10).forEach { Person(null, "foo $it", it).save() }
val dp = SqlDataLoader(Person::class.java, "select * from Test where 1=1 {{WHERE}} order by 1=1{{ORDER}} {{PAGING}}")
val cb = ComboBox<Person>().apply {
setItemLabelGenerator { it.personName }
setItems(dp.withStringFilterOn("name"))
}
expect((0..10).map { "foo $it" }) { cb.getSuggestions() }
cb.setUserInput("foo 1")
expectList("foo 1", "foo 10") { cb.getSuggestions() }
}
}
group("grid") {
// test that the EntityDataProvider and SqlDataProviders are compatible with Vaadin ComboBox
// since ComboBox emits String as a filter (it emits whatever the user typed into the ComboBox).
test("entity data provider") {
(0..10).forEach { Person(null, "foo $it", it).save() }
val cb: Grid<Person> = UI.getCurrent().grid<Person> {
setDataLoader(Person.dataLoader)
}
expect((0..10).map { "foo $it" }) { cb._findAll().map { it.personName } }
}
}
}
})
| vok-framework-vokdb/src/test/kotlin/eu/vaadinonkotlin/vaadin/vokdb/DataProvidersTest.kt | 2951399763 |
/*
* Copyright 2015-2019 The twitlatte 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 com.github.moko256.twitlatte
import android.content.Context
import android.view.ViewGroup
import android.widget.ImageView
import androidx.annotation.DrawableRes
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.RequestManager
import com.github.moko256.latte.client.base.entity.Emoji
import com.github.moko256.twitlatte.view.dpToPx
/**
* Created by moko256 on 2018/12/11.
*
* @author moko256
*/
class EmojiAdapter(
private val list: List<Emoji>,
private val context: Context,
private val glideRequests: RequestManager,
private val onEmojiClick: (Emoji) -> Unit,
private val onLoadClick: () -> Unit
) : RecyclerView.Adapter<EmojiViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): EmojiViewHolder {
val imageView = ImageView(context)
val dp32 = context.dpToPx(32)
imageView.layoutParams = ViewGroup.LayoutParams(dp32, dp32)
return EmojiViewHolder(
imageView = imageView,
glideRequests = glideRequests
)
}
override fun getItemCount(): Int {
return list.size + 1
}
override fun onBindViewHolder(holder: EmojiViewHolder, position: Int) {
if (position != list.size) {
val emoji = list[position]
holder.setImage(emoji.url)
holder.itemView.setOnClickListener {
onEmojiClick(emoji)
}
} else {
holder.setImage(R.drawable.list_add_icon)
holder.itemView.setOnClickListener {
onLoadClick()
}
}
}
override fun onViewRecycled(holder: EmojiViewHolder) {
holder.clearImage()
}
}
class EmojiViewHolder(private val imageView: ImageView, private val glideRequests: RequestManager) : RecyclerView.ViewHolder(imageView) {
fun setImage(url: String) {
glideRequests.load(url).into(imageView)
}
fun setImage(@DrawableRes resId: Int) {
glideRequests.load(resId).into(imageView)
}
fun clearImage() {
glideRequests.clear(imageView)
}
} | app/src/main/java/com/github/moko256/twitlatte/EmojiAdapter.kt | 1927495822 |
package base
interface <!LINE_MARKER("descr='Is implemented by CheckClass SubCheck SubCheckClass Click or press ... to navigate'")!>Check<!> {
fun <!LINE_MARKER("descr='Is overridden in SubCheck'")!>test<!>(): String {
return "fail";
}
}
open class <!LINE_MARKER("descr='Is subclassed by SubCheckClass Click or press ... to navigate'")!>CheckClass<!> : Check
| plugins/kotlin/idea/tests/testData/multiplatform/jvmDefaultNonMpp/base/base.kt | 4077808984 |
/**
* Copyright 2010 - 2022 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.exodus.crypto
import jetbrains.exodus.core.dataStructures.hash.LongHashMap
import jetbrains.exodus.core.dataStructures.hash.LongSet
import jetbrains.exodus.entitystore.BlobVault
import jetbrains.exodus.entitystore.BlobVaultItem
import jetbrains.exodus.entitystore.DiskBasedBlobVault
import jetbrains.exodus.entitystore.FileSystemBlobVaultOld
import jetbrains.exodus.env.Transaction
import java.io.File
import java.io.FileInputStream
import java.io.InputStream
import java.io.OutputStream
class EncryptedBlobVault(private val decorated: FileSystemBlobVaultOld,
private val cipherProvider: StreamCipherProvider,
private val cipherKey: ByteArray,
private val cipherBasicIV: Long) : BlobVault(decorated), DiskBasedBlobVault {
override fun getSourceVault() = decorated
override fun clear() = decorated.clear()
override fun getBackupStrategy() = decorated.backupStrategy
override fun getBlob(blobHandle: Long): BlobVaultItem {
return decorated.getBlob(blobHandle)
}
override fun getContent(blobHandle: Long, txn: Transaction): InputStream? {
return decorated.getContent(blobHandle, txn)?.run {
StreamCipherInputStream(this) {
newCipher(blobHandle)
}
}
}
override fun delete(blobHandle: Long): Boolean {
return decorated.delete(blobHandle)
}
override fun getBlobLocation(blobHandle: Long): File {
return decorated.getBlobLocation(blobHandle)
}
override fun getBlobLocation(blobHandle: Long, readonly: Boolean): File {
return decorated.getBlobLocation(blobHandle, readonly)
}
override fun getBlobKey(blobHandle: Long): String {
return decorated.getBlobKey(blobHandle)
}
override fun getSize(blobHandle: Long, txn: Transaction) = decorated.getSize(blobHandle, txn)
override fun requiresTxn() = decorated.requiresTxn()
override fun flushBlobs(blobStreams: LongHashMap<InputStream>?,
blobFiles: LongHashMap<File>?,
deferredBlobsToDelete: LongSet?,
txn: Transaction) {
val streams = LongHashMap<InputStream>()
blobStreams?.forEach {
streams[it.key] = StreamCipherInputStream(it.value) {
newCipher(it.key)
}
}
var openFiles: MutableList<InputStream>? = null
try {
if (blobFiles != null && blobFiles.isNotEmpty()) {
openFiles = mutableListOf()
blobFiles.forEach {
streams[it.key] = StreamCipherInputStream(
FileInputStream(it.value)
.also { openFiles.add(it) }
.asBuffered
.apply { mark(Int.MAX_VALUE) }
) {
newCipher(it.key)
}
}
}
decorated.flushBlobs(streams, null, deferredBlobsToDelete, txn)
} finally {
openFiles?.forEach { it.close() }
}
}
override fun size() = decorated.size()
override fun nextHandle(txn: Transaction) = decorated.nextHandle(txn)
override fun close() = decorated.close()
fun wrapOutputStream(blobHandle: Long, output: OutputStream): StreamCipherOutputStream {
return StreamCipherOutputStream(output, newCipher(blobHandle))
}
private fun newCipher(blobHandle: Long) =
cipherProvider.newCipher().apply { init(cipherKey, (cipherBasicIV - blobHandle).asHashedIV()) }
}
| entity-store/src/main/kotlin/jetbrains/exodus/crypto/EncryptedBlobVault.kt | 1434668565 |
package co.zsmb.materialdrawerktexample.customitems.overflow
import android.view.MenuItem
import androidx.appcompat.widget.PopupMenu
import co.zsmb.materialdrawerkt.builders.Builder
import co.zsmb.materialdrawerkt.createItem
import co.zsmb.materialdrawerkt.draweritems.base.BaseDescribeableDrawerItemKt
// Functions so that the item can be used in the appropriate parts of the DSL
// the exact same way as a library item
// For use with no params or String params
fun Builder.overflowMenuItem(
name: String = "",
description: String? = null,
setup: OverflowMenuDrawerItemKt.() -> Unit): OverflowMenuDrawerItem {
return createItem(OverflowMenuDrawerItemKt(), name, description, setup)
}
// For use with String resource params
fun Builder.overflowMenuItem(
nameRes: Int,
descriptionRes: Int,
setup: OverflowMenuDrawerItemKt.() -> Unit): OverflowMenuDrawerItem {
return createItem(OverflowMenuDrawerItemKt(), nameRes, descriptionRes, setup)
}
// Wrapper class for nice DSL access
class OverflowMenuDrawerItemKt : BaseDescribeableDrawerItemKt<OverflowMenuDrawerItem>(OverflowMenuDrawerItem()) {
var menuRes: Int
get() = item.menu
set(value) {
item.withMenu(value)
}
fun onDismiss(handler: (PopupMenu) -> Unit) {
item.withOnDismissListener(PopupMenu.OnDismissListener { handler(it) })
}
fun onMenuItemClick(handler: (MenuItem) -> Boolean) {
item.withOnMenuItemClickListener(PopupMenu.OnMenuItemClickListener { handler(it) })
}
}
| app/src/main/java/co/zsmb/materialdrawerktexample/customitems/overflow/OverflowMenuDrawerItemKt.kt | 2572860545 |
/**
* Copyright 2010 - 2022 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.exodus.log
import jetbrains.exodus.io.Block
import jetbrains.exodus.io.DataReader
import jetbrains.exodus.io.DataWriter
abstract class AbstractBlockListener() : BlockListener {
override fun blockCreated(block: Block, reader: DataReader, writer: DataWriter) {
}
override fun beforeBlockDeleted(block: Block, reader: DataReader, writer: DataWriter) {
}
override fun afterBlockDeleted(address: Long, reader: DataReader, writer: DataWriter) {
}
override fun blockModified(block: Block, reader: DataReader, writer: DataWriter) {
}
} | environment/src/main/kotlin/jetbrains/exodus/log/AbstractBlockListener.kt | 2361360144 |
// 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.configuration
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.ProjectKeys
import com.intellij.openapi.externalSystem.model.project.LibraryData
import com.intellij.openapi.externalSystem.model.project.ModuleData
import com.intellij.openapi.externalSystem.model.project.ProjectData
import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider
import com.intellij.openapi.externalSystem.service.project.manage.AbstractProjectDataService
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.roots.impl.libraries.LibraryEx
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.util.Key
import com.intellij.util.PathUtil
import org.jetbrains.kotlin.cli.common.arguments.K2JSCompilerArguments
import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments
import org.jetbrains.kotlin.cli.common.arguments.parseCommandLineArguments
import org.jetbrains.kotlin.config.*
import org.jetbrains.kotlin.extensions.ProjectExtensionDescriptor
import org.jetbrains.kotlin.gradle.ArgsInfo
import org.jetbrains.kotlin.gradle.CompilerArgumentsBySourceSet
import org.jetbrains.kotlin.ide.konan.NativeLibraryKind
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinCommonCompilerArgumentsHolder
import org.jetbrains.kotlin.idea.configuration.GradlePropertiesFileFacade.Companion.KOTLIN_CODE_STYLE_GRADLE_SETTING
import org.jetbrains.kotlin.idea.configuration.klib.KotlinNativeLibraryNameUtil.KOTLIN_NATIVE_LIBRARY_PREFIX
import org.jetbrains.kotlin.idea.facet.*
import org.jetbrains.kotlin.idea.formatter.ProjectCodeStyleImporter
import org.jetbrains.kotlin.idea.framework.CommonLibraryKind
import org.jetbrains.kotlin.idea.framework.JSLibraryKind
import org.jetbrains.kotlin.idea.framework.detectLibraryKind
import org.jetbrains.kotlin.idea.gradle.KotlinGradleFacadeImpl
import org.jetbrains.kotlin.idea.inspections.gradle.getResolvedVersionByModuleData
import org.jetbrains.kotlin.idea.platform.tooling
import org.jetbrains.kotlin.idea.roots.findAll
import org.jetbrains.kotlin.idea.roots.migrateNonJvmSourceFolders
import org.jetbrains.kotlin.idea.statistics.KotlinGradleFUSLogger
import org.jetbrains.kotlin.library.KLIB_FILE_EXTENSION
import org.jetbrains.kotlin.platform.IdePlatformKind
import org.jetbrains.kotlin.platform.impl.isCommon
import org.jetbrains.kotlin.platform.impl.isJavaScript
import org.jetbrains.kotlin.platform.impl.isJvm
import org.jetbrains.kotlin.psi.UserDataProperty
import org.jetbrains.plugins.gradle.model.data.BuildScriptClasspathData
import org.jetbrains.plugins.gradle.model.data.GradleSourceSetData
import org.jetbrains.plugins.gradle.util.GradleConstants
import java.io.File
import java.util.*
var Module.compilerArgumentsBySourceSet
by UserDataProperty(Key.create<CompilerArgumentsBySourceSet>("CURRENT_COMPILER_ARGUMENTS"))
var Module.sourceSetName
by UserDataProperty(Key.create<String>("SOURCE_SET_NAME"))
interface GradleProjectImportHandler {
companion object : ProjectExtensionDescriptor<GradleProjectImportHandler>(
"org.jetbrains.kotlin.gradleProjectImportHandler",
GradleProjectImportHandler::class.java
)
fun importBySourceSet(facet: KotlinFacet, sourceSetNode: DataNode<GradleSourceSetData>)
fun importByModule(facet: KotlinFacet, moduleNode: DataNode<ModuleData>)
}
class KotlinGradleProjectSettingsDataService : AbstractProjectDataService<ProjectData, Void>() {
override fun getTargetDataKey() = ProjectKeys.PROJECT
override fun postProcess(
toImport: MutableCollection<out DataNode<ProjectData>>,
projectData: ProjectData?,
project: Project,
modelsProvider: IdeModifiableModelsProvider
) {
val allSettings = modelsProvider.modules.mapNotNull { module ->
if (module.isDisposed) return@mapNotNull null
val settings = modelsProvider
.getModifiableFacetModel(module)
.findFacet(KotlinFacetType.TYPE_ID, KotlinFacetType.INSTANCE.defaultFacetName)
?.configuration
?.settings ?: return@mapNotNull null
if (settings.useProjectSettings) null else settings
}
val languageVersion = allSettings.asSequence().mapNotNullTo(LinkedHashSet()) { it.languageLevel }.singleOrNull()
val apiVersion = allSettings.asSequence().mapNotNullTo(LinkedHashSet()) { it.apiLevel }.singleOrNull()
KotlinCommonCompilerArgumentsHolder.getInstance(project).update {
if (languageVersion != null) {
this.languageVersion = languageVersion.versionString
}
if (apiVersion != null) {
this.apiVersion = apiVersion.versionString
}
}
}
}
class KotlinGradleSourceSetDataService : AbstractProjectDataService<GradleSourceSetData, Void>() {
override fun getTargetDataKey() = GradleSourceSetData.KEY
override fun postProcess(
toImport: Collection<out DataNode<GradleSourceSetData>>,
projectData: ProjectData?,
project: Project,
modelsProvider: IdeModifiableModelsProvider
) {
for (sourceSetNode in toImport) {
val sourceSetData = sourceSetNode.data
val ideModule = modelsProvider.findIdeModule(sourceSetData) ?: continue
val moduleNode = ExternalSystemApiUtil.findParent(sourceSetNode, ProjectKeys.MODULE) ?: continue
val kotlinFacet = configureFacetByGradleModule(ideModule, modelsProvider, moduleNode, sourceSetNode) ?: continue
GradleProjectImportHandler.getInstances(project).forEach { it.importBySourceSet(kotlinFacet, sourceSetNode) }
}
}
}
class KotlinGradleProjectDataService : AbstractProjectDataService<ModuleData, Void>() {
override fun getTargetDataKey() = ProjectKeys.MODULE
override fun postProcess(
toImport: MutableCollection<out DataNode<ModuleData>>,
projectData: ProjectData?,
project: Project,
modelsProvider: IdeModifiableModelsProvider
) {
for (moduleNode in toImport) {
// If source sets are present, configure facets in the their modules
if (ExternalSystemApiUtil.getChildren(moduleNode, GradleSourceSetData.KEY).isNotEmpty()) continue
val moduleData = moduleNode.data
val ideModule = modelsProvider.findIdeModule(moduleData) ?: continue
val kotlinFacet = configureFacetByGradleModule(ideModule, modelsProvider, moduleNode, null) ?: continue
GradleProjectImportHandler.getInstances(project).forEach { it.importByModule(kotlinFacet, moduleNode) }
}
runReadAction {
val codeStyleStr = GradlePropertiesFileFacade.forProject(project).readProperty(KOTLIN_CODE_STYLE_GRADLE_SETTING)
ProjectCodeStyleImporter.apply(project, codeStyleStr)
}
ApplicationManager.getApplication().executeOnPooledThread {
KotlinGradleFUSLogger.reportStatistics()
}
}
}
class KotlinGradleLibraryDataService : AbstractProjectDataService<LibraryData, Void>() {
override fun getTargetDataKey() = ProjectKeys.LIBRARY
override fun postProcess(
toImport: MutableCollection<out DataNode<LibraryData>>,
projectData: ProjectData?,
project: Project,
modelsProvider: IdeModifiableModelsProvider
) {
if (toImport.isEmpty()) return
val projectDataNode = toImport.first().parent!!
@Suppress("UNCHECKED_CAST")
val moduleDataNodes = projectDataNode.children.filter { it.data is ModuleData } as List<DataNode<ModuleData>>
val anyNonJvmModules = moduleDataNodes
.any { node -> detectPlatformKindByPlugin(node)?.takeIf { !it.isJvm } != null }
for (libraryDataNode in toImport) {
val ideLibrary = modelsProvider.findIdeLibrary(libraryDataNode.data) ?: continue
val modifiableModel = modelsProvider.getModifiableLibraryModel(ideLibrary) as LibraryEx.ModifiableModelEx
if (anyNonJvmModules || ideLibrary.looksAsNonJvmLibrary()) {
detectLibraryKind(modifiableModel.getFiles(OrderRootType.CLASSES))?.let { modifiableModel.kind = it }
} else if (
ideLibrary is LibraryEx &&
(ideLibrary.kind === JSLibraryKind || ideLibrary.kind === NativeLibraryKind || ideLibrary.kind === CommonLibraryKind)
) {
modifiableModel.kind = null
}
}
}
private fun Library.looksAsNonJvmLibrary(): Boolean {
name?.let { name ->
if (nonJvmSuffixes.any { it in name } || name.startsWith(KOTLIN_NATIVE_LIBRARY_PREFIX))
return true
}
return getFiles(OrderRootType.CLASSES).firstOrNull()?.extension == KLIB_FILE_EXTENSION
}
companion object {
val LOG = Logger.getInstance(KotlinGradleLibraryDataService::class.java)
val nonJvmSuffixes = listOf("-common", "-js", "-native", "-kjsm", "-metadata")
}
}
fun detectPlatformKindByPlugin(moduleNode: DataNode<ModuleData>): IdePlatformKind<*>? {
val pluginId = moduleNode.platformPluginId
return IdePlatformKind.ALL_KINDS.firstOrNull { it.tooling.gradlePluginId == pluginId }
}
@Suppress("DEPRECATION_ERROR")
@Deprecated(
"Use detectPlatformKindByPlugin() instead",
replaceWith = ReplaceWith("detectPlatformKindByPlugin(moduleNode)"),
level = DeprecationLevel.ERROR
)
fun detectPlatformByPlugin(moduleNode: DataNode<ModuleData>): TargetPlatformKind<*>? {
return when (moduleNode.platformPluginId) {
"kotlin-platform-jvm" -> TargetPlatformKind.Jvm[JvmTarget.DEFAULT]
"kotlin-platform-js" -> TargetPlatformKind.JavaScript
"kotlin-platform-common" -> TargetPlatformKind.Common
else -> null
}
}
private fun detectPlatformByLibrary(moduleNode: DataNode<ModuleData>): IdePlatformKind<*>? {
val detectedPlatforms =
mavenLibraryIdToPlatform.entries
.filter { moduleNode.getResolvedVersionByModuleData(KOTLIN_GROUP_ID, listOf(it.key)) != null }
.map { it.value }.distinct()
return detectedPlatforms.singleOrNull() ?: detectedPlatforms.firstOrNull { !it.isCommon }
}
@Suppress("unused") // Used in the Android plugin
fun configureFacetByGradleModule(
moduleNode: DataNode<ModuleData>,
sourceSetName: String?,
ideModule: Module,
modelsProvider: IdeModifiableModelsProvider
): KotlinFacet? {
return configureFacetByGradleModule(ideModule, modelsProvider, moduleNode, null, sourceSetName)
}
fun configureFacetByGradleModule(
ideModule: Module,
modelsProvider: IdeModifiableModelsProvider,
moduleNode: DataNode<ModuleData>,
sourceSetNode: DataNode<GradleSourceSetData>?,
sourceSetName: String? = sourceSetNode?.data?.id?.let { it.substring(it.lastIndexOf(':') + 1) }
): KotlinFacet? {
if (moduleNode.kotlinSourceSet != null) return null // Suppress in the presence of new MPP model
if (!moduleNode.isResolved) return null
if (!moduleNode.hasKotlinPlugin) {
val facetModel = modelsProvider.getModifiableFacetModel(ideModule)
val facet = facetModel.getFacetByType(KotlinFacetType.TYPE_ID)
if (facet != null) {
facetModel.removeFacet(facet)
}
return null
}
val compilerVersion = KotlinGradleFacadeImpl.findKotlinPluginVersion(moduleNode) ?: return null
val platformKind = detectPlatformKindByPlugin(moduleNode) ?: detectPlatformByLibrary(moduleNode)
// TODO there should be a way to figure out the correct platform version
val platform = platformKind?.defaultPlatform
val kotlinFacet = ideModule.getOrCreateFacet(modelsProvider, false, GradleConstants.SYSTEM_ID.id)
kotlinFacet.configureFacet(
compilerVersion,
platform,
modelsProvider
)
if (sourceSetNode == null) {
ideModule.compilerArgumentsBySourceSet = moduleNode.compilerArgumentsBySourceSet
ideModule.sourceSetName = sourceSetName
}
ideModule.hasExternalSdkConfiguration = sourceSetNode?.data?.sdkName != null
val argsInfo = moduleNode.compilerArgumentsBySourceSet?.get(sourceSetName ?: "main")
if (argsInfo != null) {
configureFacetByCompilerArguments(kotlinFacet, argsInfo, modelsProvider)
}
with(kotlinFacet.configuration.settings) {
implementedModuleNames = (sourceSetNode ?: moduleNode).implementedModuleNames
productionOutputPath = getExplicitOutputPath(moduleNode, platformKind, "main")
testOutputPath = getExplicitOutputPath(moduleNode, platformKind, "test")
}
kotlinFacet.noVersionAutoAdvance()
if (platformKind != null && !platformKind.isJvm) {
migrateNonJvmSourceFolders(modelsProvider.getModifiableRootModel(ideModule))
}
return kotlinFacet
}
fun configureFacetByCompilerArguments(kotlinFacet: KotlinFacet, argsInfo: ArgsInfo, modelsProvider: IdeModifiableModelsProvider?) {
val currentCompilerArguments = argsInfo.currentArguments
val defaultCompilerArguments = argsInfo.defaultArguments
val dependencyClasspath = argsInfo.dependencyClasspath.map { PathUtil.toSystemIndependentName(it) }
if (currentCompilerArguments.isNotEmpty()) {
parseCompilerArgumentsToFacet(currentCompilerArguments, defaultCompilerArguments, kotlinFacet, modelsProvider)
}
adjustClasspath(kotlinFacet, dependencyClasspath)
}
private fun getExplicitOutputPath(moduleNode: DataNode<ModuleData>, platformKind: IdePlatformKind<*>?, sourceSet: String): String? {
if (!platformKind.isJavaScript) {
return null
}
val k2jsArgumentList = moduleNode.compilerArgumentsBySourceSet?.get(sourceSet)?.currentArguments ?: return null
return K2JSCompilerArguments().apply { parseCommandLineArguments(k2jsArgumentList, this) }.outputFile
}
internal fun adjustClasspath(kotlinFacet: KotlinFacet, dependencyClasspath: List<String>) {
if (dependencyClasspath.isEmpty()) return
val arguments = kotlinFacet.configuration.settings.compilerArguments as? K2JVMCompilerArguments ?: return
val fullClasspath = arguments.classpath?.split(File.pathSeparator) ?: emptyList()
if (fullClasspath.isEmpty()) return
val newClasspath = fullClasspath - dependencyClasspath
arguments.classpath = if (newClasspath.isNotEmpty()) newClasspath.joinToString(File.pathSeparator) else null
}
| plugins/kotlin/gradle/gradle-idea/src/org/jetbrains/kotlin/idea/configuration/KotlinGradleSourceSetDataService.kt | 1630970413 |
// "Make block type suspend" "true"
// WITH_RUNTIME
import kotlin.coroutines.suspendCoroutine
import kotlin.coroutines.startCoroutine
suspend fun <T> suspending(block: () -> T): T = suspendCoroutine { block.<caret>startCoroutine(it) }
| plugins/kotlin/idea/tests/testData/quickfix/modifiers/suspend/startCoroutine.kt | 1666270795 |
// 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.editor
import com.intellij.openapi.editor.ex.EditorSettingsExternalizable
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.psi.PsiDocumentManager
import com.intellij.testFramework.EditorTestUtil
import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase
import org.jetbrains.kotlin.idea.test.IDEA_TEST_DATA_DIR
import org.jetbrains.kotlin.idea.test.util.slashedPath
import org.junit.internal.runners.JUnit38ClassRunner
import org.junit.runner.RunWith
@RunWith(JUnit38ClassRunner::class)
class StripTrailingSpacesTest : LightJavaCodeInsightFixtureTestCase() {
override fun getTestDataPath() = IDEA_TEST_DATA_DIR.resolve("editor/stripTrailingSpaces").slashedPath
fun testKeepTrailingSpacesInRawString() {
doTest()
}
fun doTest() {
myFixture.configureByFile("${getTestName(true)}.kt")
val editorSettings = EditorSettingsExternalizable.getInstance()
val stripSpaces = editorSettings.stripTrailingSpaces
try {
editorSettings.stripTrailingSpaces = EditorSettingsExternalizable.STRIP_TRAILING_SPACES_WHOLE
val doc = myFixture.editor.document
EditorTestUtil.performTypingAction(editor, ' ')
PsiDocumentManager.getInstance(project).commitDocument(doc)
FileDocumentManager.getInstance().saveDocument(doc)
} finally {
editorSettings.stripTrailingSpaces = stripSpaces
}
myFixture.checkResultByFile("${getTestName(true)}.kt.after")
}
}
| plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/editor/StripTrailingSpacesTest.kt | 708107617 |
// FIR_IDENTICAL
// FIR_COMPARISON
fun test() {
Numb<caret>
}
// EXIST: "Number"
// EXIST: "NumberFormatException"
| plugins/kotlin/completion/tests/testData/basic/java/ClassFromDependency.kt | 342051367 |
// 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.inspections.migration
import com.intellij.codeInspection.CleanupLocalInspectionTool
import org.jetbrains.kotlin.config.LanguageVersion
import org.jetbrains.kotlin.diagnostics.DiagnosticFactoryWithPsiElement
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.migration.MigrationInfo
import org.jetbrains.kotlin.idea.migration.isLanguageVersionUpdate
import org.jetbrains.kotlin.idea.quickfix.migration.MigrationFix
import org.jetbrains.kotlin.psi.KtElement
class RedundantLabelMigrationInspection :
AbstractDiagnosticBasedMigrationInspection<KtElement>(KtElement::class.java),
MigrationFix,
CleanupLocalInspectionTool {
override fun isApplicable(migrationInfo: MigrationInfo): Boolean {
return migrationInfo.isLanguageVersionUpdate(LanguageVersion.KOTLIN_1_3, LanguageVersion.KOTLIN_1_4)
}
override fun descriptionMessage(): String = KotlinBundle.message("inspection.redundant.label.text")
override val diagnosticFactory: DiagnosticFactoryWithPsiElement<KtElement, *>
get() = Errors.REDUNDANT_LABEL_WARNING
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/migration/RedundantLabelMigrationInspection.kt | 4102386912 |
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed -> in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.konan.target
import org.jetbrains.kotlin.konan.file.File
internal object Android {
const val API = "21"
private val architectureMap = mapOf(
KonanTarget.ANDROID_X86 to "x86",
KonanTarget.ANDROID_X64 to "x86_64",
KonanTarget.ANDROID_ARM32 to "arm",
KonanTarget.ANDROID_ARM64 to "arm64"
)
fun architectureDirForTarget(target: KonanTarget) =
"android-${API}/arch-${architectureMap.getValue(target)}"
}
class ClangArgs(private val configurables: Configurables) : Configurables by configurables {
private val targetArg = if (configurables is TargetableConfigurables)
configurables.targetArg
else null
private val clangArgsSpecificForKonanSources
get() = runtimeDefinitions.map { "-D$it" }
private val binDir = when (HostManager.host) {
KonanTarget.LINUX_X64 -> "$absoluteTargetToolchain/bin"
KonanTarget.MINGW_X64 -> "$absoluteTargetToolchain/bin"
KonanTarget.MACOS_X64 -> "$absoluteTargetToolchain/usr/bin"
else -> throw TargetSupportException("Unexpected host platform")
}
// TODO: Use buildList
private val commonClangArgs: List<String> = mutableListOf<List<String>>().apply {
add(listOf("-B$binDir", "-fno-stack-protector"))
if (configurables is GccConfigurables) {
add(listOf("--gcc-toolchain=${configurables.absoluteGccToolchain}"))
}
if (configurables is TargetableConfigurables) {
add(listOf("-target", configurables.targetArg!!))
}
val hasCustomSysroot = configurables is ZephyrConfigurables
|| configurables is WasmConfigurables
|| configurables is AndroidConfigurables
if (!hasCustomSysroot) {
when (configurables) {
// isysroot and sysroot on darwin are _almost_ synonyms.
// The first one parses SDKSettings.json while second one is not.
is AppleConfigurables -> add(listOf("-isysroot", absoluteTargetSysRoot))
else -> add(listOf("--sysroot=$absoluteTargetSysRoot"))
}
}
// PIC is not required on Windows (and Clang will fail with `error: unsupported option '-fPIC'`)
if (configurables !is MingwConfigurables) {
// `-fPIC` allows us to avoid some problems when producing dynamic library.
// See KT-43502.
add(listOf("-fPIC"))
}
}.flatten()
private val osVersionMin: String
get() {
require(configurables is AppleConfigurables)
return configurables.osVersionMin
}
private val specificClangArgs: List<String> = when (target) {
KonanTarget.LINUX_X64,
KonanTarget.LINUX_MIPS32, KonanTarget.LINUX_MIPSEL32,
KonanTarget.LINUX_ARM64,
KonanTarget.MINGW_X64, KonanTarget.MINGW_X86 -> emptyList()
KonanTarget.LINUX_ARM32_HFP -> listOf(
"-mfpu=vfp", "-mfloat-abi=hard"
)
KonanTarget.MACOS_X64 -> listOf(
"-mmacosx-version-min=$osVersionMin"
)
// Here we workaround Clang 8 limitation: macOS major version should be 10.
// So we compile runtime with version 10.16 and then override version in BitcodeCompiler.
// TODO: Fix with LLVM Update.
KonanTarget.MACOS_ARM64 -> listOf(
"-arch", "arm64",
"-mmacosx-version-min=10.16"
)
KonanTarget.IOS_ARM32 -> listOf(
"-stdlib=libc++",
"-arch", "armv7",
"-miphoneos-version-min=$osVersionMin"
)
KonanTarget.IOS_ARM64 -> listOf(
"-stdlib=libc++",
"-arch", "arm64",
"-miphoneos-version-min=$osVersionMin"
)
KonanTarget.IOS_X64 -> listOf(
"-stdlib=libc++",
"-miphoneos-version-min=$osVersionMin"
)
KonanTarget.TVOS_ARM64 -> listOf(
"-stdlib=libc++",
"-arch", "arm64",
"-mtvos-version-min=$osVersionMin"
)
KonanTarget.TVOS_X64 -> listOf(
"-stdlib=libc++",
"-mtvos-simulator-version-min=$osVersionMin"
)
KonanTarget.WATCHOS_ARM64,
KonanTarget.WATCHOS_ARM32 -> listOf(
"-stdlib=libc++",
"-arch", "armv7k",
"-mwatchos-version-min=$osVersionMin"
)
KonanTarget.WATCHOS_X86 -> listOf(
"-stdlib=libc++",
"-arch", "i386",
"-mwatchos-simulator-version-min=$osVersionMin"
)
KonanTarget.WATCHOS_X64 -> listOf(
"-stdlib=libc++",
"-mwatchos-simulator-version-min=$osVersionMin"
)
KonanTarget.ANDROID_ARM32, KonanTarget.ANDROID_ARM64,
KonanTarget.ANDROID_X86, KonanTarget.ANDROID_X64 -> {
val clangTarget = targetArg!!
val architectureDir = Android.architectureDirForTarget(target)
val toolchainSysroot = "$absoluteTargetToolchain/sysroot"
listOf(
"-D__ANDROID_API__=${Android.API}",
"--sysroot=$absoluteTargetSysRoot/$architectureDir",
"-I$toolchainSysroot/usr/include/c++/v1",
"-I$toolchainSysroot/usr/include",
"-I$toolchainSysroot/usr/include/$clangTarget"
)
}
// By default WASM target forces `hidden` visibility which causes linkage problems.
KonanTarget.WASM32 -> listOf(
"-fno-rtti",
"-fno-exceptions",
"-fvisibility=default",
"-D_LIBCPP_ABI_VERSION=2",
"-D_LIBCPP_NO_EXCEPTIONS=1",
"-nostdinc",
"-Xclang", "-nobuiltininc",
"-Xclang", "-nostdsysteminc",
"-Xclang", "-isystem$absoluteTargetSysRoot/include/libcxx",
"-Xclang", "-isystem$absoluteTargetSysRoot/lib/libcxxabi/include",
"-Xclang", "-isystem$absoluteTargetSysRoot/include/compat",
"-Xclang", "-isystem$absoluteTargetSysRoot/include/libc"
)
is KonanTarget.ZEPHYR -> listOf(
"-fno-rtti",
"-fno-exceptions",
"-fno-asynchronous-unwind-tables",
"-fno-pie",
"-fno-pic",
"-fshort-enums",
"-nostdinc",
// TODO: make it a libGcc property?
// We need to get rid of wasm sysroot first.
"-isystem $targetToolchain/../lib/gcc/arm-none-eabi/7.2.1/include",
"-isystem $targetToolchain/../lib/gcc/arm-none-eabi/7.2.1/include-fixed",
"-isystem$absoluteTargetSysRoot/include/libcxx",
"-isystem$absoluteTargetSysRoot/include/libc"
) + (configurables as ZephyrConfigurables).constructClangArgs()
}
val clangPaths = listOf("$absoluteLlvmHome/bin", binDir)
private val jdkDir by lazy {
val home = File.javaHome.absoluteFile
if (home.child("include").exists)
home.absolutePath
else
home.parentFile.absolutePath
}
val hostCompilerArgsForJni = listOf("", HostManager.jniHostPlatformIncludeDir).map { "-I$jdkDir/include/$it" }.toTypedArray()
val clangArgs = (commonClangArgs + specificClangArgs).toTypedArray()
val clangArgsForKonanSources =
clangArgs + clangArgsSpecificForKonanSources
val targetLibclangArgs: List<String> =
// libclang works not exactly the same way as the clang binary and
// (in particular) uses different default header search path.
// See e.g. http://lists.llvm.org/pipermail/cfe-dev/2013-November/033680.html
// We workaround the problem with -isystem flag below.
listOf("-isystem", "$absoluteLlvmHome/lib/clang/$llvmVersion/include", *clangArgs)
private val targetClangCmd
= listOf("${absoluteLlvmHome}/bin/clang") + clangArgs
private val targetClangXXCmd
= listOf("${absoluteLlvmHome}/bin/clang++") + clangArgs
fun clangC(vararg userArgs: String) = targetClangCmd + userArgs.asList()
fun clangCXX(vararg userArgs: String) = targetClangXXCmd + userArgs.asList()
companion object {
@JvmStatic
fun filterGradleNativeSoftwareFlags(args: MutableList<String>) {
args.remove("/usr/include") // HACK: over gradle-4.4.
args.remove("-nostdinc") // HACK: over gradle-5.1.
when (HostManager.host) {
KonanTarget.LINUX_X64 -> args.remove("/usr/include/x86_64-linux-gnu") // HACK: over gradle-4.4.
KonanTarget.MACOS_X64 -> {
val indexToRemove = args.indexOf(args.find { it.contains("MacOSX.platform")}) // HACK: over gradle-4.7.
if (indexToRemove != -1) {
args.removeAt(indexToRemove - 1) // drop -I.
args.removeAt(indexToRemove - 1) // drop /Application/Xcode.app/...
}
}
}
}
}
}
| shared/src/main/kotlin/org/jetbrains/kotlin/konan/target/ClangArgs.kt | 3035212731 |
// 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.idea.maven.config
import com.intellij.openapi.fileTypes.LanguageFileType
import com.intellij.openapi.fileTypes.PlainTextLanguage
import icons.OpenapiIcons.RepositoryLibraryLogo
import org.jetbrains.idea.maven.project.MavenProjectBundle
import javax.swing.Icon
class MavenConfigFileType private constructor(): LanguageFileType(PlainTextLanguage.INSTANCE, true) {
override fun getName(): String {
return "MavenConfig"
}
override fun getDescription(): String = MavenProjectBundle.message("filetype.maven.config.description")
override fun getDisplayName(): String = MavenProjectBundle.message("filetype.maven.config.display.name")
override fun getDefaultExtension(): String {
return "config"
}
override fun getIcon(): Icon? {
return RepositoryLibraryLogo
}
}
| plugins/maven/src/main/java/org/jetbrains/idea/maven/config/MavenConfigFileType.kt | 3207978037 |
// 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.documentation.mdn
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.core.TreeNode
import com.fasterxml.jackson.databind.DeserializationContext
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.JsonDeserializer
import com.fasterxml.jackson.databind.annotation.JsonDeserialize
import com.fasterxml.jackson.databind.node.ObjectNode
import com.fasterxml.jackson.databind.node.TextNode
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import com.github.benmanes.caffeine.cache.Caffeine
import com.github.benmanes.caffeine.cache.LoadingCache
import com.intellij.lang.documentation.DocumentationMarkup
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.text.StringUtil.capitalize
import com.intellij.openapi.util.text.StringUtil.toLowerCase
import com.intellij.psi.PsiElement
import com.intellij.psi.impl.source.html.dtd.HtmlSymbolDeclaration
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.xml.*
import com.intellij.util.castSafelyTo
import com.intellij.xml.psi.XmlPsiBundle
import com.intellij.xml.util.HtmlUtil
import java.util.*
import java.util.concurrent.TimeUnit
import java.util.function.Consumer
import kotlin.text.Regex.Companion.escapeReplacement
fun getJsMdnDocumentation(namespace: MdnApiNamespace, qualifiedName: String): MdnSymbolDocumentation? {
assert(namespace == MdnApiNamespace.WebApi || namespace == MdnApiNamespace.GlobalObjects)
val mdnQualifiedName = qualifiedName.let {
when {
it.startsWith("HTMLDocument") -> it.removePrefix("HTML")
it.contains('.') -> it.replace("Constructor", "")
it.endsWith("Constructor") -> "$it.$it"
else -> it
}
}.lowercase(Locale.US).let { webApiIndex[it] ?: it }
val jsNamespace = qualifiedName.takeWhile { it != '.' }
if (jsNamespace.endsWith("EventMap")) {
getDomEventDocumentation(qualifiedName.substring(jsNamespace.length + 1))?.let { return it }
}
val documentation = documentationCache[
Pair(namespace, if (namespace == MdnApiNamespace.WebApi) getWebApiFragment(mdnQualifiedName) else null)
] as? MdnJsDocumentation ?: return null
return documentation.symbols[mdnQualifiedName]
?.let { MdnSymbolDocumentationAdapter(mdnQualifiedName, documentation, it) }
?: qualifiedName.takeIf { it.startsWith("CSSStyleDeclaration.") }
?.let { getCssMdnDocumentation(it.substring("CSSStyleDeclaration.".length).toKebabCase(), MdnCssSymbolKind.Property) }
}
fun getDomEventDocumentation(name: String): MdnSymbolDocumentation? =
innerGetEventDoc(name)?.let { MdnSymbolDocumentationAdapter(name, it.first, it.second) }
fun getCssMdnDocumentation(name: String, kind: MdnCssSymbolKind): MdnSymbolDocumentation? {
val documentation = documentationCache[Pair(MdnApiNamespace.Css, null)] as? MdnCssDocumentation ?: return null
return kind.getSymbolDoc(documentation, name) ?: getUnprefixedName(name)?.let { kind.getSymbolDoc(documentation, it) }
}
fun getHtmlMdnDocumentation(element: PsiElement, context: XmlTag?): MdnSymbolDocumentation? {
var symbolName: String? = null
return when {
// Directly from the file
element is XmlTag && !element.containingFile.name.endsWith(".xsd", true) -> {
symbolName = element.localName
getTagDocumentation(getHtmlApiNamespace(element.namespace, element, toLowerCase(symbolName)), toLowerCase(symbolName))
}
// TODO support special documentation for attribute values
element is XmlAttribute || element is XmlAttributeValue -> {
PsiTreeUtil.getParentOfType(element, XmlAttribute::class.java, false)?.let { attr ->
symbolName = attr.localName
getAttributeDocumentation(getHtmlApiNamespace(attr.namespace, attr, toLowerCase(symbolName)),
attr.parent.localName, toLowerCase(symbolName))
}
}
else -> {
var isTag = true
when (element) {
// XSD
is XmlTag -> {
element.metaData?.let { metaData ->
isTag = element.localName == "element"
symbolName = metaData.name
}
}
// DTD
is XmlElementDecl -> {
symbolName = element.name
}
is XmlAttributeDecl -> {
isTag = false
symbolName = element.nameElement.text
}
is HtmlSymbolDeclaration -> {
isTag = element.kind == HtmlSymbolDeclaration.Kind.ELEMENT
symbolName = element.name
}
}
symbolName?.let {
val lcName = toLowerCase(it)
val namespace = getHtmlApiNamespace(context?.namespace, context, lcName)
if (isTag) {
getTagDocumentation(namespace, lcName)
}
else {
getAttributeDocumentation(namespace, context?.localName?.let(::toLowerCase), lcName)
}
}
}
}
?.takeIf { symbolName != null }
?.let { (source, doc) ->
MdnSymbolDocumentationAdapter(if (context?.isCaseSensitive == true) symbolName!! else toLowerCase(symbolName!!), source, doc)
}
}
fun getHtmlMdnTagDocumentation(namespace: MdnApiNamespace, tagName: String): MdnSymbolDocumentation? {
assert(namespace == MdnApiNamespace.Html || namespace == MdnApiNamespace.MathML || namespace == MdnApiNamespace.Svg)
return getTagDocumentation(namespace, tagName)?.let { (source, doc) ->
MdnSymbolDocumentationAdapter(tagName, source, doc)
}
}
fun getHtmlMdnAttributeDocumentation(namespace: MdnApiNamespace,
tagName: String?,
attributeName: String): MdnSymbolDocumentation? {
assert(namespace == MdnApiNamespace.Html || namespace == MdnApiNamespace.MathML || namespace == MdnApiNamespace.Svg)
return getAttributeDocumentation(namespace, tagName, attributeName)?.let { (source, doc) ->
MdnSymbolDocumentationAdapter(attributeName, source, doc)
}
}
private fun getTagDocumentation(namespace: MdnApiNamespace, tagName: String): Pair<MdnHtmlDocumentation, MdnHtmlElementDocumentation>? {
val documentation = documentationCache[Pair(namespace, null)] as? MdnHtmlDocumentation ?: return null
return documentation.tags[tagName.let { documentation.tagAliases[it] ?: it }]?.let { Pair(documentation, it) }
}
private fun getAttributeDocumentation(namespace: MdnApiNamespace,
tagName: String?,
attributeName: String): Pair<MdnDocumentation, MdnRawSymbolDocumentation>? {
val documentation = documentationCache[Pair(namespace, null)] as? MdnHtmlDocumentation ?: return null
return tagName
?.let { name ->
getTagDocumentation(namespace, name)
?.let { (source, tagDoc) ->
tagDoc.attrs?.get(attributeName)
?.let { mergeWithGlobal(it, documentation.attrs[attributeName]) }
?.let { Pair(source, it) }
}
}
?: documentation.attrs[attributeName]?.let { Pair(documentation, it) }
?: attributeName.takeIf { it.startsWith("on") }
?.let { innerGetEventDoc(it.substring(2)) }
}
private fun mergeWithGlobal(tag: MdnHtmlAttributeDocumentation, global: MdnHtmlAttributeDocumentation?): MdnHtmlAttributeDocumentation =
global?.let {
MdnHtmlAttributeDocumentation(
tag.url,
tag.status ?: global.status,
tag.compatibility ?: global.compatibility,
tag.doc ?: global.doc
)
} ?: tag
private fun innerGetEventDoc(eventName: String): Pair<MdnDocumentation, MdnDomEventDocumentation>? =
(documentationCache[Pair(MdnApiNamespace.DomEvents, null)] as MdnDomEventsDocumentation)
.let { Pair(it, it.events[eventName] ?: return@let null) }
interface MdnSymbolDocumentation {
val name: String
val url: String
val isDeprecated: Boolean
val isExperimental: Boolean
val description: String
val sections: Map<String, String>
val footnote: String?
fun getDocumentation(withDefinition: Boolean): @NlsSafe String
fun getDocumentation(withDefinition: Boolean,
additionalSectionsContent: Consumer<java.lang.StringBuilder>?): @NlsSafe String
}
private const val defaultBcdContext = "default_context"
class MdnSymbolDocumentationAdapter(override val name: String,
private val source: MdnDocumentation,
private val doc: MdnRawSymbolDocumentation) : MdnSymbolDocumentation {
override val url: String
get() = fixMdnUrls(doc.url, source.lang)
override val isDeprecated: Boolean
get() = doc.status?.contains(MdnApiStatus.Deprecated) == true
override val isExperimental: Boolean
get() = doc.status?.contains(MdnApiStatus.Experimental) == true
override val description: String
get() = capitalize(doc.doc ?: "").fixUrls()
override val sections: Map<String, String>
get() {
val result = doc.sections.toMutableMap()
if (doc.compatibility != null) {
doc.compatibility!!.entries.forEach { (id, map) ->
val actualId = if (id == defaultBcdContext) "browser_compatibility" else id
val bundleKey = "mdn.documentation.section.compat.$actualId"
val sectionName: String = if (actualId.startsWith("support_of_") && !XmlPsiBundle.hasKey(bundleKey)) {
XmlPsiBundle.message("mdn.documentation.section.compat.support_of", actualId.substring("support_of_".length))
}
else {
XmlPsiBundle.message(bundleKey)
}
result[sectionName] = map.entries
.joinToString(", ") { it.key.displayName + (if (it.value.isNotEmpty()) " " + it.value else "") }
.ifBlank { XmlPsiBundle.message("mdn.documentation.section.compat.supported_by.none") }
}
}
doc.status?.asSequence()
?.filter { it != MdnApiStatus.StandardTrack }
?.map { Pair(XmlPsiBundle.message("mdn.documentation.section.status." + it.name), "") }
?.toMap(result)
return result.map { (key, value) -> Pair(key.fixUrls(), value.fixUrls()) }.toMap()
}
override val footnote: String
get() = "By <a href='${doc.url}/contributors.txt'>Mozilla Contributors</a>, <a href='https://creativecommons.org/licenses/by-sa/2.5/'>CC BY-SA 2.5</a>"
.fixUrls()
override fun getDocumentation(withDefinition: Boolean): String =
getDocumentation(withDefinition, null)
override fun getDocumentation(withDefinition: Boolean,
additionalSectionsContent: Consumer<java.lang.StringBuilder>?) =
buildDoc(this, withDefinition, additionalSectionsContent)
private fun String.fixUrls(): String =
fixMdnUrls(replace(Regex("<a[ \n\t]+href=[ \t]*['\"]#([^'\"]*)['\"]"), "<a href=\"${escapeReplacement(doc.url)}#$1\""),
source.lang)
}
typealias CompatibilityMap = Map<String, Map<MdnJavaScriptRuntime, String>>
interface MdnRawSymbolDocumentation {
val url: String
val status: Set<MdnApiStatus>?
val compatibility: CompatibilityMap?
val doc: String?
val sections: Map<String, String> get() = emptyMap()
}
interface MdnDocumentation {
val lang: String
}
data class MdnHtmlDocumentation(override val lang: String,
val attrs: Map<String, MdnHtmlAttributeDocumentation>,
val tags: Map<String, MdnHtmlElementDocumentation>,
val tagAliases: Map<String, String> = emptyMap()) : MdnDocumentation
data class MdnJsDocumentation(override val lang: String,
val symbols: Map<String, MdnJsSymbolDocumentation>) : MdnDocumentation
data class MdnDomEventsDocumentation(override val lang: String,
val events: Map<String, MdnDomEventDocumentation>) : MdnDocumentation
data class MdnCssDocumentation(override val lang: String,
val atRules: Map<String, MdnCssAtRuleSymbolDocumentation>,
val properties: Map<String, MdnCssPropertySymbolDocumentation>,
val pseudoClasses: Map<String, MdnCssBasicSymbolDocumentation>,
val pseudoElements: Map<String, MdnCssBasicSymbolDocumentation>,
val functions: Map<String, MdnCssBasicSymbolDocumentation>,
val dataTypes: Map<String, MdnCssBasicSymbolDocumentation>) : MdnDocumentation
data class MdnHtmlElementDocumentation(override val url: String,
override val status: Set<MdnApiStatus>?,
@JsonDeserialize(using = CompatibilityMapDeserializer::class)
override val compatibility: CompatibilityMap?,
override val doc: String,
val details: Map<String, String>?,
val attrs: Map<String, MdnHtmlAttributeDocumentation>?) : MdnRawSymbolDocumentation
data class MdnHtmlAttributeDocumentation(override val url: String,
override val status: Set<MdnApiStatus>?,
@JsonDeserialize(using = CompatibilityMapDeserializer::class)
override val compatibility: CompatibilityMap?,
override val doc: String?) : MdnRawSymbolDocumentation
data class MdnDomEventDocumentation(override val url: String,
override val status: Set<MdnApiStatus>?,
@JsonDeserialize(using = CompatibilityMapDeserializer::class)
override val compatibility: CompatibilityMap?,
override val doc: String?) : MdnRawSymbolDocumentation
data class MdnJsSymbolDocumentation(override val url: String,
override val status: Set<MdnApiStatus>?,
@JsonDeserialize(using = CompatibilityMapDeserializer::class)
override val compatibility: CompatibilityMap?,
override val doc: String?,
val parameters: Map<String, String>?,
val returns: String?,
val throws: Map<String, String>?) : MdnRawSymbolDocumentation {
override val sections: Map<String, String>
get() {
val result = mutableMapOf<String, String>()
parameters?.takeIf { it.isNotEmpty() }?.let {
result.put(XmlPsiBundle.message("mdn.documentation.section.parameters"), buildSubSection(it))
}
returns?.let { result.put(XmlPsiBundle.message("mdn.documentation.section.returns"), it) }
throws?.takeIf { it.isNotEmpty() }?.let {
result.put(XmlPsiBundle.message("mdn.documentation.section.throws"), buildSubSection(it))
}
return result
}
}
data class MdnCssBasicSymbolDocumentation(override val url: String,
override val status: Set<MdnApiStatus>?,
@JsonDeserialize(using = CompatibilityMapDeserializer::class)
override val compatibility: CompatibilityMap?,
override val doc: String?) : MdnRawSymbolDocumentation
data class MdnCssAtRuleSymbolDocumentation(override val url: String,
override val status: Set<MdnApiStatus>?,
@JsonDeserialize(using = CompatibilityMapDeserializer::class)
override val compatibility: CompatibilityMap?,
override val doc: String?,
val properties: Map<String, MdnCssPropertySymbolDocumentation>?) : MdnRawSymbolDocumentation
data class MdnCssPropertySymbolDocumentation(override val url: String,
override val status: Set<MdnApiStatus>?,
@JsonDeserialize(using = CompatibilityMapDeserializer::class)
override val compatibility: CompatibilityMap?,
override val doc: String?,
val formalSyntax: String?,
val values: Map<String, String>?) : MdnRawSymbolDocumentation {
override val sections: Map<String, String>
get() {
val result = mutableMapOf<String, String>()
formalSyntax?.takeIf { it.isNotEmpty() }?.let {
result.put(XmlPsiBundle.message("mdn.documentation.section.syntax"), "<pre><code>$it</code></pre>")
}
values?.takeIf { it.isNotEmpty() }?.let {
result.put(XmlPsiBundle.message("mdn.documentation.section.values"), buildSubSection(values))
}
return result
}
}
enum class MdnApiNamespace {
Html,
Svg,
MathML,
WebApi,
GlobalObjects,
DomEvents,
Css
}
enum class MdnApiStatus {
Experimental,
StandardTrack,
Deprecated
}
enum class MdnJavaScriptRuntime(displayName: String? = null, mdnId: String? = null, val firstVersion: String = "1") {
Chrome,
ChromeAndroid(displayName = "Chrome Android", mdnId = "chrome_android", firstVersion = "18"),
Edge(firstVersion = "12"),
Firefox,
IE,
Opera,
Safari,
SafariIOS(displayName = "Safari iOS", mdnId = "safari_ios"),
Nodejs(displayName = "Node.js", firstVersion = "0.10.0");
val mdnId: String = mdnId ?: toLowerCase(name)
val displayName: String = displayName ?: name
}
enum class MdnCssSymbolKind {
AtRule {
override fun decorateName(name: String): String = "@$name"
override fun getDocumentationMap(documentation: MdnCssDocumentation): Map<String, MdnRawSymbolDocumentation> = documentation.atRules
},
Property {
override fun decorateName(name: String): String = name
override fun getDocumentationMap(documentation: MdnCssDocumentation): Map<String, MdnRawSymbolDocumentation> = documentation.properties
override fun getSymbolDoc(documentation: MdnCssDocumentation, name: String): MdnSymbolDocumentation? {
if (name.startsWith("@")) {
val atRule = name.takeWhile { it != '.' }.substring(1).lowercase(Locale.US)
val propertyName = name.takeLastWhile { it != '.' }.lowercase(Locale.US)
documentation.atRules[atRule]?.properties?.get(propertyName)?.let {
return MdnSymbolDocumentationAdapter(name, documentation, it)
}
return super.getSymbolDoc(documentation, propertyName)
}
return super.getSymbolDoc(documentation, name)
}
},
PseudoClass {
override fun decorateName(name: String): String = ":$name"
override fun getDocumentationMap(documentation: MdnCssDocumentation): Map<String, MdnRawSymbolDocumentation> = documentation.pseudoClasses
override fun getSymbolDoc(documentation: MdnCssDocumentation, name: String): MdnSymbolDocumentation? =
// In case of pseudo class query we should fallback to pseudo element
super.getSymbolDoc(documentation, name) ?: PseudoElement.getSymbolDoc(documentation, name)
},
PseudoElement {
override fun decorateName(name: String): String = "::$name"
override fun getDocumentationMap(documentation: MdnCssDocumentation): Map<String, MdnRawSymbolDocumentation> = documentation.pseudoElements
},
Function {
override fun decorateName(name: String): String = "$name()"
override fun getDocumentationMap(documentation: MdnCssDocumentation): Map<String, MdnRawSymbolDocumentation> = documentation.functions
},
DataType {
override fun decorateName(name: String): String = name
override fun getDocumentationMap(documentation: MdnCssDocumentation): Map<String, MdnRawSymbolDocumentation> = documentation.dataTypes
}, ;
protected abstract fun getDocumentationMap(documentation: MdnCssDocumentation): Map<String, MdnRawSymbolDocumentation>
protected abstract fun decorateName(name: String): String
open fun getSymbolDoc(documentation: MdnCssDocumentation, name: String): MdnSymbolDocumentation? =
getDocumentationMap(documentation)[name.lowercase(Locale.US)]?.let {
MdnSymbolDocumentationAdapter(decorateName(name), documentation, it)
}
}
val webApiFragmentStarts = arrayOf('a', 'e', 'l', 'r', 'u')
private class CompatibilityMapDeserializer : JsonDeserializer<CompatibilityMap>() {
override fun deserialize(p: JsonParser, ctxt: DeserializationContext): CompatibilityMap =
p.readValueAsTree<TreeNode>()
.castSafelyTo<ObjectNode>()
?.let {
if (it.firstOrNull() is ObjectNode) {
it.fields().asSequence()
.map { (key, value) -> Pair(key, (value as ObjectNode).toBcdMap()) }
.toMap()
}
else {
mapOf(Pair(defaultBcdContext, it.toBcdMap()))
}
}
?: emptyMap()
private fun ObjectNode.toBcdMap(): Map<MdnJavaScriptRuntime, String> =
this.fields().asSequence().map { (key, value) ->
Pair(MdnJavaScriptRuntime.valueOf(key), (value as TextNode).asText())
}.toMap()
}
private fun getWebApiFragment(name: String): Char =
webApiFragmentStarts.findLast { it <= name[0].lowercaseChar() }!!
private const val MDN_DOCS_URL_PREFIX = "\$MDN_URL\$"
private val documentationCache: LoadingCache<Pair<MdnApiNamespace, Char?>, MdnDocumentation> = Caffeine.newBuilder()
.expireAfterAccess(10, TimeUnit.MINUTES)
.build { (namespace, segment) -> loadDocumentation(namespace, segment) }
private val webApiIndex: Map<String, String> by lazy {
MdnHtmlDocumentation::class.java.getResource("WebApi-index.json")!!
.let { jacksonObjectMapper().disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES).readValue(it) }
}
private fun fixMdnUrls(content: String, lang: String): String =
content.replace("$MDN_DOCS_URL_PREFIX/", "https://developer.mozilla.org/$lang/docs/")
.replace(MDN_DOCS_URL_PREFIX, "https://developer.mozilla.org/$lang/docs")
fun getHtmlApiNamespace(namespace: String?, element: PsiElement?, symbolName: String): MdnApiNamespace =
when {
symbolName.equals("svg", true) -> MdnApiNamespace.Svg
symbolName.equals("math", true) -> MdnApiNamespace.MathML
namespace == HtmlUtil.SVG_NAMESPACE -> MdnApiNamespace.Svg
namespace == HtmlUtil.MATH_ML_NAMESPACE -> MdnApiNamespace.MathML
else -> PsiTreeUtil.findFirstParent(element, false) { parent ->
parent is XmlTag && parent.localName.lowercase(Locale.US).let { it == "svg" || it == "math" }
}?.castSafelyTo<XmlTag>()?.let {
when (it.name.lowercase(Locale.US)) {
"svg" -> MdnApiNamespace.Svg
"math" -> MdnApiNamespace.MathML
else -> null
}
} ?: MdnApiNamespace.Html
}
private fun loadDocumentation(namespace: MdnApiNamespace, segment: Char?): MdnDocumentation =
loadDocumentation(namespace, segment, when (namespace) {
MdnApiNamespace.Css -> MdnCssDocumentation::class.java
MdnApiNamespace.WebApi, MdnApiNamespace.GlobalObjects -> MdnJsDocumentation::class.java
MdnApiNamespace.DomEvents -> MdnDomEventsDocumentation::class.java
else -> MdnHtmlDocumentation::class.java
})
private fun <T : MdnDocumentation> loadDocumentation(namespace: MdnApiNamespace, segment: Char?, clazz: Class<T>): T =
MdnHtmlDocumentation::class.java.getResource("${namespace.name}${segment?.let { "-$it" } ?: ""}.json")!!
.let { jacksonObjectMapper().disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES).readValue(it, clazz) }
private fun buildDoc(doc: MdnSymbolDocumentation,
withDefinition: Boolean,
additionalSectionsContent: Consumer<java.lang.StringBuilder>?): @NlsSafe String {
val buf = StringBuilder()
if (withDefinition)
buf.append(DocumentationMarkup.DEFINITION_START)
.append(doc.name)
.append(DocumentationMarkup.DEFINITION_END)
.append("\n")
buf.append(DocumentationMarkup.CONTENT_START)
.append(doc.description)
.append(DocumentationMarkup.CONTENT_END)
val sections = doc.sections
if (sections.isNotEmpty() || additionalSectionsContent != null) {
buf.append("\n")
.append(DocumentationMarkup.SECTIONS_START)
for (entry in sections) {
buf.append("\n")
.append(DocumentationMarkup.SECTION_HEADER_START)
.append(entry.key)
if (entry.value.isNotEmpty()) {
if (!entry.key.endsWith(":"))
buf.append(':')
buf.append(DocumentationMarkup.SECTION_SEPARATOR)
.append(entry.value)
}
buf.append(DocumentationMarkup.SECTION_END)
}
additionalSectionsContent?.accept(buf)
buf.append(DocumentationMarkup.SECTIONS_END)
}
buf.append("\n")
.append(DocumentationMarkup.CONTENT_START)
.append(doc.footnote)
.append(DocumentationMarkup.CONTENT_END)
.append("\n")
// Expand MDN URL prefix and fix relative "#" references to point to external MDN docs
return buf.toString()
}
fun buildSubSection(items: Map<String, String>): String {
val result = StringBuilder()
items.forEach { (name, doc) ->
result.append("<p><code>")
.append(name)
.append("</code> – ")
.append(doc)
.append("<br><span style='font-size:0.2em'> </span>\n")
}
return result.toString()
}
private fun getUnprefixedName(name: String): String? {
if (name.length < 4 || name[0] != '-' || name[1] == '-') return null
val index = name.indexOf('-', 2)
return if (index < 0 || index == name.length - 1) null else name.substring(index + 1)
}
private val UPPER_CASE = Regex("(?=\\p{Upper})")
private fun String.toKebabCase() =
this.split(UPPER_CASE).joinToString("-") { it.lowercase(Locale.US) }
| xml/xml-psi-impl/src/com/intellij/documentation/mdn/MdnDocumentation.kt | 1942929000 |
// FIR_IDENTICAL
// FIR_COMPARISON
package testing
fun testTop() {
}
class TestSample() {
fun main(args : Array<String>) {
val testVar = ""
test<caret>.testFun()
}
fun testFun() {
}
}
// INVOCATION_COUNT: 2
// EXIST: testVar, testFun, testTop | plugins/kotlin/completion/tests/testData/basic/common/BeforeDotInCall.kt | 3341644324 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:RestrictTo(RestrictTo.Scope.LIBRARY)
package androidx.health.connect.client.impl.converters.records
import androidx.annotation.RestrictTo
import androidx.health.connect.client.records.metadata.Device
import androidx.health.connect.client.records.metadata.DeviceTypes
val DEVICE_TYPE_STRING_TO_INT_MAP =
mapOf(
DeviceTypes.UNKNOWN to Device.TYPE_UNKNOWN,
DeviceTypes.CHEST_STRAP to Device.TYPE_CHEST_STRAP,
DeviceTypes.FITNESS_BAND to Device.TYPE_FITNESS_BAND,
DeviceTypes.HEAD_MOUNTED to Device.TYPE_HEAD_MOUNTED,
DeviceTypes.PHONE to Device.TYPE_PHONE,
DeviceTypes.RING to Device.TYPE_RING,
DeviceTypes.SCALE to Device.TYPE_SCALE,
DeviceTypes.SMART_DISPLAY to Device.TYPE_SMART_DISPLAY,
DeviceTypes.WATCH to Device.TYPE_WATCH
)
val DEVICE_TYPE_INT_TO_STRING_MAP: Map<Int, String> =
DEVICE_TYPE_STRING_TO_INT_MAP.entries.associate { it.value to it.key }
| health/connect/connect-client/src/main/java/androidx/health/connect/client/impl/converters/records/DeviceTypeConverters.kt | 4076609050 |
/*
* Copyright 2020 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.app.playhvz
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import androidx.test.rule.ActivityTestRule
import com.app.playhvz.firebase.constants.GamePath
import com.app.playhvz.firebase.constants.PlayerPath
import com.app.playhvz.firebase.firebaseprovider.FirebaseProvider
import com.app.playhvz.screens.MainActivity
import com.app.playhvz.testutils.PlayHvzTestHelper
import com.app.playhvz.testutils.TestUtil
import com.app.playhvz.testutils.firebase.FirebaseTestUtil
import com.app.playhvz.testutils.firebase.MockAuthManager
import com.app.playhvz.testutils.firebase.MockDatabaseManager
import com.google.firebase.firestore.Query
import com.google.firebase.firestore.QueryDocumentSnapshot
import com.google.firebase.firestore.QuerySnapshot
import io.mockk.every
import io.mockk.mockkClass
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@LargeTest
class JoinGameEspressoTest {
@get:Rule
val activityRule =
ActivityTestRule(MainActivity::class.java, true, /* launchActivity= */ false)
private val helper: PlayHvzTestHelper = PlayHvzTestHelper()
private var mockAuthManager: MockAuthManager? = null
private var mockDatabaseManager: MockDatabaseManager? = null
@Before
fun setup() {
helper.initializeTestEnvironment()
mockAuthManager = MockAuthManager(FirebaseProvider.getFirebaseAuth())
mockDatabaseManager = MockDatabaseManager(FirebaseProvider.getFirebaseFirestore())
mockAuthManager!!.useSignedInUser()
mockDatabaseManager!!.initializePassingVersionCodeCheck()
mockDatabaseManager!!.initilizeCollectionMocks()
// Initialize empty game lists
val mockAdminQuery = mockkClass(Query::class)
val mockAdminQuerySnapshot = mockkClass(QuerySnapshot::class)
val adminGameResultList: MutableList<QueryDocumentSnapshot> =
mutableListOf()
every {
mockDatabaseManager!!.collectionMap!![GamePath.GAME_COLLECTION_PATH]!!.whereEqualTo(
any<String>(),
mockAuthManager!!.USER_ID
)
} returns mockAdminQuery
every { mockAdminQuerySnapshot.documents } returns mutableListOf()
every { mockAdminQuerySnapshot.iterator() } answers {
return@answers adminGameResultList.iterator()
}
FirebaseTestUtil.onAddQuerySnapshotListener(mockAdminQuery, mockAdminQuerySnapshot)
val mockPlayerQuery = mockkClass(Query::class)
val mockPlayerQuerySnapshot = mockkClass(QuerySnapshot::class)
val playerGameResultList: MutableList<QueryDocumentSnapshot> =
mutableListOf()
every {
mockDatabaseManager!!.collectionMap!![PlayerPath.PLAYER_COLLECTION_PATH]!!.whereEqualTo(
any<String>(),
mockAuthManager!!.USER_ID
)
} returns mockPlayerQuery
every {
mockDatabaseManager!!.collectionMap!![GamePath.GAME_COLLECTION_PATH]!!.whereEqualTo(
any<String>(),
mockAuthManager!!.USER_ID
)
} returns mockPlayerQuery
every { mockPlayerQuerySnapshot.documents } returns mutableListOf()
every { mockPlayerQuerySnapshot.iterator() } answers {
return@answers playerGameResultList.iterator()
}
FirebaseTestUtil.onAddQuerySnapshotListener(mockPlayerQuery, mockPlayerQuerySnapshot)
}
@After
fun tearDown() {
helper.tearDownTestEnvironment()
}
@Test
fun whenNoGames_showsEmptyGameView() {
startApp()
TestUtil.pauseForDebugging()
onView(withId(R.id.empty_game_list_view)).check(matches(isDisplayed()))
}
@Test
fun whenNoGames_clicksJoinGame_opensDialog() {
startApp()
onView(withId(R.id.join_button)).perform(click())
onView(withId(R.id.editText)).check(matches(isDisplayed()))
}
/* @Test
fun whenNoGames_clicksJoinGame_callsFirebaseToJoinGame() {
val gameName = "Test Game"
val gameId = "game1234"
// Allow for joining game
val mockGameQuery = mockkClass(Query::class)
val mockGameTask: Task<QuerySnapshot> = mockk<Task<QuerySnapshot>>()
val mockGameQuerySnapshot = mockkClass(QuerySnapshot::class)
val mockGame = mockkClass(DocumentSnapshot::class)
every {
mockDatabaseManager!!.collectionMap!![GamePath.GAME_COLLECTION_PATH]!!.whereEqualTo(
GAME_FIELD__NAME,
gameName
)
} returns mockGameQuery
every { mockGameQuery.get() } returns mockGameTask
FirebaseTestUtil.onTaskAddSnapshotListener(mockGameTask, mockGameQuerySnapshot)
every { mockGame.id } returns gameId
// fail fast, we just want to verify we got to this point then end the test.
every { mockGameQuerySnapshot.isEmpty } returns true
startApp()
onView(withId(R.id.join_button)).perform(click())
onView(withId(R.id.gameNameText)).perform(typeText(gameName))
TestUtil.pauseForDebugging()
onView(withText(android.R.string.ok)).perform(click())
TestUtil.pauseForDebugging()
verify(exactly = 1) { mockGameTask.addOnSuccessListener(any()) }
}
*/
private fun startApp() {
activityRule.launchActivity(null)
}
} | Android/ghvzApp/app/src/androidTest/java/com/app/playhvz/JoinGameEspressoTest.kt | 2226859616 |
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.navigation
import android.net.Uri
import androidx.navigation.test.nullableStringArgument
import androidx.test.filters.SmallTest
import com.google.common.truth.Truth.assertThat
import com.google.common.truth.Truth.assertWithMessage
import org.junit.Test
@SmallTest
class NavGraphAndroidTest {
companion object {
const val DESTINATION_ID = 1
const val DESTINATION_ROUTE = "destination_route"
const val DESTINATION_LABEL = "test_label"
const val GRAPH_ID = 2
const val GRAPH_ROUTE = "graph_route"
const val GRAPH_LABEL = "graph_label"
}
@Test
fun matchDeepLink() {
val navigatorProvider = NavigatorProvider().apply {
addNavigator(NavGraphNavigator(this))
}
val graph = navigatorProvider.getNavigator(NavGraphNavigator::class.java)
.createDestination()
val idArgument = NavArgument.Builder()
.setType(NavType.IntType)
.build()
graph.addArgument("id", idArgument)
graph.addDeepLink("www.example.com/users/{id}")
val match = graph.matchDeepLink(
Uri.parse("https://www.example.com/users/43")
)
assertWithMessage("Deep link should match")
.that(match)
.isNotNull()
assertWithMessage("Deep link should extract id argument correctly")
.that(match?.matchingArgs?.getInt("id"))
.isEqualTo(43)
}
@Test
fun matchDeepLinkBestMatchExact() {
val navigatorProvider = NavigatorProvider().apply {
addNavigator(NavGraphNavigator(this))
}
val graph = navigatorProvider.getNavigator(NavGraphNavigator::class.java)
.createDestination()
graph.addDeepLink("www.example.com/users/index.html")
graph.addArgument("id", nullableStringArgument(null))
graph.addDeepLink("www.example.com/users/{id}")
val match = graph.matchDeepLink(
Uri.parse("https://www.example.com/users/index.html")
)
assertWithMessage("Deep link should match")
.that(match)
.isNotNull()
assertWithMessage("Deep link should pick the exact match")
.that(match?.matchingArgs?.size())
.isEqualTo(0)
}
@Test
fun matchDotStar() {
val navigatorProvider = NavigatorProvider().apply {
addNavigator(NavGraphNavigator(this))
}
val graph = navigatorProvider.getNavigator(NavGraphNavigator::class.java)
.createDestination()
graph.addDeepLink("www.example.com/.*")
graph.addDeepLink("www.example.com/{name}")
val match = graph.matchDeepLink(Uri.parse("https://www.example.com/foo"))
assertWithMessage("Deep link should match")
.that(match)
.isNotNull()
assertWithMessage("Deep link should pick name over .*")
.that(match?.matchingArgs?.size())
.isEqualTo(1)
}
@Test
fun matchDeepLinkBestMatch() {
val navigatorProvider = NavigatorProvider().apply {
addNavigator(NavGraphNavigator(this))
}
val graph = navigatorProvider.getNavigator(NavGraphNavigator::class.java)
.createDestination()
val idArgument = NavArgument.Builder()
.setType(NavType.IntType)
.build()
graph.addArgument("id", idArgument)
graph.addDeepLink("www.example.com/users/{id}")
val postIdArgument = NavArgument.Builder()
.setType(NavType.IntType)
.build()
graph.addArgument("postId", postIdArgument)
graph.addDeepLink("www.example.com/users/{id}/posts/{postId}")
val match = graph.matchDeepLink(
Uri.parse("https://www.example.com/users/43/posts/99")
)
assertWithMessage("Deep link should match")
.that(match)
.isNotNull()
assertWithMessage("Deep link should pick the argument with more matching arguments")
.that(match?.matchingArgs?.size())
.isEqualTo(2)
assertWithMessage("Deep link should extract id argument correctly")
.that(match?.matchingArgs?.getInt("id"))
.isEqualTo(43)
assertWithMessage("Deep link should extract postId argument correctly")
.that(match?.matchingArgs?.getInt("postId"))
.isEqualTo(99)
}
@Test
fun matchDeepLinkBestMatchPathAndQuery() {
val navigatorProvider = NavigatorProvider().apply {
addNavigator(NavGraphNavigator(this))
}
val graph = navigatorProvider.getNavigator(NavGraphNavigator::class.java)
.createDestination()
graph.addArgument("code", nullableStringArgument(null))
graph.addDeepLink("www.example.com/users?code={code}")
graph.addArgument("id", nullableStringArgument(null))
graph.addDeepLink("www.example.com/users?id={id}")
val match = graph.matchDeepLink(
Uri.parse("https://www.example.com/users?id=1234")
)
assertWithMessage("Deep link should match")
.that(match)
.isNotNull()
assertWithMessage("Deep link should pick the argument with given values")
.that(match?.matchingArgs?.size())
.isEqualTo(1)
assertWithMessage("Deep link should extract id argument correctly")
.that(match?.matchingArgs?.getString("id"))
.isEqualTo("1234")
}
@Test
fun matchDeepLinkBestMatchChildren() {
val navigatorProvider = NavigatorProvider().apply {
addNavigator(NavGraphNavigator(this))
addNavigator(NoOpNavigator())
}
val graph = navigatorProvider.getNavigator(NavGraphNavigator::class.java)
.createDestination()
val userDestination = navigatorProvider.getNavigator(NoOpNavigator::class.java)
.createDestination()
userDestination.id = 1
val idArgument = NavArgument.Builder()
.setType(NavType.IntType)
.build()
userDestination.addArgument("id", idArgument)
userDestination.addDeepLink("www.example.com/users/{id}")
graph.addDestination(userDestination)
val postDestination = navigatorProvider.getNavigator(NoOpNavigator::class.java)
.createDestination()
postDestination.id = 2
val postIdArgument = NavArgument.Builder()
.setType(NavType.IntType)
.build()
postDestination.addArgument("id", idArgument)
postDestination.addArgument("postId", postIdArgument)
postDestination.addDeepLink("www.example.com/users/{id}/posts/{postId}")
graph.addDestination(postDestination)
val match = graph.matchDeepLink(
Uri.parse("https://www.example.com/users/43/posts/99")
)
assertWithMessage("Deep link should match")
.that(match)
.isNotNull()
assertWithMessage("Deep link should point to correct destination")
.that(match?.destination)
.isSameInstanceAs(postDestination)
assertWithMessage("Deep link should extract id argument correctly")
.that(match?.matchingArgs?.getInt("id"))
.isEqualTo(43)
assertWithMessage("Deep link should extract postId argument correctly")
.that(match?.matchingArgs?.getInt("postId"))
.isEqualTo(99)
}
@Test
fun toStringStartDestIdOnly() {
val navigatorProvider = NavigatorProvider().apply {
addNavigator(NavGraphNavigator(this))
addNavigator(NoOpNavigator())
}
val graph = navigatorProvider.getNavigator(NavGraphNavigator::class.java)
.createDestination().apply {
id = GRAPH_ID
label = GRAPH_LABEL
setStartDestination(DESTINATION_ID)
}
val expected = "NavGraph(0x${GRAPH_ID.toString(16)}) label=$GRAPH_LABEL " +
"startDestination=0x${DESTINATION_ID.toString(16)}"
assertThat(graph.toString()).isEqualTo(expected)
}
@Test
fun toStringStartDestRouteOnly() {
val navigatorProvider = NavigatorProvider().apply {
addNavigator(NavGraphNavigator(this))
addNavigator(NoOpNavigator())
}
val graph = navigatorProvider.getNavigator(NavGraphNavigator::class.java)
.createDestination().apply {
route = GRAPH_ROUTE
id = GRAPH_ID
label = GRAPH_LABEL
setStartDestination(DESTINATION_ROUTE)
}
val expected = "NavGraph(0x${GRAPH_ID.toString(16)}) route=$GRAPH_ROUTE " +
"label=$GRAPH_LABEL startDestination=$DESTINATION_ROUTE"
assertThat(graph.toString()).isEqualTo(expected)
}
@Test
fun startDestDisplayNameWithRoute() {
val navigatorProvider = NavigatorProvider().apply {
addNavigator(NavGraphNavigator(this))
addNavigator(NoOpNavigator())
}
val graph = navigatorProvider.getNavigator(NavGraphNavigator::class.java)
.createDestination().apply {
route = GRAPH_ROUTE
id = GRAPH_ID
label = GRAPH_LABEL
setStartDestination(DESTINATION_ROUTE)
}
assertThat(graph.startDestDisplayName).isEqualTo(DESTINATION_ROUTE)
}
@Test
fun toStringStartDestInNodes() {
val navigatorProvider = NavigatorProvider().apply {
addNavigator(NavGraphNavigator(this))
addNavigator(NoOpNavigator())
}
val destination = navigatorProvider.getNavigator(NoOpNavigator::class.java)
.createDestination().apply {
id = DESTINATION_ID
label = DESTINATION_LABEL
}
val graph = navigatorProvider.getNavigator(NavGraphNavigator::class.java)
.createDestination().apply {
id = GRAPH_ID
label = GRAPH_LABEL
setStartDestination(DESTINATION_ID)
addDestination(destination)
}
val expected = "NavGraph(0x${GRAPH_ID.toString(16)}) label=$GRAPH_LABEL " +
"startDestination={NavDestination(0x${DESTINATION_ID.toString(16)}) " +
"label=$DESTINATION_LABEL}"
assertThat(graph.toString()).isEqualTo(expected)
}
@Test
fun toStringStartDestInNodesRoute() {
val navigatorProvider = NavigatorProvider().apply {
addNavigator(NavGraphNavigator(this))
addNavigator(NoOpNavigator())
}
val destination = navigatorProvider.getNavigator(NoOpNavigator::class.java)
.createDestination().apply {
route = DESTINATION_ROUTE
id = DESTINATION_ID
label = DESTINATION_LABEL
}
val graph = navigatorProvider.getNavigator(NavGraphNavigator::class.java)
.createDestination().apply {
route = GRAPH_ROUTE
id = GRAPH_ID
label = GRAPH_LABEL
setStartDestination(DESTINATION_ROUTE)
setStartDestination(DESTINATION_ID)
addDestination(destination)
}
val expected = "NavGraph(0x${GRAPH_ID.toString(16)}) route=$GRAPH_ROUTE " +
"label=$GRAPH_LABEL " +
"startDestination={NavDestination(0x${DESTINATION_ID.toString(16)}) " +
"route=$DESTINATION_ROUTE label=$DESTINATION_LABEL}"
assertThat(graph.toString()).isEqualTo(expected)
}
@Test
fun toStringStartDestInNodesRouteWithStartDestID() {
val navigatorProvider = NavigatorProvider().apply {
addNavigator(NavGraphNavigator(this))
addNavigator(NoOpNavigator())
}
val destination = navigatorProvider.getNavigator(NoOpNavigator::class.java)
.createDestination().apply {
route = DESTINATION_ROUTE
label = DESTINATION_LABEL
}
val graph = navigatorProvider.getNavigator(NavGraphNavigator::class.java)
.createDestination().apply {
route = GRAPH_ROUTE
id = GRAPH_ID
label = GRAPH_LABEL
setStartDestination(DESTINATION_ROUTE)
setStartDestination(DESTINATION_ID)
addDestination(destination)
}
val expected = "NavGraph(0x${GRAPH_ID.toString(16)}) route=$GRAPH_ROUTE " +
"label=$GRAPH_LABEL startDestination=0x${DESTINATION_ID.toString(16)}"
assertThat(graph.toString()).isEqualTo(expected)
}
@Test
fun toStringStartDestInNodesRouteWithID() {
val navigatorProvider = NavigatorProvider().apply {
addNavigator(NavGraphNavigator(this))
addNavigator(NoOpNavigator())
}
val destination = navigatorProvider.getNavigator(NoOpNavigator::class.java)
.createDestination().apply {
route = DESTINATION_ROUTE
id = DESTINATION_ID
label = DESTINATION_LABEL
}
val graph = navigatorProvider.getNavigator(NavGraphNavigator::class.java)
.createDestination().apply {
route = GRAPH_ROUTE
id = GRAPH_ID
label = GRAPH_LABEL
setStartDestination(DESTINATION_ROUTE)
addDestination(destination)
}
val expected = "NavGraph(0x${GRAPH_ID.toString(16)}) route=$GRAPH_ROUTE " +
"label=$GRAPH_LABEL startDestination=$DESTINATION_ROUTE"
assertThat(graph.toString()).isEqualTo(expected)
}
}
| navigation/navigation-common/src/androidTest/java/androidx/navigation/NavGraphAndroidTest.kt | 3022733665 |
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.input.key
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.input.key.Key.Companion.Number
import java.awt.event.KeyEvent
import java.awt.event.KeyEvent.KEY_LOCATION_LEFT
import java.awt.event.KeyEvent.KEY_LOCATION_NUMPAD
import java.awt.event.KeyEvent.KEY_LOCATION_RIGHT
import java.awt.event.KeyEvent.KEY_LOCATION_STANDARD
import androidx.compose.ui.util.unpackInt1
// TODO(demin): implement most of key codes
/**
* Actual implementation of [Key] for Desktop.
*
* @param keyCode an integer code representing the key pressed. Note: This keycode can be used to
* uniquely identify a hardware key. It is different from the native keycode.
*/
@JvmInline
actual value class Key(val keyCode: Long) {
actual companion object {
/** Unknown key. */
@ExperimentalComposeUiApi
actual val Unknown = Key(KeyEvent.VK_UNDEFINED)
/**
* Home key.
*
* This key is handled by the framework and is never delivered to applications.
*/
@ExperimentalComposeUiApi
actual val Home = Key(KeyEvent.VK_HOME)
/** Help key. */
@ExperimentalComposeUiApi
actual val Help = Key(KeyEvent.VK_HELP)
/**
* Up Arrow Key / Directional Pad Up key.
*
* May also be synthesized from trackball motions.
*/
@ExperimentalComposeUiApi
actual val DirectionUp = Key(KeyEvent.VK_UP)
/**
* Down Arrow Key / Directional Pad Down key.
*
* May also be synthesized from trackball motions.
*/
@ExperimentalComposeUiApi
actual val DirectionDown = Key(KeyEvent.VK_DOWN)
/**
* Left Arrow Key / Directional Pad Left key.
*
* May also be synthesized from trackball motions.
*/
@ExperimentalComposeUiApi
actual val DirectionLeft = Key(KeyEvent.VK_LEFT)
/**
* Right Arrow Key / Directional Pad Right key.
*
* May also be synthesized from trackball motions.
*/
@ExperimentalComposeUiApi
actual val DirectionRight = Key(KeyEvent.VK_RIGHT)
/** '0' key. */
@ExperimentalComposeUiApi
actual val Zero = Key(KeyEvent.VK_0)
/** '1' key. */
@ExperimentalComposeUiApi
actual val One = Key(KeyEvent.VK_1)
/** '2' key. */
@ExperimentalComposeUiApi
actual val Two = Key(KeyEvent.VK_2)
/** '3' key. */
@ExperimentalComposeUiApi
actual val Three = Key(KeyEvent.VK_3)
/** '4' key. */
@ExperimentalComposeUiApi
actual val Four = Key(KeyEvent.VK_4)
/** '5' key. */
@ExperimentalComposeUiApi
actual val Five = Key(KeyEvent.VK_5)
/** '6' key. */
@ExperimentalComposeUiApi
actual val Six = Key(KeyEvent.VK_6)
/** '7' key. */
@ExperimentalComposeUiApi
actual val Seven = Key(KeyEvent.VK_7)
/** '8' key. */
@ExperimentalComposeUiApi
actual val Eight = Key(KeyEvent.VK_8)
/** '9' key. */
@ExperimentalComposeUiApi
actual val Nine = Key(KeyEvent.VK_9)
/** '+' key. */
@ExperimentalComposeUiApi
actual val Plus = Key(KeyEvent.VK_PLUS)
/** '-' key. */
@ExperimentalComposeUiApi
actual val Minus = Key(KeyEvent.VK_MINUS)
/** '*' key. */
@ExperimentalComposeUiApi
actual val Multiply = Key(KeyEvent.VK_MULTIPLY)
/** '=' key. */
@ExperimentalComposeUiApi
actual val Equals = Key(KeyEvent.VK_EQUALS)
/** '#' key. */
@ExperimentalComposeUiApi
actual val Pound = Key(KeyEvent.VK_NUMBER_SIGN)
/** 'A' key. */
@ExperimentalComposeUiApi
actual val A = Key(KeyEvent.VK_A)
/** 'B' key. */
@ExperimentalComposeUiApi
actual val B = Key(KeyEvent.VK_B)
/** 'C' key. */
@ExperimentalComposeUiApi
actual val C = Key(KeyEvent.VK_C)
/** 'D' key. */
@ExperimentalComposeUiApi
actual val D = Key(KeyEvent.VK_D)
/** 'E' key. */
@ExperimentalComposeUiApi
actual val E = Key(KeyEvent.VK_E)
/** 'F' key. */
@ExperimentalComposeUiApi
actual val F = Key(KeyEvent.VK_F)
/** 'G' key. */
@ExperimentalComposeUiApi
actual val G = Key(KeyEvent.VK_G)
/** 'H' key. */
@ExperimentalComposeUiApi
actual val H = Key(KeyEvent.VK_H)
/** 'I' key. */
@ExperimentalComposeUiApi
actual val I = Key(KeyEvent.VK_I)
/** 'J' key. */
@ExperimentalComposeUiApi
actual val J = Key(KeyEvent.VK_J)
/** 'K' key. */
@ExperimentalComposeUiApi
actual val K = Key(KeyEvent.VK_K)
/** 'L' key. */
@ExperimentalComposeUiApi
actual val L = Key(KeyEvent.VK_L)
/** 'M' key. */
@ExperimentalComposeUiApi
actual val M = Key(KeyEvent.VK_M)
/** 'N' key. */
@ExperimentalComposeUiApi
actual val N = Key(KeyEvent.VK_N)
/** 'O' key. */
@ExperimentalComposeUiApi
actual val O = Key(KeyEvent.VK_O)
/** 'P' key. */
@ExperimentalComposeUiApi
actual val P = Key(KeyEvent.VK_P)
/** 'Q' key. */
@ExperimentalComposeUiApi
actual val Q = Key(KeyEvent.VK_Q)
/** 'R' key. */
@ExperimentalComposeUiApi
actual val R = Key(KeyEvent.VK_R)
/** 'S' key. */
@ExperimentalComposeUiApi
actual val S = Key(KeyEvent.VK_S)
/** 'T' key. */
@ExperimentalComposeUiApi
actual val T = Key(KeyEvent.VK_T)
/** 'U' key. */
@ExperimentalComposeUiApi
actual val U = Key(KeyEvent.VK_U)
/** 'V' key. */
@ExperimentalComposeUiApi
actual val V = Key(KeyEvent.VK_V)
/** 'W' key. */
@ExperimentalComposeUiApi
actual val W = Key(KeyEvent.VK_W)
/** 'X' key. */
@ExperimentalComposeUiApi
actual val X = Key(KeyEvent.VK_X)
/** 'Y' key. */
@ExperimentalComposeUiApi
actual val Y = Key(KeyEvent.VK_Y)
/** 'Z' key. */
@ExperimentalComposeUiApi
actual val Z = Key(KeyEvent.VK_Z)
/** ',' key. */
@ExperimentalComposeUiApi
actual val Comma = Key(KeyEvent.VK_COMMA)
/** '.' key. */
@ExperimentalComposeUiApi
actual val Period = Key(KeyEvent.VK_PERIOD)
/** Left Alt modifier key. */
@ExperimentalComposeUiApi
actual val AltLeft = Key(KeyEvent.VK_ALT, KEY_LOCATION_LEFT)
/** Right Alt modifier key. */
@ExperimentalComposeUiApi
actual val AltRight = Key(KeyEvent.VK_ALT, KEY_LOCATION_RIGHT)
/** Left Shift modifier key. */
@ExperimentalComposeUiApi
actual val ShiftLeft = Key(KeyEvent.VK_SHIFT, KEY_LOCATION_LEFT)
/** Right Shift modifier key. */
@ExperimentalComposeUiApi
actual val ShiftRight = Key(KeyEvent.VK_SHIFT, KEY_LOCATION_RIGHT)
/** Tab key. */
@ExperimentalComposeUiApi
actual val Tab = Key(KeyEvent.VK_TAB)
/** Space key. */
@ExperimentalComposeUiApi
actual val Spacebar = Key(KeyEvent.VK_SPACE)
/** Enter key. */
@ExperimentalComposeUiApi
actual val Enter = Key(KeyEvent.VK_ENTER)
/**
* Backspace key.
*
* Deletes characters before the insertion point, unlike [Delete].
*/
@ExperimentalComposeUiApi
actual val Backspace = Key(KeyEvent.VK_BACK_SPACE)
/**
* Delete key.
*
* Deletes characters ahead of the insertion point, unlike [Backspace].
*/
@ExperimentalComposeUiApi
actual val Delete = Key(KeyEvent.VK_DELETE)
/** Escape key. */
@ExperimentalComposeUiApi
actual val Escape = Key(KeyEvent.VK_ESCAPE)
/** Left Control modifier key. */
@ExperimentalComposeUiApi
actual val CtrlLeft = Key(KeyEvent.VK_CONTROL, KEY_LOCATION_LEFT)
/** Right Control modifier key. */
@ExperimentalComposeUiApi
actual val CtrlRight = Key(KeyEvent.VK_CONTROL, KEY_LOCATION_RIGHT)
/** Caps Lock key. */
@ExperimentalComposeUiApi
actual val CapsLock = Key(KeyEvent.VK_CAPS_LOCK)
/** Scroll Lock key. */
@ExperimentalComposeUiApi
actual val ScrollLock = Key(KeyEvent.VK_SCROLL_LOCK)
/** Left Meta modifier key. */
@ExperimentalComposeUiApi
actual val MetaLeft = Key(KeyEvent.VK_META, KEY_LOCATION_LEFT)
/** Right Meta modifier key. */
@ExperimentalComposeUiApi
actual val MetaRight = Key(KeyEvent.VK_META, KEY_LOCATION_RIGHT)
/** System Request / Print Screen key. */
@ExperimentalComposeUiApi
actual val PrintScreen = Key(KeyEvent.VK_PRINTSCREEN)
/**
* Insert key.
*
* Toggles insert / overwrite edit mode.
*/
@ExperimentalComposeUiApi
actual val Insert = Key(KeyEvent.VK_INSERT)
/** Cut key. */
@ExperimentalComposeUiApi
actual val Cut = Key(KeyEvent.VK_CUT)
/** Copy key. */
@ExperimentalComposeUiApi
actual val Copy = Key(KeyEvent.VK_COPY)
/** Paste key. */
@ExperimentalComposeUiApi
actual val Paste = Key(KeyEvent.VK_PASTE)
/** '`' (backtick) key. */
@ExperimentalComposeUiApi
actual val Grave = Key(KeyEvent.VK_BACK_QUOTE)
/** '[' key. */
@ExperimentalComposeUiApi
actual val LeftBracket = Key(KeyEvent.VK_OPEN_BRACKET)
/** ']' key. */
@ExperimentalComposeUiApi
actual val RightBracket = Key(KeyEvent.VK_CLOSE_BRACKET)
/** '/' key. */
@ExperimentalComposeUiApi
actual val Slash = Key(KeyEvent.VK_SLASH)
/** '\' key. */
@ExperimentalComposeUiApi
actual val Backslash = Key(KeyEvent.VK_BACK_SLASH)
/** ';' key. */
@ExperimentalComposeUiApi
actual val Semicolon = Key(KeyEvent.VK_SEMICOLON)
/** ''' (apostrophe) key. */
@ExperimentalComposeUiApi
actual val Apostrophe = Key(KeyEvent.VK_QUOTE)
/** '@' key. */
@ExperimentalComposeUiApi
actual val At = Key(KeyEvent.VK_AT)
/** Page Up key. */
@ExperimentalComposeUiApi
actual val PageUp = Key(KeyEvent.VK_PAGE_UP)
/** Page Down key. */
@ExperimentalComposeUiApi
actual val PageDown = Key(KeyEvent.VK_PAGE_DOWN)
/** F1 key. */
@ExperimentalComposeUiApi
actual val F1 = Key(KeyEvent.VK_F1)
/** F2 key. */
@ExperimentalComposeUiApi
actual val F2 = Key(KeyEvent.VK_F2)
/** F3 key. */
@ExperimentalComposeUiApi
actual val F3 = Key(KeyEvent.VK_F3)
/** F4 key. */
@ExperimentalComposeUiApi
actual val F4 = Key(KeyEvent.VK_F4)
/** F5 key. */
@ExperimentalComposeUiApi
actual val F5 = Key(KeyEvent.VK_F5)
/** F6 key. */
@ExperimentalComposeUiApi
actual val F6 = Key(KeyEvent.VK_F6)
/** F7 key. */
@ExperimentalComposeUiApi
actual val F7 = Key(KeyEvent.VK_F7)
/** F8 key. */
@ExperimentalComposeUiApi
actual val F8 = Key(KeyEvent.VK_F8)
/** F9 key. */
@ExperimentalComposeUiApi
actual val F9 = Key(KeyEvent.VK_F9)
/** F10 key. */
@ExperimentalComposeUiApi
actual val F10 = Key(KeyEvent.VK_F10)
/** F11 key. */
@ExperimentalComposeUiApi
actual val F11 = Key(KeyEvent.VK_F11)
/** F12 key. */
@ExperimentalComposeUiApi
actual val F12 = Key(KeyEvent.VK_F12)
/**
* Num Lock key.
*
* This is the Num Lock key; it is different from [Number].
* This key alters the behavior of other keys on the numeric keypad.
*/
@ExperimentalComposeUiApi
actual val NumLock = Key(KeyEvent.VK_NUM_LOCK, KEY_LOCATION_NUMPAD)
/** Numeric keypad '0' key. */
@ExperimentalComposeUiApi
actual val NumPad0 = Key(KeyEvent.VK_NUMPAD0, KEY_LOCATION_NUMPAD)
/** Numeric keypad '1' key. */
@ExperimentalComposeUiApi
actual val NumPad1 = Key(KeyEvent.VK_NUMPAD1, KEY_LOCATION_NUMPAD)
/** Numeric keypad '2' key. */
@ExperimentalComposeUiApi
actual val NumPad2 = Key(KeyEvent.VK_NUMPAD2, KEY_LOCATION_NUMPAD)
/** Numeric keypad '3' key. */
@ExperimentalComposeUiApi
actual val NumPad3 = Key(KeyEvent.VK_NUMPAD3, KEY_LOCATION_NUMPAD)
/** Numeric keypad '4' key. */
@ExperimentalComposeUiApi
actual val NumPad4 = Key(KeyEvent.VK_NUMPAD4, KEY_LOCATION_NUMPAD)
/** Numeric keypad '5' key. */
@ExperimentalComposeUiApi
actual val NumPad5 = Key(KeyEvent.VK_NUMPAD5, KEY_LOCATION_NUMPAD)
/** Numeric keypad '6' key. */
@ExperimentalComposeUiApi
actual val NumPad6 = Key(KeyEvent.VK_NUMPAD6, KEY_LOCATION_NUMPAD)
/** Numeric keypad '7' key. */
@ExperimentalComposeUiApi
actual val NumPad7 = Key(KeyEvent.VK_NUMPAD7, KEY_LOCATION_NUMPAD)
/** Numeric keypad '8' key. */
@ExperimentalComposeUiApi
actual val NumPad8 = Key(KeyEvent.VK_NUMPAD8, KEY_LOCATION_NUMPAD)
/** Numeric keypad '9' key. */
@ExperimentalComposeUiApi
actual val NumPad9 = Key(KeyEvent.VK_NUMPAD9, KEY_LOCATION_NUMPAD)
/** Numeric keypad '/' key (for division). */
@ExperimentalComposeUiApi
actual val NumPadDivide = Key(KeyEvent.VK_DIVIDE, KEY_LOCATION_NUMPAD)
/** Numeric keypad '*' key (for multiplication). */
@ExperimentalComposeUiApi
actual val NumPadMultiply = Key(KeyEvent.VK_MULTIPLY, KEY_LOCATION_NUMPAD)
/** Numeric keypad '-' key (for subtraction). */
@ExperimentalComposeUiApi
actual val NumPadSubtract = Key(KeyEvent.VK_SUBTRACT, KEY_LOCATION_NUMPAD)
/** Numeric keypad '+' key (for addition). */
@ExperimentalComposeUiApi
actual val NumPadAdd = Key(KeyEvent.VK_ADD, KEY_LOCATION_NUMPAD)
/** Numeric keypad '.' key (for decimals or digit grouping). */
@ExperimentalComposeUiApi
actual val NumPadDot = Key(KeyEvent.VK_PERIOD, KEY_LOCATION_NUMPAD)
/** Numeric keypad ',' key (for decimals or digit grouping). */
@ExperimentalComposeUiApi
actual val NumPadComma = Key(KeyEvent.VK_COMMA, KEY_LOCATION_NUMPAD)
/** Numeric keypad Enter key. */
@ExperimentalComposeUiApi
actual val NumPadEnter = Key(KeyEvent.VK_ENTER, KEY_LOCATION_NUMPAD)
/** Numeric keypad '=' key. */
@ExperimentalComposeUiApi
actual val NumPadEquals = Key(KeyEvent.VK_EQUALS, KEY_LOCATION_NUMPAD)
/** Numeric keypad '(' key. */
@ExperimentalComposeUiApi
actual val NumPadLeftParenthesis = Key(KeyEvent.VK_LEFT_PARENTHESIS, KEY_LOCATION_NUMPAD)
/** Numeric keypad ')' key. */
@ExperimentalComposeUiApi
actual val NumPadRightParenthesis = Key(KeyEvent.VK_RIGHT_PARENTHESIS, KEY_LOCATION_NUMPAD)
@ExperimentalComposeUiApi
actual val MoveHome = Key(KeyEvent.VK_HOME)
@ExperimentalComposeUiApi
actual val MoveEnd = Key(KeyEvent.VK_END)
// Unsupported Keys. These keys will never be sent by the desktop. However we need unique
// keycodes so that these constants can be used in a when statement without a warning.
@ExperimentalComposeUiApi
actual val SoftLeft = Key(-1000000001)
@ExperimentalComposeUiApi
actual val SoftRight = Key(-1000000002)
@ExperimentalComposeUiApi
actual val Back = Key(-1000000003)
@ExperimentalComposeUiApi
actual val NavigatePrevious = Key(-1000000004)
@ExperimentalComposeUiApi
actual val NavigateNext = Key(-1000000005)
@ExperimentalComposeUiApi
actual val NavigateIn = Key(-1000000006)
@ExperimentalComposeUiApi
actual val NavigateOut = Key(-1000000007)
@ExperimentalComposeUiApi
actual val SystemNavigationUp = Key(-1000000008)
@ExperimentalComposeUiApi
actual val SystemNavigationDown = Key(-1000000009)
@ExperimentalComposeUiApi
actual val SystemNavigationLeft = Key(-1000000010)
@ExperimentalComposeUiApi
actual val SystemNavigationRight = Key(-1000000011)
@ExperimentalComposeUiApi
actual val Call = Key(-1000000012)
@ExperimentalComposeUiApi
actual val EndCall = Key(-1000000013)
@ExperimentalComposeUiApi
actual val DirectionCenter = Key(-1000000014)
@ExperimentalComposeUiApi
actual val DirectionUpLeft = Key(-1000000015)
@ExperimentalComposeUiApi
actual val DirectionDownLeft = Key(-1000000016)
@ExperimentalComposeUiApi
actual val DirectionUpRight = Key(-1000000017)
@ExperimentalComposeUiApi
actual val DirectionDownRight = Key(-1000000018)
@ExperimentalComposeUiApi
actual val VolumeUp = Key(-1000000019)
@ExperimentalComposeUiApi
actual val VolumeDown = Key(-1000000020)
@ExperimentalComposeUiApi
actual val Power = Key(-1000000021)
@ExperimentalComposeUiApi
actual val Camera = Key(-1000000022)
@ExperimentalComposeUiApi
actual val Clear = Key(-1000000023)
@ExperimentalComposeUiApi
actual val Symbol = Key(-1000000024)
@ExperimentalComposeUiApi
actual val Browser = Key(-1000000025)
@ExperimentalComposeUiApi
actual val Envelope = Key(-1000000026)
@ExperimentalComposeUiApi
actual val Function = Key(-1000000027)
@ExperimentalComposeUiApi
actual val Break = Key(-1000000028)
@ExperimentalComposeUiApi
actual val Number = Key(-1000000031)
@ExperimentalComposeUiApi
actual val HeadsetHook = Key(-1000000032)
@ExperimentalComposeUiApi
actual val Focus = Key(-1000000033)
@ExperimentalComposeUiApi
actual val Menu = Key(-1000000034)
@ExperimentalComposeUiApi
actual val Notification = Key(-1000000035)
@ExperimentalComposeUiApi
actual val Search = Key(-1000000036)
@ExperimentalComposeUiApi
actual val PictureSymbols = Key(-1000000037)
@ExperimentalComposeUiApi
actual val SwitchCharset = Key(-1000000038)
@ExperimentalComposeUiApi
actual val ButtonA = Key(-1000000039)
@ExperimentalComposeUiApi
actual val ButtonB = Key(-1000000040)
@ExperimentalComposeUiApi
actual val ButtonC = Key(-1000000041)
@ExperimentalComposeUiApi
actual val ButtonX = Key(-1000000042)
@ExperimentalComposeUiApi
actual val ButtonY = Key(-1000000043)
@ExperimentalComposeUiApi
actual val ButtonZ = Key(-1000000044)
@ExperimentalComposeUiApi
actual val ButtonL1 = Key(-1000000045)
@ExperimentalComposeUiApi
actual val ButtonR1 = Key(-1000000046)
@ExperimentalComposeUiApi
actual val ButtonL2 = Key(-1000000047)
@ExperimentalComposeUiApi
actual val ButtonR2 = Key(-1000000048)
@ExperimentalComposeUiApi
actual val ButtonThumbLeft = Key(-1000000049)
@ExperimentalComposeUiApi
actual val ButtonThumbRight = Key(-1000000050)
@ExperimentalComposeUiApi
actual val ButtonStart = Key(-1000000051)
@ExperimentalComposeUiApi
actual val ButtonSelect = Key(-1000000052)
@ExperimentalComposeUiApi
actual val ButtonMode = Key(-1000000053)
@ExperimentalComposeUiApi
actual val Button1 = Key(-1000000054)
@ExperimentalComposeUiApi
actual val Button2 = Key(-1000000055)
@ExperimentalComposeUiApi
actual val Button3 = Key(-1000000056)
@ExperimentalComposeUiApi
actual val Button4 = Key(-1000000057)
@ExperimentalComposeUiApi
actual val Button5 = Key(-1000000058)
@ExperimentalComposeUiApi
actual val Button6 = Key(-1000000059)
@ExperimentalComposeUiApi
actual val Button7 = Key(-1000000060)
@ExperimentalComposeUiApi
actual val Button8 = Key(-1000000061)
@ExperimentalComposeUiApi
actual val Button9 = Key(-1000000062)
@ExperimentalComposeUiApi
actual val Button10 = Key(-1000000063)
@ExperimentalComposeUiApi
actual val Button11 = Key(-1000000064)
@ExperimentalComposeUiApi
actual val Button12 = Key(-1000000065)
@ExperimentalComposeUiApi
actual val Button13 = Key(-1000000066)
@ExperimentalComposeUiApi
actual val Button14 = Key(-1000000067)
@ExperimentalComposeUiApi
actual val Button15 = Key(-1000000068)
@ExperimentalComposeUiApi
actual val Button16 = Key(-1000000069)
@ExperimentalComposeUiApi
actual val Forward = Key(-1000000070)
@ExperimentalComposeUiApi
actual val MediaPlay = Key(-1000000071)
@ExperimentalComposeUiApi
actual val MediaPause = Key(-1000000072)
@ExperimentalComposeUiApi
actual val MediaPlayPause = Key(-1000000073)
@ExperimentalComposeUiApi
actual val MediaStop = Key(-1000000074)
@ExperimentalComposeUiApi
actual val MediaRecord = Key(-1000000075)
@ExperimentalComposeUiApi
actual val MediaNext = Key(-1000000076)
@ExperimentalComposeUiApi
actual val MediaPrevious = Key(-1000000077)
@ExperimentalComposeUiApi
actual val MediaRewind = Key(-1000000078)
@ExperimentalComposeUiApi
actual val MediaFastForward = Key(-1000000079)
@ExperimentalComposeUiApi
actual val MediaClose = Key(-1000000080)
@ExperimentalComposeUiApi
actual val MediaAudioTrack = Key(-1000000081)
@ExperimentalComposeUiApi
actual val MediaEject = Key(-1000000082)
@ExperimentalComposeUiApi
actual val MediaTopMenu = Key(-1000000083)
@ExperimentalComposeUiApi
actual val MediaSkipForward = Key(-1000000084)
@ExperimentalComposeUiApi
actual val MediaSkipBackward = Key(-1000000085)
@ExperimentalComposeUiApi
actual val MediaStepForward = Key(-1000000086)
@ExperimentalComposeUiApi
actual val MediaStepBackward = Key(-1000000087)
@ExperimentalComposeUiApi
actual val MicrophoneMute = Key(-1000000088)
@ExperimentalComposeUiApi
actual val VolumeMute = Key(-1000000089)
@ExperimentalComposeUiApi
actual val Info = Key(-1000000090)
@ExperimentalComposeUiApi
actual val ChannelUp = Key(-1000000091)
@ExperimentalComposeUiApi
actual val ChannelDown = Key(-1000000092)
@ExperimentalComposeUiApi
actual val ZoomIn = Key(-1000000093)
@ExperimentalComposeUiApi
actual val ZoomOut = Key(-1000000094)
@ExperimentalComposeUiApi
actual val Tv = Key(-1000000095)
@ExperimentalComposeUiApi
actual val Window = Key(-1000000096)
@ExperimentalComposeUiApi
actual val Guide = Key(-1000000097)
@ExperimentalComposeUiApi
actual val Dvr = Key(-1000000098)
@ExperimentalComposeUiApi
actual val Bookmark = Key(-1000000099)
@ExperimentalComposeUiApi
actual val Captions = Key(-1000000100)
@ExperimentalComposeUiApi
actual val Settings = Key(-1000000101)
@ExperimentalComposeUiApi
actual val TvPower = Key(-1000000102)
@ExperimentalComposeUiApi
actual val TvInput = Key(-1000000103)
@ExperimentalComposeUiApi
actual val SetTopBoxPower = Key(-1000000104)
@ExperimentalComposeUiApi
actual val SetTopBoxInput = Key(-1000000105)
@ExperimentalComposeUiApi
actual val AvReceiverPower = Key(-1000000106)
@ExperimentalComposeUiApi
actual val AvReceiverInput = Key(-1000000107)
@ExperimentalComposeUiApi
actual val ProgramRed = Key(-1000000108)
@ExperimentalComposeUiApi
actual val ProgramGreen = Key(-1000000109)
@ExperimentalComposeUiApi
actual val ProgramYellow = Key(-1000000110)
@ExperimentalComposeUiApi
actual val ProgramBlue = Key(-1000000111)
@ExperimentalComposeUiApi
actual val AppSwitch = Key(-1000000112)
@ExperimentalComposeUiApi
actual val LanguageSwitch = Key(-1000000113)
@ExperimentalComposeUiApi
actual val MannerMode = Key(-1000000114)
@ExperimentalComposeUiApi
actual val Toggle2D3D = Key(-1000000125)
@ExperimentalComposeUiApi
actual val Contacts = Key(-1000000126)
@ExperimentalComposeUiApi
actual val Calendar = Key(-1000000127)
@ExperimentalComposeUiApi
actual val Music = Key(-1000000128)
@ExperimentalComposeUiApi
actual val Calculator = Key(-1000000129)
@ExperimentalComposeUiApi
actual val ZenkakuHankaru = Key(-1000000130)
@ExperimentalComposeUiApi
actual val Eisu = Key(-1000000131)
@ExperimentalComposeUiApi
actual val Muhenkan = Key(-1000000132)
@ExperimentalComposeUiApi
actual val Henkan = Key(-1000000133)
@ExperimentalComposeUiApi
actual val KatakanaHiragana = Key(-1000000134)
@ExperimentalComposeUiApi
actual val Yen = Key(-1000000135)
@ExperimentalComposeUiApi
actual val Ro = Key(-1000000136)
@ExperimentalComposeUiApi
actual val Kana = Key(-1000000137)
@ExperimentalComposeUiApi
actual val Assist = Key(-1000000138)
@ExperimentalComposeUiApi
actual val BrightnessDown = Key(-1000000139)
@ExperimentalComposeUiApi
actual val BrightnessUp = Key(-1000000140)
@ExperimentalComposeUiApi
actual val Sleep = Key(-1000000141)
@ExperimentalComposeUiApi
actual val WakeUp = Key(-1000000142)
@ExperimentalComposeUiApi
actual val SoftSleep = Key(-1000000143)
@ExperimentalComposeUiApi
actual val Pairing = Key(-1000000144)
@ExperimentalComposeUiApi
actual val LastChannel = Key(-1000000145)
@ExperimentalComposeUiApi
actual val TvDataService = Key(-1000000146)
@ExperimentalComposeUiApi
actual val VoiceAssist = Key(-1000000147)
@ExperimentalComposeUiApi
actual val TvRadioService = Key(-1000000148)
@ExperimentalComposeUiApi
actual val TvTeletext = Key(-1000000149)
@ExperimentalComposeUiApi
actual val TvNumberEntry = Key(-1000000150)
@ExperimentalComposeUiApi
actual val TvTerrestrialAnalog = Key(-1000000151)
@ExperimentalComposeUiApi
actual val TvTerrestrialDigital = Key(-1000000152)
@ExperimentalComposeUiApi
actual val TvSatellite = Key(-1000000153)
@ExperimentalComposeUiApi
actual val TvSatelliteBs = Key(-1000000154)
@ExperimentalComposeUiApi
actual val TvSatelliteCs = Key(-1000000155)
@ExperimentalComposeUiApi
actual val TvSatelliteService = Key(-1000000156)
@ExperimentalComposeUiApi
actual val TvNetwork = Key(-1000000157)
@ExperimentalComposeUiApi
actual val TvAntennaCable = Key(-1000000158)
@ExperimentalComposeUiApi
actual val TvInputHdmi1 = Key(-1000000159)
@ExperimentalComposeUiApi
actual val TvInputHdmi2 = Key(-1000000160)
@ExperimentalComposeUiApi
actual val TvInputHdmi3 = Key(-1000000161)
@ExperimentalComposeUiApi
actual val TvInputHdmi4 = Key(-1000000162)
@ExperimentalComposeUiApi
actual val TvInputComposite1 = Key(-1000000163)
@ExperimentalComposeUiApi
actual val TvInputComposite2 = Key(-1000000164)
@ExperimentalComposeUiApi
actual val TvInputComponent1 = Key(-1000000165)
@ExperimentalComposeUiApi
actual val TvInputComponent2 = Key(-1000000166)
@ExperimentalComposeUiApi
actual val TvInputVga1 = Key(-1000000167)
@ExperimentalComposeUiApi
actual val TvAudioDescription = Key(-1000000168)
@ExperimentalComposeUiApi
actual val TvAudioDescriptionMixingVolumeUp = Key(-1000000169)
@ExperimentalComposeUiApi
actual val TvAudioDescriptionMixingVolumeDown = Key(-1000000170)
@ExperimentalComposeUiApi
actual val TvZoomMode = Key(-1000000171)
@ExperimentalComposeUiApi
actual val TvContentsMenu = Key(-1000000172)
@ExperimentalComposeUiApi
actual val TvMediaContextMenu = Key(-1000000173)
@ExperimentalComposeUiApi
actual val TvTimerProgramming = Key(-1000000174)
@ExperimentalComposeUiApi
actual val StemPrimary = Key(-1000000175)
@ExperimentalComposeUiApi
actual val Stem1 = Key(-1000000176)
@ExperimentalComposeUiApi
actual val Stem2 = Key(-1000000177)
@ExperimentalComposeUiApi
actual val Stem3 = Key(-1000000178)
@ExperimentalComposeUiApi
actual val AllApps = Key(-1000000179)
@ExperimentalComposeUiApi
actual val Refresh = Key(-1000000180)
@ExperimentalComposeUiApi
actual val ThumbsUp = Key(-1000000181)
@ExperimentalComposeUiApi
actual val ThumbsDown = Key(-1000000182)
@ExperimentalComposeUiApi
actual val ProfileSwitch = Key(-1000000183)
}
actual override fun toString(): String {
return "Key: ${KeyEvent.getKeyText(nativeKeyCode)}"
}
}
/**
* Creates instance of [Key].
*
* @param nativeKeyCode represents this key as defined in [java.awt.event.KeyEvent]
* @param nativeKeyLocation represents the location of key as defined in [java.awt.event.KeyEvent]
*/
fun Key(nativeKeyCode: Int, nativeKeyLocation: Int = KEY_LOCATION_STANDARD): Key {
// First 32 bits are for keycode.
val keyCode = nativeKeyCode.toLong().shl(32)
// Next 3 bits are for location.
val location = (nativeKeyLocation.toLong() and 0x7).shl(29)
return Key(keyCode or location)
}
/**
* The native keycode corresponding to this [Key].
*/
val Key.nativeKeyCode: Int
get() = unpackInt1(keyCode)
/**
* The native location corresponding to this [Key].
*/
val Key.nativeKeyLocation: Int
get() = (keyCode and 0xFFFFFFFF).shr(29).toInt()
| compose/ui/ui/src/desktopMain/kotlin/androidx/compose/ui/input/key/Key.desktop.kt | 1134802193 |
/*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.annotation
/**
* Denotes that an integer parameter, field or method return value is expected
* to be a color resource reference (e.g. `android.R.color.black`).
*/
@MustBeDocumented
@kotlin.annotation.Retention(AnnotationRetention.BINARY)
@Target(
AnnotationTarget.FUNCTION,
AnnotationTarget.PROPERTY_GETTER,
AnnotationTarget.PROPERTY_SETTER,
AnnotationTarget.VALUE_PARAMETER,
AnnotationTarget.FIELD,
AnnotationTarget.LOCAL_VARIABLE
)
public annotation class ColorRes | annotation/annotation/src/jvmMain/kotlin/androidx/annotation/ColorRes.kt | 2037997636 |
package com.sedsoftware.yaptalker.data.network.thumbnails
import com.sedsoftware.yaptalker.data.repository.thumbnail.data.RutubeData
import io.reactivex.Single
import retrofit2.http.GET
import retrofit2.http.Path
import retrofit2.http.Query
interface RutubeLoader {
@GET("/api/video/{id}")
fun loadThumbnail(@Path("id") id: String, @Query("format") format: String): Single<RutubeData>
}
| data/src/main/java/com/sedsoftware/yaptalker/data/network/thumbnails/RutubeLoader.kt | 2301911377 |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.wear.tiles.testing
import org.junit.runners.model.FrameworkMethod
import org.robolectric.RobolectricTestRunner
import org.robolectric.internal.bytecode.InstrumentationConfiguration
public class TilesTestingTestRunner(testClass: Class<*>) : RobolectricTestRunner(testClass) {
override fun createClassLoaderConfig(method: FrameworkMethod): InstrumentationConfiguration =
InstrumentationConfiguration.Builder(super.createClassLoaderConfig(method))
.doNotInstrumentPackage("androidx.wear.tiles.connection")
.doNotInstrumentPackage("androidx.wear.tiles.testing")
.build()
} | wear/tiles/tiles-testing/src/test/java/androidx/wear/tiles/testing/TilesTestingTestRunner.kt | 1600015848 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.internal.statistic
import com.intellij.internal.statistic.eventLog.validator.ValidationResultType
import com.intellij.internal.statistic.eventLog.validator.rules.EventContext
import com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule
/**
* All valid allowed library names are bundled with IDE.
* <br/>
* See 'library-jar-statistics.xml' and 'library-usage-statistics.xml' files.
*/
internal class LibraryNameValidationRule : CustomValidationRule() {
override fun getRuleId(): String = "used_library_name"
override fun doValidate(data: String, context: EventContext): ValidationResultType {
return acceptWhenReportedByJetBrainsPlugin(context)
}
} | java/java-impl/src/com/intellij/internal/statistic/LibraryNameValidationRule.kt | 741139018 |
// 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.structuralsearch.replace
import org.jetbrains.kotlin.idea.structuralsearch.KotlinStructuralReplaceTest
class KotlinSSRQualifiedExpressionReplaceTest : KotlinStructuralReplaceTest() {
fun testQualifiedExpressionReceiverWithCountFilter() {
doTest(
searchPattern = "'_BEFORE{0,1}.'_FUN()",
replacePattern = "'_BEFORE.foo('_ARG)",
match = """
fun main() {
bar()
}
""".trimIndent(),
result = """
fun main() {
foo()
}
""".trimIndent()
)
}
fun testDoubleQualifiedExpression() {
doTest(
searchPattern = """
'_REC.foo = '_INIT
'_REC.bar = '_INIT
""".trimIndent(),
replacePattern = """
'_REC.fooBar = '_INIT
""".trimIndent(),
match = """
fun main() {
x.foo = true
x.bar = true
}
""".trimIndent(),
result = """
fun main() {
x.fooBar = true
}
""".trimIndent()
)
}
} | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/structuralsearch/replace/KotlinSSRQualifiedExpressionReplaceTest.kt | 2202882604 |
// 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.codevision
import com.intellij.openapi.util.io.FileUtil
import com.intellij.testFramework.utils.inlays.InlayHintsProviderTestCase
import org.jetbrains.kotlin.idea.test.InTextDirectivesUtils
import java.io.File
abstract class AbstractKotlinCodeVisionProviderTest :
InlayHintsProviderTestCase() { // Abstract- prefix is just a convention for GenerateTests
companion object {
const val INHERITORS_KEY = "kotlin.code-vision.inheritors"
const val USAGES_KEY = "kotlin.code-vision.usages"
}
fun doTest(testPath: String) { // named according to the convention imposed by GenerateTests
assertThatActualHintsMatch(testPath)
}
private fun assertThatActualHintsMatch(fileName: String) {
val fileContents = FileUtil.loadFile(File(fileName), true)
val usagesLimit = InTextDirectivesUtils.findStringWithPrefixes(fileContents, "// USAGES-LIMIT: ")?.toInt() ?: 100
val inheritorsLimit = InTextDirectivesUtils.findStringWithPrefixes(fileContents, "// INHERITORS-LIMIT: ")?.toInt() ?: 100
val provider = KotlinCodeVisionProvider()
provider.usagesLimit = usagesLimit
provider.inheritorsLimit = inheritorsLimit
when (InTextDirectivesUtils.findStringWithPrefixes(fileContents, "// MODE: ")) {
"inheritors" -> provider.mode(usages = false, inheritors = true)
"usages" -> provider.mode(usages = true, inheritors = false)
"usages-&-inheritors" -> provider.mode(usages = true, inheritors = true)
else -> provider.mode(usages = false, inheritors = false)
}
doTestProvider("kotlinCodeVision.kt", fileContents, provider)
}
private fun KotlinCodeVisionProvider.mode(usages: Boolean, inheritors: Boolean) {
showUsages = usages
showInheritors = inheritors
}
}
| plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/codeInsight/codevision/AbstractKotlinCodeVisionProviderTest.kt | 3560865672 |
// 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.debugger.ui.breakpoints
import com.intellij.debugger.InstanceFilter
import com.intellij.debugger.JavaDebuggerBundle
import com.intellij.debugger.engine.JavaDebugProcess
import com.intellij.debugger.engine.JavaStackFrame
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.NlsActions.ActionText
import com.intellij.openapi.util.text.StringUtil
import com.intellij.ui.classFilter.ClassFilter
import com.intellij.util.ArrayUtil
import com.intellij.xdebugger.XDebugSession
import com.intellij.xdebugger.breakpoints.XBreakpoint
import com.intellij.xdebugger.impl.breakpoints.XBreakpointBase
import org.jetbrains.java.debugger.breakpoints.properties.JavaBreakpointProperties
internal abstract class BreakpointIntentionAction(protected val myBreakpoint: XBreakpoint<*>, @ActionText text : String) : AnAction(text) {
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.EDT
}
internal class AddCallerNotFilter(breakpoint: XBreakpoint<*>, private val myCaller: String) :
BreakpointIntentionAction(breakpoint, JavaDebuggerBundle.message(
"action.do.not.stop.if.called.from.text", StringUtil.getShortName(StringUtil.substringBefore(myCaller, "(") ?: myCaller))) {
override fun update(e: AnActionEvent) {
with(myBreakpoint.properties as JavaBreakpointProperties<*>) {
e.presentation.setEnabled(!isCALLER_FILTERS_ENABLED || !callerExclusionFilters.contains(ClassFilter(myCaller)))
}
}
override fun actionPerformed(e: AnActionEvent) {
with(myBreakpoint.properties as JavaBreakpointProperties<*>) {
isCALLER_FILTERS_ENABLED = true
val callerFilter = ClassFilter(myCaller)
callerFilters = ArrayUtil.remove(callerFilters, callerFilter)
callerExclusionFilters = appendIfNeeded(callerExclusionFilters, callerFilter)
}
(myBreakpoint as XBreakpointBase<*, *, *>).fireBreakpointChanged()
}
}
internal class AddCallerFilter(breakpoint: XBreakpoint<*>, private val myCaller: String) :
BreakpointIntentionAction(breakpoint,
JavaDebuggerBundle.message("action.stop.only.if.called.from.text", StringUtil.getShortName(StringUtil.substringBefore(myCaller, "(") ?: myCaller))) {
override fun update(e: AnActionEvent) {
with(myBreakpoint.properties as JavaBreakpointProperties<*>) {
e.presentation.setEnabled(!isCALLER_FILTERS_ENABLED || !callerFilters.contains(ClassFilter(myCaller)))
}
}
override fun actionPerformed(e: AnActionEvent) {
with(myBreakpoint.properties as JavaBreakpointProperties<*>) {
isCALLER_FILTERS_ENABLED = true
val callerFilter = ClassFilter(myCaller)
callerFilters = appendIfNeeded(callerFilters, callerFilter)
callerExclusionFilters = ArrayUtil.remove(callerExclusionFilters, callerFilter)
}
(myBreakpoint as XBreakpointBase<*, *, *>).fireBreakpointChanged()
}
}
internal class AddInstanceFilter(breakpoint: XBreakpoint<*>, private val myInstance: Long) :
BreakpointIntentionAction(breakpoint, JavaDebuggerBundle.message("action.stop.only.in.current.object.text")) {
override fun update(e: AnActionEvent) {
with(myBreakpoint.properties as JavaBreakpointProperties<*>) {
e.presentation.setEnabled(!isINSTANCE_FILTERS_ENABLED || !instanceFilters.contains(InstanceFilter.create(myInstance)))
}
}
override fun actionPerformed(e: AnActionEvent) {
with(myBreakpoint.properties as JavaBreakpointProperties<*>) {
isINSTANCE_FILTERS_ENABLED = true
instanceFilters = appendIfNeeded(instanceFilters, InstanceFilter.create(myInstance))
}
(myBreakpoint as XBreakpointBase<*, *, *>).fireBreakpointChanged()
}
}
internal class AddClassFilter(breakpoint: XBreakpoint<*>, private val myClass: String) :
BreakpointIntentionAction(breakpoint, JavaDebuggerBundle.message("action.stop.only.in.class.text", StringUtil.getShortName(myClass))) {
override fun update(e: AnActionEvent) {
with(myBreakpoint.properties as JavaBreakpointProperties<*>) {
e.presentation.setEnabled(!isCLASS_FILTERS_ENABLED || !classFilters.contains(ClassFilter(myClass)))
}
}
override fun actionPerformed(e: AnActionEvent) {
with(myBreakpoint.properties as JavaBreakpointProperties<*>) {
isCLASS_FILTERS_ENABLED = true
val classFilter = ClassFilter(myClass)
classFilters = appendIfNeeded(classFilters, classFilter)
classExclusionFilters = ArrayUtil.remove(classExclusionFilters, classFilter)
}
(myBreakpoint as XBreakpointBase<*, *, *>).fireBreakpointChanged()
}
}
internal class AddClassNotFilter(breakpoint: XBreakpoint<*>, private val myClass: String) :
BreakpointIntentionAction(breakpoint, JavaDebuggerBundle.message("action.do.not.stop.in.class.text", StringUtil.getShortName(myClass))) {
override fun update(e: AnActionEvent) {
with(myBreakpoint.properties as JavaBreakpointProperties<*>) {
e.presentation.setEnabled(!isCLASS_FILTERS_ENABLED || !classExclusionFilters.contains(ClassFilter(myClass)))
}
}
override fun actionPerformed(e: AnActionEvent) {
with(myBreakpoint.properties as JavaBreakpointProperties<*>) {
isCLASS_FILTERS_ENABLED = true
val classFilter = ClassFilter(myClass)
classExclusionFilters = appendIfNeeded(classExclusionFilters, classFilter)
classFilters = ArrayUtil.remove(classFilters, classFilter)
}
(myBreakpoint as XBreakpointBase<*, *, *>).fireBreakpointChanged()
}
}
companion object {
@JvmField
val CALLER_KEY = Key.create<String>("CALLER_KEY")
@JvmField
val THIS_TYPE_KEY = Key.create<String>("THIS_TYPE_KEY")
@JvmField
val THIS_ID_KEY = Key.create<Long>("THIS_ID_KEY")
@JvmStatic
fun getIntentions(breakpoint: XBreakpoint<*>, currentSession: XDebugSession?): List<AnAction> {
val process = currentSession?.debugProcess
if (process is JavaDebugProcess) {
val res = ArrayList<AnAction>()
val currentStackFrame = currentSession.currentStackFrame
if (currentStackFrame is JavaStackFrame) {
val frameDescriptor = currentStackFrame.descriptor
frameDescriptor.getUserData(THIS_TYPE_KEY)?.let {
res.add(AddClassFilter(breakpoint, it))
res.add(AddClassNotFilter(breakpoint, it))
}
frameDescriptor.getUserData(THIS_ID_KEY)?.let {
res.add(AddInstanceFilter(breakpoint, it))
}
frameDescriptor.getUserData(CALLER_KEY)?.let {
res.add(AddCallerFilter(breakpoint, it))
res.add(AddCallerNotFilter(breakpoint, it))
}
}
return res
}
return emptyList()
}
private fun <T> appendIfNeeded(array: Array<T>, element: T): Array<T> {
return if (array.contains(element)) {
array
}
else {
ArrayUtil.append(array, element)
}
}
}
}
| java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/BreakpointIntentionAction.kt | 1542505585 |
// 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 org.jetbrains.plugins.github.extensions
import com.intellij.openapi.project.Project
import com.intellij.util.AuthData
import com.intellij.util.concurrency.annotations.RequiresEdt
import git4idea.DialogManager
import git4idea.i18n.GitBundle
import git4idea.remote.InteractiveGitHttpAuthDataProvider
import org.jetbrains.plugins.github.authentication.GHAccountAuthData
import org.jetbrains.plugins.github.authentication.GHAccountsUtil
import org.jetbrains.plugins.github.authentication.accounts.GithubAccount
import org.jetbrains.plugins.github.authentication.ui.GithubChooseAccountDialog
import org.jetbrains.plugins.github.i18n.GithubBundle
import org.jetbrains.plugins.github.util.GithubUtil.GIT_AUTH_PASSWORD_SUBSTITUTE
import java.awt.Component
internal class GHSelectAccountHttpAuthDataProvider(
private val project: Project,
private val potentialAccounts: Map<GithubAccount, String?>
) : InteractiveGitHttpAuthDataProvider {
@RequiresEdt
override fun getAuthData(parentComponent: Component?): AuthData? {
val (account, setDefault) = chooseAccount(parentComponent) ?: return null
val token = potentialAccounts[account]
?: GHAccountsUtil.requestNewToken(account, project, parentComponent)
?: return null
if (setDefault) {
GHAccountsUtil.setDefaultAccount(project, account)
}
return GHAccountAuthData(account, GIT_AUTH_PASSWORD_SUBSTITUTE, token)
}
private fun chooseAccount(parentComponent: Component?): Pair<GithubAccount, Boolean>? {
val dialog = GithubChooseAccountDialog(
project, parentComponent,
potentialAccounts.keys, null, false, true,
GithubBundle.message("account.choose.title"), GitBundle.message("login.dialog.button.login")
)
DialogManager.show(dialog)
return if (dialog.isOK) dialog.account to dialog.setDefault else null
}
} | plugins/github/src/org/jetbrains/plugins/github/extensions/GHSelectAccountHttpAuthDataProvider.kt | 320477422 |
// PROBLEM: none
class Test {
var test = "OK"
<caret>set(value) {
throw UnsupportedOperationException()
}
}
| plugins/kotlin/idea/tests/testData/inspectionsLocal/setterBackingFieldAssignment/throw.kt | 1842244033 |
// PROBLEM: Condition is always true
// FIX: none
fun test(x: Double) : Boolean = x > 5 && <caret>x > 4 | plugins/kotlin/idea/tests/testData/inspectionsLocal/dfa/doubleCompareInt2.kt | 3566636193 |
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.codeInsight.hint.types
import com.intellij.codeInsight.hints.*
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiFile
import com.intellij.ui.layout.*
import org.jetbrains.plugins.groovy.GroovyBundle
import javax.swing.JPanel
class GroovyLocalVariableTypeHintsInlayProvider : InlayHintsProvider<GroovyLocalVariableTypeHintsInlayProvider.Settings> {
companion object {
private val ourKey: SettingsKey<Settings> = SettingsKey("groovy.variable.type.hints")
}
override fun getCollectorFor(file: PsiFile, editor: Editor, settings: Settings, sink: InlayHintsSink): InlayHintsCollector = GroovyLocalVariableTypeHintsCollector(editor, settings)
override fun createSettings(): Settings = Settings()
data class Settings(var insertBeforeIdentifier : Boolean = false)
override val name: String = GroovyBundle.message("local.variable.types")
override val key: SettingsKey<Settings> = ourKey
override val previewText: String = """
def foo() {
def x = 1
var y = "abc"
}
""".trimIndent()
override fun createConfigurable(settings: Settings): ImmediateConfigurable = object : ImmediateConfigurable {
override val cases: List<ImmediateConfigurable.Case> = listOf(
ImmediateConfigurable.Case(GroovyBundle.message("settings.inlay.put.type.hint.before.identifier"), "inferred.parameter.types", settings::insertBeforeIdentifier),
)
override fun createComponent(listener: ChangeListener): JPanel = panel {}
override val mainCheckboxText: String
get() = GroovyBundle.message("settings.inlay.show.variable.type.hints")
}
} | plugins/groovy/src/org/jetbrains/plugins/groovy/codeInsight/hint/types/GroovyLocalVariableTypeHintsInlayProvider.kt | 3994608625 |
// 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.testGenerator.generator.methods
import com.intellij.openapi.util.io.systemIndependentPath
import org.jetbrains.kotlin.test.TestMetadata
import org.jetbrains.kotlin.testGenerator.generator.Code
import org.jetbrains.kotlin.testGenerator.generator.TestMethod
import org.jetbrains.kotlin.testGenerator.generator.appendAnnotation
import org.jetbrains.kotlin.testGenerator.generator.appendBlock
import org.jetbrains.kotlin.testGenerator.model.TAnnotation
import org.jetbrains.kotlin.testGenerator.model.makeJavaIdentifier
import java.io.File
class TestCaseMethod(private val methodNameBase: String, private val contentRootPath: String, private val localPath: String) : TestMethod {
override val methodName = run {
"test" + when (val qualifier = File(localPath).parentFile?.systemIndependentPath ?: "") {
"" -> methodNameBase
else -> makeJavaIdentifier(qualifier).capitalize() + "_" + methodNameBase
}
}
fun embed(path: String): TestCaseMethod {
return TestCaseMethod(methodNameBase, contentRootPath, File(path, localPath).systemIndependentPath)
}
override fun Code.render() {
appendAnnotation(TAnnotation<TestMetadata>(localPath))
appendBlock("public void $methodName() throws Exception") {
append("runTest(\"$contentRootPath\");")
}
}
} | plugins/kotlin/generators/test/org/jetbrains/kotlin/testGenerator/generator/methods/TestCaseMethod.kt | 554902972 |
package com.github.bjansen.intellij.pebble
import com.intellij.CommonBundle
import com.intellij.reference.SoftReference
import org.jetbrains.annotations.PropertyKey
import java.lang.ref.Reference
import java.util.*
/**
* I18N messages.
*/
object PebbleBundle {
private var ourBundle: Reference<ResourceBundle>? = null
private const val bundleName = "messages.PebbleBundle"
fun message(@PropertyKey(resourceBundle = bundleName) key: String, vararg params: Any): String {
return CommonBundle.message(bundle, key, *params)
}
private val bundle: ResourceBundle get() {
var resourceBundle = SoftReference.dereference(ourBundle)
if (resourceBundle == null) {
resourceBundle = ResourceBundle.getBundle(bundleName)
ourBundle = java.lang.ref.SoftReference<ResourceBundle>(resourceBundle)
}
return resourceBundle!!
}
}
| src/main/kotlin/com/github/bjansen/intellij/pebble/PebbleBundle.kt | 3789916025 |
package net.erikkarlsson.smashapp.base.data.net.smashranking.jsonmodel
import com.google.gson.annotations.SerializedName
import net.erikkarlsson.smashapp.base.data.model.ranking.Smasher
data class SmasherJsonModel(val region: String?,
val twitch: String?,
val eurank: Int,
val ts: Float,
val tag: String,
val secondary: String?,
val tertiary: String?,
val quaternary: String?,
val city: String?,
val twitter: String?,
val sigma: Float,
val name: String?,
val facebook: String?,
val youtube: String?,
val losses: Int,
@SerializedName("character_rank") val characterRank: Int,
val tournaments: Int,
val mu: Float,
val team: String?,
val main: String?,
val country: String?,
val nationality: String?,
val ratio: Float,
val active: Boolean,
@SerializedName("country_rank") val countryRank: Int,
val wins: Int) {
fun toSmasher(): Smasher {
return Smasher(tag, eurank, main, secondary, tertiary, quaternary)
}
}
| app/src/main/java/net/erikkarlsson/smashapp/base/data/net/smashranking/jsonmodel/SmasherJsonModel.kt | 2058856631 |
// 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.core.breakpoints
import com.intellij.debugger.engine.DebugProcessImpl
import com.intellij.openapi.progress.util.ProgressWindow
import com.intellij.xdebugger.breakpoints.XBreakpoint
import com.intellij.xdebugger.breakpoints.XBreakpointListener
object BreakpointListenerConnector {
@JvmStatic
fun subscribe(debugProcess: DebugProcessImpl, indicator: ProgressWindow, listener: XBreakpointListener<XBreakpoint<*>>) {
debugProcess.project.messageBus.connect(indicator).subscribe(XBreakpointListener.TOPIC, listener)
}
}
| plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/core/breakpoints/BreakpointListenerConnector.kt | 1421497570 |
// "Make constructor parameter a property in class 'B'" "true"
class B(bar: String) {
inner class A {
fun foo() {
val a = bar<caret>
}
}
} | plugins/kotlin/idea/tests/testData/quickfix/makeConstructorParameterProperty/inner.kt | 3081785099 |
<warning descr="SSR">fun a() { }</warning>
fun b() { } | plugins/kotlin/idea/tests/testData/structuralsearch/function/fun.kt | 158420275 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.