content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
package com.esafirm.androidplayground.ui
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.Spinner
import com.esafirm.androidplayground.R
import com.esafirm.androidplayground.common.BaseAct
class SpinnerPositionAct : BaseAct() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_ui_spinner)
val context = this
findViewById<Spinner>(R.id.spinner_data)
.apply {
dropDownVerticalOffset = 500
adapter = ArrayAdapter<String>(context, android.R.layout.simple_dropdown_item_1line, arrayListOf("Satu", "Dua", "Tiga"))
}
}
}
| app/src/main/java/com/esafirm/androidplayground/ui/SpinnerPositionAct.kt | 394178833 |
package org.runestar.client.api.overlay
import java.awt.Dimension
import java.awt.Graphics2D
class HideableOverlay(
val overlay: Overlay
) : Overlay {
var show = true
override fun draw(g: Graphics2D, size: Dimension) {
if (show) overlay.draw(g, size)
}
override fun getSize(g: Graphics2D, result: Dimension) {
if (show) overlay.getSize(g, result) else result.setSize(0, 0)
}
}
fun Overlay.hideable() = HideableOverlay(this) | api/src/main/java/org/runestar/client/api/overlay/HideableOverlay.kt | 783167237 |
package com.intellij.settingsSync
import com.intellij.configurationStore.getPerOsSettingsStorageFolderName
import com.intellij.openapi.components.RoamingType
import com.intellij.openapi.components.SettingsCategory
import com.intellij.settingsSync.config.EDITOR_FONT_SUBCATEGORY_ID
import com.intellij.testFramework.LightPlatformTestCase
class SettingsFilteringTest : LightPlatformTestCase() {
fun `test editor settings sync enabled via Code category` () {
assertTrue(isSyncEnabled("editor.xml", RoamingType.DEFAULT))
SettingsSyncSettings.getInstance().setCategoryEnabled(SettingsCategory.CODE, false)
try {
assertFalse(isSyncEnabled("editor.xml", RoamingType.DEFAULT))
}
finally {
SettingsSyncSettings.getInstance().setCategoryEnabled(SettingsCategory.CODE, true)
}
}
fun `test color scheme sync enabled via UI category` () {
assertTrue(isSyncEnabled("colors/my_scheme.icls", RoamingType.DEFAULT))
SettingsSyncSettings.getInstance().setCategoryEnabled(SettingsCategory.UI, false)
try {
assertFalse(isSyncEnabled("colors/my_scheme.icls", RoamingType.DEFAULT))
}
finally {
SettingsSyncSettings.getInstance().setCategoryEnabled(SettingsCategory.UI, true)
}
}
fun `test passing the whole scheme storage directory`() {
assertTrue(isSyncEnabled("keymaps", RoamingType.DEFAULT))
SettingsSyncSettings.getInstance().setCategoryEnabled(SettingsCategory.KEYMAP, false)
try {
assertFalse(isSyncEnabled("keymaps", RoamingType.DEFAULT))
}
finally {
SettingsSyncSettings.getInstance().setCategoryEnabled(SettingsCategory.KEYMAP, true)
}
}
fun `test font sync enabled via subcategory` () {
assertTrue(isSyncEnabled("editor-font.xml", RoamingType.DEFAULT))
SettingsSyncSettings.getInstance().setSubcategoryEnabled(SettingsCategory.UI, EDITOR_FONT_SUBCATEGORY_ID, false)
try {
assertFalse(isSyncEnabled("editor-font.xml", RoamingType.DEFAULT))
}
finally {
SettingsSyncSettings.getInstance().setSubcategoryEnabled(SettingsCategory.UI, EDITOR_FONT_SUBCATEGORY_ID, true)
}
}
fun `test keymap settings enabled via Keymap category` () {
val osPrefix = getPerOsSettingsStorageFolderName() + "/"
val fileSpec = osPrefix + "keymap.xml"
assertTrue(isSyncEnabled(fileSpec, RoamingType.PER_OS))
SettingsSyncSettings.getInstance().setCategoryEnabled(SettingsCategory.KEYMAP, false)
try {
assertFalse(isSyncEnabled(fileSpec, RoamingType.PER_OS))
}
finally {
SettingsSyncSettings.getInstance().setCategoryEnabled(SettingsCategory.KEYMAP, true)
}
}
fun `test settings sync settings always synchronized` () {
assertTrue(isSyncEnabled("settingsSync.xml", RoamingType.DEFAULT))
}
} | plugins/settings-sync/tests/com/intellij/settingsSync/SettingsFilteringTest.kt | 340602439 |
package com.apollographql.apollo3.cache.normalized.api
import com.apollographql.apollo3.api.CompiledField
import com.apollographql.apollo3.api.CompiledListType
import com.apollographql.apollo3.api.CompiledNamedType
import com.apollographql.apollo3.api.CompiledNotNullType
import com.apollographql.apollo3.api.Executable
import com.apollographql.apollo3.api.isComposite
import kotlin.jvm.JvmSuppressWildcards
/**
* A [CacheResolver] that resolves objects and list of objects and fallbacks to the default resolver for scalar fields.
* It is intended to simplify the usage of [CacheResolver] when no special handling is needed for scalar fields.
*
* Override [cacheKeyForField] to compute a cache key for a field of composite type.
* Override [listOfCacheKeysForField] to compute a list of cache keys for a field of 'list-of-composite' type.
*
* For simplicity, this only handles one level of list. Implement [CacheResolver] if you need arbitrary nested lists of objects.
*/
abstract class CacheKeyResolver : CacheResolver {
/**
* Return the computed the cache key for a composite field.
*
* If the field is of object type, you can get the object typename with `field.type.leafType().name`
* If the field is of interface type, the concrete object typename is not predictable and the returned [CacheKey] must be unique
* in the whole schema as it cannot be namespaced by the typename anymore.
*
* If the returned [CacheKey] is null, the resolver will use the default handling and use any previously cached value.
*/
abstract fun cacheKeyForField(field: CompiledField, variables: Executable.Variables): CacheKey?
/**
* For a field that contains a list of objects, [listOfCacheKeysForField ] returns a list of [CacheKey]s where each [CacheKey] identifies an object.
*
* If the field is of object type, you can get the object typename with `field.type.leafType().name`
* If the field is of interface type, the concrete object typename is not predictable and the returned [CacheKey] must be unique
* in the whole schema as it cannot be namespaced by the typename anymore.
*
* If an individual [CacheKey] is null, the resulting object will be null in the response.
* If the returned list of [CacheKey]s is null, the resolver will use the default handling and use any previously cached value.
*/
open fun listOfCacheKeysForField(field: CompiledField, variables: Executable.Variables): List<CacheKey?>? = null
final override fun resolveField(
field: CompiledField,
variables: Executable.Variables,
parent: Map<String, @JvmSuppressWildcards Any?>,
parentId: String,
): Any? {
var type = field.type
if (type is CompiledNotNullType) {
type = type.ofType
}
if (type is CompiledNamedType && type.isComposite()) {
val result = cacheKeyForField(field, variables)
if (result != null) {
return result
}
}
if (type is CompiledListType) {
type = type.ofType
if (type is CompiledNotNullType) {
type = type.ofType
}
if (type is CompiledNamedType && type.isComposite()) {
val result = listOfCacheKeysForField(field, variables)
if (result != null) {
return result
}
}
}
return DefaultCacheResolver.resolveField(field, variables, parent, parentId)
}
}
| apollo-normalized-cache-api/src/commonMain/kotlin/com/apollographql/apollo3/cache/normalized/api/CacheKeyResolver.kt | 3101839496 |
package com.apollographql.apollo3.api.http
import okio.BufferedSink
import okio.ByteString
import okio.ByteString.Companion.encodeUtf8
class ByteStringHttpBody(
override val contentType: String,
private val byteString: ByteString
): HttpBody {
constructor(contentType: String, string: String): this(contentType, string.encodeUtf8())
override val contentLength
get() = byteString.size.toLong()
override fun writeTo(bufferedSink: BufferedSink) {
bufferedSink.write(byteString)
}
}
| apollo-api/src/commonMain/kotlin/com/apollographql/apollo3/api/http/ByteStringHttpBody.kt | 2013036165 |
// FIR_COMPARISON
// FIR_IDENTICAL
interface I {
fun takeXxx(): Int = 0
fun takeYyy(): String = ""
fun takeZzz(): Int = 0
}
fun foo(i: I): String {
return i.take<caret>
}
// ORDER: takeYyy
// ORDER: takeXxx
// ORDER: takeZzz
| plugins/kotlin/completion/testData/weighers/basic/expectedInfo/ExpectedType2.kt | 1882800500 |
// 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.base.projectStructure
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.IndexNotReadyException
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.LibraryOrderEntry
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.roots.impl.libraries.LibraryEx
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.ThrowableComputable
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.search.DelegatingGlobalSearchScope
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.util.indexing.DumbModeAccessType
import com.intellij.util.indexing.FileBasedIndex
import com.intellij.util.messages.MessageBusConnection
import com.intellij.workspaceModel.ide.WorkspaceModelChangeListener
import com.intellij.workspaceModel.ide.WorkspaceModelTopics
import com.intellij.workspaceModel.storage.VersionedStorageChange
import com.intellij.workspaceModel.storage.bridgeEntities.ModuleEntity
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.*
import org.jetbrains.kotlin.idea.base.util.caching.SynchronizedFineGrainedEntityCache
import org.jetbrains.kotlin.idea.vfilefinder.KotlinStdlibIndex
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
// TODO(kirpichenkov): works only for JVM (see KT-44552)
interface KotlinStdlibCache {
fun isStdlib(libraryInfo: LibraryInfo): Boolean
fun isStdlibDependency(libraryInfo: LibraryInfo): Boolean
fun findStdlibInModuleDependencies(module: IdeaModuleInfo): LibraryInfo?
companion object {
fun getInstance(project: Project): KotlinStdlibCache =
if (IdeBuiltInsLoadingState.isFromClassLoader) {
Disabled
} else {
project.getService(KotlinStdlibCache::class.java)
?: error("Failed to load service ${KotlinStdlibCache::class.java.name}")
}
val Disabled = object : KotlinStdlibCache {
override fun isStdlib(libraryInfo: LibraryInfo) = false
override fun isStdlibDependency(libraryInfo: LibraryInfo) = false
override fun findStdlibInModuleDependencies(module: IdeaModuleInfo): LibraryInfo? = null
}
}
}
internal class KotlinStdlibCacheImpl(private val project: Project) : KotlinStdlibCache, Disposable {
companion object {
private const val KOTLIN_JAVA_RUNTIME_NAME = "KotlinJavaRuntime"
private val noStdlibDependency = StdlibDependency(null)
}
@JvmInline
private value class StdlibDependency(val libraryInfo: LibraryInfo?)
private val stdlibCache = StdLibCache()
private val stdlibDependencyCache = StdlibDependencyCache()
private val moduleStdlibDependencyCache = ModuleStdlibDependencyCache()
init {
Disposer.register(this, stdlibCache)
Disposer.register(this, stdlibDependencyCache)
Disposer.register(this, moduleStdlibDependencyCache)
}
private class LibraryScope(
project: Project,
private val directories: Set<VirtualFile>
) : DelegatingGlobalSearchScope(GlobalSearchScope.allScope(project)) {
private val fileSystems = directories.mapTo(hashSetOf(), VirtualFile::getFileSystem)
override fun contains(file: VirtualFile): Boolean = file.fileSystem in fileSystems && VfsUtilCore.isUnder(file, directories)
override fun toString() = "All files under: $directories"
}
private fun libraryScopeContainsIndexedFilesForNames(libraryInfo: LibraryInfo, names: Collection<FqName>): Boolean {
val libraryScope = LibraryScope(project, libraryInfo.library.getFiles(OrderRootType.CLASSES).toSet())
return names.any { name ->
DumbModeAccessType.RELIABLE_DATA_ONLY.ignoreDumbMode(ThrowableComputable {
FileBasedIndex.getInstance().getContainingFilesIterator(KotlinStdlibIndex.KEY, name, libraryScope).hasNext()
})
}
}
private fun libraryScopeContainsIndexedFilesForName(libraryInfo: LibraryInfo, name: FqName) =
libraryScopeContainsIndexedFilesForNames(libraryInfo, listOf(name))
private fun isFatJar(libraryInfo: LibraryInfo) = libraryInfo.getLibraryRoots().size > 1
private fun isKotlinJavaRuntime(libraryInfo: LibraryInfo) = libraryInfo.library.name == KOTLIN_JAVA_RUNTIME_NAME
override fun isStdlib(libraryInfo: LibraryInfo): Boolean = stdlibCache[libraryInfo]
override fun isStdlibDependency(libraryInfo: LibraryInfo): Boolean = stdlibDependencyCache[libraryInfo]
override fun findStdlibInModuleDependencies(module: IdeaModuleInfo): LibraryInfo? {
ProgressManager.checkCanceled()
val stdlibDependency = moduleStdlibDependencyCache.get(module)
return stdlibDependency.libraryInfo
}
override fun dispose() = Unit
private sealed class BaseStdLibCache(project: Project) :
SynchronizedFineGrainedEntityCache<LibraryInfo, Boolean>(project, cleanOnLowMemory = true),
LibraryInfoListener {
override fun subscribe() {
val busConnection = project.messageBus.connect(this)
busConnection.subscribe(LibraryInfoListener.TOPIC, this)
}
override fun checkKeyValidity(key: LibraryInfo) {
key.checkValidity()
}
override fun libraryInfosRemoved(libraryInfos: Collection<LibraryInfo>) {
invalidateKeys(libraryInfos)
}
}
private inner class StdLibCache : BaseStdLibCache(project) {
override fun calculate(key: LibraryInfo): Boolean =
libraryScopeContainsIndexedFilesForName(key, KotlinStdlibIndex.KOTLIN_STDLIB_NAME) &&
(!isFatJar(key) || isKotlinJavaRuntime(key))
}
private inner class StdlibDependencyCache : BaseStdLibCache(project) {
override fun calculate(key: LibraryInfo): Boolean =
libraryScopeContainsIndexedFilesForNames(key, KotlinStdlibIndex.STANDARD_LIBRARY_DEPENDENCY_NAMES) &&
(!isFatJar(key) || isKotlinJavaRuntime(key))
}
private inner class ModuleStdlibDependencyCache : Disposable {
private val libraryCache = LibraryCache()
private val moduleCache = ModuleCache()
init {
Disposer.register(this, libraryCache)
Disposer.register(this, moduleCache)
}
fun get(key: IdeaModuleInfo): StdlibDependency = when (key) {
is LibraryInfo -> libraryCache[key]
is SdkInfo, is NotUnderContentRootModuleInfo -> noStdlibDependency
else -> moduleCache[key]
}
override fun dispose() = Unit
private abstract inner class AbstractCache<Key : IdeaModuleInfo> :
SynchronizedFineGrainedEntityCache<Key, StdlibDependency>(project, cleanOnLowMemory = true),
LibraryInfoListener {
override fun subscribe() {
val connection = project.messageBus.connect(this)
connection.subscribe(LibraryInfoListener.TOPIC, this)
subscribe(connection)
}
protected open fun subscribe(connection: MessageBusConnection) {
}
protected fun Key.findStdLib(): LibraryInfo? {
val dependencies = if (this is LibraryInfo) {
if (isStdlib(this)) return this
LibraryDependenciesCache.getInstance(project).getLibraryDependencies(this).libraries
} else {
dependencies()
}
return dependencies.firstNotNullOfOrNull { it.safeAs<LibraryInfo>()?.takeIf(::isStdlib) }
}
protected fun LibraryInfo?.toStdlibDependency(): StdlibDependency {
if (this != null) {
return StdlibDependency(this)
}
val flag = runReadAction {
when {
project.isDisposed -> null
DumbService.isDumb(project) -> true
else -> false
}
}
return when (flag) {
null -> throw ProcessCanceledException()
true -> throw IndexNotReadyException.create()
else -> noStdlibDependency
}
}
override fun checkValueValidity(value: StdlibDependency) {
value.libraryInfo?.checkValidity()
}
}
private inner class LibraryCache : AbstractCache<LibraryInfo>() {
override fun calculate(key: LibraryInfo): StdlibDependency = key.findStdLib().toStdlibDependency()
fun putExtraValues(map: Map<LibraryInfo, StdlibDependency>) {
putAll(map)
}
override fun checkKeyValidity(key: LibraryInfo) {
key.checkValidity()
}
override fun libraryInfosRemoved(libraryInfos: Collection<LibraryInfo>) {
invalidateEntries({ k, v -> k in libraryInfos || v.libraryInfo in libraryInfos })
}
}
private inner class ModuleCache : AbstractCache<IdeaModuleInfo>(), WorkspaceModelChangeListener {
override fun subscribe(connection: MessageBusConnection) {
connection.subscribe(WorkspaceModelTopics.CHANGED, this)
}
override fun calculate(key: IdeaModuleInfo): StdlibDependency {
val moduleSourceInfo = key.safeAs<ModuleSourceInfo>()
val stdLib = moduleSourceInfo?.module?.moduleWithLibrariesScope?.let index@{ scope ->
val stdlibManifests = DumbModeAccessType.RELIABLE_DATA_ONLY.ignoreDumbMode(ThrowableComputable {
FileBasedIndex.getInstance().getContainingFiles(
KotlinStdlibIndex.KEY,
KotlinStdlibIndex.KOTLIN_STDLIB_NAME,
scope
)
})
val projectFileIndex = ProjectFileIndex.getInstance(project)
val libraryInfoCache = LibraryInfoCache.getInstance(project)
for (manifest in stdlibManifests) {
val orderEntries = projectFileIndex.getOrderEntriesForFile(manifest)
for (entry in orderEntries) {
val library = entry.safeAs<LibraryOrderEntry>()?.library.safeAs<LibraryEx>() ?: continue
val libraryInfos = libraryInfoCache[library]
return@index libraryInfos.find(::isStdlib) ?: continue
}
}
null
} ?: key.findStdLib()
return stdLib.toStdlibDependency()
}
override fun postProcessNewValue(key: IdeaModuleInfo, value: StdlibDependency) {
if (key !is ModuleSourceInfo) return
val result = hashMapOf<LibraryInfo, StdlibDependency>()
// all module dependencies have same stdlib as module itself
key.dependencies().forEach {
if (it is LibraryInfo) {
result[it] = value
}
}
libraryCache.putExtraValues(result)
}
override fun checkKeyValidity(key: IdeaModuleInfo) {
key.checkValidity()
}
override fun libraryInfosRemoved(libraryInfos: Collection<LibraryInfo>) {
invalidateEntries({ _, v -> v.libraryInfo in libraryInfos }, validityCondition = { _, v -> v.libraryInfo != null })
}
override fun changed(event: VersionedStorageChange) {
event.getChanges(ModuleEntity::class.java).ifEmpty { return }
invalidate(writeAccessRequired = true)
}
}
}
}
fun LibraryInfo.isCoreKotlinLibrary(project: Project): Boolean = isKotlinStdlib(project) || isKotlinStdlibDependency(project)
fun LibraryInfo.isKotlinStdlib(project: Project): Boolean = KotlinStdlibCache.getInstance(project).isStdlib(this)
fun LibraryInfo.isKotlinStdlibDependency(project: Project): Boolean = KotlinStdlibCache.getInstance(project).isStdlibDependency(this) | plugins/kotlin/base/project-structure/src/org/jetbrains/kotlin/idea/base/projectStructure/KotlinStdlibCache.kt | 1305042185 |
package com.github.vhromada.catalog.web.fo
import com.github.vhromada.catalog.web.validator.constraints.DateRange
import com.github.vhromada.catalog.web.validator.constraints.Years
import org.hibernate.validator.constraints.Range
import javax.validation.constraints.NotNull
/**
* A class represents FO for season.
*
* @author Vladimir Hromada
*/
@Years
data class SeasonFO(
/**
* UUID
*/
val uuid: String?,
/**
* Number of season
*/
@field:Range(min = 1, max = 100)
val number: String?,
/**
* Starting year
*/
@field:DateRange
val startYear: String?,
/**
* Ending year
*/
@field:DateRange
val endYear: String?,
/**
* Language
*/
@field:NotNull
val language: String?,
/**
* Subtitles
*/
val subtitles: List<String>?,
/**
* Note
*/
val note: String?
)
| web/src/main/kotlin/com/github/vhromada/catalog/web/fo/SeasonFO.kt | 1316908832 |
package com.raybritton.jsonquery.parsing.query
import com.raybritton.jsonquery.SyntaxException
import com.raybritton.jsonquery.ext.joinStringOr
import com.raybritton.jsonquery.ext.toSegments
import com.raybritton.jsonquery.models.*
import com.raybritton.jsonquery.models.Target
import com.raybritton.jsonquery.parsing.tokens.Operator
/**
* Used by QueryParser to build the query
*
* It checks that values set correctly
*
*/
internal class QueryBuilder(val queryString: String) {
var method: Query.Method? = null
set(value) {
checkMethodNotSet()
field = value
}
var target: Target? = null
set(value) {
checkMethodSet()
if (field != null) {
throw SyntaxException("Target already set: $field")
}
if (value is Target.TargetQuery) {
if (value.query.method != Query.Method.SELECT) {
throw SyntaxException("Only SELECT queries can be nested")
}
}
if (value is Target.TargetField) {
checkJsonTargetIsValid(value.value)
}
field = value
}
var describeProjection: String? = null
set(value) {
checkMethodSet()
if (field != null) {
throw SyntaxException("Projection already set: $field")
}
checkJsonPathIsValid(value!!, "DESCRIBE")
field = value
}
var selectProjection: SelectProjection? = null
set(value) {
checkMethodSet()
if (field != null) {
throw SyntaxException("Projection already set: $field")
}
checkMath()
when (value) {
is SelectProjection.SingleField -> checkJsonPathIsValid(value.field, "SELECT")
is SelectProjection.MultipleFields -> value.fields.forEach { checkJsonPathIsValid(it.first, "SELECT") }
}
field = value
}
var where: Where? = null
set(value) {
checkMethod("WHERE", Query.Method.SELECT, Query.Method.DESCRIBE)
if (value!!.projection is WhereProjection.Field) {
checkJsonPathIsValid((value.projection as WhereProjection.Field).value, "WHERE")
}
field = value
}
var searchOperator: Operator? = null
set(value) {
if (field != null) {
throw SyntaxException("Search operator already set: $field")
}
field = value
}
var targetRange: SearchQuery.TargetRange? = null
set(value) {
checkMethod(value!!.name, Query.Method.SEARCH)
if (field != null) {
throw SyntaxException("Search target range already set: $field")
}
field = value
}
var searchValue: Value<*>? = null
set(value) {
if (field != null) {
throw SyntaxException("Search value already set: $field")
}
field = value
}
var limit: Int? = null
set(value) {
checkMethod("LIMIT", Query.Method.SELECT, Query.Method.DESCRIBE)
if (field != null) {
throw SyntaxException("Limit already set: $field")
}
field = value
}
var offset: Int? = null
set(value) {
checkMethod("OFFSET", Query.Method.SELECT, Query.Method.DESCRIBE)
if (field != null) {
throw SyntaxException("Offset already set: $field")
}
field = value
}
var orderBy: ElementFieldProjection? = null
set(value) {
checkMethod("ORDER BY", Query.Method.SELECT)
if (field != null) {
throw SyntaxException("Order already set: $field")
}
if (value is ElementFieldProjection.Field) {
checkJsonPathIsValid(value.value, "ORDER BY")
}
checkMath()
field = value
}
var isDistinct: Boolean? = null
set(value) {
checkMethodSet()
if (selectProjection is SelectProjection.Math) {
throw SyntaxException("Can not use DISTINCT and MIN, MAX, SUM or COUNT together")
}
checkMath()
field = value
}
var isCaseSensitive: Boolean? = null
set(value) {
checkMethodSet()
if (method == Query.Method.SELECT || method == Query.Method.DESCRIBE) {
if (where == null) {
throw SyntaxException("In SELECT or DESCRIBE: CASE SENSITIVE is only allowed after WHERE")
}
}
field = value
}
var isWithValues: Boolean? = null
set(value) {
checkMethod("WITH VALUES", Query.Method.SEARCH)
checkMath()
field = value
}
var isWithKeys: Boolean? = null
set(value) {
checkMethod("WITH KEYS", Query.Method.DESCRIBE)
field = value
}
var isByElement: Boolean? = null
set(value) {
checkMethod("BY ELEMENT", Query.Method.SELECT)
field = value
}
var isAsJson: Boolean? = null
set(value) {
checkIsFalse("AS JSON", "KEYS", isOnlyPrintKeys)
checkIsFalse("AS JSON", "VALUES", isOnlyPrintValues)
checkMethod("AS JSON", Query.Method.SELECT)
checkMath()
field = value
}
var isPrettyPrinted: Boolean? = null
set(value) {
checkMethod("PRETTY", Query.Method.SELECT, Query.Method.DESCRIBE)
if (isAsJson != true) {
throw SyntaxException("In SELECT: PRETTY is only allowed after AS JSON")
}
field = value
}
var isOnlyPrintKeys: Boolean? = null
set(value) {
checkIsFalse("KEYS", "AS JSON", isAsJson)
checkIsFalse("KEYS", "VALUES", isOnlyPrintValues)
checkMethod("KEYS", Query.Method.SELECT)
checkMath()
field = value
}
var isOnlyPrintValues: Boolean? = null
set(value) {
checkIsFalse("VALUES", "AS JSON", isAsJson)
checkIsFalse("VALUES", "KEYS", isOnlyPrintKeys)
checkMethod("VALUES", Query.Method.SELECT)
checkMath()
field = value
}
var isOrderByDesc: Boolean? = null
set(value) {
checkMethod("VALUES", Query.Method.SELECT)
if (orderBy == null) {
throw SyntaxException("DESC is only allowed after ORDER BY")
}
field = value
}
fun build(): Query {
if (method == null) {
throw SyntaxException("No SELECT, DESCRIBE or SEARCH method found")
}
if (target == null) {
throw SyntaxException("No target found")
}
val flags = Query.Flags(
isDistinct = (isDistinct == true),
isCaseSensitive = (isCaseSensitive == true),
isAsJson = (isAsJson == true),
isByElement = (isByElement == true),
isOnlyPrintKeys = (isOnlyPrintKeys == true),
isOnlyPrintValues = (isOnlyPrintValues == true),
isPrettyPrinted = (isPrettyPrinted == true),
isWithKeys = (isWithKeys == true),
isWithValues = (isWithValues == true),
isOrderByDesc = (isOrderByDesc == true)
)
var searchQuery: SearchQuery? = null
var selectQuery: SelectQuery? = null
var describeQuery: DescribeQuery? = null
when (method!!) {
Query.Method.SELECT -> {
selectQuery = SelectQuery(selectProjection, limit, offset, orderBy)
}
Query.Method.DESCRIBE -> {
describeQuery = DescribeQuery(describeProjection, limit, offset)
}
Query.Method.SEARCH -> {
if (targetRange == null) {
throw SyntaxException("No target range found")
}
if (searchOperator == null) {
throw SyntaxException("No operator found")
}
if (searchValue == null) {
throw SyntaxException("No value found")
}
searchQuery = SearchQuery(targetRange!!, searchOperator!!, searchValue!!)
}
}
return Query(queryString, method!!, target!!, flags, where, searchQuery, selectQuery, describeQuery)
}
private fun checkMath() {
if (selectProjection is SelectProjection.Math) {
if (isDistinct == true) {
throw SyntaxException("Can not use DISTINCT and MIN, MAX, SUM or COUNT together")
}
if (orderBy != null) {
throw SyntaxException("Can not use ORDER BY and MIN, MAX, SUM or COUNT together")
}
if (isOnlyPrintKeys != null) {
throw SyntaxException("Can not use KEYS and MIN, MAX, SUM or COUNT together")
}
if (isOnlyPrintValues != null) {
throw SyntaxException("Can not use VALUES and MIN, MAX, SUM or COUNT together")
}
if (isAsJson != null) {
throw SyntaxException("Can not use VALUES and MIN, MAX, SUM or COUNT together")
}
}
}
private fun checkJsonTargetIsValid(path: String) {
if (path.isEmpty()) throw SyntaxException("Json target is empty", SyntaxException.ExtraInfo.JSON_TARGET)
if (path == ".") return
if (path.endsWith(".")) throw SyntaxException("Json target ends with .", SyntaxException.ExtraInfo.JSON_TARGET)
if (path.toSegments().any { it.isEmpty() }) throw SyntaxException("Json target contains blank segments", SyntaxException.ExtraInfo.JSON_TARGET)
}
private fun checkJsonPathIsValid(path: String, type: String) {
if (path.isEmpty()) throw SyntaxException("Json path is empty", SyntaxException.ExtraInfo.JSON_PATH)
if (path.startsWith(".")) throw SyntaxException("Json path for $type starts with .", SyntaxException.ExtraInfo.JSON_PATH)
if (path.endsWith(".")) throw SyntaxException("Json path for $type ends with .", SyntaxException.ExtraInfo.JSON_PATH)
if (path.toSegments().any { it.isEmpty() }) throw SyntaxException("Json path for $type contains blank segments", SyntaxException.ExtraInfo.JSON_PATH)
}
private fun checkIsFalse(field: String, flag: String, flagValue: Boolean?) {
if (flagValue == true) {
throw SyntaxException("$field can not be used with $flag")
}
}
private fun checkMethod(keyword: String, vararg allowedMethods: Query.Method) {
checkMethodSet()
if (!allowedMethods.contains(method)) {
throw SyntaxException("$keyword only works with ${allowedMethods.joinStringOr()}")
}
}
private fun checkMethodSet() {
if (method == null) {
throw SyntaxException("Method (SELECT, DESCRIBE or SEARCH) must be first")
}
}
private fun checkMethodNotSet() {
if (method != null) {
throw SyntaxException("Method can only be set once, already set to $method")
}
}
} | lib/src/main/kotlin/com/raybritton/jsonquery/parsing/query/QueryBuilder.kt | 3473319 |
package me.nya_n.notificationnotifier.ui.screen
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import me.nya_n.notificationnotifier.model.Fab
import me.nya_n.notificationnotifier.ui.util.Event
class MainViewModel : ViewModel() {
private val _fab = MutableLiveData<Event<Fab>>()
val fab: LiveData<Event<Fab>> = _fab
/**
* Fabの状態を更新
*/
fun changeFabState(fab: Fab) {
_fab.postValue(Event(fab))
}
} | AndroidApp/ui/src/main/java/me/nya_n/notificationnotifier/ui/screen/MainViewModel.kt | 273611339 |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.grazie
import com.intellij.ide.plugins.IdeaPluginDescriptor
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.openapi.extensions.PluginId
import java.nio.file.Path
internal object GraziePlugin {
const val id = "tanvd.grazi"
object LanguageTool {
const val version = "5.2"
const val url = "https://resources.jetbrains.com/grazie/model/language-tool"
}
private val descriptor: IdeaPluginDescriptor
get() = PluginManagerCore.getPlugin(PluginId.getId(id))!!
val group: String
get() = GrazieBundle.message("grazie.group.name")
val name: String
get() = GrazieBundle.message("grazie.name")
val isBundled: Boolean
get() = descriptor.isBundled
val classLoader: ClassLoader
get() = descriptor.pluginClassLoader
val libFolder: Path
get() = descriptor.pluginPath.resolve("lib")
}
| plugins/grazie/src/main/kotlin/com/intellij/grazie/GraziePlugin.kt | 1814887388 |
package com.faendir.acra.setup
import com.faendir.acra.model.User
import com.faendir.acra.service.UserService
import com.faendir.acra.util.zip
import mu.KotlinLogging
import org.springframework.boot.ApplicationArguments
import org.springframework.boot.ApplicationRunner
import org.springframework.stereotype.Component
private val logger = KotlinLogging.logger {}
private const val CREATE_USER_OPTION = "create-user"
private const val PASSWORD_OPTION = "password"
private const val ROLES_OPTION = "roles"
@Component
class UserSetup(private val userService: UserService) : ApplicationRunner {
override fun run(args: ApplicationArguments) {
if (args.containsOption(CREATE_USER_OPTION)) {
val names = args.getOptionValues(CREATE_USER_OPTION)
if (names.isEmpty()) {
logger.error { "No username provided. No users created." }
return
}
if (!args.containsOption(PASSWORD_OPTION)) {
logger.error { "No password provided. No users created." }
return
}
val passwords = args.getOptionValues(PASSWORD_OPTION)
if (names.size != passwords.size) {
logger.error { "User and password count do not match. No users created." }
return
}
val rolesList = (args.getOptionValues(ROLES_OPTION)?.map { rolesString ->
rolesString.split(",").map {
try {
User.Role.valueOf(it.uppercase())
} catch (e: Exception) {
logger.error { "Unknown role $it. No users created." }
return
}
}
} ?: emptyList()).let { it + MutableList(names.size - it.size) { listOf(User.Role.ADMIN, User.Role.USER, User.Role.API) } }
names.zip(passwords, rolesList).forEach { (name, password, roles) ->
if (name.isBlank()) {
logger.error { "Username may not be blank." }
return@forEach
}
if (userService.getUser(name) != null) {
logger.warn { "User $name already exists." }
return@forEach
}
if (password.isBlank()) {
logger.error { "Password my not be blank." }
return@forEach
}
if (roles.contains(User.Role.REPORTER)) {
logger.error { "Reporter users may not be created manually." }
return@forEach
}
val user = User(name, "", roles.toMutableSet().apply { if (contains(User.Role.ADMIN)) add(User.Role.USER) }, password, null)
userService.store(user)
logger.info { "Created user $name with roles $roles." }
}
}
}
} | acrarium/src/main/kotlin/com/faendir/acra/setup/UserSetup.kt | 3077362322 |
/*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.channels
import kotlinx.coroutines.*
import org.junit.Test
import org.junit.runner.*
import org.junit.runners.*
import java.io.*
import kotlin.test.*
@RunWith(Parameterized::class)
class ActorTest(private val capacity: Int) : TestBase() {
companion object {
@Parameterized.Parameters(name = "Capacity: {0}")
@JvmStatic
fun params(): Collection<Array<Any>> = listOf(0, 1, Channel.UNLIMITED, Channel.CONFLATED).map { arrayOf<Any>(it) }
}
@Test
fun testEmpty() = runBlocking {
expect(1)
val actor = actor<String>(capacity = capacity) {
expect(3)
}
actor as Job // type assertion
assertTrue(actor.isActive)
assertFalse(actor.isCompleted)
assertFalse(actor.isClosedForSend)
expect(2)
yield() // to actor code
assertFalse(actor.isActive)
assertTrue(actor.isCompleted)
assertTrue(actor.isClosedForSend)
finish(4)
}
@Test
fun testOne() = runBlocking {
expect(1)
val actor = actor<String>(capacity = capacity) {
expect(3)
assertEquals("OK", receive())
expect(6)
}
actor as Job // type assertion
assertTrue(actor.isActive)
assertFalse(actor.isCompleted)
assertFalse(actor.isClosedForSend)
expect(2)
yield() // to actor code
assertTrue(actor.isActive)
assertFalse(actor.isCompleted)
assertFalse(actor.isClosedForSend)
expect(4)
// send message to actor
actor.send("OK")
expect(5)
yield() // to actor code
assertFalse(actor.isActive)
assertTrue(actor.isCompleted)
assertTrue(actor.isClosedForSend)
finish(7)
}
@Test
fun testCloseWithoutCause() = runTest {
val actor = actor<Int>(capacity = capacity) {
val element = channel.receive()
expect(2)
assertEquals(42, element)
val next = channel.receiveCatching()
assertNull(next.exceptionOrNull())
expect(3)
}
expect(1)
actor.send(42)
yield()
actor.close()
yield()
finish(4)
}
@Test
fun testCloseWithCause() = runTest {
val actor = actor<Int>(capacity = capacity) {
val element = channel.receive()
expect(2)
require(element == 42)
try {
channel.receive()
} catch (e: IOException) {
expect(3)
}
}
expect(1)
actor.send(42)
yield()
actor.close(IOException())
yield()
finish(4)
}
@Test
fun testCancelEnclosingJob() = runTest {
val job = async {
actor<Int>(capacity = capacity) {
expect(1)
channel.receive()
expectUnreached()
}
}
yield()
yield()
expect(2)
yield()
job.cancel()
try {
job.await()
expectUnreached()
} catch (e: CancellationException) {
assertTrue(e.message?.contains("DeferredCoroutine was cancelled") ?: false)
}
finish(3)
}
@Test
fun testThrowingActor() = runTest(unhandled = listOf({e -> e is IllegalArgumentException})) {
val parent = Job()
val actor = actor<Int>(parent) {
channel.consumeEach {
expect(1)
throw IllegalArgumentException()
}
}
actor.send(1)
parent.cancel()
parent.join()
finish(2)
}
@Test
fun testChildJob() = runTest {
val parent = Job()
actor<Int>(parent) {
launch {
try {
delay(Long.MAX_VALUE)
} finally {
expect(1)
}
}
}
yield()
yield()
parent.cancel()
parent.join()
finish(2)
}
@Test
fun testCloseFreshActor() = runTest {
for (start in CoroutineStart.values()) {
val job = launch {
val actor = actor<Int>(start = start) {
for (i in channel) {
}
}
actor.close()
}
job.join()
}
}
@Test
fun testCancelledParent() = runTest({ it is CancellationException }) {
cancel()
expect(1)
actor<Int> {
expectUnreached()
}
finish(2)
}
}
| kotlinx-coroutines-core/jvm/test/channels/ActorTest.kt | 4093802427 |
package jetbrains.buildServer.dotnet.test.dotnet
import io.mockk.*
import io.mockk.impl.annotations.MockK
import jetbrains.buildServer.agent.Path
import jetbrains.buildServer.agent.ToolPath
import jetbrains.buildServer.agent.VirtualContext
import jetbrains.buildServer.dotnet.*
import org.testng.Assert
import org.testng.annotations.BeforeMethod
import org.testng.annotations.DataProvider
import org.testng.annotations.Test
import java.io.File
class VSTestLoggerArgumentsProviderTest {
@MockK private lateinit var _loggerParameters: LoggerParameters
@MockK private lateinit var _virtualContext: VirtualContext
@BeforeMethod
fun setUp() {
MockKAnnotations.init(this)
clearAllMocks()
every { _virtualContext.resolvePath(any()) } answers { "v_" + arg<String>(0)}
}
@DataProvider
fun testLoggerArgumentsData(): Array<Array<Any?>> {
return arrayOf(
// Success scenario
arrayOf(
File("loggerPath", "vstestlogger.dll") as File?,
Verbosity.Normal,
listOf(
"/logger:logger://teamcity",
"/TestAdapterPath:v_${File("loggerPath").canonicalPath}",
"/logger:console;verbosity=normal")),
arrayOf(
File("loggerPath", "vstestlogger.dll") as File?,
Verbosity.Detailed,
listOf(
"/logger:logger://teamcity",
"/TestAdapterPath:v_${File("loggerPath").canonicalPath}",
"/logger:console;verbosity=detailed"))
)
}
@Test(dataProvider = "testLoggerArgumentsData")
fun shouldGetArguments(
loggerFile: File,
verbosity: Verbosity,
expectedArguments: List<String>) {
// Given
val context = DotnetBuildContext(ToolPath(Path("wd")), mockk<DotnetCommand>())
val argumentsProvider = VSTestLoggerArgumentsProvider(LoggerResolverStub(File("msbuildlogger"), loggerFile), _loggerParameters, _virtualContext)
every { _loggerParameters.vsTestVerbosity } returns verbosity
// When
val actualArguments = argumentsProvider.getArguments(context).map { it.value }.toList()
// Then
verify { _virtualContext.resolvePath(any()) }
Assert.assertEquals(actualArguments, expectedArguments)
}
} | plugin-dotnet-agent/src/test/kotlin/jetbrains/buildServer/dotnet/test/dotnet/VSTestLoggerArgumentsProviderTest.kt | 3795753517 |
/*
* Copyright (C) 2021 Veli Tasalı
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.monora.uprotocol.client.android.fragment
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.navigation.fragment.findNavController
import com.genonbeta.android.framework.io.OpenableContent
import dagger.hilt.android.AndroidEntryPoint
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import org.monora.uprotocol.client.android.R
import org.monora.uprotocol.client.android.database.model.UTransferItem
import org.monora.uprotocol.client.android.databinding.LayoutPrepareSharingBinding
import org.monora.uprotocol.core.protocol.Direction
import java.lang.ref.WeakReference
import java.text.Collator
import java.util.*
import javax.inject.Inject
import kotlin.random.Random
@AndroidEntryPoint
class PrepareSharingFragment : Fragment(R.layout.layout_prepare_sharing) {
private val preparationViewModel: PreparationViewModel by activityViewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val activity = activity
val intent = activity?.intent
if (activity != null && intent != null) {
if (Intent.ACTION_SEND == intent.action && intent.hasExtra(Intent.EXTRA_TEXT)) {
findNavController().navigate(
PrepareSharingFragmentDirections.actionPrepareSharingFragmentToNavTextEditor(
text = intent.getStringExtra(Intent.EXTRA_TEXT)
)
)
} else {
val list: List<Uri>? = try {
when (intent.action) {
Intent.ACTION_SEND -> (intent.getParcelableExtra(Intent.EXTRA_STREAM) as Uri?)?.let {
Collections.singletonList(it)
}
Intent.ACTION_SEND_MULTIPLE -> intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM)
else -> null
}
} catch (e: Throwable) {
null
}
if (list.isNullOrEmpty()) {
activity.finish()
return
}
preparationViewModel.consume(list)
}
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val binding = LayoutPrepareSharingBinding.bind(view)
binding.button.setOnClickListener {
if (!findNavController().navigateUp()) activity?.finish()
}
preparationViewModel.shared.observe(viewLifecycleOwner) {
when (it) {
is PreparationState.Progress -> {
binding.progressBar.max = it.total
if (Build.VERSION.SDK_INT >= 24) {
binding.progressBar.setProgress(it.index, true)
} else {
binding.progressBar.progress = it.index
}
}
is PreparationState.Ready -> {
findNavController().navigate(
PrepareSharingFragmentDirections.actionPrepareSharingFragmentToSharingFragment(
it.list.toTypedArray(), it.id
)
)
}
}
}
}
}
@HiltViewModel
class PreparationViewModel @Inject internal constructor(
@ApplicationContext context: Context,
) : ViewModel() {
private var consumer: Job? = null
private val context = WeakReference(context)
val shared = MutableLiveData<PreparationState>()
@Synchronized
fun consume(contents: List<Uri>) {
if (consumer != null) return
consumer = viewModelScope.launch(Dispatchers.IO) {
val groupId = Random.nextLong()
val list = mutableListOf<UTransferItem>()
val direction = Direction.Outgoing
contents.forEachIndexed { index, uri ->
val context = context.get() ?: return@launch
val id = index.toLong()
OpenableContent.from(context, uri).runCatching {
shared.postValue(PreparationState.Progress(index, contents.size, name))
list.add(UTransferItem(id, groupId, name, mimeType, size, null, uri.toString(), direction))
}
}
val collator = Collator.getInstance()
list.sortWith { o1, o2 -> collator.compare(o1.name, o2.name) }
shared.postValue(PreparationState.Ready(groupId, list))
consumer = null
}
}
}
sealed class PreparationState {
class Progress(val index: Int, val total: Int, val title: String) : PreparationState()
class Ready(val id: Long, val list: List<UTransferItem>) : PreparationState()
}
| app/src/main/java/org/monora/uprotocol/client/android/fragment/PrepareSharingFragment.kt | 244448528 |
package test.setup
import slatekit.apis.*
import slatekit.apis.AuthModes
import slatekit.common.*
import slatekit.common.auth.Roles
import slatekit.common.crypto.EncDouble
import slatekit.common.crypto.EncInt
import slatekit.common.crypto.EncLong
import slatekit.common.crypto.EncString
import slatekit.requests.Request
import slatekit.utils.smartvalues.Email
import slatekit.utils.smartvalues.PhoneUS
import slatekit.connectors.entities.AppEntContext
import slatekit.results.Notice
import slatekit.results.Success
@Api(area = "app", name = "tests", desc = "sample to test features of Slate Kit APIs", auth = AuthModes.TOKEN, roles= ["admin"])
class SampleAnnoApi(val context: AppEntContext) {
@Action(desc = "accepts supplied basic data types from send")
fun inputBasicTypes(string1: String, bool1: Boolean, numShort: Short, numInt: Int, numLong: Long, numFloat: Float, numDouble: Double, date: DateTime): String {
return "$string1, $bool1, $numShort $numInt, $numLong, $numFloat, $numDouble, $date"
}
@Action(desc = "access the send model directly instead of auto-conversion", roles= [Roles.ALL])
fun inputRequest(req: Request): Notice<String> {
return Success("ok", msg = "raw send id: " + req.data!!.getInt("id"))
}
@Action(desc = "auto-convert json to objects", roles= [Roles.ALL])
fun inputObject(movie: Movie): Movie {
return movie
}
@Action(desc = "auto-convert json to objects", roles= [Roles.ALL])
fun inputObjectlist(movies:List<Movie>): List<Movie> {
return movies
}
@Action(desc = "accepts a list of strings from send", roles= [Roles.ALL])
fun inputListString(items:List<String>): Notice<String> {
return Success("ok", msg = items.fold("", { acc, curr -> acc + "," + curr } ))
}
@Action(desc = "accepts a list of integers from send", roles= [Roles.ALL])
fun inputListInt(items:List<Int>): Notice<String> {
return Success("ok", msg = items.fold("", { acc, curr -> acc + "," + curr.toString() } ))
}
@Action(desc = "accepts a map of string/ints from send", roles= [Roles.ALL])
fun inputMapInt(items:Map<String,Int>): Notice<String> {
val sortedPairs = items.keys.toList().sortedBy{ k:String -> k }.map{ key -> Pair(key, items[key]) }
val delimited = sortedPairs.fold("", { acc, curr -> acc + "," + curr.first + "=" + curr.second } )
return Success("ok", msg = delimited)
}
@Action(desc = "accepts an encrypted int that will be decrypted", roles= [Roles.ALL])
fun inputDecInt(id: EncInt): Notice<String> {
return Success("ok", msg ="decrypted int : " + id.value)
}
@Action(desc = "accepts an encrypted long that will be decrypted", roles= [Roles.ALL])
fun inputDecLong(id: EncLong): Notice<String> {
return Success("ok", msg ="decrypted long : " + id.value)
}
@Action(desc = "accepts an encrypted double that will be decrypted", roles= [Roles.ALL])
fun inputDecDouble(id: EncDouble): Notice<String>
{
return Success("ok", msg = "decrypted double : " + id.value)
}
@Action(desc = "accepts an encrypted string that will be decrypted", roles= [Roles.ALL])
fun inputDecString(id: EncString): Notice<String>
{
return Success("ok", msg = "decrypted string : " + id.value)
}
@Action(desc = "accepts a smart string of phone", roles= [Roles.GUEST])
fun smartStringPhone(text: PhoneUS): String = "${text.value}"
@Action(desc = "accepts a smart string of email", roles= [Roles.GUEST])
fun smartStringEmail(text: Email): String = "${text.value}"
}
| src/lib/kotlin/slatekit-tests/src/test/kotlin/test/setup/SampleAnnoApi.kt | 1031882245 |
@file:JvmName("ActivityExtensions")
package acr.browser.lightning.extensions
import android.app.Activity
import android.view.View
import androidx.annotation.StringRes
import com.google.android.material.snackbar.Snackbar
/**
* Displays a snackbar to the user with a [StringRes] message.
*
* NOTE: If there is an accessibility manager enabled on
* the device, such as LastPass, then the snackbar animations
* will not work.
*
* @param resource the string resource to display to the user.
*/
fun Activity.snackbar(@StringRes resource: Int) {
val view = findViewById<View>(android.R.id.content)
Snackbar.make(view, resource, Snackbar.LENGTH_SHORT).show()
}
/**
* Display a snackbar to the user with a [String] message.
*
* @param message the message to display to the user.
* @see snackbar
*/
fun Activity.snackbar(message: String) {
val view = findViewById<View>(android.R.id.content)
Snackbar.make(view, message, Snackbar.LENGTH_SHORT).show()
}
| app/src/main/java/acr/browser/lightning/extensions/ActivityExtensions.kt | 460197075 |
/*
* 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.widget
import android.content.Context
import android.net.Uri
import android.os.Build
import android.util.AttributeSet
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputConnection
import androidx.appcompat.widget.AppCompatEditText
import androidx.core.view.inputmethod.EditorInfoCompat
import androidx.core.view.inputmethod.InputConnectionCompat
import androidx.core.view.inputmethod.InputContentInfoCompat
/**
* Created by moko256 on 2017/12/20.
*
* @author moko256
*/
class ImageKeyboardEditText : AppCompatEditText {
constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(context, attrs, defStyle)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context) : super(context)
var imageAddedListener: OnImageAddedListener? = null
private var permitInputContentInfo: InputContentInfoCompat? = null
override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection {
val ic = super.onCreateInputConnection(outAttrs)
EditorInfoCompat.setContentMimeTypes(outAttrs, arrayOf("image/*", "video/*"))
return InputConnectionCompat.createWrapper(ic, outAttrs) { inputContentInfo, flags, _ ->
if (Build.VERSION.SDK_INT >= 25 && flags and InputConnectionCompat.INPUT_CONTENT_GRANT_READ_URI_PERMISSION != 0) {
try {
inputContentInfo.requestPermission()
permitInputContentInfo = inputContentInfo
} catch (e: Exception) {
return@createWrapper false
}
}
val result = imageAddedListener?.onAdded(inputContentInfo.contentUri)
if (inputContentInfo.linkUri != null && result == true) {
text?.append(" " + inputContentInfo.linkUri?.toString())
}
true
}
}
fun close() {
permitInputContentInfo?.releasePermission()
imageAddedListener = null
}
interface OnImageAddedListener {
fun onAdded(imageUri: Uri): Boolean
}
} | app/src/main/java/com/github/moko256/twitlatte/widget/ImageKeyboardEditText.kt | 3316327255 |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.configurationStore
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.*
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ex.ProjectManagerEx
import org.jdom.Element
import java.io.Writer
import java.nio.file.Path
import java.nio.file.Paths
private const val FILE_SPEC = "${APP_CONFIG}/project.default.xml"
private class DefaultProjectStorage(file: Path, fileSpec: String, pathMacroManager: PathMacroManager) : FileBasedStorage(file, fileSpec, "defaultProject", pathMacroManager.createTrackingSubstitutor(), RoamingType.DISABLED) {
override val configuration = object: FileBasedStorageConfiguration by defaultFileBasedStorageConfiguration {
override val isUseVfsForWrite: Boolean
get() = false
}
public override fun loadLocalData(): Element? {
val element = super.loadLocalData() ?: return null
try {
return element.getChild("component")?.getChild("defaultProject")
}
catch (e: NullPointerException) {
LOG.warn("Cannot read default project")
return null
}
}
override fun createSaveSession(states: StateMap) = object : FileBasedStorage.FileSaveSession(states, this) {
override fun saveLocally(dataWriter: DataWriter?) {
super.saveLocally(when (dataWriter) {
null -> null
else -> object : StringDataWriter() {
override fun hasData(filter: DataWriterFilter) = dataWriter.hasData(filter)
override fun write(writer: Writer, lineSeparator: String, filter: DataWriterFilter?) {
val lineSeparatorWithIndent = "$lineSeparator "
writer.append("<application>").append(lineSeparator)
writer.append(""" <component name="ProjectManager">""")
writer.append(lineSeparatorWithIndent)
(dataWriter as StringDataWriter).write(writer, lineSeparatorWithIndent, filter)
writer.append(lineSeparator)
writer.append(" </component>").append(lineSeparator)
writer.append("</application>")
}
}
})
}
}
}
// cannot be `internal`, used in Upsource
class DefaultProjectStoreImpl(override val project: Project) : ChildlessComponentStore() {
// see note about default state in project store
override val loadPolicy: StateLoadPolicy
get() = if (ApplicationManager.getApplication().isUnitTestMode) StateLoadPolicy.NOT_LOAD else StateLoadPolicy.LOAD
private val storage by lazy {
DefaultProjectStorage(Paths.get(ApplicationManager.getApplication().stateStore.storageManager.expandMacros(FILE_SPEC)), FILE_SPEC, PathMacroManager.getInstance(project))
}
override val storageManager = object : StateStorageManager {
override val componentManager: ComponentManager?
get() = null
override fun addStreamProvider(provider: StreamProvider, first: Boolean) {
}
override fun removeStreamProvider(clazz: Class<out StreamProvider>) {
}
override fun rename(path: String, newName: String) {
}
override fun getStateStorage(storageSpec: Storage) = storage
override fun expandMacros(path: String) = throw UnsupportedOperationException()
override fun getOldStorage(component: Any, componentName: String, operation: StateStorageOperation) = storage
}
override fun isUseLoadedStateAsExisting(storage: StateStorage) = false
// don't want to optimize and use already loaded data - it will add unnecessary complexity and implementation-lock (currently we store loaded archived state in memory, but later implementation can be changed)
fun getStateCopy() = storage.loadLocalData()
override fun getPathMacroManagerForDefaults() = PathMacroManager.getInstance(project)
override fun <T> getStorageSpecs(component: PersistentStateComponent<T>, stateSpec: State, operation: StateStorageOperation) = listOf(PROJECT_FILE_STORAGE_ANNOTATION)
override fun setPath(path: String) {
}
override fun toString() = "default project"
}
// ExportSettingsAction checks only "State" annotation presence, but doesn't require PersistentStateComponent implementation, so, we can just specify annotation
@State(name = "ProjectManager", storages = [(Storage(FILE_SPEC))])
internal class DefaultProjectExportableAndSaveTrigger {
suspend fun save(forceSavingAllSettings: Boolean): SaveResult {
val result = SaveResult()
(ProjectManagerEx.getInstanceEx().defaultProject.stateStore as ComponentStoreImpl).doSave(result, forceSavingAllSettings)
return result
}
} | platform/configuration-store-impl/src/DefaultProjectStoreImpl.kt | 2085025202 |
package codegen.controlflow.for_loops_nested
import kotlin.test.*
@Test fun runTest() {
// Simple
for (i in 0..2) {
for (j in 0..2) {
print("$i$j ")
}
}
println()
// Break
l1@for (i in 0..2) {
l2@for (j in 0..2) {
print("$i$j ")
if (j == 1) break
}
}
println()
l1@for (i in 0..2) {
l2@for (j in 0..2) {
print("$i$j ")
if (j == 1) break@l2
}
}
println()
l1@for (i in 0..2) {
l2@for (j in 0..2) {
print("$i$j ")
if (j == 1) break@l1
}
}
println()
// Continue
l1@for (i in 0..2) {
l2@for (j in 0..2) {
if (j == 1) continue
print("$i$j ")
}
}
println()
l1@for (i in 0..2) {
l2@for (j in 0..2) {
if (j == 1) continue@l2
print("$i$j ")
}
}
println()
l1@for (i in 0..2) {
l2@for (j in 0..2) {
if (j == 1) continue@l1
print("$i$j ")
}
}
println()
} | backend.native/tests/codegen/controlflow/for_loops_nested.kt | 24859479 |
package com.jamescoggan.smartgps.Observables
import android.content.Context
import android.location.Location
import com.jamescoggan.smartgps.Logger.SmartLog
import org.joda.time.DateTime
import org.joda.time.Seconds
import rx.Observable
class OneGpsFixObservable private constructor(ctx: Context) : BaseObservable<Location>(ctx, null) {
override fun isConnected() {
SmartLog.d("isConnected")
val location = baseProvider.lastKnowLocation
if (Seconds.secondsBetween(DateTime.now(), DateTime(location.time))
.isLessThan(Seconds.ONE)) {
SmartLog.d("Last gps fix at %s", DateTime(location.time))
SmartLog.d("Last location is valid seconds %d", Seconds.secondsBetween(DateTime.now(), DateTime(location.time)).seconds)
subscriber!!.onNext(location)
subscriber!!.onCompleted()
} else {
SmartLog.d("Last location is invalid")
baseProvider.startGpsUpdates()
}
}
override fun location(location: Location) {
SmartLog.d("Received location %s", location.toString())
baseProvider.stopGpsUpdates()
subscriber!!.onNext(location)
subscriber!!.onCompleted()
}
companion object {
fun createObservable(ctx: Context): Observable<Location> {
return Observable.create(OneGpsFixObservable(ctx))
}
}
} | smartgps/src/main/java/com/jamescoggan/smartgps/Observables/OneGpsFixObservable.kt | 3860210933 |
package ru.fantlab.android.ui.modules.awards.item
import android.view.View
import io.reactivex.Single
import io.reactivex.functions.Consumer
import ru.fantlab.android.data.dao.model.Awards
import ru.fantlab.android.data.dao.model.Nomination
import ru.fantlab.android.data.dao.model.Translator
import ru.fantlab.android.data.dao.response.AuthorResponse
import ru.fantlab.android.data.dao.response.PersonAwardsResponse
import ru.fantlab.android.data.dao.response.TranslatorResponse
import ru.fantlab.android.data.dao.response.WorkResponse
import ru.fantlab.android.provider.rest.*
import ru.fantlab.android.provider.storage.DbProvider
import ru.fantlab.android.ui.base.mvp.presenter.BasePresenter
class ItemAwardsPresenter : BasePresenter<ItemAwardsMvp.View>(),
ItemAwardsMvp.Presenter {
override fun getWorkAwards(workId: Int) {
makeRestCall(
getWorkAwardsInternal(workId).toObservable(),
Consumer { nominations ->
sendToView { it.onInitViews(nominations) }
}
)
}
private fun getWorkAwardsInternal(workId: Int) =
getWorkAwardsFromServer(workId)
.onErrorResumeNext {
getWorkAwardsFromDb(workId)
}
.onErrorResumeNext { ext -> Single.error(ext) }
.doOnError { err -> sendToView { it.showErrorMessage(err.message) } }
private fun getWorkAwardsFromServer(workId: Int):
Single<Awards> =
DataManager.getWork(workId, showAwards = true)
.map { getAwardsFromWork(it) }
private fun getWorkAwardsFromDb(workId: Int):
Single<Awards> =
DbProvider.mainDatabase
.responseDao()
.get(getWorkPath(workId, showAwards = true))
.map { it.response }
.map { WorkResponse.Deserializer().deserialize(it) }
.map { getAwardsFromWork(it) }
private fun getAwardsFromWork(response: WorkResponse): Awards? = response.awards
override fun getAuthorAwards(authorId: Int) {
makeRestCall(
getAuthorAwardsInternal(authorId).toObservable(),
Consumer { nominations ->
sendToView { it.onInitViews(nominations) }
}
)
}
private fun getAuthorAwardsInternal(authorId: Int) =
getAuthorAwardsFromServer(authorId)
.onErrorResumeNext {
getAuthorAwardsFromDb(authorId)
}
.onErrorResumeNext { ext -> Single.error(ext) }
.doOnError { err -> sendToView { it.showErrorMessage(err.message) } }
private fun getAuthorAwardsFromServer(authorId: Int):
Single<Awards> =
DataManager.getPersonAwards(authorId, "autor")
.map { getAwardsFromPerson(it) }
private fun getAuthorAwardsFromDb(authorId: Int):
Single<Awards> =
DbProvider.mainDatabase
.responseDao()
.get(getPersonAwardsPath(authorId, "autor"))
.map { it.response }
.map { PersonAwardsResponse.Deserializer().deserialize(it) }
.map { getAwardsFromPerson(it) }
override fun getTranslatorAwards(translatorId: Int) {
makeRestCall(
getTranslatorAwardsInternal(translatorId).toObservable(),
Consumer { nominations ->
sendToView { it.onInitViews(nominations) }
}
)
}
private fun getTranslatorAwardsInternal(translatorId: Int) =
getTranslatorAwardsFromServer(translatorId)
.onErrorResumeNext {
getTranslatorAwardsFromDb(translatorId)
}
.onErrorResumeNext { ext -> Single.error(ext) }
.doOnError { err -> sendToView { it.showErrorMessage(err.message) } }
private fun getTranslatorAwardsFromServer(translatorId: Int):
Single<Awards> =
DataManager.getPersonAwards(translatorId, "translator")
.map { getAwardsFromPerson(it) }
private fun getTranslatorAwardsFromDb(translatorId: Int):
Single<Awards> =
DbProvider.mainDatabase
.responseDao()
.get(getPersonAwardsPath(translatorId, "translator"))
.map { it.response }
.map { PersonAwardsResponse.Deserializer().deserialize(it) }
.map { getAwardsFromPerson(it) }
private fun getAwardsFromPerson(response: PersonAwardsResponse): Awards? {
var res = Awards(arrayListOf(), arrayListOf())
response.awards.forEach { nomination ->
if (nomination.isWinner == 1) {
res.wins.add(nomination)
} else {
res.nominations.add(nomination)
}
}
return res
}
} | app/src/main/kotlin/ru/fantlab/android/ui/modules/awards/item/ItemAwardsPresenter.kt | 3760780310 |
/*
* 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.activity.result
import android.content.Intent
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.junit.runner.RunWith
@SmallTest
@RunWith(AndroidJUnit4::class)
class ActivityResultTest {
@Test
fun testDestructure() {
val intent = Intent()
val (resultCode, data) = ActivityResult(1, intent)
assertThat(resultCode).isEqualTo(1)
assertThat(data).isSameInstanceAs(intent)
}
} | activity/activity-ktx/src/androidTest/java/androidx/activity/result/ActivityResultTest.kt | 4049678020 |
/*
* 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.room.compiler.processing.ksp
import androidx.room.compiler.processing.InternalXAnnotated
import androidx.room.compiler.processing.XAnnotation
import androidx.room.compiler.processing.XAnnotationBox
import androidx.room.compiler.processing.unwrapRepeatedAnnotationsFromContainer
import com.google.devtools.ksp.symbol.AnnotationUseSiteTarget
import com.google.devtools.ksp.symbol.KSAnnotated
import com.google.devtools.ksp.symbol.KSAnnotation
import com.google.devtools.ksp.symbol.KSTypeAlias
import java.lang.annotation.ElementType
import kotlin.reflect.KClass
internal sealed class KspAnnotated(
val env: KspProcessingEnv
) : InternalXAnnotated {
abstract fun annotations(): Sequence<KSAnnotation>
private fun <T : Annotation> findAnnotations(annotation: KClass<T>): Sequence<KSAnnotation> {
return annotations().filter { it.isSameAnnotationClass(annotation) }
}
override fun getAllAnnotations(): List<XAnnotation> {
return annotations().map { ksAnnotated ->
KspAnnotation(env, ksAnnotated)
}.flatMap { annotation ->
annotation.unwrapRepeatedAnnotationsFromContainer() ?: listOf(annotation)
}.toList()
}
override fun <T : Annotation> getAnnotations(
annotation: KClass<T>,
containerAnnotation: KClass<out Annotation>?
): List<XAnnotationBox<T>> {
// we'll try both because it can be the container or the annotation itself.
// try container first
if (containerAnnotation != null) {
// if container also repeats, this won't work but we don't have that use case
findAnnotations(containerAnnotation).firstOrNull()?.let {
return KspAnnotationBox(
env = env,
annotation = it,
annotationClass = containerAnnotation.java,
).getAsAnnotationBoxArray<T>("value").toList()
}
}
// didn't find anything with the container, try the annotation class
return findAnnotations(annotation).map {
KspAnnotationBox(
env = env,
annotationClass = annotation.java,
annotation = it
)
}.toList()
}
override fun hasAnnotationWithPackage(pkg: String): Boolean {
return annotations().any {
it.annotationType.resolve().declaration.qualifiedName?.getQualifier() == pkg
}
}
override fun hasAnnotation(
annotation: KClass<out Annotation>,
containerAnnotation: KClass<out Annotation>?
): Boolean {
return annotations().any {
it.isSameAnnotationClass(annotation) ||
(containerAnnotation != null && it.isSameAnnotationClass(containerAnnotation))
}
}
private class KSAnnotatedDelegate(
env: KspProcessingEnv,
private val delegate: KSAnnotated,
private val useSiteFilter: UseSiteFilter
) : KspAnnotated(env) {
override fun annotations(): Sequence<KSAnnotation> {
return delegate.annotations.filter {
useSiteFilter.accept(env, it)
}
}
}
private class NotAnnotated(env: KspProcessingEnv) : KspAnnotated(env) {
override fun annotations(): Sequence<KSAnnotation> {
return emptySequence()
}
}
/**
* Annotation use site filter
*
* https://kotlinlang.org/docs/annotations.html#annotation-use-site-targets
*/
interface UseSiteFilter {
fun accept(env: KspProcessingEnv, annotation: KSAnnotation): Boolean
private class Impl(
val acceptedSiteTarget: AnnotationUseSiteTarget,
val acceptedTarget: AnnotationTarget,
private val acceptNoTarget: Boolean = true,
) : UseSiteFilter {
override fun accept(env: KspProcessingEnv, annotation: KSAnnotation): Boolean {
val useSiteTarget = annotation.useSiteTarget
val annotationTargets = annotation.getDeclaredTargets(env)
return if (useSiteTarget != null) {
acceptedSiteTarget == useSiteTarget
} else if (annotationTargets.isNotEmpty()) {
annotationTargets.contains(acceptedTarget)
} else {
acceptNoTarget
}
}
}
companion object {
val NO_USE_SITE = object : UseSiteFilter {
override fun accept(env: KspProcessingEnv, annotation: KSAnnotation): Boolean {
return annotation.useSiteTarget == null
}
}
val NO_USE_SITE_OR_FIELD: UseSiteFilter = Impl(
acceptedSiteTarget = AnnotationUseSiteTarget.FIELD,
acceptedTarget = AnnotationTarget.FIELD
)
val NO_USE_SITE_OR_METHOD_PARAMETER: UseSiteFilter = Impl(
acceptedSiteTarget = AnnotationUseSiteTarget.PARAM,
acceptedTarget = AnnotationTarget.VALUE_PARAMETER
)
val NO_USE_SITE_OR_GETTER: UseSiteFilter = Impl(
acceptedSiteTarget = AnnotationUseSiteTarget.GET,
acceptedTarget = AnnotationTarget.PROPERTY_GETTER
)
val NO_USE_SITE_OR_SETTER: UseSiteFilter = Impl(
acceptedSiteTarget = AnnotationUseSiteTarget.SET,
acceptedTarget = AnnotationTarget.PROPERTY_SETTER
)
val NO_USE_SITE_OR_SET_PARAM: UseSiteFilter = Impl(
acceptedSiteTarget = AnnotationUseSiteTarget.SETPARAM,
acceptedTarget = AnnotationTarget.PROPERTY_SETTER
)
val FILE: UseSiteFilter = Impl(
acceptedSiteTarget = AnnotationUseSiteTarget.FILE,
acceptedTarget = AnnotationTarget.FILE,
acceptNoTarget = false
)
private fun KSAnnotation.getDeclaredTargets(
env: KspProcessingEnv
): Set<AnnotationTarget> {
val annotationDeclaration = this.annotationType.resolve().declaration
val kotlinTargets = annotationDeclaration.annotations.firstOrNull {
it.isSameAnnotationClass(kotlin.annotation.Target::class)
}?.let { targetAnnotation ->
KspAnnotation(env, targetAnnotation)
.asAnnotationBox(kotlin.annotation.Target::class.java)
.value.allowedTargets
}?.toSet() ?: emptySet()
val javaTargets = annotationDeclaration.annotations.firstOrNull {
it.isSameAnnotationClass(java.lang.annotation.Target::class)
}?.let { targetAnnotation ->
KspAnnotation(env, targetAnnotation)
.asAnnotationBox(java.lang.annotation.Target::class.java)
.value.value.toList()
}?.mapNotNull { it.toAnnotationTarget() }?.toSet() ?: emptySet()
return kotlinTargets + javaTargets
}
private fun ElementType.toAnnotationTarget() = when (this) {
ElementType.TYPE -> AnnotationTarget.CLASS
ElementType.FIELD -> AnnotationTarget.FIELD
ElementType.METHOD -> AnnotationTarget.FUNCTION
ElementType.PARAMETER -> AnnotationTarget.VALUE_PARAMETER
ElementType.CONSTRUCTOR -> AnnotationTarget.CONSTRUCTOR
ElementType.LOCAL_VARIABLE -> AnnotationTarget.LOCAL_VARIABLE
ElementType.ANNOTATION_TYPE -> AnnotationTarget.ANNOTATION_CLASS
ElementType.TYPE_PARAMETER -> AnnotationTarget.TYPE_PARAMETER
ElementType.TYPE_USE -> AnnotationTarget.TYPE
else -> null
}
}
}
companion object {
fun create(
env: KspProcessingEnv,
delegate: KSAnnotated?,
filter: UseSiteFilter
): KspAnnotated {
return delegate?.let {
KSAnnotatedDelegate(env, it, filter)
} ?: NotAnnotated(env)
}
internal fun KSAnnotation.isSameAnnotationClass(
annotationClass: KClass<out Annotation>
): Boolean {
var declaration = annotationType.resolve().declaration
while (declaration is KSTypeAlias) {
declaration = declaration.type.resolve().declaration
}
val qualifiedName = declaration.qualifiedName?.asString() ?: return false
return qualifiedName == annotationClass.qualifiedName
}
}
} | room/room-compiler-processing/src/main/java/androidx/room/compiler/processing/ksp/KspAnnotated.kt | 348125422 |
/*
* 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.preference.tests
import android.content.Context
import android.graphics.drawable.Drawable
import android.widget.TextView
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import androidx.preference.PreferenceViewHolder
import androidx.preference.test.R
import androidx.preference.tests.helpers.PreferenceTestHelperActivity
import androidx.test.annotation.UiThreadTest
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.repeatedlyUntil
import androidx.test.espresso.action.ViewActions.swipeUp
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.hasDescendant
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.espresso.matcher.ViewMatchers.withText
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
/**
* Test for resetting [PreferenceViewHolder] state.
*/
@RunWith(AndroidJUnit4::class)
@LargeTest
class PreferenceViewHolderStateTest {
@Suppress("DEPRECATION")
@get:Rule
val activityRule = androidx.test.rule.ActivityTestRule(PreferenceTestHelperActivity::class.java)
private lateinit var fragment: PreferenceFragmentCompat
@Before
@UiThreadTest
fun setUp() {
fragment = activityRule.activity.setupPreferenceHierarchy()
}
@Test
fun testReusingViewHolder_unselectablePreference_stateReset() {
val preferenceScreen = fragment.preferenceScreen
val copyableTitle = "Copyable"
// Add 20 unselectable + copyable Preferences. This is so that when we add a new item, it
// will be offscreen, and when scrolling to it RecyclerView will attempt to reuse an
// existing cached ViewHolder.
val preferences = (1..20).map { index ->
TestPreference(fragment.context!!).apply {
title = copyableTitle + index
summary = "Summary to copy"
isCopyingEnabled = true
isSelectable = false
}
}
activityRule.runOnUiThread {
preferences.forEach { preferenceScreen.addPreference(it) }
}
// Wait for a Preference to be visible
onView(withText("${copyableTitle}1")).check(matches(isDisplayed()))
// The title color should be the same as the summary color for unselectable Preferences
val unselectableTitleColor = preferences[0].titleColor
val unselectableSummaryColor = preferences[0].summaryColor
assertEquals(unselectableTitleColor!!, unselectableSummaryColor!!)
val normalTitle = "Normal"
// Add a normal, selectable Preference to the end. This will currently be displayed off
// screen, and not yet bound.
val normalPreference = TestPreference(fragment.context!!).apply {
title = normalTitle
summary = "Normal summary"
}
// Assert that we haven't bound this Preference yet
assertNull(normalPreference.background)
assertNull(normalPreference.titleColor)
assertNull(normalPreference.summaryColor)
activityRule.runOnUiThread {
preferenceScreen.addPreference(normalPreference)
}
val maxAttempts = 10
// Scroll until we find the new Preference, which will trigger RecyclerView to rebind an
// existing cached ViewHolder, so we can ensure that the state is reset. We use swipeUp
// here instead of scrolling directly to the item, as we need to allow time for older
// views to be cached first, instead of instantly snapping to the item.
onView(withId(R.id.recycler_view))
.perform(repeatedlyUntil(swipeUp(), hasDescendant(withText(normalTitle)), maxAttempts))
// We should have a ripple / state list drawable as the background
assertNotNull(normalPreference.background)
// The title color should be different from the title of the unselected Preference
assertNotEquals(unselectableTitleColor, normalPreference.titleColor)
// The summary color should be the same as the unselected Preference
assertEquals(unselectableSummaryColor, normalPreference.summaryColor)
}
@Test
fun testReusingViewHolder_disabledPreference_stateReset() {
val preferenceScreen = fragment.preferenceScreen
val disabledTitle = "Disabled"
// Add 40 disabled Preferences. The ones at the end haven't been bound yet, and we want
// to ensure that when they are bound, reusing a ViewHolder, they should have the correct
// disabled state.
val preferences = (1..40).map { index ->
TestPreference(fragment.context!!).apply {
title = disabledTitle + index
isEnabled = false
}
}
activityRule.runOnUiThread {
preferences.forEach { preferenceScreen.addPreference(it) }
}
// Wait for a Preference to be visible
onView(withText("${disabledTitle}1")).check(matches(isDisplayed()))
val expectedTitleColor = preferences[0].titleColor
val maxAttempts = 10
// Scroll until the end, ensuring all Preferences have been bound.
onView(withId(R.id.recycler_view))
.perform(
repeatedlyUntil(
swipeUp(),
hasDescendant(withText("${disabledTitle}40")),
maxAttempts
)
)
// All preferences should have the correct title color
preferences.forEach { preference ->
assertEquals(expectedTitleColor, preference.titleColor)
}
}
}
/**
* Testing [Preference] class that records the background [Drawable] and the color of its title
* and summary once bound.
*/
private class TestPreference(context: Context) : Preference(context) {
var background: Drawable? = null
var titleColor: Int? = null
var summaryColor: Int? = null
override fun onBindViewHolder(holder: PreferenceViewHolder) {
super.onBindViewHolder(holder)
background = holder.itemView.background
titleColor = (holder.findViewById(android.R.id.title) as TextView).currentTextColor
summaryColor = (holder.findViewById(android.R.id.summary) as TextView).currentTextColor
}
}
| preference/preference/src/androidTest/java/androidx/preference/tests/PreferenceViewHolderStateTest.kt | 2926387519 |
// 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.intellij.plugins.markdown.extensions.common
import com.intellij.openapi.project.Project
import org.intellij.plugins.markdown.extensions.MarkdownBrowserPreviewExtension
import org.intellij.plugins.markdown.settings.MarkdownSettings
import org.intellij.plugins.markdown.ui.preview.MarkdownHtmlPanel
import org.intellij.plugins.markdown.ui.preview.PreviewLAFThemeStyles
import org.intellij.plugins.markdown.ui.preview.ResourceProvider
import java.io.File
internal class BaseStylesExtension(private val project: Project?) : MarkdownBrowserPreviewExtension, ResourceProvider {
override val priority = MarkdownBrowserPreviewExtension.Priority.BEFORE_ALL
override val styles: List<String> = listOf("baseStyles/default.css", COLORS_CSS_FILENAME)
override val resourceProvider: ResourceProvider = this
override fun loadResource(resourceName: String): ResourceProvider.Resource? {
if (resourceName == COLORS_CSS_FILENAME) {
return ResourceProvider.Resource(PreviewLAFThemeStyles.createStylesheet().toByteArray())
}
val settings = project?.let(MarkdownSettings::getInstance)
val path = settings?.customStylesheetPath.takeIf { settings?.useCustomStylesheetPath == true }
return when (path) {
null -> ResourceProvider.loadInternalResource(BaseStylesExtension::class, resourceName)
else -> ResourceProvider.loadExternalResource(File(path))
}
}
override fun canProvide(resourceName: String): Boolean = resourceName in styles
override fun dispose() = Unit
class Provider: MarkdownBrowserPreviewExtension.Provider {
override fun createBrowserExtension(panel: MarkdownHtmlPanel): MarkdownBrowserPreviewExtension {
return BaseStylesExtension(panel.project)
}
}
companion object {
private const val COLORS_CSS_FILENAME = "baseStyles/colors.css"
}
}
| plugins/markdown/core/src/org/intellij/plugins/markdown/extensions/common/BaseStylesExtension.kt | 352762148 |
class Foo
fun foo(p : Any){
var a : Foo? = <caret>
}
// ELEMENT: Foo
| plugins/kotlin/completion/tests/testData/handlers/smart/ConstructorForNullable.kt | 3608689715 |
// "Specify supertype" "true"
// DISABLE-ERRORS
interface Z {
fun foo(): CharSequence = ""
}
open class Y {
override fun foo(): String = ""
}
class Test : Z, Y() {
override fun foo(): String {
return <caret>super.foo()
}
} | plugins/kotlin/idea/tests/testData/quickfix/specifySuperType/typeMismatch.kt | 215792149 |
// "Add '@Throws' annotation" "true"
fun test() {
<caret>throw Throwable()
} | plugins/kotlin/idea/tests/testData/multiModuleQuickFix/addThrowAnnotation/jvm/jvm_dep(stdlib)/jvm.kt | 3753232468 |
// "Replace with 'emptyList()' call" "true"
// WITH_STDLIB
fun foo(a: String?): Collection<String> {
val w = a ?: return null<caret>
return listOf(w)
}
| plugins/kotlin/idea/tests/testData/quickfix/typeMismatch/wrapWithCollectionLiteral/returnEmptyCollection.kt | 231408790 |
/*
* Copyright (C) 2017 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 com.example.android.system.runtimepermissions.extensions
import android.content.pm.PackageManager
import android.support.v4.app.ActivityCompat
import android.support.v7.app.AppCompatActivity
fun AppCompatActivity.isPermissionGranted(permission: String) =
ActivityCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED
fun AppCompatActivity.shouldShowPermissionRationale(permission: String) =
ActivityCompat.shouldShowRequestPermissionRationale(this, permission)
fun AppCompatActivity.requestPermission(permission: String, requestId: Int) =
ActivityCompat.requestPermissions(this, arrayOf(permission), requestId)
fun AppCompatActivity.batchRequestPermissions(permissions: Array<String>, requestId: Int) =
ActivityCompat.requestPermissions(this, permissions, requestId) | kotlinApp/app/src/main/java/com/example/android/system/runtimepermissions/extensions/AppCompatActivityExts.kt | 3850043438 |
package org.ccci.gto.android.common.napier
import android.util.Log
import io.github.aakira.napier.Antilog
import io.github.aakira.napier.LogLevel
import timber.log.Timber
object TimberAntilog : Antilog() {
override fun performLog(priority: LogLevel, tag: String?, throwable: Throwable?, message: String?) =
Timber.apply { tag?.let { tag(it) } }.log(priority.toValue(), throwable, message)
private fun LogLevel.toValue() = when (this) {
LogLevel.VERBOSE -> Log.VERBOSE
LogLevel.DEBUG -> Log.DEBUG
LogLevel.INFO -> Log.INFO
LogLevel.WARNING -> Log.WARN
LogLevel.ERROR -> Log.ERROR
LogLevel.ASSERT -> Log.ASSERT
}
}
| gto-support-napier/src/main/kotlin/org/ccci/gto/android/common/napier/TimberAntilog.kt | 2474262499 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.externalSystem.test
import com.intellij.platform.externalSystem.testFramework.*
import com.intellij.externalSystem.JavaProjectData
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.pom.java.LanguageLevel
class JavaProject : AbstractNode<JavaProjectData>("javaProject") {
var compileOutputPath: String
get() = props["compileOutputPath"]!!
set(value) {
props["compileOutputPath"] = value
}
var languageLevel: LanguageLevel?
get() = props["languageLevel"]?.run { LanguageLevel.valueOf(this) }
set(value) {
if (value == null) props.remove("languageLevel")
else props["languageLevel"] = value.name
}
var targetBytecodeVersion: String?
get() = props["targetBytecodeVersion"]
set(value) {
if (value == null) props.remove("targetBytecodeVersion")
else props["targetBytecodeVersion"] = value
}
override fun createDataNode(parentData: Any?): DataNode<JavaProjectData> {
val javaProjectData = JavaProjectData(systemId, compileOutputPath, languageLevel, targetBytecodeVersion)
return DataNode(JavaProjectData.KEY, javaProjectData, null)
}
}
fun Project.javaProject(compileOutputPath: String,
languageLevel: LanguageLevel? = null,
targetBytecodeVersion: String? = null) =
initChild(JavaProject()) {
this.compileOutputPath = compileOutputPath
this.languageLevel = languageLevel
this.targetBytecodeVersion = targetBytecodeVersion
}
| platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/test/JavaTestProjectModelBuilder.kt | 3058753410 |
package com.junerver.cloudnote.ui.fragment
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.AnimationUtils
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.drakeet.multitype.MultiTypeAdapter
import com.junerver.cloudnote.net.BmobMethods
import com.edusoa.ideallecturer.createJsonRequestBody
import com.edusoa.ideallecturer.fetchNetwork
import com.edusoa.ideallecturer.toBean
import com.edusoa.ideallecturer.toJson
import com.elvishew.xlog.XLog
import com.idealworkshops.idealschool.utils.SpUtils
import com.junerver.cloudnote.Constants
import com.junerver.cloudnote.R
import com.junerver.cloudnote.adapter.NoteViewBinder
import com.junerver.cloudnote.bean.*
import com.junerver.cloudnote.databinding.FragmentNoteBinding
import com.junerver.cloudnote.db.NoteUtils
import com.junerver.cloudnote.ui.activity.EditNoteActivity
import com.junerver.cloudnote.utils.NetUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import java.util.*
/**
* A simple [Fragment] subclass.
*/
class NoteFragment : BaseFragment() {
private var _binding: FragmentNoteBinding? = null
private val binding get() = _binding!!
private lateinit var mLayoutManager: LinearLayoutManager
private val adapter = MultiTypeAdapter()
private val items = ArrayList<Any>()
private lateinit var mContext: Context
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentNoteBinding.inflate(inflater, container, false)
mContext = requireContext()
init()
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
XLog.d("自动同步一次")
syncToDb()
}
private fun init() {
val binder = NoteViewBinder()
binder.setLongClickListener { item ->
val builder: AlertDialog.Builder = AlertDialog.Builder(mContext)
builder.setTitle("确认要删除这个笔记么?")
builder.setPositiveButton(
"确认"
) { _, _ ->
if (NetUtils.isConnected(mContext)) {
lifecycleScope.launch {
//云端删除
fetchNetwork {
doNetwork {
BmobMethods.INSTANCE.delNoteById(item.objId)
}
onSuccess {
val delResp = it.toBean<DelResp>()
//本地删除
item.delete()
listAllFromDb()
}
onHttpError { errorBody, errorMsg, code ->
errorBody?.let {
val bean = it.toBean<ErrorResp>()
if (code == 101) {
//云端没有该对象
item.delete()
} else {
item.isLocalDel = true
item.saveOrUpdate("objId = ?", item.objId)
}
listAllFromDb()
}
}
}
}
} else {
item.isLocalDel = true
item.saveOrUpdate("objId = ?", item.objId)
listAllFromDb()
}
}
builder.setNegativeButton("取消", null)
builder.show()
}
adapter.register(binder)
binding.rvList.adapter = adapter
//设置固定大小
binding.rvList.setHasFixedSize(true)
//创建线性布局
mLayoutManager = LinearLayoutManager(activity)
//垂直方向
mLayoutManager.orientation = RecyclerView.VERTICAL
//给RecyclerView设置布局管理器
binding.rvList.layoutManager = mLayoutManager
adapter.items = items
//同步按钮点击事件
binding.ivSync.setOnClickListener {
binding.ivSync.startAnimation(
//动画效果
AnimationUtils.loadAnimation(
activity,
R.anim.anim_sync
)
)
syncToDb()
}
binding.fabAddNote.setOnClickListener {
startActivity(Intent(activity, EditNoteActivity::class.java))
}
listAllFromDb()
}
private fun syncToDb() {
lifecycleScope.launch {
//sync to db
flow {
val map = mapOf("userObjId" to SpUtils.decodeString(Constants.SP_USER_ID))
val resp = BmobMethods.INSTANCE.getAllNoteByUserId(map.toJson())
emit(resp)
}.catch { e ->
XLog.e(e)
}.flatMapConcat {
val allNote = it.toBean<GetAllNoteResp>()
allNote.results.asFlow()
}.onEach { note ->
//云端的每一条笔记
val objId = note.objectId
//根据bmob的objid查表
val dbBean = NoteUtils.queryNoteById(objId)
if (dbBean == null) {
//本地没有次数据 新建本地数据并保存数据库
val entity = note.toEntity()
entity.save()
XLog.d("本地没有该数据 新建\n$entity")
}
//存在本地对象 对比是否跟新 or 删除
dbBean?.let {
if (it.isLocalDel) {
//本地删除
val resp = BmobMethods.INSTANCE.delNoteById(it.objId)
if (resp.contains("ok")) {
//远端删除成功 本地删除
it.delete()
XLog.d("远端删除成功 本地删除\n$resp")
}
return@let
}
//未本地删除对比数据相互更新
when {
note.updatedTime > it.updatedTime -> {
//云端内容更新更新本地数据
it.update(note)
XLog.d("使用云端数据更新本地数据库\n$it\n$note")
}
note.updatedTime < it.updatedTime -> {
//云端数据小于本地 更新云端
note.update(it)
val resp = BmobMethods.INSTANCE.putNoteById(
objId,
note.toJson(excludeFields = Constants.DEFAULT_EXCLUDE_FIELDS)
.createJsonRequestBody()
)
val putResp = resp.toBean<PutResp>()
XLog.d("使用本地数据更新云端数据 \n$it\n$note")
}
else -> {
//数据相同 do nothing
XLog.d("本地数据与云端数据相同\n$it\n$note")
return@let
}
}
it.isSync = true
it.save()
}
}.flowOn(Dispatchers.IO).onCompletion {
//完成时调用与末端流操作符处于同一个协程上下文范围
XLog.d("Bmob☁️同步执行完毕,开始同步本地数据到云端")
syncToBmob()
}.collect {
}
}
}
//同步本地其他数据到云端
private suspend fun syncToBmob() {
//未同步的即本地有而云端无
NoteUtils.listNotSync().asFlow()
.onEach {
XLog.d(it)
if (it.objId.isEmpty()) {
//本地有云端无 本地无objId 直接上传
val note = it.toBmob()
val resp = BmobMethods.INSTANCE.postNote(
note.toJson(excludeFields = Constants.DEFAULT_EXCLUDE_FIELDS)
.createJsonRequestBody()
)
val postResp = resp.toBean<PostResp>()
//保存objectId
it.objId = postResp.objectId
XLog.d("本地有云端无 新建数据")
} else {
//云端同步后 本地不可能出现本地有记录,且存在云端objid,但是没有和云端同步
// 这种情况只可能是云端手动删除了记录,但是本地没有同步,
// 即一个账号登录了两个客户端,但是在一个客户端中对该记录进行了删除,在另一个客户端中还存在本地记录
//此情况可以加入特殊标记 isCloudDel
it.isCloudDel = true
XLog.d("不太可能出现的一种情况\n$it")
}
it.isSync = true
it.save()
}.flowOn(Dispatchers.IO).onCompletion {
//完成时调用与末端流操作符处于同一个协程上下文范围
listAllFromDb()
}.collect {
XLog.d(it)
}
}
//列出本地数据
private fun listAllFromDb() {
lifecycleScope.launch {
val dbwork = async(Dispatchers.IO) {
NoteUtils.listAll()
}
val list = dbwork.await()
items.clear()
items.addAll(list)
adapter.notifyDataSetChanged()
}
}
override fun onResume() {
super.onResume()
listAllFromDb()
}
} | app/src/main/java/com/junerver/cloudnote/ui/fragment/NoteFragment.kt | 4258601866 |
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.configurationStore
import com.intellij.AbstractBundle
import com.intellij.CommonBundle
import com.intellij.ide.IdeBundle
import com.intellij.ide.actions.ImportSettingsFilenameFilter
import com.intellij.ide.actions.ShowFilePathAction
import com.intellij.ide.plugins.IdeaPluginDescriptor
import com.intellij.ide.plugins.PluginManager
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.application.impl.ApplicationImpl
import com.intellij.openapi.components.*
import com.intellij.openapi.components.impl.ServiceManagerImpl
import com.intellij.openapi.components.impl.stores.StoreUtil
import com.intellij.openapi.extensions.PluginDescriptor
import com.intellij.openapi.options.OptionsBundle
import com.intellij.openapi.options.SchemeManagerFactory
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.vfs.CharsetToolkit
import com.intellij.util.PlatformUtils
import com.intellij.util.ReflectionUtil
import com.intellij.util.containers.putValue
import com.intellij.util.io.*
import gnu.trove.THashMap
import gnu.trove.THashSet
import java.io.IOException
import java.io.OutputStream
import java.io.OutputStreamWriter
import java.nio.file.Path
import java.nio.file.Paths
import java.util.*
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
private class ExportSettingsAction : AnAction(), DumbAware {
override fun actionPerformed(e: AnActionEvent?) {
ApplicationManager.getApplication().saveSettings()
val dialog = ChooseComponentsToExportDialog(getExportableComponentsMap(true, true), true,
IdeBundle.message("title.select.components.to.export"),
IdeBundle.message(
"prompt.please.check.all.components.to.export"))
if (!dialog.showAndGet()) {
return
}
val markedComponents = dialog.exportableComponents
if (markedComponents.isEmpty()) {
return
}
val exportFiles = markedComponents.mapTo(THashSet()) { it.file }
val saveFile = dialog.exportFile
try {
if (saveFile.exists() && Messages.showOkCancelDialog(
IdeBundle.message("prompt.overwrite.settings.file", saveFile.toString()),
IdeBundle.message("title.file.already.exists"), Messages.getWarningIcon()) != Messages.OK) {
return
}
exportSettings(exportFiles, saveFile.outputStream(), FileUtilRt.toSystemIndependentName(PathManager.getConfigPath()))
ShowFilePathAction.showDialog(getEventProject(e), IdeBundle.message("message.settings.exported.successfully"),
IdeBundle.message("title.export.successful"), saveFile.toFile(), null)
}
catch (e1: IOException) {
Messages.showErrorDialog(IdeBundle.message("error.writing.settings", e1.toString()), IdeBundle.message("title.error.writing.file"))
}
}
}
// not internal only to test
fun exportSettings(exportFiles: Set<Path>, out: OutputStream, configPath: String) {
val zipOut = MyZipOutputStream(out)
try {
val writtenItemRelativePaths = THashSet<String>()
for (file in exportFiles) {
if (file.exists()) {
val relativePath = FileUtilRt.getRelativePath(configPath, file.toAbsolutePath().systemIndependentPath, '/')!!
ZipUtil.addFileOrDirRecursively(zipOut, null, file.toFile(), relativePath, null, writtenItemRelativePaths)
}
}
exportInstalledPlugins(zipOut)
val zipEntry = ZipEntry(ImportSettingsFilenameFilter.SETTINGS_JAR_MARKER)
zipOut.putNextEntry(zipEntry)
zipOut.closeEntry()
}
finally {
zipOut.doClose()
}
}
private class MyZipOutputStream(out: OutputStream) : ZipOutputStream(out) {
override fun close() {
}
fun doClose() {
super.close()
}
}
data class ExportableItem(val file: Path, val presentableName: String, val roamingType: RoamingType = RoamingType.DEFAULT)
private fun exportInstalledPlugins(zipOut: MyZipOutputStream) {
val plugins = ArrayList<String>()
for (descriptor in PluginManagerCore.getPlugins()) {
if (!descriptor.isBundled && descriptor.isEnabled) {
plugins.add(descriptor.pluginId.idString)
}
}
if (plugins.isEmpty()) {
return
}
val e = ZipEntry(PluginManager.INSTALLED_TXT)
zipOut.putNextEntry(e)
try {
PluginManagerCore.writePluginsList(plugins, OutputStreamWriter(zipOut, CharsetToolkit.UTF8_CHARSET))
}
finally {
zipOut.closeEntry()
}
}
// onlyPaths - include only specified paths (relative to config dir, ends with "/" if directory)
fun getExportableComponentsMap(onlyExisting: Boolean,
computePresentableNames: Boolean,
storageManager: StateStorageManager = ApplicationManager.getApplication().stateStore.stateStorageManager,
onlyPaths: Set<String>? = null): Map<Path, List<ExportableItem>> {
val result = LinkedHashMap<Path, MutableList<ExportableItem>>()
@Suppress("DEPRECATION")
val processor = { component: ExportableComponent ->
for (file in component.exportFiles) {
val item = ExportableItem(file.toPath(), component.presentableName, RoamingType.DEFAULT)
result.putValue(item.file, item)
}
}
@Suppress("DEPRECATION")
ApplicationManager.getApplication().getComponents(ExportableApplicationComponent::class.java).forEach(processor)
@Suppress("DEPRECATION")
ServiceBean.loadServicesFromBeans(ExportableComponent.EXTENSION_POINT, ExportableComponent::class.java).forEach(processor)
val configPath = storageManager.expandMacros(ROOT_CONFIG)
fun isSkipFile(file: Path): Boolean {
if (onlyPaths != null) {
var relativePath = FileUtilRt.getRelativePath(configPath, file.systemIndependentPath, '/')!!
if (!file.fileName.toString().contains('.') && !file.isFile()) {
relativePath += '/'
}
if (!onlyPaths.contains(relativePath)) {
return true
}
}
return onlyExisting && !file.exists()
}
if (onlyExisting || onlyPaths != null) {
result.keys.removeAll(::isSkipFile)
}
val fileToContent = THashMap<Path, String>()
ServiceManagerImpl.processAllImplementationClasses(ApplicationManager.getApplication() as ApplicationImpl, { aClass, pluginDescriptor ->
val stateAnnotation = StoreUtil.getStateSpec(aClass)
@Suppress("DEPRECATION")
if (stateAnnotation == null || stateAnnotation.name.isEmpty() || ExportableComponent::class.java.isAssignableFrom(aClass)) {
return@processAllImplementationClasses true
}
val storage = stateAnnotation.storages.sortByDeprecated().firstOrNull() ?: return@processAllImplementationClasses true
if (!(storage.roamingType != RoamingType.DISABLED && storage.storageClass == StateStorage::class && !storage.path.isEmpty())) {
return@processAllImplementationClasses true
}
var additionalExportFile: Path? = null
val additionalExportPath = stateAnnotation.additionalExportFile
if (additionalExportPath.isNotEmpty()) {
// backward compatibility - path can contain macro
if (additionalExportPath[0] == '$') {
additionalExportFile = Paths.get(storageManager.expandMacros(additionalExportPath))
}
else {
additionalExportFile = Paths.get(storageManager.expandMacros(ROOT_CONFIG), additionalExportPath)
}
if (isSkipFile(additionalExportFile)) {
additionalExportFile = null
}
}
val file = Paths.get(storageManager.expandMacros(storage.path))
val isFileIncluded = !isSkipFile(file)
if (isFileIncluded || additionalExportFile != null) {
if (computePresentableNames && onlyExisting && additionalExportFile == null && file.fileName.toString().endsWith(".xml")) {
val content = fileToContent.getOrPut(file) { file.readText() }
if (!content.contains("""<component name="${stateAnnotation.name}">""")) {
return@processAllImplementationClasses true
}
}
val presentableName = if (computePresentableNames) getComponentPresentableName(stateAnnotation, aClass, pluginDescriptor) else ""
if (isFileIncluded) {
result.putValue(file, ExportableItem(file, presentableName, storage.roamingType))
}
if (additionalExportFile != null) {
result.putValue(additionalExportFile, ExportableItem(additionalExportFile, "$presentableName (schemes)", RoamingType.DEFAULT))
}
}
true
})
// must be in the end - because most of SchemeManager clients specify additionalExportFile in the State spec
(SchemeManagerFactory.getInstance() as SchemeManagerFactoryBase).process {
if (it.roamingType != RoamingType.DISABLED && it.fileSpec.getOrNull(0) != '$') {
val file = Paths.get(storageManager.expandMacros(ROOT_CONFIG), it.fileSpec)
if (!result.containsKey(file) && !isSkipFile(file)) {
result.putValue(file, ExportableItem(file, it.presentableName ?: "", it.roamingType))
}
}
}
return result
}
private fun getComponentPresentableName(state: State, aClass: Class<*>, pluginDescriptor: PluginDescriptor?): String {
val presentableName = state.presentableName.java
if (presentableName != State.NameGetter::class.java) {
try {
return ReflectionUtil.newInstance(presentableName).get()
}
catch (e: Exception) {
LOG.error(e)
}
}
val defaultName = state.name
fun trimDefaultName(): String {
// Vcs.Log.App.Settings
return defaultName
.removeSuffix(".Settings")
.removeSuffix(".Settings")
}
var resourceBundleName: String?
if (pluginDescriptor is IdeaPluginDescriptor && "com.intellij" != pluginDescriptor.pluginId.idString) {
resourceBundleName = pluginDescriptor.resourceBundleBaseName
if (resourceBundleName == null) {
if (pluginDescriptor.vendor == "JetBrains") {
resourceBundleName = OptionsBundle.PATH_TO_BUNDLE
}
else {
return trimDefaultName()
}
}
}
else {
resourceBundleName = OptionsBundle.PATH_TO_BUNDLE
}
val classLoader = pluginDescriptor?.pluginClassLoader ?: aClass.classLoader
if (classLoader != null) {
val message = messageOrDefault(classLoader, resourceBundleName, defaultName)
if (message !== defaultName) {
return message
}
if (PlatformUtils.isRubyMine()) {
// ruby plugin in RubyMine has id "com.intellij", so, we cannot set "resource-bundle" in plugin.xml
return messageOrDefault(classLoader, "org.jetbrains.plugins.ruby.RBundle", defaultName)
}
}
return trimDefaultName()
}
private fun messageOrDefault(classLoader: ClassLoader, bundleName: String, defaultName: String): String {
val bundle = AbstractBundle.getResourceBundle(bundleName, classLoader) ?: return defaultName
return CommonBundle.messageOrDefault(bundle, "exportable.$defaultName.presentable.name", defaultName)
}
| platform/configuration-store-impl/src/ExportSettingsAction.kt | 1794262485 |
package com.habitrpg.shared.habitica
import android.util.Log
import space.thelen.shared.cluetective.BuildConfig
actual class PlatformLogger actual constructor() {
actual val enabled: Boolean
get() = BuildConfig.DEBUG
actual fun logDebug(tag: String, message: String) {
Log.d(tag, message)
}
actual fun logInfo(tag: String, message: String) {
Log.i(tag, message)
}
actual fun logError(tag: String, message: String) {
Log.e(tag, message)
}
actual fun logError(tag: String, message: String, exception: Throwable) {
Log.e(tag, message, exception)
}
} | shared/src/androidMain/kotlin/com/habitrpg/shared/habitica/PlatformLogger.kt | 2398391928 |
package info.nightscout.androidaps.dana
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}
| dana/src/test/java/info/nightscout/androidaps/dana/ExampleUnitTest.kt | 3158582689 |
package io.gbaldeck.vuekt.wrapper
interface VueCommon
fun VueCommon._name() = this::class.simpleName!!.camelToDashCase().toLowerCase()
object Vue{
infix fun component(vueComponent: VueComponent){
val component = vueComponent.asDynamic()
val ownNames = js("Object").getOwnPropertyNames(component) as Array<String>
val protoNames = js("Object").getOwnPropertyNames(component.constructor.prototype) as Array<String>
println(ownNames)
println(protoNames)
val definition = createJsObject<dynamic>()
val data = createJsObject<dynamic>()
definition.methods = createJsObject<dynamic>()
definition.computed = createJsObject<dynamic>()
definition.watches = createJsObject<dynamic>()
definition.props = arrayOf<String>().asDynamic()
val lifeCycleHooks = arrayOf("beforeCreate","created","beforeMount",
"mounted","beforeUpdate","updated","activated","deactivated","beforeDestroy","destroyed","errorCaptured")
val protoNamesList = protoNames.toMutableList()
protoNamesList.removeAll(arrayOf("constructor", "template", "elementName"))
protoNamesList.removeAll(lifeCycleHooks)
ownNames.forEach {
if(component[it] !is VueKtDelegate) {
val dataKey = stripGeneratedPostfix(it)
if(dataKey != "template" && dataKey != "elementName")
data[dataKey] = component[it]
} else {
val delegatePropertyKey = stripGeneratedPostfix(it)
when(component[it]) {
is VueComponent.Computed<*> -> {
val (propertyName, methodName) = component[delegatePropertyKey] as Pair<String, String>
definition.computed[propertyName] = component[methodName]
protoNamesList.remove(methodName)
}
is VueComponent.Watch<*> -> {
val (propertyName, propertyValue, methodName) = component[delegatePropertyKey] as Triple<String, dynamic, String>
data[propertyName] = propertyValue
definition.watches[propertyName] = component[methodName]
protoNamesList.remove(methodName)
}
is VueComponent.Ref<*> -> {
val (propertyName, refComputedFun) = component[delegatePropertyKey] as Pair<String, dynamic>
definition.computed[propertyName] = refComputedFun
}
is VueComponent.Prop<*> -> {
val propName = component[delegatePropertyKey]
definition.props.push(propName)
}
}
protoNamesList.remove(delegatePropertyKey)
}
}
protoNamesList.forEach {
definition.methods[it] = component[it]
}
definition.data = {
js("Object").assign(createJsObject(), data)
}
lifeCycleHooks.forEach {
definition[it] = component[it]
}
definition.render = component.template.render
definition.staticRenderFns = component.template.staticRenderFns
Communicator.setComponentDefinition(vueComponent.elementName, definition)
}
infix fun directive(vueDirective: VueDirective){
val directive = vueDirective.asDynamic()
val protoNames = js("Object").getOwnPropertyNames(directive.constructor.prototype) as Array<String>
val lifeCycleHooks = arrayOf("bind", "inserted", "update", "componentUpdated", "unbind")
val definition = createJsObject<dynamic>()
lifeCycleHooks.forEach {
definition[it] = directive[it]
}
Communicator.setDirectiveDefinition(vueDirective.name, definition)
}
infix fun filter(vueFilter: VueFilter){
val filter = vueFilter.asDynamic()
val filterFun = filter[vueFilter.filter.name]
Communicator.setFilterFunction(vueFilter.name, filterFun)
}
}
fun stripGeneratedPostfix(name: String): String{
if(name.matches("^[.\\S]+$postfixRegex\$")){
val subIt = name.substringBeforeLast("$")
return subIt.substringBeforeLast("_")
}
return name
}
private val postfixRegex = "_[.\\S]+[\$](?:_\\d)?"
//
//fun findSpecificNamesWithPostfix(searchArr: Array<String>, names: Array<String>): Array<String>{
// val arr = mutableListOf<String>()
//
// names.forEach {
// name ->
// val item = searchArr.find { it.matches("^$name(?:$postfixRegex)?\$") }
//
// item?.let{ arr.add(it) }
// }
//
// return arr.toTypedArray()
//}
//
| src/kotlin/io/gbaldeck/vuekt/wrapper/Vue.kt | 3212925150 |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.stats.completion
import com.intellij.codeInsight.lookup.impl.LookupImpl
import com.intellij.completion.settings.CompletionMLRankingSettings
import com.intellij.internal.statistic.utils.StatisticsUploadAssistant
import com.intellij.internal.statistic.utils.getPluginInfo
import com.intellij.lang.Language
import com.intellij.openapi.application.ApplicationManager
import com.intellij.reporting.isUnitTestMode
import com.intellij.stats.experiment.WebServiceStatus
import com.intellij.stats.storage.factors.MutableLookupStorage
import kotlin.random.Random
class CompletionLoggerInitializer(private val actionListener: LookupActionsListener) : LookupTracker() {
companion object {
fun shouldInitialize(): Boolean =
(ApplicationManager.getApplication().isEAP && StatisticsUploadAssistant.isSendAllowed()) || isUnitTestMode()
private val LOGGED_SESSIONS_RATIO: Map<String, Double> = mapOf(
"python" to 0.5,
"scala" to 0.3,
"php" to 0.2,
"kotlin" to 0.2,
"java" to 0.1,
"ecmascript 6" to 0.2,
"typescript" to 0.5,
"c/c++" to 0.5,
"c#" to 0.1
)
}
override fun lookupClosed() {
actionListener.listener = CompletionPopupListener.Adapter()
}
override fun lookupCreated(lookup: LookupImpl,
storage: MutableLookupStorage) {
if (isUnitTestMode() && !CompletionTrackerInitializer.isEnabledInTests) return
val experimentHelper = WebServiceStatus.getInstance()
if (sessionShouldBeLogged(experimentHelper, storage.language)) {
val tracker = actionsTracker(lookup, storage, experimentHelper)
actionListener.listener = tracker
lookup.addLookupListener(tracker)
lookup.setPrefixChangeListener(tracker)
storage.markLoggingEnabled()
}
else {
actionListener.listener = CompletionPopupListener.Adapter()
}
}
private fun actionsTracker(lookup: LookupImpl,
storage: MutableLookupStorage,
experimentHelper: WebServiceStatus): CompletionActionsListener {
val logger = CompletionLoggerProvider.getInstance().newCompletionLogger()
val actionsTracker = CompletionActionsTracker(lookup, storage, logger, experimentHelper)
return LoggerPerformanceTracker(actionsTracker, storage.performanceTracker)
}
private fun sessionShouldBeLogged(experimentHelper: WebServiceStatus, language: Language): Boolean {
if (CompletionTrackerDisabler.isDisabled() || !getPluginInfo(language::class.java).isSafeToReport()) return false
val application = ApplicationManager.getApplication()
if (application.isUnitTestMode || experimentHelper.isExperimentOnCurrentIDE()) return true
if (!CompletionMLRankingSettings.getInstance().isCompletionLogsSendAllowed)
return false
val logSessionChance = LOGGED_SESSIONS_RATIO.getOrDefault(language.displayName.toLowerCase(), 1.0)
return Random.nextDouble() < logSessionChance
}
}
| plugins/stats-collector/src/com/intellij/stats/completion/CompletionLoggerInitializer.kt | 148866834 |
package pl.ches.citybikes.presentation.screen.main.stations
import android.support.v7.util.DiffUtil
import pl.ches.citybikes.data.disk.entity.Station
/**
* @author Michał Seroczyński <[email protected]>
*/
class StationDiffCallback(private val old: List<Pair<Station, Float>>,
private val new: List<Pair<Station, Float>>) : DiffUtil.Callback() {
override fun getOldListSize(): Int = old.size
override fun getNewListSize(): Int = new.size
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return old[oldItemPosition].first.id == new[newItemPosition].first.id
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
// val distanceDiff = Math.abs(old[oldItemPosition].second - new[newItemPosition].second)
// return && distanceDiff < 10
return old[oldItemPosition].second.toInt() == new[newItemPosition].second.toInt()
}
} | app/src/main/kotlin/pl/ches/citybikes/presentation/screen/main/stations/StationDiffCallback.kt | 1753907853 |
package com.kingz.module.wanandroid.bean
/**
* WanAndroid 用户收藏文章列表
*/
class CollectListBean {
/**
* curPage : 1
* datas : [{"apkLink": "",
"author": "MannaYang",
"chapterId": 97,
"chapterName": "音视频",
"collectInside": false,
"courseId": 13,
"desc": "",
"envelopePic": "",
"fresh": true,
"id": 8824,
"link": "https://juejin.im/post/5d42d4946fb9a06ae439d46b",
"niceDate": "22分钟前",
"origin": "",
"prefix": "",
"projectLink": "",
"publishTime": 1564713410000,
"superChapterId": 97,
"superChapterName": "多媒体技术",
"tags": [],
"title": "Android 基于MediaCodec+MediaMuxer实现音视频录制合成",
"type": 0,
"userId": -1,
"visible": 1,
"zan": 0
}, {
"apkLink": "",
"author": " coder-pig",
"chapterId": 74,
"chapterName": "反编译",
"collectInside": false,
"courseId": 13,
"desc": "",
"envelopePic": "",
"fresh": true,
"id": 8823,
"link": "https://juejin.im/post/5d42f440e51d4561e53538b6",
"niceDate": "33分钟前",
"origin": "",
"prefix": "",
"projectLink": "",
"publishTime": 1564712761000,
"superChapterId": 74,
"superChapterName": "热门专题",
"tags": [],
"title": "忘了他吧!我偷别人APP的代码养你",
"type": 0,
"userId": -1,
"visible": 1,
"zan": 0
},
.........
]
* offset : 0
* over : false
* pageCount : 342
* size : 20
* total : 6840
*/
var curPage = 0
var offset = 0
var over = false
var pageCount = 0
var size = 0
var total = 0
var datas: List<Article>? = null
override fun toString(): String {
return "CollectListBean(curPage=$curPage, collectList=$datas)"
}
} | module-Common/src/main/java/com/kingz/module/wanandroid/bean/CollectListBean.kt | 721567547 |
package eu.kanade.tachiyomi
import android.app.Application
import com.google.gson.Gson
import eu.kanade.tachiyomi.data.cache.ChapterCache
import eu.kanade.tachiyomi.data.cache.CoverCache
import eu.kanade.tachiyomi.data.database.DatabaseHelper
import eu.kanade.tachiyomi.data.download.DownloadManager
import eu.kanade.tachiyomi.data.mangasync.MangaSyncManager
import eu.kanade.tachiyomi.data.network.NetworkHelper
import eu.kanade.tachiyomi.data.preference.PreferencesHelper
import eu.kanade.tachiyomi.data.source.SourceManager
import uy.kohesive.injekt.api.InjektModule
import uy.kohesive.injekt.api.InjektRegistrar
import uy.kohesive.injekt.api.addSingletonFactory
class AppModule(val app: Application) : InjektModule {
override fun InjektRegistrar.registerInjectables() {
addSingletonFactory { PreferencesHelper(app) }
addSingletonFactory { DatabaseHelper(app) }
addSingletonFactory { ChapterCache(app) }
addSingletonFactory { CoverCache(app) }
addSingletonFactory { NetworkHelper(app) }
addSingletonFactory { SourceManager(app) }
addSingletonFactory { DownloadManager(app) }
addSingletonFactory { MangaSyncManager(app) }
addSingletonFactory { Gson() }
}
} | app/src/main/java/eu/kanade/tachiyomi/AppModule.kt | 81297259 |
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.diff
import com.intellij.diff.comparison.ComparisonManagerImpl
import com.intellij.diff.comparison.iterables.DiffIterableUtil
import com.intellij.diff.util.ThreeSide
import com.intellij.openapi.editor.Document
import com.intellij.openapi.progress.DumbProgressIndicator
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.util.Couple
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.text.StringUtil
import com.intellij.testFramework.UsefulTestCase
import com.intellij.util.containers.HashMap
import com.intellij.util.text.CharSequenceSubSequence
import junit.framework.ComparisonFailure
import java.util.*
import java.util.concurrent.atomic.AtomicLong
abstract class DiffTestCase : UsefulTestCase() {
companion object {
private val DEFAULT_CHAR_COUNT = 12
private val DEFAULT_CHAR_TABLE: Map<Int, Char> = {
val map = HashMap<Int, Char>()
listOf('\n', '\n', '\t', ' ', ' ', '.', '<', '!').forEachIndexed { i, c -> map.put(i, c) }
map
}()
}
val RNG: Random = Random()
private var gotSeedException = false
val INDICATOR: ProgressIndicator = DumbProgressIndicator.INSTANCE
val MANAGER: ComparisonManagerImpl = ComparisonManagerImpl()
override fun setUp() {
super.setUp()
DiffIterableUtil.setVerifyEnabled(true)
}
override fun tearDown() {
DiffIterableUtil.setVerifyEnabled(Registry.`is`("diff.verify.iterable"))
super.tearDown()
}
//
// Assertions
//
fun assertTrue(actual: Boolean, message: String = "") {
assertTrue(message, actual)
}
fun assertEquals(expected: Any?, actual: Any?, message: String = "") {
assertEquals(message, expected, actual)
}
fun assertEquals(expected: CharSequence?, actual: CharSequence?, message: String = "") {
if (!StringUtil.equals(expected, actual)) throw ComparisonFailure(message, expected?.toString(), actual?.toString())
}
fun assertEqualsCharSequences(chunk1: CharSequence, chunk2: CharSequence, ignoreSpaces: Boolean, skipLastNewline: Boolean) {
if (ignoreSpaces) {
assertTrue(StringUtil.equalsIgnoreWhitespaces(chunk1, chunk2))
} else {
if (skipLastNewline) {
if (StringUtil.equals(chunk1, chunk2)) return
if (StringUtil.equals(stripNewline(chunk1), chunk2)) return
if (StringUtil.equals(chunk1, stripNewline(chunk2))) return
assertTrue(false)
} else {
assertTrue(StringUtil.equals(chunk1, chunk2))
}
}
}
//
// Parsing
//
fun textToReadableFormat(text: CharSequence?): String {
if (text == null) return "null"
return "'" + text.toString().replace('\n', '*').replace('\t', '+') + "'"
}
fun parseSource(string: CharSequence): String = string.toString().replace('_', '\n')
fun parseMatching(matching: String): BitSet {
val set = BitSet()
matching.filterNot { it == '.' }.forEachIndexed { i, c -> if (c != ' ') set.set(i) }
return set
}
//
// Misc
//
fun getLineCount(document: Document): Int {
return Math.max(1, document.lineCount)
}
infix fun Int.until(a: Int): IntRange = this..a - 1
//
// AutoTests
//
fun doAutoTest(seed: Long, runs: Int, test: (DebugData) -> Unit) {
RNG.setSeed(seed)
var lastSeed: Long = -1
val debugData = DebugData()
for (i in 1..runs) {
if (i % 1000 == 0) println(i)
try {
lastSeed = getCurrentSeed()
test(debugData)
debugData.reset()
} catch (e: Throwable) {
println("Seed: " + seed)
println("Runs: " + runs)
println("I: " + i)
println("Current seed: " + lastSeed)
debugData.dump()
throw e
}
}
}
fun generateText(maxLength: Int, charCount: Int, predefinedChars: Map<Int, Char>): String {
val length = RNG.nextInt(maxLength + 1)
val builder = StringBuilder(length)
for (i in 1..length) {
val rnd = RNG.nextInt(charCount)
val char = predefinedChars[rnd] ?: (rnd + 97).toChar()
builder.append(char)
}
return builder.toString()
}
fun generateText(maxLength: Int): String {
return generateText(maxLength, DEFAULT_CHAR_COUNT, DEFAULT_CHAR_TABLE)
}
fun getCurrentSeed(): Long {
if (gotSeedException) return -1
try {
val seedField = RNG.javaClass.getDeclaredField("seed")
seedField.isAccessible = true
val seedFieldValue = seedField.get(RNG) as AtomicLong
return seedFieldValue.get() xor 0x5DEECE66DL
} catch (e: Exception) {
gotSeedException = true
System.err.println("Can't get random seed: " + e.message)
return -1
}
}
private fun stripNewline(text: CharSequence): CharSequence? {
return when (StringUtil.endsWithChar(text, '\n') ) {
true -> CharSequenceSubSequence(text, 0, text.length - 1)
false -> null
}
}
class DebugData() {
private val data: MutableList<Pair<String, Any>> = ArrayList()
fun put(key: String, value: Any) {
data.add(Pair(key, value))
}
fun reset() {
data.clear()
}
fun dump() {
data.forEach { println(it.first + ": " + it.second) }
}
}
//
// Helpers
//
open class Trio<T : Any>(val data1: T, val data2: T, val data3: T) {
companion object {
fun <V : Any> from(f: (ThreeSide) -> V): Trio<V> = Trio(f(ThreeSide.LEFT), f(ThreeSide.BASE), f(ThreeSide.RIGHT))
}
fun <V : Any> map(f: (T) -> V): Trio<V> = Trio(f(data1), f(data2), f(data3))
fun <V : Any> map(f: (T, ThreeSide) -> V): Trio<V> = Trio(f(data1, ThreeSide.LEFT), f(data2, ThreeSide.BASE), f(data3, ThreeSide.RIGHT))
fun forEach(f: (T, ThreeSide) -> Unit): Unit {
f(data1, ThreeSide.LEFT)
f(data2, ThreeSide.BASE)
f(data3, ThreeSide.RIGHT)
}
operator fun invoke(side: ThreeSide): T = side.select(data1, data2, data3) as T
override fun toString(): String {
return "($data1, $data2, $data3)"
}
override fun equals(other: Any?): Boolean {
return other is Trio<*> && other.data1 == data1 && other.data2 == data2 && other.data3 == data3
}
override fun hashCode(): Int {
return data1.hashCode() * 37 * 37 + data2.hashCode() * 37 + data3.hashCode()
}
}
} | platform/diff-impl/tests/com/intellij/diff/DiffTestCase.kt | 1798440792 |
// 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.gradle.importing
import com.intellij.openapi.externalSystem.importing.ImportSpecBuilder
import com.intellij.openapi.externalSystem.service.execution.ProgressExecutionMode
import com.intellij.openapi.externalSystem.service.project.ProjectDataManager
import com.intellij.openapi.externalSystem.test.ExternalSystemTestUtil.assertMapsEqual
import com.intellij.openapi.externalSystem.util.ExternalSystemUtil
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.util.io.FileUtil.pathsEqual
import com.intellij.testFramework.registerServiceInstance
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Condition
import org.gradle.tooling.model.BuildModel
import org.gradle.tooling.model.ProjectModel
import org.gradle.util.GradleVersion
import org.jetbrains.plugins.gradle.importing.GradleBuildScriptBuilder.Companion.buildscript
import org.jetbrains.plugins.gradle.model.ModelsHolder
import org.jetbrains.plugins.gradle.model.Project
import org.jetbrains.plugins.gradle.model.ProjectImportAction
import org.jetbrains.plugins.gradle.service.project.*
import org.jetbrains.plugins.gradle.tooling.annotation.TargetVersions
import org.jetbrains.plugins.gradle.tooling.builder.ProjectPropertiesTestModelBuilder.ProjectProperties
import org.jetbrains.plugins.gradle.util.GradleConstants.SYSTEM_ID
import org.junit.Test
import java.util.function.Predicate
class GradlePartialImportingTest : BuildViewMessagesImportingTestCase() {
override fun setUp() {
super.setUp()
myProject.registerServiceInstance(ModelConsumer::class.java, ModelConsumer())
GradleProjectResolverExtension.EP_NAME.point.registerExtension(TestPartialProjectResolverExtension(), testRootDisposable)
ProjectModelContributor.EP_NAME.point.registerExtension(TestProjectModelContributor(), testRootDisposable)
}
@Test
fun `test re-import with partial project data resolve`() {
createAndImportTestProject()
assertReceivedModels(
projectPath, "project",
mapOf("name" to "project", "prop_loaded_1" to "val1"),
mapOf("name" to "project", "prop_finished_2" to "val2")
)
val initialProjectStructure = ProjectDataManager.getInstance()
.getExternalProjectData(myProject, SYSTEM_ID, projectPath)!!
.externalProjectStructure!!
.graphCopy()
createProjectSubFile(
"gradle.properties",
"prop_loaded_1=val1_inc\n" +
"prop_finished_2=val2_inc\n"
)
cleanupBeforeReImport()
ExternalSystemUtil.refreshProject(
projectPath,
ImportSpecBuilder(myProject, SYSTEM_ID)
.use(ProgressExecutionMode.MODAL_SYNC)
.projectResolverPolicy(
GradlePartialResolverPolicy(Predicate { it is TestPartialProjectResolverExtension })
)
)
assertSyncViewTreeEquals(
"-\n" +
" finished"
)
assertReceivedModels(
projectPath, "project",
mapOf("name" to "project", "prop_loaded_1" to "val1_inc"),
mapOf("name" to "project", "prop_finished_2" to "val2_inc")
)
val projectStructureAfterIncrementalImport = ProjectDataManager.getInstance()
.getExternalProjectData(myProject, SYSTEM_ID, projectPath)!!
.externalProjectStructure!!
.graphCopy()
assertEquals(initialProjectStructure, projectStructureAfterIncrementalImport)
}
@Test
@TargetVersions("3.3+")
fun `test composite project partial re-import`() {
createAndImportTestCompositeProject()
// since Gradle 6.8, included (of the "main" build) builds became visible for `buildSrc` project
// there are separate TAPI request per `buildSrc` project in a composite
// and hence included build models can be handled more than once
// should be fixed with https://github.com/gradle/gradle/issues/14563
val includedBuildModelsReceivedQuantity = if (isGradleOlderThan("6.8")) 1 else 2
assertReceivedModels(
projectPath, "project",
mapOf("name" to "project", "prop_loaded_1" to "val1"),
mapOf("name" to "project", "prop_finished_2" to "val2")
)
assertReceivedModels(
path("buildSrc"), "buildSrc",
mapOf("name" to "buildSrc"),
mapOf("name" to "buildSrc")
)
assertReceivedModels(
path("includedBuild"), "includedBuild",
mapOf("name" to "includedBuild", "prop_loaded_included" to "val1"),
mapOf("name" to "includedBuild", "prop_finished_included" to "val2"),
includedBuildModelsReceivedQuantity
)
assertReceivedModels(
path("includedBuild"), "subProject",
mapOf("name" to "subProject", "prop_loaded_included" to "val1"),
mapOf("name" to "subProject", "prop_finished_included" to "val2"),
includedBuildModelsReceivedQuantity
)
assertReceivedModels(
path("includedBuild/buildSrc"), "buildSrc",
mapOf("name" to "buildSrc"),
mapOf("name" to "buildSrc")
)
val initialProjectStructure = ProjectDataManager.getInstance()
.getExternalProjectData(myProject, SYSTEM_ID, projectPath)!!
.externalProjectStructure!!
.graphCopy()
createProjectSubFile(
"gradle.properties",
"prop_loaded_1=val1_inc\n" +
"prop_finished_2=val2_inc\n"
)
createProjectSubFile(
"includedBuild/gradle.properties",
"prop_loaded_included=val1_1\n" +
"prop_finished_included=val2_2\n"
)
cleanupBeforeReImport()
ExternalSystemUtil.refreshProject(
projectPath,
ImportSpecBuilder(myProject, SYSTEM_ID)
.use(ProgressExecutionMode.MODAL_SYNC)
.projectResolverPolicy(
GradlePartialResolverPolicy(Predicate { it is TestPartialProjectResolverExtension })
)
)
assertReceivedModels(
projectPath, "project",
mapOf("name" to "project", "prop_loaded_1" to "val1_inc"),
mapOf("name" to "project", "prop_finished_2" to "val2_inc")
)
assertReceivedModels(
path("buildSrc"), "buildSrc",
mapOf("name" to "buildSrc"),
mapOf("name" to "buildSrc")
)
assertReceivedModels(
path("includedBuild"), "includedBuild",
mapOf("name" to "includedBuild", "prop_loaded_included" to "val1_1"),
mapOf("name" to "includedBuild", "prop_finished_included" to "val2_2"),
includedBuildModelsReceivedQuantity
)
assertReceivedModels(
path("includedBuild"), "subProject",
mapOf("name" to "subProject", "prop_loaded_included" to "val1_1"),
mapOf("name" to "subProject", "prop_finished_included" to "val2_2"),
includedBuildModelsReceivedQuantity
)
assertReceivedModels(
path("includedBuild/buildSrc"), "buildSrc",
mapOf("name" to "buildSrc"),
mapOf("name" to "buildSrc")
)
val projectStructureAfterIncrementalImport = ProjectDataManager.getInstance()
.getExternalProjectData(myProject, SYSTEM_ID, projectPath)!!
.externalProjectStructure!!
.graphCopy()
assertEquals(initialProjectStructure, projectStructureAfterIncrementalImport)
}
private fun createAndImportTestCompositeProject() {
createProjectSubFile("buildSrc/build.gradle", buildscript {
withGroovyPlugin()
addImplementationDependency(code("gradleApi()"))
addImplementationDependency(code("localGroovy()"))
})
createProjectSubFile(
"gradle.properties",
"prop_loaded_1=val1\n" +
"prop_finished_2=val2\n"
)
createProjectSubFile("includedBuild/settings.gradle", "include 'subProject'")
createProjectSubDir("includedBuild/subProject")
createProjectSubFile("includedBuild/buildSrc/build.gradle", buildscript {
withGroovyPlugin()
addImplementationDependency(code("gradleApi()"))
addImplementationDependency(code("localGroovy()"))
})
createSettingsFile("includeBuild 'includedBuild'")
createProjectSubFile(
"includedBuild/gradle.properties",
"prop_loaded_included=val1\n" +
"prop_finished_included=val2\n"
)
importProject("")
}
@Test
fun `test import cancellation on project loaded phase`() {
createAndImportTestProject()
assertReceivedModels(projectPath, "project",
mapOf("name" to "project", "prop_loaded_1" to "val1"),
mapOf("name" to "project", "prop_finished_2" to "val2")
)
createProjectSubFile(
"gradle.properties",
"prop_loaded_1=error\n" +
"prop_finished_2=val22\n"
)
cleanupBeforeReImport()
ExternalSystemUtil.refreshProject(projectPath, ImportSpecBuilder(myProject, SYSTEM_ID).use(ProgressExecutionMode.MODAL_SYNC))
if (currentGradleBaseVersion >= GradleVersion.version("4.8")) {
if (currentGradleBaseVersion != GradleVersion.version("4.10.3")) {
assertSyncViewTreeEquals { treeTestPresentation ->
assertThat(treeTestPresentation).satisfiesAnyOf(
{
assertThat(it).isEqualTo("-\n" +
" -failed\n" +
" Build cancelled")
},
{
assertThat(it).isEqualTo("-\n" +
" cancelled")
},
{
assertThat(it).startsWith("-\n" +
" -failed\n" +
" Build cancelled\n" +
" Could not build ")
}
)
}
}
assertReceivedModels(projectPath, "project", mapOf("name" to "project", "prop_loaded_1" to "error"))
}
else {
assertSyncViewTreeEquals(
"-\n" +
" finished"
)
assertReceivedModels(projectPath, "project",
mapOf("name" to "project", "prop_loaded_1" to "error"),
mapOf("name" to "project", "prop_finished_2" to "val22"))
}
}
private fun cleanupBeforeReImport() {
myProject.getService(ModelConsumer::class.java).projectLoadedModels.clear()
myProject.getService(ModelConsumer::class.java).buildFinishedModels.clear()
}
private fun createAndImportTestProject() {
createProjectSubFile(
"gradle.properties",
"prop_loaded_1=val1\n" +
"prop_finished_2=val2\n"
)
importProject(buildscript { withJavaPlugin() })
}
private fun assertReceivedModels(
buildPath: String, projectName: String,
expectedProjectLoadedModelsMap: Map<String, String>,
expectedBuildFinishedModelsMap: Map<String, String>? = null,
receivedQuantity: Int = 1
) {
val modelConsumer = myProject.getService(ModelConsumer::class.java)
val projectLoadedPredicate = Predicate<Pair<Project, ProjectLoadedModel>> {
val project = it.first
project.name == projectName &&
pathsEqual(project.projectIdentifier.buildIdentifier.rootDir.path, buildPath)
}
assertThat(modelConsumer.projectLoadedModels)
.haveExactly(receivedQuantity, Condition(projectLoadedPredicate, "project loaded model for '$projectName' at '$buildPath'"))
val (_, projectLoadedModel) = modelConsumer.projectLoadedModels.find(projectLoadedPredicate::test)!!
assertMapsEqual(expectedProjectLoadedModelsMap, projectLoadedModel.map)
if (expectedBuildFinishedModelsMap != null) {
val buildFinishedPredicate = Predicate<Pair<Project, BuildFinishedModel>> {
val project = it.first
project.name == projectName &&
pathsEqual(project.projectIdentifier.buildIdentifier.rootDir.path, buildPath)
}
assertThat(modelConsumer.buildFinishedModels)
.haveExactly(receivedQuantity, Condition(buildFinishedPredicate, "build finished model for '$projectName' at '$buildPath'"))
val (_, buildFinishedModel) = modelConsumer.buildFinishedModels.find(buildFinishedPredicate::test)!!
assertMapsEqual(expectedBuildFinishedModelsMap, buildFinishedModel.map)
}
else {
assertEmpty(modelConsumer.buildFinishedModels)
}
}
}
class TestPartialProjectResolverExtension : AbstractProjectResolverExtension() {
override fun getToolingExtensionsClasses(): Set<Class<*>> {
return setOf(ProjectProperties::class.java)
}
override fun projectsLoaded(models: ModelsHolder<BuildModel, ProjectModel>?) {
val buildFinishedModel = models?.getModel(BuildFinishedModel::class.java)
if (buildFinishedModel != null) {
throw ProcessCanceledException(RuntimeException("buildFinishedModel should not be available for projectsLoaded callback"))
}
val projectLoadedModel = models?.getModel(ProjectLoadedModel::class.java)
if (projectLoadedModel == null) {
throw ProcessCanceledException(RuntimeException("projectLoadedModel should be available for projectsLoaded callback"))
}
if (projectLoadedModel.map.containsValue("error")) {
val modelConsumer = resolverCtx.externalSystemTaskId.findProject()!!.getService(ModelConsumer::class.java)
val build = (models as ProjectImportAction.AllModels).mainBuild
for (project in build.projects) {
modelConsumer.projectLoadedModels.add(project to models.getModel(project, ProjectLoadedModel::class.java)!!)
}
throw ProcessCanceledException(RuntimeException(projectLoadedModel.map.toString()))
}
}
override fun getProjectsLoadedModelProvider() = ProjectLoadedModelProvider()
override fun getModelProvider() = BuildFinishedModelProvider()
}
internal class TestProjectModelContributor : ProjectModelContributor {
override fun accept(
modifiableGradleProjectModel: ModifiableGradleProjectModel,
toolingModelsProvider: ToolingModelsProvider,
resolverContext: ProjectResolverContext
) {
val modelConsumer = resolverContext.externalSystemTaskId.findProject()!!.getService(ModelConsumer::class.java)
toolingModelsProvider.projects().forEach {
modelConsumer.projectLoadedModels.add(it to toolingModelsProvider.getProjectModel(it, ProjectLoadedModel::class.java)!!)
modelConsumer.buildFinishedModels.add(it to toolingModelsProvider.getProjectModel(it, BuildFinishedModel::class.java)!!)
}
}
}
internal data class ModelConsumer(
val projectLoadedModels: MutableList<Pair<Project, ProjectLoadedModel>> = mutableListOf(),
val buildFinishedModels: MutableList<Pair<Project, BuildFinishedModel>> = mutableListOf()
)
| plugins/gradle/java/testSources/importing/GradlePartialImportingTest.kt | 2357747090 |
// 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.caches.project
import com.intellij.ide.highlighter.ArchiveFileType
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.fileTypes.FileTypeEvent
import com.intellij.openapi.fileTypes.FileTypeListener
import com.intellij.openapi.fileTypes.FileTypeManager
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.SimpleModificationTracker
import com.intellij.openapi.vfs.JarFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.vfs.newvfs.BulkFileListener
import com.intellij.openapi.vfs.newvfs.events.VFileCopyEvent
import com.intellij.openapi.vfs.newvfs.events.VFileCreateEvent
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.openapi.vfs.newvfs.events.VFileMoveEvent
import org.jetbrains.kotlin.idea.core.KotlinPluginDisposable
import org.jetbrains.kotlin.idea.util.application.getServiceSafe
class LibraryModificationTracker(project: Project) : SimpleModificationTracker() {
companion object {
@JvmStatic
fun getInstance(project: Project): LibraryModificationTracker = project.getServiceSafe()
}
init {
val disposable = KotlinPluginDisposable.getInstance(project)
val connection = project.messageBus.connect(disposable)
connection.subscribe(VirtualFileManager.VFS_CHANGES, object : BulkFileListener {
override fun after(events: List<VFileEvent>) {
events.filter(::isRelevantEvent).let { createEvents ->
if (createEvents.isNotEmpty()) {
ApplicationManager.getApplication().invokeLater {
if (!Disposer.isDisposed(disposable)) {
processBulk(createEvents) {
projectFileIndex.isInLibraryClasses(it) || isLibraryArchiveRoot(it)
}
}
}
}
}
}
override fun before(events: List<VFileEvent>) {
processBulk(events) {
projectFileIndex.isInLibraryClasses(it)
}
}
})
connection.subscribe(DumbService.DUMB_MODE, object : DumbService.DumbModeListener {
override fun enteredDumbMode() {
incModificationCount()
}
override fun exitDumbMode() {
incModificationCount()
}
})
connection.subscribe(FileTypeManager.TOPIC, object : FileTypeListener {
override fun beforeFileTypesChanged(event: FileTypeEvent) {
incModificationCount()
}
override fun fileTypesChanged(event: FileTypeEvent) {
incModificationCount()
}
})
}
private val projectFileIndex = ProjectFileIndex.SERVICE.getInstance(project)
private inline fun processBulk(events: List<VFileEvent>, check: (VirtualFile) -> Boolean) {
events.forEach { event ->
if (event.isValid) {
val file = event.file
if (file != null && check(file)) {
incModificationCount()
return
}
}
}
}
// if library points to a jar, the jar does not pass isInLibraryClasses check, so we have to perform additional check for this case
private fun isLibraryArchiveRoot(virtualFile: VirtualFile): Boolean {
if (virtualFile.fileType != ArchiveFileType.INSTANCE) return false
val archiveRoot = JarFileSystem.getInstance().getRootByLocal(virtualFile) ?: return false
return projectFileIndex.isInLibraryClasses(archiveRoot)
}
}
private fun isRelevantEvent(vFileEvent: VFileEvent) =
vFileEvent is VFileCreateEvent || vFileEvent is VFileMoveEvent || vFileEvent is VFileCopyEvent
| plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/caches/project/LibraryModificationTracker.kt | 2321089863 |
package com.github.kerubistan.kerub.services
import com.nhaarman.mockito_kotlin.eq
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.whenever
import org.infinispan.AdvancedCache
import org.infinispan.Cache
import org.infinispan.CacheSet
import org.infinispan.commons.util.CloseableIterator
import org.infinispan.manager.EmbeddedCacheManager
import org.junit.Test
import java.io.ByteArrayOutputStream
import javax.ws.rs.core.StreamingOutput
class DbDumpServiceImplTest {
@Test
fun dump() {
val cacheManager = mock<EmbeddedCacheManager>()
whenever(cacheManager.cacheNames).thenReturn(
mutableSetOf("testCache")
)
val cache = mock<Cache<Any, Any>>()
val advancedCache = mock<AdvancedCache<Any, Any>>()
whenever(cacheManager.getCache<Any, Any>(eq("testCache"))).thenReturn(cache)
whenever(cache.advancedCache).thenReturn(advancedCache)
val keys = mock<CacheSet<Any>>()
whenever(keys.iterator()).then { val keyIterator = mock<CloseableIterator<Any>>()
whenever(keyIterator.hasNext()).thenReturn(true, true, true, false)
whenever(keyIterator.next()).thenReturn("A", "B", "C")
keyIterator
}
whenever(advancedCache[eq("A")]).thenReturn("A-VALUE")
whenever(advancedCache[eq("B")]).thenReturn("B-VALUE")
whenever(advancedCache[eq("C")]).thenReturn("C-VALUE")
whenever(advancedCache.keys).thenReturn(keys)
val tar = ByteArrayOutputStream()
(DbDumpServiceImpl(cacheManager).dump().entity as StreamingOutput).write(tar)
}
} | src/test/kotlin/com/github/kerubistan/kerub/services/DbDumpServiceImplTest.kt | 3877233825 |
package com.intellij.codeInsight.codeVision.ui.popup
import com.intellij.codeInsight.codeVision.CodeVisionBundle
import com.intellij.codeInsight.codeVision.CodeVisionEntry
import com.intellij.codeInsight.codeVision.CodeVisionEntryExtraActionModel
import com.intellij.codeInsight.codeVision.CodeVisionHost
import com.intellij.codeInsight.codeVision.ui.model.CodeVisionListData
import com.intellij.codeInsight.codeVision.ui.model.ProjectCodeVisionModel
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.ListPopupStep
import com.intellij.openapi.ui.popup.ListSeparator
import com.intellij.ui.popup.list.ListPopupImpl
class CodeVisionContextPopup private constructor(project: Project, aStep: ListPopupStep<CodeVisionEntryExtraActionModel>) : ListPopupImpl(
project,
aStep) {
companion object {
fun createLensList(entry: CodeVisionEntry, model: CodeVisionListData, project: Project): CodeVisionContextPopup {
val activeProvider = CodeVisionHost.getInstance(project).getProviderById(entry.providerId) ?: error("Can't find provider with id: ${entry.providerId}")
val lst = entry.extraActions +
CodeVisionEntryExtraActionModel(CodeVisionBundle.message("action.hide.this.metric.text", activeProvider.name), ProjectCodeVisionModel.HIDE_PROVIDER_ID) +
CodeVisionEntryExtraActionModel(CodeVisionBundle.message("action.hide.all.text"), ProjectCodeVisionModel.HIDE_ALL) +
CodeVisionEntryExtraActionModel(CodeVisionBundle.message("LensListPopup.tooltip.settings"), CodeVisionHost.settingsLensProviderId)
val aStep = object : SubCodeVisionMenu(lst,
{
model.rangeCodeVisionModel.handleLensExtraAction(entry, it)
}) {
override fun getSeparatorAbove(value: CodeVisionEntryExtraActionModel): ListSeparator? {
return null
}
}
return CodeVisionContextPopup(project, aStep)
}
}
init {
setMaxRowCount(15)
}
override fun beforeShow(): Boolean {
setHandleAutoSelectionBeforeShow(false)
list.clearSelection()
return super.beforeShow()
}
override fun afterShow() {
}
} | platform/lang-impl/src/com/intellij/codeInsight/codeVision/ui/popup/CodeVisionContextPopup.kt | 3842221439 |
// automatically generated by the FlatBuffers compiler, do not modify
package NamespaceA.NamespaceB
import java.nio.*
import kotlin.math.sign
import com.google.flatbuffers.*
@Suppress("unused")
@ExperimentalUnsignedTypes
class TableInNestedNS : Table() {
fun __init(_i: Int, _bb: ByteBuffer) {
__reset(_i, _bb)
}
fun __assign(_i: Int, _bb: ByteBuffer) : TableInNestedNS {
__init(_i, _bb)
return this
}
val foo : Int
get() {
val o = __offset(4)
return if(o != 0) bb.getInt(o + bb_pos) else 0
}
fun mutateFoo(foo: Int) : Boolean {
val o = __offset(4)
return if (o != 0) {
bb.putInt(o + bb_pos, foo)
true
} else {
false
}
}
companion object {
fun validateVersion() = Constants.FLATBUFFERS_22_10_26()
fun getRootAsTableInNestedNS(_bb: ByteBuffer): TableInNestedNS = getRootAsTableInNestedNS(_bb, TableInNestedNS())
fun getRootAsTableInNestedNS(_bb: ByteBuffer, obj: TableInNestedNS): TableInNestedNS {
_bb.order(ByteOrder.LITTLE_ENDIAN)
return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb))
}
fun createTableInNestedNS(builder: FlatBufferBuilder, foo: Int) : Int {
builder.startTable(1)
addFoo(builder, foo)
return endTableInNestedNS(builder)
}
fun startTableInNestedNS(builder: FlatBufferBuilder) = builder.startTable(1)
fun addFoo(builder: FlatBufferBuilder, foo: Int) = builder.addInt(0, foo, 0)
fun endTableInNestedNS(builder: FlatBufferBuilder) : Int {
val o = builder.endTable()
return o
}
}
}
| tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNS.kt | 3217538206 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.compilerPlugin.allopen.gradleJava
import org.jetbrains.kotlin.allopen.AllOpenCommandLineProcessor
import org.jetbrains.kotlin.idea.gradleTooling.model.allopen.AllOpenModel
import org.jetbrains.kotlin.idea.artifacts.KotlinArtifacts
import org.jetbrains.kotlin.idea.gradleJava.compilerPlugin.AbstractAnnotationBasedCompilerPluginGradleImportHandler
import org.jetbrains.kotlin.idea.compilerPlugin.toJpsVersionAgnosticKotlinBundledPath
class AllOpenGradleProjectImportHandler : AbstractAnnotationBasedCompilerPluginGradleImportHandler<AllOpenModel>() {
override val compilerPluginId = AllOpenCommandLineProcessor.PLUGIN_ID
override val pluginName = "allopen"
override val annotationOptionName = AllOpenCommandLineProcessor.ANNOTATION_OPTION.optionName
override val pluginJarFileFromIdea = KotlinArtifacts.instance.allopenCompilerPlugin.toJpsVersionAgnosticKotlinBundledPath()
override val modelKey = AllOpenProjectResolverExtension.KEY
override fun getAnnotationsForPreset(presetName: String): List<String> {
for ((name, annotations) in AllOpenCommandLineProcessor.SUPPORTED_PRESETS.entries) {
if (presetName == name) {
return annotations
}
}
return super.getAnnotationsForPreset(presetName)
}
}
| plugins/kotlin/compiler-plugins/allopen/gradle/src/org/jetbrains/kotlin/idea/compilerPlugin/allopen/gradleJava/AllOpenGradleProjectImportHandler.kt | 2402724257 |
// 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.analysis.problemsView.toolWindow
import com.intellij.openapi.actionSystem.ex.ActionUtil
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.registry.Registry
import com.intellij.ui.SimpleTextAttributes
import java.awt.event.ActionEvent
class ProblemsViewProjectErrorsPanelProvider(private val project: Project) : ProblemsViewPanelProvider {
companion object {
const val ID = "ProjectErrors"
}
private val ACTION_IDS = listOf("CompileDirty", "InspectCode")
override fun create(): ProblemsViewTab? {
val state = ProblemsViewState.getInstance(project)
val panel = ProblemsViewPanel(project, ID, state, ProblemsViewBundle.messagePointer("problems.view.project"))
panel.treeModel.root = CollectorBasedRoot(panel)
val status = panel.tree.emptyText
status.text = ProblemsViewBundle.message("problems.view.project.empty")
if (Registry.`is`("ide.problems.view.empty.status.actions")) {
val or = ProblemsViewBundle.message("problems.view.project.empty.or")
var index = 0
for (id in ACTION_IDS) {
val action = ActionUtil.getAction(id) ?: continue
val text = action.templateText
if (text.isNullOrBlank()) continue
if (index == 0) {
status.appendText(".")
status.appendLine("")
}
else {
status.appendText(" ").appendText(or).appendText(" ")
}
status.appendText(text, SimpleTextAttributes.LINK_PLAIN_ATTRIBUTES
) { event: ActionEvent? ->
ActionUtil.invokeAction(action, panel, "ProblemsView", null, null)
}
val shortcut = KeymapUtil.getFirstKeyboardShortcutText(action)
if (!shortcut.isBlank()) status.appendText(" (").appendText(shortcut).appendText(")")
index++
}
}
return panel
}
} | platform/lang-impl/src/com/intellij/analysis/problemsView/toolWindow/ProblemsViewProjectErrorsPanelProvider.kt | 928767750 |
package no.skatteetaten.aurora.boober.feature.toxiproxy
import no.skatteetaten.aurora.boober.feature.createSchemaRequests
import no.skatteetaten.aurora.boober.feature.findDatabases
import no.skatteetaten.aurora.boober.feature.getSecretName
import no.skatteetaten.aurora.boober.feature.name
import no.skatteetaten.aurora.boober.model.AuroraDeploymentSpec
import no.skatteetaten.aurora.boober.model.PortNumbers
import no.skatteetaten.aurora.boober.service.AuroraDeploymentSpecValidationException
import no.skatteetaten.aurora.boober.service.UserDetailsProvider
import no.skatteetaten.aurora.boober.service.resourceprovisioning.DatabaseSchemaProvisioner
import no.skatteetaten.aurora.boober.utils.UrlParser
import no.skatteetaten.aurora.boober.utils.addIfNotNull
import no.skatteetaten.aurora.boober.utils.countSetValues
import no.skatteetaten.aurora.boober.utils.takeIfNotEmpty
import no.skatteetaten.aurora.boober.utils.whenTrue
import java.net.URI
// This class is meant to exactly reflect the information given in the spec, in order to simplify further processing.
// It contains functions for validating the given properties and converting to the correct type of the ToxiproxyProxy class.
internal data class ToxiproxyProxySpec(
val proxyName: String,
val enabled: Boolean,
val initialEnabledState: Boolean,
val urlVariableKey: String?,
val serverVariableKey: String?,
val portVariableKey: String?,
val database: Boolean,
val databaseName: String?
) {
fun toToxiproxyProxyIfEnabled() = enabled.whenTrue {
when {
isEndpointProxy() -> toEndpointToxiproxyProxy()
isServerAndPortProxy() -> toServerAndPortToxiproxyProxy()
isDatabaseProxy() -> toDatabaseToxiproxyProxy()
else -> null
}
}
fun validate(ads: AuroraDeploymentSpec): List<AuroraDeploymentSpecValidationException> =
invalidCombinationError()?.let(::listOf)
?: toToxiproxyProxyIfEnabled()?.validate(ads)
?: emptyList()
private fun isEndpointProxy() = hasValidCombination() && !urlVariableKey.isNullOrBlank()
private fun isServerAndPortProxy() = hasValidCombination() && hasServerOrPortVariableKey()
private fun isNamedDatabaseProxy() = hasValidCombination() && !databaseName.isNullOrBlank()
private fun isDefaultDatabaseProxy() = hasValidCombination() && database
private fun isDatabaseProxy() = isDefaultDatabaseProxy() || isNamedDatabaseProxy()
private fun toEndpointToxiproxyProxy() = EndpointToxiproxyProxy(urlVariableKey!!, proxyName, initialEnabledState)
private fun toServerAndPortToxiproxyProxy() =
ServerAndPortToxiproxyProxy(serverVariableKey, portVariableKey, proxyName, initialEnabledState)
private fun toDatabaseToxiproxyProxy() = DatabaseToxiproxyProxy(databaseName, proxyName, initialEnabledState)
private fun hasValidCombination() = numberOfGivenValues() == 1
private fun invalidCombinationError() = when (numberOfGivenValues()) {
0 ->
"Neither of the fields urlVariableKey, serverVariableKey, portVariableKey, database or " +
"databaseName are set for the Toxiproxy proxy named $proxyName."
1 -> null
else -> "The combination of fields specified for the Toxiproxy proxy named $proxyName is not valid."
}?.let { exceptionMessage ->
AuroraDeploymentSpecValidationException(
exceptionMessage +
" A valid configuration must contain a value for exactly one of the properties urlVariableKey," +
" database, or databaseName, or both the properties serverVariableKey and portVariableKey."
)
}
private fun numberOfGivenValues() =
countSetValues(urlVariableKey, hasServerOrPortVariableKey(), database, databaseName)
private fun hasServerOrPortVariableKey() = countSetValues(serverVariableKey, portVariableKey) > 0
}
internal typealias UpstreamUrlAndSecretName = Pair<String, String?>
// Parent class for all ToxiproxyProxies
internal abstract class ToxiproxyProxy {
abstract val proxyName: String
abstract val initialEnabledState: Boolean
// Generate information that will be stored in the feature context.
// That is, the Toxiproxy config for the container's config map, the port it will listen to, and, if needed, the secret name.
fun generateConfig(
ads: AuroraDeploymentSpec,
port: Int,
userDetailsProvider: UserDetailsProvider,
databaseSchemaProvisioner: DatabaseSchemaProvisioner?
) = upstreamUrlAndSecretName(ads, userDetailsProvider, databaseSchemaProvisioner)
.takeIf { it?.first != null }
?.let { (upstreamUrl, secretName) ->
ToxiproxyConfigAndSecret(
port = port,
secretName = secretName,
toxiproxyConfig = ToxiproxyConfig(
name = proxyName,
listen = "0.0.0.0:$port",
upstream = upstreamUrl,
enabled = initialEnabledState
)
)
}
// Run both validation functions and return a list of exceptions.
fun validate(ads: AuroraDeploymentSpec) = validateVariables(ads).addIfNotNull(validateProxyName())
// Generate the upstream URL and, if the target is a database, find the secret name.
abstract fun upstreamUrlAndSecretName(
ads: AuroraDeploymentSpec,
userDetailsProvider: UserDetailsProvider,
databaseSchemaProvisioner: DatabaseSchemaProvisioner?
): UpstreamUrlAndSecretName?
// Validate that the given variables or database names exist in the spec and that the URLs given in those variables are valid.
abstract fun validateVariables(ads: AuroraDeploymentSpec): List<AuroraDeploymentSpecValidationException>
// Return an exception if the proxy name is "app".
private fun validateProxyName(): AuroraDeploymentSpecValidationException? = (proxyName == MAIN_PROXY_NAME).whenTrue {
AuroraDeploymentSpecValidationException("The name \"$MAIN_PROXY_NAME\" is reserved for the proxy for incoming calls.")
}
}
internal class EndpointToxiproxyProxy(
val urlVariableKey: String,
override val proxyName: String,
override val initialEnabledState: Boolean
) : ToxiproxyProxy() {
override fun upstreamUrlAndSecretName(
ads: AuroraDeploymentSpec,
userDetailsProvider: UserDetailsProvider,
databaseSchemaProvisioner: DatabaseSchemaProvisioner?
) = ads
.getOrNull<String>("config/$urlVariableKey")
?.let(::URI)
?.let { uri ->
val upstreamPort = if (uri.port == -1) {
if (uri.scheme == "https") PortNumbers.HTTPS_PORT else PortNumbers.HTTP_PORT
} else uri.port
uri.host + ":" + upstreamPort
}
?.let { UpstreamUrlAndSecretName(it, null) }
override fun validateVariables(ads: AuroraDeploymentSpec): List<AuroraDeploymentSpecValidationException> {
val envVar = ads.getOrNull<String>("config/$urlVariableKey")
val message = if (envVar == null) {
"Found Toxiproxy config for endpoint named $urlVariableKey, but there is no such environment variable."
} else if (!UrlParser(envVar).isValid()) {
"The format of the URL \"$envVar\" given by the config variable $urlVariableKey is not supported."
} else return emptyList()
return listOf(AuroraDeploymentSpecValidationException(message))
}
}
internal class ServerAndPortToxiproxyProxy(
val serverVariableKey: String?,
val portVariableKey: String?,
override val proxyName: String,
override val initialEnabledState: Boolean
) : ToxiproxyProxy() {
override fun upstreamUrlAndSecretName(
ads: AuroraDeploymentSpec,
userDetailsProvider: UserDetailsProvider,
databaseSchemaProvisioner: DatabaseSchemaProvisioner?
): UpstreamUrlAndSecretName? {
val upstreamServer: String? = ads.getOrNull("config/$serverVariableKey")
val upstreamPort: String? = ads.getOrNull("config/$portVariableKey")
return if (upstreamServer != null && upstreamPort != null)
UpstreamUrlAndSecretName("$upstreamServer:$upstreamPort", null)
else null
}
override fun validateVariables(ads: AuroraDeploymentSpec) =
listOf("server" to serverVariableKey, "port" to portVariableKey)
.mapNotNull { (name, value) ->
if (value.isNullOrBlank()) {
return@mapNotNull "The $name variable is missing for the Toxiproxy proxy named $proxyName."
}
val isServerOrPortMissingFromConfig = ads.getSubKeyValues("config").none { it == value }
if (isServerOrPortMissingFromConfig) {
"Found Toxiproxy config for a $name variable named $value, " +
"but there is no such environment variable."
} else null
}
.map(::AuroraDeploymentSpecValidationException)
}
internal class DatabaseToxiproxyProxy(
val databaseName: String?, // Null signifies that the database config in the AuroraDeploymentSpec is simplified
override val proxyName: String,
override val initialEnabledState: Boolean
) : ToxiproxyProxy() {
fun isDefault() = databaseName == null
override fun upstreamUrlAndSecretName(
ads: AuroraDeploymentSpec,
userDetailsProvider: UserDetailsProvider,
databaseSchemaProvisioner: DatabaseSchemaProvisioner?
): UpstreamUrlAndSecretName? {
if (databaseSchemaProvisioner == null) return null
val request = findDatabases(ads)
.filter { databaseName == null || it.name == databaseName }
.createSchemaRequests(userDetailsProvider, ads)
.takeIfNotEmpty()
?.first()
?: return null
val schema = databaseSchemaProvisioner.findSchema(request) ?: return null
val upstreamUrl = schema.databaseInstance.host + ":" + schema.databaseInstance.port
val secretName = request.getSecretName(prefix = ads.name)
return UpstreamUrlAndSecretName(upstreamUrl, secretName)
}
override fun validateVariables(ads: AuroraDeploymentSpec) = if (
databaseName == null ||
ads.isSimplifiedAndEnabled("database") ||
ads.getSubKeyValues("database").contains(databaseName)
) emptyList() else {
listOf(
AuroraDeploymentSpecValidationException(
"Found Toxiproxy config for database named $databaseName, but there is no such database configured."
)
)
}
}
| src/main/kotlin/no/skatteetaten/aurora/boober/feature/toxiproxy/ToxiproxyProxy.kt | 3882362236 |
package com.sedsoftware.yaptalker.domain.entity.base
import com.sedsoftware.yaptalker.domain.entity.BaseEntity
/**
* Class which represents single topic post tag item in domain layer.
*/
class Tag(
val name: String,
val link: String,
val searchParameter: String
) : BaseEntity
| domain/src/main/java/com/sedsoftware/yaptalker/domain/entity/base/Tag.kt | 1611112724 |
/*
* 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.compose.foundation.benchmark.text.empirical
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.testutils.LayeredComposeTestCase
import androidx.compose.testutils.ToggleableTestCase
import androidx.compose.testutils.benchmark.ComposeBenchmarkRule
import androidx.compose.testutils.benchmark.toggleStateBenchmarkComposeMeasureLayout
import androidx.compose.testutils.benchmark.toggleStateBenchmarkRecompose
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.font.FontFamily
import androidx.test.filters.LargeTest
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
/**
* Show the behavior of several spans stacked on top of each other, for the full length of the text.
*
* 38% of all text displayed contains at least 1 span. The most common # of spans is 16 (due to
* usage of spans as text formatting).
*
* Spans are intentionally limited to
*
* 1) Not MetricsAffectingSpans (usage is very low)
* 2) Not inlineContent (usage is very low).
*
* TODO: If introducing more optimizations that depend on the "full length" assumption, confirm the
* frequency of spans that use the full length. This is not verified in the data set that produced
* this benchmark.
*/
class IfNotEmptyCallTextWithSpans(
private val text: AnnotatedString
) : LayeredComposeTestCase(), ToggleableTestCase {
private var toggleText = mutableStateOf(AnnotatedString(""))
@Composable
override fun MeasuredContent() {
Text(toggleText.value, fontFamily = FontFamily.Monospace)
}
override fun toggleState() {
if (toggleText.value.text.isEmpty()) {
toggleText.value = text
} else {
toggleText.value = AnnotatedString("")
}
}
}
@LargeTest
@RunWith(Parameterized::class)
open class IfNotEmptyCallTextWithSpansParent(
private val size: Int,
private val spanCount: Int
) {
@get:Rule
val benchmarkRule = ComposeBenchmarkRule()
private val caseFactory = {
val text = generateCacheableStringOf(size)
IfNotEmptyCallTextWithSpans(text.annotateWithSpans(spanCount))
}
companion object {
@JvmStatic
@Parameterized.Parameters(name = "size={0}, spanCount={1}")
fun initParameters(): List<Array<Any>> = listOf()
}
@Test
fun recomposeOnly() {
benchmarkRule.toggleStateBenchmarkRecompose(caseFactory)
}
@Test
fun recomposeMeasureLayout() {
benchmarkRule.toggleStateBenchmarkComposeMeasureLayout(caseFactory)
}
}
@LargeTest
@RunWith(Parameterized::class)
class AllAppsIfNotEmptyCallTextWithSpans(
size: Int,
spanCount: Int
) : IfNotEmptyCallTextWithSpansParent(size, spanCount) {
companion object {
@JvmStatic
@Parameterized.Parameters(name = "size={0}, spanCount={1}")
fun initParameters() = AllApps.TextLengthsWithSpans
}
}
@LargeTest
@RunWith(Parameterized::class)
class SocialAppIfNotEmptyCallTextWithSpans(
size: Int,
spanCount: Int
) : IfNotEmptyCallTextWithSpansParent(size, spanCount) {
companion object {
@JvmStatic
@Parameterized.Parameters(name = "size={0}, spanCount={1}")
fun initParameters() = SocialApps.TextLengthsWithSpans
}
}
@LargeTest
@RunWith(Parameterized::class)
class ChatAppIfNotEmptyCallTextWithSpans(
size: Int,
spanCount: Int
) : IfNotEmptyCallTextWithSpansParent(size, spanCount) {
companion object {
@JvmStatic
@Parameterized.Parameters(name = "size={0}, spanCount={1}")
fun initParameters() = ChatApps.TextLengthsWithSpans
}
}
@LargeTest
@RunWith(Parameterized::class)
class ShoppingAppIfNotEmptyCallTextWithSpans(
size: Int,
spanCount: Int
) : IfNotEmptyCallTextWithSpansParent(size, spanCount) {
companion object {
@JvmStatic
@Parameterized.Parameters(name = "size={0}, spanCount={1}")
fun initParameters() = ShoppingApps.TextLengthsWithSpans
}
} | compose/foundation/foundation/benchmark/src/androidTest/java/androidx/compose/foundation/benchmark/text/empirical/IfNotEmptyCallTextWithSpans.kt | 588700534 |
package taiwan.no1.app.ssfm.internal.di.annotations.qualifiers
import javax.inject.Qualifier
/**
* A qualifier for providing the [taiwan.no1.app.ssfm.mvvm.models.data.remote.RemoteDataStore].
*
* @author jieyi
* @since 8/9/17
*/
@Qualifier
@Retention
@MustBeDocumented
annotation class Remote | app/src/main/kotlin/taiwan/no1/app/ssfm/internal/di/annotations/qualifiers/Remote.kt | 371826172 |
/*
* 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.drawerlayout.widget
import android.os.Build
import android.view.KeyEvent
import android.view.View
import androidx.drawerlayout.test.R
import androidx.test.espresso.Espresso
import androidx.test.espresso.action.ViewActions
import androidx.test.espresso.matcher.ViewMatchers
import androidx.test.ext.junit.rules.ActivityScenarioRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import androidx.testutils.PollingCheck
import androidx.testutils.withActivity
import org.junit.Assert
import org.junit.Ignore
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
public class DrawerBackHandlingTest {
@get:Rule
public val activityScenarioRule = ActivityScenarioRule(
DrawerSingleStartActivity::class.java
)
@Ignore
@Test
@SmallTest
public fun testBackPress() {
val listener = ObservableDrawerListener()
val drawerLayout = activityScenarioRule.withActivity {
val drawerLayout = findViewById<DrawerLayout>(R.id.drawer)
drawerLayout.addDrawerListener(listener)
drawerLayout.open()
drawerLayout
}
// Wait until the animation ends. We disable animations on test
// devices, but this is useful when running on a local device.
PollingCheck.waitFor {
listener.drawerOpenedCalled
}
listener.reset()
// Ensure that back pressed dispatcher callback is registered on T+.
if (Build.VERSION.SDK_INT >= 33) {
Assert.assertTrue(drawerLayout.isBackInvokedCallbackRegistered)
}
Espresso.onView(ViewMatchers.isRoot()).perform(ViewActions.pressKey(KeyEvent.KEYCODE_BACK))
PollingCheck.waitFor {
listener.drawerClosedCalled
}
listener.reset()
Assert.assertNull(drawerLayout.findOpenDrawer())
// Ensure that back pressed dispatcher callback is unregistered on T+.
if (Build.VERSION.SDK_INT >= 33) {
Assert.assertFalse(drawerLayout.isBackInvokedCallbackRegistered)
}
}
internal inner class ObservableDrawerListener : DrawerLayout.DrawerListener {
var drawerOpenedCalled = false
var drawerClosedCalled = false
override fun onDrawerSlide(drawerView: View, slideOffset: Float) {}
override fun onDrawerOpened(drawerView: View) {
drawerOpenedCalled = true
}
override fun onDrawerClosed(drawerView: View) {
drawerClosedCalled = true
}
override fun onDrawerStateChanged(newState: Int) {}
fun reset() {
drawerOpenedCalled = false
drawerClosedCalled = false
}
}
}
| drawerlayout/drawerlayout/src/androidTest/java/androidx/drawerlayout/widget/DrawerBackHandlingTest.kt | 2953318125 |
/*
* 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.fragment.app
import androidx.fragment.app.test.FragmentTestActivity
import androidx.fragment.app.test.TestViewModel
import androidx.fragment.app.test.ViewModelActivity
import androidx.fragment.test.R
import androidx.lifecycle.HasDefaultViewModelProviderFactory
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.test.core.app.ActivityScenario
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import androidx.testutils.withActivity
import androidx.testutils.withUse
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@SmallTest
class FragmentViewLifecycleOwnerTest {
/**
* Test representing a Non-Hilt case, in which the default factory is not overwritten at the
* Fragment level.
*/
@Test
fun defaultFactoryNotOverwritten() {
withUse(ActivityScenario.launch(FragmentTestActivity::class.java)) {
val fm = withActivity {
setContentView(R.layout.simple_container)
supportFragmentManager
}
val fragment = StrictViewFragment()
fm.beginTransaction()
.add(R.id.fragmentContainer, fragment)
.commit()
executePendingTransactions()
val defaultFactory1 = (
fragment.viewLifecycleOwner as HasDefaultViewModelProviderFactory
).defaultViewModelProviderFactory
val defaultFactory2 = (
fragment.viewLifecycleOwner as HasDefaultViewModelProviderFactory
).defaultViewModelProviderFactory
// Assure that multiple call return the same default factory
assertThat(defaultFactory1).isSameInstanceAs(defaultFactory2)
assertThat(defaultFactory1).isNotSameInstanceAs(
fragment.defaultViewModelProviderFactory
)
}
}
/**
* Test representing a Hilt case, in which the default factory is overwritten at the
* Fragment level.
*/
@Test
fun defaultFactoryOverwritten() {
withUse(ActivityScenario.launch(FragmentTestActivity::class.java)) {
val fm = withActivity {
setContentView(R.layout.simple_container)
supportFragmentManager
}
val fragment = FragmentWithFactoryOverride()
fm.beginTransaction()
.add(R.id.fragmentContainer, fragment)
.commit()
executePendingTransactions()
val defaultFactory = (
fragment.viewLifecycleOwner as HasDefaultViewModelProviderFactory
).defaultViewModelProviderFactory
assertThat(defaultFactory).isInstanceOf(FakeViewModelProviderFactory::class.java)
}
}
@Test
fun testCreateViewModelViaExtras() {
withUse(ActivityScenario.launch(FragmentTestActivity::class.java)) {
val fm = withActivity {
setContentView(R.layout.simple_container)
supportFragmentManager
}
val fragment = StrictViewFragment()
fm.beginTransaction()
.add(R.id.fragmentContainer, fragment, "fragment")
.commit()
executePendingTransactions()
val viewLifecycleOwner = (fragment.viewLifecycleOwner as FragmentViewLifecycleOwner)
val creationViewModel = ViewModelProvider(
viewLifecycleOwner.viewModelStore,
viewLifecycleOwner.defaultViewModelProviderFactory,
viewLifecycleOwner.defaultViewModelCreationExtras
)["test", TestViewModel::class.java]
recreate()
val recreatedViewLifecycleOwner = withActivity {
supportFragmentManager.findFragmentByTag("fragment")?.viewLifecycleOwner
as FragmentViewLifecycleOwner
}
assertThat(
ViewModelProvider(recreatedViewLifecycleOwner)["test", TestViewModel::class.java]
).isSameInstanceAs(creationViewModel)
}
}
@Test
fun testCreateViewModelViaExtrasSavedState() {
withUse(ActivityScenario.launch(FragmentTestActivity::class.java)) {
val fm = withActivity {
setContentView(R.layout.simple_container)
supportFragmentManager
}
val fragment = StrictViewFragment()
fm.beginTransaction()
.add(R.id.fragmentContainer, fragment, "fragment")
.commit()
executePendingTransactions()
val viewLifecycleOwner = (fragment.viewLifecycleOwner as FragmentViewLifecycleOwner)
val creationViewModel = ViewModelProvider(
viewLifecycleOwner.viewModelStore,
viewLifecycleOwner.defaultViewModelProviderFactory,
viewLifecycleOwner.defaultViewModelCreationExtras
)["test", ViewModelActivity.TestSavedStateViewModel::class.java]
creationViewModel.savedStateHandle["key"] = "value"
recreate()
val recreatedViewLifecycleOwner = withActivity {
supportFragmentManager.findFragmentByTag("fragment")?.viewLifecycleOwner
as FragmentViewLifecycleOwner
}
val recreateViewModel = ViewModelProvider(recreatedViewLifecycleOwner)[
"test", ViewModelActivity.TestSavedStateViewModel::class.java
]
assertThat(recreateViewModel).isSameInstanceAs(creationViewModel)
val value: String? = recreateViewModel.savedStateHandle["key"]
assertThat(value).isEqualTo("value")
}
}
class FakeViewModelProviderFactory : ViewModelProvider.Factory {
private var createCalled: Boolean = false
override fun <T : ViewModel> create(modelClass: Class<T>): T {
require(modelClass == TestViewModel::class.java)
createCalled = true
@Suppress("UNCHECKED_CAST")
return TestViewModel() as T
}
}
public class FragmentWithFactoryOverride : StrictViewFragment() {
public override fun getDefaultViewModelProviderFactory(): ViewModelProvider.Factory =
FakeViewModelProviderFactory()
}
} | fragment/fragment/src/androidTest/java/androidx/fragment/app/FragmentViewLifecycleOwnerTest.kt | 1233720783 |
/*
* 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:Suppress("UnstableApiUsage")
package androidx.compose.material3.lint
import androidx.compose.lint.test.Stubs
import androidx.compose.lint.test.compiledStub
import com.android.tools.lint.checks.infrastructure.LintDetectorTest
import com.android.tools.lint.detector.api.Detector
import com.android.tools.lint.detector.api.Issue
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
/* ktlint-disable max-line-length */
@RunWith(JUnit4::class)
/**
* Test for [ScaffoldPaddingDetector].
*/
class ScaffoldPaddingDetectorTest : LintDetectorTest() {
override fun getDetector(): Detector = ScaffoldPaddingDetector()
override fun getIssues(): MutableList<Issue> =
mutableListOf(ScaffoldPaddingDetector.UnusedMaterial3ScaffoldPaddingParameter)
// Simplified Scaffold.kt stubs
private val ScaffoldStub = compiledStub(
filename = "Scaffold.kt",
filepath = "androidx/compose/material3",
checksum = 0xfee46355,
"""
package androidx.compose.material3
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
@Composable
fun Scaffold(
modifier: Modifier = Modifier,
topBar: @Composable () -> Unit = {},
bottomBar: @Composable () -> Unit = {},
content: @Composable (PaddingValues) -> Unit
) {}
""",
"""
META-INF/main.kotlin_module:
H4sIAAAAAAAAAGNgYGBmYGBgBGI2Bijg0uCSSsxLKcrPTKnQS87PLcgvTtXL
TSxJLcpMzDEW4gpOTkxLy89J8S7h4uViTsvPF2ILSS0u8S5RYtBiAACpks1u
UQAAAA==
""",
"""
androidx/compose/material3/ScaffoldKt$Scaffold$1.class:
H4sIAAAAAAAAAKVU604TQRT+Zlt62RZbEOUi3kFbULYt3ktICIG4oWBisYnh
17S7haG7s6a7bfAfD+ET+ASiiSSaGOJPH8p4ZmkNhogaN9mzJ+d835lzm/32
/dMXAPfwhKHApdX2hLVnNDz3lefbhssDuy24M29UG7zZ9BxrLZjqq1PFOBjD
WqXlBY6Qxm7XNYQkguSOUeFu3eLlk75mRzYC4UnfWO1phYW+/4UUQXmxzDDx
+2BxRBmunB0wjhhDbEFQuEWGSC5fY4jmzHwtjQR0HQNIkSHYET5DqfKv9VJ+
MSG7XstmGMnlK7u8yw2Hy23jWX3XbgTlNDJI6tAwxJA6UVoc5xkS5kZ1c2lj
eYVh8Je607iAi0mMYJRACw0nzF4lHIaaUO5zSdImGYb6xHU74BYPOKWkud0I
jZApEVMCDKyllAg594TSCqRZRYbJo/2EfrSva1mNPtmj/QmtwJ7qX9/GtISm
MCVKfIFLT752vY5PPaRg03/VpzjuMGR/Nsuym7zjBAxvcqf73BHGumeJprDb
f1qR//QXy+bpMal1mINBpfbTnWtRptFlz6LJDle8BndqnAqsO/amEgyZipD2
Rset2+2eJW1KabeXHe77Nm1TZkU2HM8XcptGs+NZDMmq2JY86LQJrFe9Trth
rwrFHH/ekYFw7ZrwBYVaktILeJg2CjTmAWo53SyMq7nT7KL00i6QpUTaFCGY
mvRM5BDpg3Da8yTTx1YMhpwhtYg9xmyIoVeBNbrqCqYMqRNEdkzMLhEx2yOW
1CKpw2c+Yvg9xt6dwU/0Dk5Q2v2DRwmtntRnaC8PcekDLh+EhgHcJ6kT7Bgw
hgdhnXep/ofhIRE8Cr9FPA7/TnTxiXV1CxET10xcN3EDN01qxrSJW7i9BeYj
hzz5fcz4mPWR+QHL6C/y2gQAAA==
""",
"""
androidx/compose/material3/ScaffoldKt$Scaffold$2.class:
H4sIAAAAAAAAAKVUbU/TUBR+bjf2xnADUV7Ed9ANlI7h+wgJIRAbBiYOlxg+
3bUdXNbemrVd8Bs/wl/gLxBNNNHEED/6o4znlk0xRNTYpKcn5zzPueft9uu3
j58B3MEjhhKXVtsT1p5ueu4Lz7d1lwd2W3BnXq+ZvNn0HGstmOypk+UkGMNa
teUFjpD6bsfVhSSC5I5e5W7D4pXjvmYozUB40tdXu1ppoed/JkVQWawwjP8+
WBJxhkunB0wiwZBYEBRukSFWKNYZ4gWjWM8ihUwGfegnQ7AjfIZy9V/rpfwS
Qna8ls0wXChWd3mH6w6X2/qTxq5tBpUsckhnoGGQof9YaUmcZUgZG7XNpY3l
FYaBX+rO4hzOpzGMEQItmE6UvUo4CjWu3GfSpE0wDPaI63bALR5wSklzOzEa
IVMioQQYWEspMXLuCaWVSLPmGCYO91OZw/2Mltfokz/cH9dK7HHmy+uEltIU
pkyJL3DpyZeuF/rUQwo29Vd9SuIWQ/5Hsyy7yUMnYHhVONnnUOjrniWawm7/
aUX+0z9XMU6OSa3DLHQqtZfubIsyjS97Fk12qOqZ3KlzKrDh2JtKMOSqQtob
oduw211L1pDSbi873Pdt2qbcijQdzxdym0az41kM6ZrYljwI2wTO1Lywbdqr
QjHHnoYyEK5dF76gUEtSegGP0kaJxtxHLaebhTE1d5pdnF7aBbKUSZskBFOT
no59QPYgmvY8yeyRFQMRZ1AtYpcxE2HoVWCNrrqCsYjyk8iOiPklIua7xLJa
JHX49HsMvcXom1P4qe7BKUq7d/AIodXT/wna8w+48A4XDyJDH+6SzBDsCDCK
e1Gdt6n++9EhMTyIvnN4GP2d6OIT6/IWYgauGLhq4BquG9SMKQM3cHMLzEcB
RfL7mPYx4yP3HfQNQiHaBAAA
""",
"""
androidx/compose/material3/ScaffoldKt.class:
H4sIAAAAAAAAAMVUS3PbVBT+ru1YkmOnrhKniVtCaRya5lHZbnk6FFLTtCK2
6eA2m6yuZdkolq8yemTKhgnDX2DDln8Aqw4LxsOSf8EfYXok2yGNOwm0zLDQ
Pc97zneOzj1//PXrbwDuos6wwkXbdaz2M81w+oeOZ2p97puuxe07WtPgnY5j
t3d9CYwhe8CPuGZz0dW+bB2YBmnjDPLYi+G71dpEtMDS6k7b6limW6n1HN+2
hHZw1Nc6gTB8yxGetjPiim9oL1Vu7TH8+WYYtsb2p8LyK/f+W/fS1uYkuI4T
iDYPzdTab5zA1x7zdtsS3T1uB6ZXOZMhrHFlMoobCN/qm1o1knnLNisMyzXH
7WoHpt9yuUU4uBCOz4eYGo7fCGybvOT+qDcyUgxLpyqwBE2C4LamC9+lAJbh
SUgz5IyvTaM3ivCYu7xvkiPDzdXa2RGpnNI0wyBdqiCNGVxKIYMsQ9J3Du9z
yq0yKC3H951+JM4xSIZDAIQvY55wnf9bGa5fND0XupTIJTue5kLb7PDA9hl+
+J+nWp9sajgE184DJeEtamc4DFxQEIbzayiceFbSeBvXFSzhHYbiP9oNhZOW
lSQs0zzpjeaT7Ub1AUN5MusFESj/Ct5VUMDNl2fxFZ2TcOvfYyxLWH8NYOUI
2KaCDdxOYwrJFGIoMlwe/7266XN6xpxmKNY/itN6ZeGRDA8wsF7IxMj4zAo5
uhprlxi+HxzfSA2OU7FsLCILJyT65NiYzz/NDo7zsSIryzI5ExcvzxKXyGfU
hEr64tTvPyVjcjLSShPaK1k5PxvpUiOLMrQ8kkIoZRaiVMfVnH41E8rwnbyi
gRctMobpcTtv9+hdJapO22S4VLOE2Qj6LdN9Eu6tMKFjcHuP098geaRUmlZX
cD9wib/61XDb6eLI8iwyb/+92BgKZ60nG+olt0zT50avzg9HCdK6EKZbtbnn
mWRONZ3ANcwdK7QtjkLuTaRDieYgEf5joovhYJBUJYmP9Itr6vRzXF5XZ+nc
UHN0bqpX6Pw5uvJ5OCPU+QVaiQ+IXxteQoo0iDiVPhZxc/TFIm4eecSxE0WQ
8HAUQyb6KLQnSFCisTtzZhVcxTXiQ4R9SpUkWs4lEt/+iNQvuDHA0m4uMTWU
VgdYq+US0lDSSKqvrW9sPkdpCF2ncwrxmUwmqmKJkICSSIR9hmgO05RKwTLS
VJVCeL8gu0oXC1FlC/SUhnQ3CncfNaI1AlemsHf2EddxV8d7Ot7HBzo+xEc6
PkZlH8zDFj7Zx7SHKQ/3PKQ8LHhQPXzqQfYw52Hew2cetl8ABZTb8egIAAA=
"""
)
@Test
fun unreferencedParameters() {
lint().files(
kotlin(
"""
package foo
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.*
@Composable
fun Test() {
Scaffold { /**/ }
Scaffold(Modifier) { /**/ }
Scaffold(Modifier, topBar = {}, bottomBar = {}) { /**/ }
Scaffold(Modifier, topBar = {}, bottomBar = {}, content = { /**/ })
Scaffold(Modifier, topBar = {}, bottomBar = {}) { _ -> /**/ }
Scaffold(Modifier, topBar = {}, bottomBar = {}) { innerPadding -> /**/ }
}
"""
),
ScaffoldStub,
Stubs.Modifier,
Stubs.PaddingValues,
Stubs.Composable
)
.run()
.expect(
"""
src/foo/test.kt:10: Error: Content padding parameter it is not used [UnusedMaterial3ScaffoldPaddingParameter]
Scaffold { /**/ }
~~~~~~~~
src/foo/test.kt:11: Error: Content padding parameter it is not used [UnusedMaterial3ScaffoldPaddingParameter]
Scaffold(Modifier) { /**/ }
~~~~~~~~
src/foo/test.kt:12: Error: Content padding parameter it is not used [UnusedMaterial3ScaffoldPaddingParameter]
Scaffold(Modifier, topBar = {}, bottomBar = {}) { /**/ }
~~~~~~~~
src/foo/test.kt:13: Error: Content padding parameter it is not used [UnusedMaterial3ScaffoldPaddingParameter]
Scaffold(Modifier, topBar = {}, bottomBar = {}, content = { /**/ })
~~~~~~~~
src/foo/test.kt:14: Error: Content padding parameter _ is not used [UnusedMaterial3ScaffoldPaddingParameter]
Scaffold(Modifier, topBar = {}, bottomBar = {}) { _ -> /**/ }
~
src/foo/test.kt:15: Error: Content padding parameter innerPadding is not used [UnusedMaterial3ScaffoldPaddingParameter]
Scaffold(Modifier, topBar = {}, bottomBar = {}) { innerPadding -> /**/ }
~~~~~~~~~~~~
6 errors, 0 warnings
"""
)
}
@Test
fun unreferencedParameter_shadowedNames() {
lint().files(
kotlin(
"""
package foo
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.*
val foo = false
@Composable
fun Test() {
Scaffold {
foo.let {
// These `it`s refer to the `let`, not the `Scaffold`, so we
// should still report an error
it.let {
if (it) { /**/ } else { /**/ }
}
}
}
Scaffold(Modifier, topBar = {}, bottomBar = {}) { innerPadding ->
foo.let { innerPadding ->
// These `innerPadding`s refer to the `let`, not the `Scaffold`, so we
// should still report an error
innerPadding.let {
if (innerPadding) { /**/ } else { /**/ }
}
}
}
}
"""
),
ScaffoldStub,
Stubs.Modifier,
Stubs.PaddingValues,
Stubs.Composable
)
.run()
.expect(
"""
src/foo/test.kt:12: Error: Content padding parameter it is not used [UnusedMaterial3ScaffoldPaddingParameter]
Scaffold {
^
src/foo/test.kt:21: Error: Content padding parameter innerPadding is not used [UnusedMaterial3ScaffoldPaddingParameter]
Scaffold(Modifier, topBar = {}, bottomBar = {}) { innerPadding ->
~~~~~~~~~~~~
2 errors, 0 warnings
"""
)
}
@Test
fun noErrors() {
lint().files(
kotlin(
"""
package foo
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.*
@Composable
fun Test() {
Scaffold {
it
}
Scaffold(Modifier, topBar = {}, bottomBar = {}) { innerPadding ->
innerPadding
}
}
"""
),
ScaffoldStub,
Stubs.Modifier,
Stubs.PaddingValues,
Stubs.Composable
)
.run()
.expectClean()
}
}
/* ktlint-enable max-line-length */
| compose/material3/material3-lint/src/test/java/androidx/compose/material3/lint/ScaffoldPaddingDetectorTest.kt | 2228527277 |
package com.simplemobiletools.commons.views
import android.content.Context
import android.util.AttributeSet
import androidx.recyclerview.widget.GridLayoutManager
class MyGridLayoutManager : GridLayoutManager {
constructor(context: Context, spanCount: Int) : super(context, spanCount)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes)
constructor(context: Context, spanCount: Int, orientation: Int, reverseLayout: Boolean) : super(context, spanCount, orientation, reverseLayout)
// fixes crash java.lang.IndexOutOfBoundsException: Inconsistency detected...
// taken from https://stackoverflow.com/a/33985508/1967672
override fun supportsPredictiveItemAnimations() = false
}
| commons/src/main/kotlin/com/simplemobiletools/commons/views/MyGridLayoutManager.kt | 3351893491 |
package org.thoughtcrime.securesms.contacts.sync
import android.content.ActivityNotFoundException
import android.content.Intent
import android.os.Bundle
import android.view.ContextThemeWrapper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.FragmentManager
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.components.FixedRoundedCornerBottomSheetDialogFragment
import org.thoughtcrime.securesms.databinding.CdsPermanentErrorBottomSheetBinding
import org.thoughtcrime.securesms.util.BottomSheetUtil
import org.thoughtcrime.securesms.util.CommunicationActions
/**
* Bottom sheet shown when CDS is in a permanent error state, preventing us from doing a sync.
*/
class CdsPermanentErrorBottomSheet : FixedRoundedCornerBottomSheetDialogFragment() {
private lateinit var binding: CdsPermanentErrorBottomSheetBinding
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
binding = CdsPermanentErrorBottomSheetBinding.inflate(inflater.cloneInContext(ContextThemeWrapper(inflater.context, themeResId)), container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
binding.learnMoreButton.setOnClickListener {
CommunicationActions.openBrowserLink(requireContext(), "https://support.signal.org/hc/articles/360007319011#android_contacts_error")
}
binding.settingsButton.setOnClickListener {
val intent = Intent().apply {
action = Intent.ACTION_VIEW
data = android.provider.ContactsContract.Contacts.CONTENT_URI
}
try {
startActivity(intent)
} catch (e: ActivityNotFoundException) {
Toast.makeText(context, R.string.CdsPermanentErrorBottomSheet_no_contacts_toast, Toast.LENGTH_SHORT).show()
}
}
}
companion object {
@JvmStatic
fun show(fragmentManager: FragmentManager) {
val fragment = CdsPermanentErrorBottomSheet()
fragment.show(fragmentManager, BottomSheetUtil.STANDARD_BOTTOM_SHEET_FRAGMENT_TAG)
}
}
}
| app/src/main/java/org/thoughtcrime/securesms/contacts/sync/CdsPermanentErrorBottomSheet.kt | 851224236 |
/*
* 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.graphics.opengl
import android.opengl.EGL14
import android.opengl.EGLConfig
import android.opengl.EGLSurface
import android.os.Handler
import android.os.HandlerThread
import android.os.SystemClock
import android.util.Log
import android.view.Surface
import androidx.annotation.AnyThread
import androidx.annotation.WorkerThread
import androidx.graphics.opengl.GLRenderer.EGLContextCallback
import androidx.graphics.opengl.GLRenderer.RenderCallback
import androidx.graphics.opengl.egl.EGLManager
import androidx.graphics.opengl.egl.EGLSpec
import java.util.concurrent.atomic.AtomicBoolean
/**
* Thread responsible for management of EGL dependencies, setup and teardown
* of EGLSurface instances as well as delivering callbacks to draw a frame
*/
internal class GLThread(
name: String = "GLThread",
private val mEglSpecFactory: () -> EGLSpec,
private val mEglConfigFactory: EGLManager.() -> EGLConfig,
) : HandlerThread(name) {
// Accessed on internal HandlerThread
private val mIsTearingDown = AtomicBoolean(false)
private var mEglManager: EGLManager? = null
private val mSurfaceSessions = HashMap<Int, SurfaceSession>()
private var mHandler: Handler? = null
private val mEglContextCallback = HashSet<EGLContextCallback>()
override fun start() {
super.start()
mHandler = Handler(looper)
}
/**
* Adds the given [android.view.Surface] to be managed by the GLThread.
* A corresponding [EGLSurface] is created on the GLThread as well as a callback
* for rendering into the surface through [RenderCallback].
* @param surface intended to be be rendered into on the GLThread
* @param width Desired width of the [surface]
* @param height Desired height of the [surface]
* @param renderer callbacks used to create a corresponding [EGLSurface] from the
* given surface as well as render content into the created [EGLSurface]
* @return Identifier used for subsequent requests to communicate
* with the provided Surface (ex. [requestRender] or [detachSurface]
*/
@AnyThread
fun attachSurface(
token: Int,
surface: Surface?,
width: Int,
height: Int,
renderer: RenderCallback
) {
withHandler {
post(token) {
attachSurfaceSessionInternal(
SurfaceSession(token, surface, renderer).apply {
this.width = width
this.height = height
}
)
}
}
}
@AnyThread
fun resizeSurface(token: Int, width: Int, height: Int, callback: Runnable? = null) {
withHandler {
post(token) {
resizeSurfaceSessionInternal(token, width, height)
requestRenderInternal(token)
callback?.run()
}
}
}
@AnyThread
fun addEGLCallbacks(callbacks: ArrayList<EGLContextCallback>) {
withHandler {
post {
mEglContextCallback.addAll(callbacks)
mEglManager?.let {
for (callback in callbacks) {
callback.onEGLContextCreated(it)
}
}
}
}
}
@AnyThread
fun addEGLCallback(callbacks: EGLContextCallback) {
withHandler {
post {
mEglContextCallback.add(callbacks)
// If EGL dependencies are already initialized, immediately invoke
// the added callback
mEglManager?.let {
callbacks.onEGLContextCreated(it)
}
}
}
}
@AnyThread
fun removeEGLCallback(callbacks: EGLContextCallback) {
withHandler {
post {
mEglContextCallback.remove(callbacks)
}
}
}
/**
* Removes the corresponding [android.view.Surface] from management of the GLThread.
* This destroys the EGLSurface associated with this surface and subsequent requests
* to render into the surface with the provided token are ignored. Any queued request
* to render to the corresponding [SurfaceSession] that has not started yet is cancelled.
* However, if this is invoked in the middle of the frame being rendered, it will continue to
* process the current frame.
*/
@AnyThread
fun detachSurface(
token: Int,
cancelPending: Boolean,
callback: Runnable?
) {
log("dispatching request to detach surface w/ token: $token")
withHandler {
if (cancelPending) {
removeCallbacksAndMessages(token)
}
post(token) {
detachSurfaceSessionInternal(token, callback)
}
}
}
/**
* Cancel all pending requests to all currently managed [SurfaceSession] instances,
* destroy all EGLSurfaces, teardown EGLManager and quit this thread
*/
@AnyThread
fun tearDown(cancelPending: Boolean, callback: Runnable?) {
withHandler {
if (cancelPending) {
removeCallbacksAndMessages(null)
}
post {
releaseResourcesInternalAndQuit(callback)
}
mIsTearingDown.set(true)
}
}
/**
* Mark the corresponding surface session with the given token as dirty
* to schedule a call to [RenderCallback#onDrawFrame].
* If there is already a queued request to render into the provided surface with
* the specified token, this request is ignored.
*/
@AnyThread
fun requestRender(token: Int, callback: Runnable? = null) {
log("dispatching request to render for token: $token")
withHandler {
post(token) {
requestRenderInternal(token)
callback?.run()
}
}
}
/**
* Lazily creates an [EGLManager] instance from the given [mEglSpecFactory]
* used to determine the configuration. This result is cached across calls
* unless [tearDown] has been called.
*/
@WorkerThread
fun obtainEGLManager(): EGLManager =
mEglManager ?: EGLManager(mEglSpecFactory.invoke()).also {
it.initialize()
val config = mEglConfigFactory.invoke(it)
it.createContext(config)
for (callback in mEglContextCallback) {
callback.onEGLContextCreated(it)
}
mEglManager = it
}
@WorkerThread
private fun disposeSurfaceSession(session: SurfaceSession) {
val eglSurface = session.eglSurface
if (eglSurface != null && eglSurface != EGL14.EGL_NO_SURFACE) {
obtainEGLManager().eglSpec.eglDestroySurface(eglSurface)
session.eglSurface = null
}
}
/**
* Helper method to obtain the cached EGLSurface for the given [SurfaceSession],
* creating one if it does not previously exist
*/
@WorkerThread
private fun obtainEGLSurfaceForSession(session: SurfaceSession): EGLSurface? {
return if (session.eglSurface != null) {
session.eglSurface
} else {
createEGLSurfaceForSession(
session.surface,
session.width,
session.height,
session.surfaceRenderer
).also {
session.eglSurface = it
}
}
}
/**
* Helper method to create the corresponding EGLSurface from the [SurfaceSession] instance
* Consumers are expected to teardown the previously existing EGLSurface instance if it exists
*/
@WorkerThread
private fun createEGLSurfaceForSession(
surface: Surface?,
width: Int,
height: Int,
surfaceRenderer: RenderCallback
): EGLSurface? {
with(obtainEGLManager()) {
return if (surface != null) {
surfaceRenderer.onSurfaceCreated(
eglSpec,
// Successful creation of EGLManager ensures non null EGLConfig
eglConfig!!,
surface,
width,
height
)
} else {
null
}
}
}
@WorkerThread
private fun releaseResourcesInternalAndQuit(callback: Runnable?) {
val eglManager = obtainEGLManager()
for (session in mSurfaceSessions) {
disposeSurfaceSession(session.value)
}
callback?.run()
mSurfaceSessions.clear()
for (eglCallback in mEglContextCallback) {
eglCallback.onEGLContextDestroyed(eglManager)
}
mEglContextCallback.clear()
eglManager.release()
mEglManager = null
quit()
}
@WorkerThread
private fun requestRenderInternal(token: Int) {
log("requesting render for token: $token")
mSurfaceSessions[token]?.let { surfaceSession ->
val eglManager = obtainEGLManager()
val eglSurface = obtainEGLSurfaceForSession(surfaceSession)
if (eglSurface != null) {
eglManager.makeCurrent(eglSurface)
} else {
eglManager.makeCurrent(eglManager.defaultSurface)
}
val width = surfaceSession.width
val height = surfaceSession.height
if (width > 0 && height > 0) {
surfaceSession.surfaceRenderer.onDrawFrame(eglManager)
}
if (eglSurface != null) {
eglManager.swapAndFlushBuffers()
}
}
}
@WorkerThread
private fun attachSurfaceSessionInternal(surfaceSession: SurfaceSession) {
mSurfaceSessions[surfaceSession.surfaceToken] = surfaceSession
}
@WorkerThread
private fun resizeSurfaceSessionInternal(
token: Int,
width: Int,
height: Int
) {
mSurfaceSessions[token]?.let { surfaceSession ->
surfaceSession.apply {
this.width = width
this.height = height
}
disposeSurfaceSession(surfaceSession)
obtainEGLSurfaceForSession(surfaceSession)
}
}
@WorkerThread
private fun detachSurfaceSessionInternal(token: Int, callback: Runnable?) {
val session = mSurfaceSessions.remove(token)
if (session != null) {
disposeSurfaceSession(session)
}
callback?.run()
}
/**
* Helper method that issues a callback on the handler instance for this thread
* ensuring proper nullability checks are handled.
* This assumes that that [GLRenderer.start] has been called before attempts
* to interact with the corresponding Handler are made with this method
*/
private inline fun withHandler(block: Handler.() -> Unit) {
val handler = mHandler
?: throw IllegalStateException("Did you forget to call GLThread.start()?")
if (!mIsTearingDown.get()) {
block(handler)
}
}
companion object {
private const val DEBUG = true
private const val TAG = "GLThread"
internal fun log(msg: String) {
if (DEBUG) {
Log.v(TAG, msg)
}
}
}
private class SurfaceSession(
/**
* Identifier used to lookup the mapping of this surface session.
* Consumers are expected to provide this identifier to operate on the corresponding
* surface to either request a frame be rendered or to remove this Surface
*/
val surfaceToken: Int,
/**
* Target surface to render into. Can be null for situations where GL is used to render
* into a frame buffer object provided from an AHardwareBuffer instance.
* In these cases the actual surface is never used.
*/
val surface: Surface?,
/**
* Callback used to create an EGLSurface from the provided surface as well as
* render content to the surface
*/
val surfaceRenderer: RenderCallback
) {
/**
* Lazily created + cached [EGLSurface] after [RenderCallback.onSurfaceCreated]
* is invoked. This is only modified on the backing thread
*/
var eglSurface: EGLSurface? = null
/**
* Target width of the [surface]. This is only modified on the backing thread
*/
var width: Int = 0
/**
* Target height of the [surface]. This is only modified on the backing thread
*/
var height: Int = 0
}
/**
* Handler does not expose a post method that takes a token and a runnable.
* We need the token to be able to cancel pending requests so just call
* postAtTime with the default of SystemClock.uptimeMillis
*/
private fun Handler.post(token: Any?, runnable: Runnable) {
postAtTime(runnable, token, SystemClock.uptimeMillis())
}
} | graphics/graphics-core/src/main/java/androidx/graphics/opengl/GLThread.kt | 777857853 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package git4idea.stash
import com.intellij.openapi.vcs.Executor.echo
import com.intellij.openapi.vcs.Executor.touch
import com.intellij.vcs.log.util.VcsLogUtil
import git4idea.history.GitLogUtil
import git4idea.test.*
import git4idea.ui.StashInfo
import org.apache.commons.lang.RandomStringUtils
import java.util.regex.Pattern
class GitStashTest : GitSingleRepoTest() {
fun `test list stashes`() {
val msg1 = "message 1"
touch("a.txt")
add()
commit(msg1)
echo("a.txt", RandomStringUtils.randomAlphanumeric(200))
stash()
val branch = "test"
branch(branch)
checkout(branch)
val msg2 = "message 2"
touch("b.txt")
add()
commit(msg2)
echo("b.txt", RandomStringUtils.randomAlphanumeric(200))
stash()
val stack = loadStashStack(project, projectRoot)
assertEquals(2, stack.size)
val stash2 = stack.first()
val stash1 = stack.last()
assertStashInfoIsCorrect(0, msg2, branch, stash2)
assertStashInfoIsCorrect(1, msg1, "master", stash1)
}
private fun assertStashInfoIsCorrect(expectedNumber: Int,
expectedMessage: String,
expectedBranch: String,
actualStash: StashInfo) {
assertEquals("stash@{$expectedNumber}", actualStash.stash)
assertStashMessageEquals(expectedMessage, actualStash)
assertEquals("WIP on $expectedBranch", actualStash.branch)
assertEquals(stashAuthorTime(expectedNumber), actualStash.authorTime)
}
private fun assertStashMessageEquals(expectedMessage: String, stash: StashInfo) {
assertTrue("Expected '<HASH> $expectedMessage', got '${stash.message}'",
stashMessagePattern(expectedMessage).matcher(stash.message).matches())
}
private fun stashMessagePattern(commitMessage: String) = Pattern.compile("${VcsLogUtil.HASH_REGEX.pattern()} ${commitMessage}")
private fun stash() = git(project, "stash")
private fun stashAuthorTime(stashNumber: Int): Long {
val noWalkParameter = GitLogUtil.getNoWalkParameter(project)
val timeString = git(project, "log --pretty=format:%at $noWalkParameter stash@{$stashNumber}")
return GitLogUtil.parseTime(timeString)
}
} | plugins/git4idea/tests/git4idea/stash/GitStashTest.kt | 2532950473 |
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.autoimport
import com.intellij.openapi.Disposable
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.externalSystem.autoimport.AutoImportProjectTracker.Companion.isAsyncChangesProcessing
import com.intellij.openapi.externalSystem.autoimport.ExternalSystemModificationType.EXTERNAL
import com.intellij.openapi.externalSystem.autoimport.ExternalSystemSettingsFilesModificationContext.Event.*
import com.intellij.openapi.externalSystem.autoimport.ExternalSystemSettingsFilesModificationContext.ReloadStatus
import com.intellij.openapi.externalSystem.autoimport.ProjectStatus.ProjectEvent.*
import com.intellij.openapi.externalSystem.autoimport.ProjectStatus.ProjectEvent.Companion.externalInvalidate
import com.intellij.openapi.externalSystem.autoimport.ProjectStatus.ProjectEvent.Companion.externalModify
import com.intellij.openapi.externalSystem.autoimport.changes.AsyncFilesChangesListener.Companion.subscribeOnDocumentsAndVirtualFilesChanges
import com.intellij.openapi.externalSystem.autoimport.changes.FilesChangesListener
import com.intellij.openapi.externalSystem.autoimport.changes.NewFilesListener.Companion.whenNewFilesCreated
import com.intellij.openapi.externalSystem.autoimport.settings.*
import com.intellij.openapi.externalSystem.util.calculateCrc
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.observable.operation.core.AtomicOperationTrace
import com.intellij.openapi.observable.operation.core.isOperationInProgress
import com.intellij.openapi.observable.operation.core.whenOperationFinished
import com.intellij.openapi.observable.operation.core.whenOperationStarted
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.LocalTimeCounter.currentTime
import org.jetbrains.annotations.ApiStatus
import java.nio.file.Path
import java.util.concurrent.Executor
import java.util.concurrent.atomic.AtomicReference
@ApiStatus.Internal
class ProjectSettingsTracker(
private val project: Project,
private val projectTracker: AutoImportProjectTracker,
private val backgroundExecutor: Executor,
private val projectAware: ExternalSystemProjectAware,
private val parentDisposable: Disposable
) {
private val projectStatus = ProjectStatus(debugName = "Settings ${projectAware.projectId.debugName}")
private val settingsFilesStatus = AtomicReference(SettingsFilesStatus())
private val applyChangesOperation = AtomicOperationTrace(name = "Apply changes operation")
private val settingsAsyncSupplier = SettingsFilesAsyncSupplier()
private fun calculateSettingsFilesCRC(settingsFiles: Set<String>): Map<String, Long> {
val localFileSystem = LocalFileSystem.getInstance()
return settingsFiles
.mapNotNull { localFileSystem.findFileByPath(it) }
.associate { it.path to calculateCrc(it) }
}
private fun calculateCrc(file: VirtualFile): Long {
val fileDocumentManager = FileDocumentManager.getInstance()
val document = fileDocumentManager.getCachedDocument(file)
if (document != null) return document.calculateCrc(project, projectAware.projectId.systemId, file)
return file.calculateCrc(project, projectAware.projectId.systemId)
}
fun isUpToDate() = projectStatus.isUpToDate()
fun getModificationType() = projectStatus.getModificationType()
fun getSettingsContext(): ExternalSystemSettingsFilesReloadContext {
val status = settingsFilesStatus.get()
return SettingsFilesReloadContext(status.updated, status.created, status.deleted)
}
/**
* Updates settings files status using new CRCs.
* @param isReloadJustFinished see [adjustCrc] for details
*/
private fun updateSettingsFilesStatus(
operationName: String,
newCRC: Map<String, Long>,
isReloadJustFinished: Boolean = false,
): SettingsFilesStatus {
return settingsFilesStatus.updateAndGet {
SettingsFilesStatus(it.oldCRC, newCRC)
.adjustCrc(operationName, isReloadJustFinished)
}
}
/**
* Adjusts settings files status. It allows ignoring files modifications by rules from
* external system. For example some build systems needed to ignore files updates during reload.
*
* @see ExternalSystemProjectAware.isIgnoredSettingsFileEvent
*/
private fun SettingsFilesStatus.adjustCrc(operationName: String, isReloadJustFinished: Boolean): SettingsFilesStatus {
val modificationType = getModificationType()
val isReloadInProgress = applyChangesOperation.isOperationInProgress()
val reloadStatus = when {
isReloadJustFinished -> ReloadStatus.JUST_FINISHED
isReloadInProgress -> ReloadStatus.IN_PROGRESS
else -> ReloadStatus.IDLE
}
val oldCRC = oldCRC.toMutableMap()
for (path in updated) {
val context = SettingsFilesModificationContext(UPDATE, modificationType, reloadStatus)
if (projectAware.isIgnoredSettingsFileEvent(path, context)) {
oldCRC[path] = newCRC[path]!!
}
}
for (path in created) {
val context = SettingsFilesModificationContext(CREATE, modificationType, reloadStatus)
if (projectAware.isIgnoredSettingsFileEvent(path, context)) {
oldCRC[path] = newCRC[path]!!
}
}
for (path in deleted) {
val context = SettingsFilesModificationContext(DELETE, modificationType, reloadStatus)
if (projectAware.isIgnoredSettingsFileEvent(path, context)) {
oldCRC.remove(path)
}
}
val status = SettingsFilesStatus(oldCRC, newCRC)
LOG.debug(
"[$operationName] " +
"ReloadStatus=$reloadStatus, " +
"ModificationType=$modificationType, " +
"Updated=${status.updated}, " +
"Created=${status.created}, " +
"Deleted=${status.deleted}"
)
return status
}
fun getState() = State(projectStatus.isDirty(), settingsFilesStatus.get().oldCRC.toMap())
fun loadState(state: State) {
val operationStamp = currentTime()
settingsFilesStatus.set(SettingsFilesStatus(state.settingsFiles.toMap()))
when (state.isDirty) {
true -> projectStatus.markDirty(operationStamp, EXTERNAL)
else -> projectStatus.markSynchronized(operationStamp)
}
}
fun refreshChanges() {
submitSettingsFilesStatusUpdate(
operationName = "refreshChanges",
isRefreshVfs = true,
syncEvent = ::Revert,
changeEvent = ::externalInvalidate
) {
projectTracker.scheduleChangeProcessing()
}
}
private fun submitSettingsFilesCollection(isInvalidateCache: Boolean = false, callback: (Set<String>) -> Unit) {
if (isInvalidateCache) {
settingsAsyncSupplier.invalidate()
}
settingsAsyncSupplier.supply(parentDisposable, callback)
}
private fun submitSettingsFilesRefresh(callback: (Set<String>) -> Unit) {
EdtAsyncSupplier.invokeOnEdt(::isAsyncChangesProcessing, parentDisposable) {
val fileDocumentManager = FileDocumentManager.getInstance()
fileDocumentManager.saveAllDocuments()
submitSettingsFilesCollection(isInvalidateCache = true) { settingsPaths ->
val localFileSystem = LocalFileSystem.getInstance()
val settingsFiles = settingsPaths.map { Path.of(it) }
localFileSystem.refreshNioFiles(settingsFiles, isAsyncChangesProcessing, false) {
callback(settingsPaths)
}
}
}
}
private fun submitSettingsFilesCRCCalculation(
operationName: String,
settingsPaths: Set<String>,
isMergeSameCalls: Boolean = false,
callback: (Map<String, Long>) -> Unit
) {
val builder = ReadAsyncSupplier.Builder { calculateSettingsFilesCRC(settingsPaths) }
.shouldKeepTasksAsynchronous(::isAsyncChangesProcessing)
if (isMergeSameCalls) {
builder.coalesceBy(this, operationName)
}
builder.build(backgroundExecutor)
.supply(parentDisposable, callback)
}
private fun submitSettingsFilesCollection(
isRefreshVfs: Boolean = false,
isInvalidateCache: Boolean = false,
callback: (Set<String>) -> Unit
) {
if (isRefreshVfs) {
submitSettingsFilesRefresh(callback)
}
else {
submitSettingsFilesCollection(isInvalidateCache, callback)
}
}
private fun submitSettingsFilesStatusUpdate(
operationName: String,
isMergeSameCalls: Boolean = false,
isReloadJustFinished: Boolean = false,
isInvalidateCache: Boolean = false,
isRefreshVfs: Boolean = false,
syncEvent: (Long) -> ProjectStatus.ProjectEvent,
changeEvent: ((Long) -> ProjectStatus.ProjectEvent)?,
callback: () -> Unit
) {
submitSettingsFilesCollection(isRefreshVfs, isInvalidateCache) { settingsPaths ->
val operationStamp = currentTime()
submitSettingsFilesCRCCalculation(operationName, settingsPaths, isMergeSameCalls) { newSettingsFilesCRC ->
val settingsFilesStatus = updateSettingsFilesStatus(operationName, newSettingsFilesCRC, isReloadJustFinished)
val event = if (settingsFilesStatus.hasChanges()) changeEvent else syncEvent
if (event != null) {
projectStatus.update(event(operationStamp))
}
callback()
}
}
}
fun beforeApplyChanges(
parentDisposable: Disposable,
listener: () -> Unit
) = applyChangesOperation.whenOperationStarted(parentDisposable, listener)
fun afterApplyChanges(
parentDisposable: Disposable,
listener: () -> Unit
) = applyChangesOperation.whenOperationFinished(parentDisposable, listener)
init {
projectAware.subscribe(ProjectListener(), parentDisposable)
whenNewFilesCreated(settingsAsyncSupplier::invalidate, parentDisposable)
subscribeOnDocumentsAndVirtualFilesChanges(settingsAsyncSupplier, ProjectSettingsListener(), parentDisposable)
}
data class State(var isDirty: Boolean = true, var settingsFiles: Map<String, Long> = emptyMap())
private class SettingsFilesStatus(
val oldCRC: Map<String, Long>,
val newCRC: Map<String, Long>,
) {
constructor(CRC: Map<String, Long> = emptyMap()) : this(CRC, CRC)
val updated: Set<String> by lazy {
oldCRC.keys.intersect(newCRC.keys)
.filterTo(HashSet()) { oldCRC[it] != newCRC[it] }
}
val created: Set<String> by lazy {
newCRC.keys.minus(oldCRC.keys)
}
val deleted: Set<String> by lazy {
oldCRC.keys.minus(newCRC.keys)
}
fun hasChanges() = updated.isNotEmpty() || created.isNotEmpty() || deleted.isNotEmpty()
}
private class SettingsFilesReloadContext(
override val updated: Set<String>,
override val created: Set<String>,
override val deleted: Set<String>
) : ExternalSystemSettingsFilesReloadContext
private class SettingsFilesModificationContext(
override val event: ExternalSystemSettingsFilesModificationContext.Event,
override val modificationType: ExternalSystemModificationType,
override val reloadStatus: ReloadStatus,
) : ExternalSystemSettingsFilesModificationContext
private inner class ProjectListener : ExternalSystemProjectListener {
override fun onProjectReloadStart() {
applyChangesOperation.traceStart()
settingsFilesStatus.updateAndGet {
SettingsFilesStatus(it.newCRC, it.newCRC)
}
projectStatus.markSynchronized(currentTime())
}
override fun onProjectReloadFinish(status: ExternalSystemRefreshStatus) {
submitSettingsFilesStatusUpdate(
operationName = "onProjectReloadFinish",
isRefreshVfs = true,
isReloadJustFinished = true,
syncEvent = ::Synchronize,
changeEvent = ::externalInvalidate
) {
applyChangesOperation.traceFinish()
}
}
override fun onSettingsFilesListChange() {
submitSettingsFilesStatusUpdate(
operationName = "onSettingsFilesListChange",
isInvalidateCache = true,
syncEvent = ::Revert,
changeEvent = ::externalModify,
) {
projectTracker.scheduleChangeProcessing()
}
}
}
private inner class ProjectSettingsListener : FilesChangesListener {
override fun onFileChange(path: String, modificationStamp: Long, modificationType: ExternalSystemModificationType) {
val operationStamp = currentTime()
logModificationAsDebug(path, modificationStamp, modificationType)
projectStatus.markModified(operationStamp, modificationType)
}
override fun apply() {
submitSettingsFilesStatusUpdate(
operationName = "ProjectSettingsListener.apply",
isMergeSameCalls = true,
syncEvent = ::Revert,
changeEvent = null
) {
projectTracker.scheduleChangeProcessing()
}
}
private fun logModificationAsDebug(path: String, modificationStamp: Long, type: ExternalSystemModificationType) {
if (LOG.isDebugEnabled) {
val projectPath = projectAware.projectId.externalProjectPath
val relativePath = FileUtil.getRelativePath(projectPath, path, '/') ?: path
LOG.debug("File $relativePath is modified at ${modificationStamp} as $type")
}
}
}
private inner class SettingsFilesAsyncSupplier : AsyncSupplier<Set<String>> {
private val cachingAsyncSupplier = CachingAsyncSupplier(
BackgroundAsyncSupplier.Builder(projectAware::settingsFiles)
.shouldKeepTasksAsynchronous(::isAsyncChangesProcessing)
.build(backgroundExecutor))
private val supplier = BackgroundAsyncSupplier.Builder(cachingAsyncSupplier)
.shouldKeepTasksAsynchronous(::isAsyncChangesProcessing)
.build(backgroundExecutor)
override fun supply(parentDisposable: Disposable, consumer: (Set<String>) -> Unit) {
supplier.supply(parentDisposable) {
consumer(it + settingsFilesStatus.get().oldCRC.keys)
}
}
fun invalidate() {
cachingAsyncSupplier.invalidate()
}
}
companion object {
private val LOG = Logger.getInstance("#com.intellij.openapi.externalSystem.autoimport")
}
} | platform/external-system-impl/src/com/intellij/openapi/externalSystem/autoimport/ProjectSettingsTracker.kt | 1589862275 |
// 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.fe10.inspections
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.NonNls
import org.jetbrains.annotations.PropertyKey
import org.jetbrains.kotlin.util.AbstractKotlinBundle
@NonNls
private const val BUNDLE = "messages.KotlinInspectionsFe10Bundle"
object KotlinInspectionsFe10Bundle : AbstractKotlinBundle(BUNDLE) {
@Nls
@JvmStatic
fun message(@NonNls @PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any): String = getMessage(key, *params)
} | plugins/kotlin/inspections-fe10/src/org/jetbrains/kotlin/idea/fe10/inspections/KotlinInspectionsFe10Bundle.kt | 2874357270 |
// PROBLEM: none
fun main() {
while (true) { <caret>-> println("Hi") }
}
fun println(s: String) {} | plugins/kotlin/idea/tests/testData/inspectionsLocal/redundantLambdaArrow/while.kt | 634657502 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.roots.impl.indexing
import com.intellij.find.ngrams.TrigramIndex
import com.intellij.openapi.fileTypes.PlainTextFileType
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.AdditionalLibraryRootsProvider
import com.intellij.openapi.roots.ModuleRootModificationUtil
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.roots.SyntheticLibrary
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.impl.cache.impl.id.IdIndex
import com.intellij.psi.search.FileTypeIndex
import com.intellij.psi.search.FilenameIndex
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.testFramework.PsiTestUtil
import com.intellij.testFramework.RunsInEdt
import com.intellij.testFramework.UsefulTestCase.assertContainsElements
import com.intellij.testFramework.UsefulTestCase.assertTrue
import com.intellij.util.indexing.FileBasedIndex
import com.intellij.util.indexing.ID
import com.intellij.util.indexing.IndexableSetContributor
import org.junit.Test
@RunsInEdt
class IndexableFilesBeneathExcludedDirectoryTest : IndexableFilesBaseTest() {
@Test
fun `excluded files must not be indexed`() {
lateinit var excludedJava: FileSpec
projectModelRule.createJavaModule("moduleName") {
content("contentRoot") {
excluded("excluded") {
excludedJava = file("ExcludedFile.java", "class ExcludedFile {}")
}
}
}
assertIndexableFiles()
assertHasNoIndexes(excludedJava.file)
}
@Test
fun `source root beneath excluded directory must be indexed`() {
lateinit var aJava: FileSpec
projectModelRule.createJavaModule("moduleName") {
content("contentRoot") {
excluded("excluded") {
source("sources") {
aJava = file("A.java", "class A {}")
}
}
}
}
assertIndexableFiles(aJava.file)
}
@Test
fun `files of a Library residing beneath module excluded directory must be indexed`() {
lateinit var libraryRoot: DirectorySpec
lateinit var libraryClass: FileSpec
val module = projectModelRule.createJavaModule("moduleName") {
content("contentRoot") {
excluded("excluded") {
// Must be indexed despite being excluded by module.
libraryRoot = dir("library") {
libraryClass = file("LibraryClass.java", "class LibraryClass {}")
}
}
}
}
projectModelRule.addModuleLevelLibrary(module, "libraryName") { model ->
model.addRoot(libraryRoot.file, OrderRootType.CLASSES)
}
assertIndexableFiles(libraryClass.file)
}
@Test
fun `files of an SDK residing beneath module excluded directory must be indexed`() {
lateinit var sdkRoot: DirectorySpec
lateinit var sdkClass: FileSpec
val module = projectModelRule.createJavaModule("moduleName") {
content("contentRoot") {
excluded("excluded") {
// Must be indexed despite being excluded by module.
sdkRoot = dir("sdk") {
sdkClass = file("SdkClass.java", "class SdkClass {}")
}
}
}
}
val sdk = projectModelRule.addSdk("sdkName") { sdkModificator ->
sdkModificator.addRoot(sdkRoot.file, OrderRootType.CLASSES)
}
ModuleRootModificationUtil.setModuleSdk(module, sdk)
assertIndexableFiles(sdkClass.file)
}
// Roots provided by AdditionalLibraryRootsProvider are considered library source roots,
// and they must be indexed even if they reside beneath excluded directories.
@Test
fun `files of AdditionalLibraryRootsProvider residing beneath module excluded directory must be indexed`() {
lateinit var targetSource: FileSpec
lateinit var targetSources: DirectorySpec
lateinit var targetBinary: FileSpec
lateinit var targetBinaries: DirectorySpec
projectModelRule.createJavaModule("moduleName") {
content("contentRoot") {
excluded("excluded") {
targetSources = moduleDir("sources") {
targetSource = file("TargetSource.java", "class TargetSource {}")
}
targetBinaries = moduleDir("binaries") {
targetBinary = file("TargetBinary.java", "class TargetBinary {}")
}
}
}
}
val additionalLibraryRootsProvider = object : AdditionalLibraryRootsProvider() {
override fun getAdditionalProjectLibraries(project: Project) = listOf(
SyntheticLibrary.newImmutableLibrary("test",
listOf(targetSources.file),
listOf(targetBinaries.file),
emptySet(),
null
)
)
}
maskAdditionalLibraryRootsProviders(additionalLibraryRootsProvider)
assertIndexableFiles(targetSource.file, targetBinary.file)
}
@Test
fun `files of IndexableSetContributor residing beneath module excluded directory must not be indexed`() {
lateinit var additionalRoots: DirectorySpec
lateinit var additionalProjectRoots: DirectorySpec
lateinit var projectFile: FileSpec
lateinit var appFile: FileSpec
projectModelRule.createJavaModule("moduleName") {
// Must not be indexed despite being provided by IndexableSetContributor.
content("contentRoot") {
excluded("excluded") {
additionalProjectRoots = dir("additionalProjectRoots") {
projectFile = file("ExcludedFile.java", "class ExcludedFile {}")
}
additionalRoots = dir("additionalRoots") {
appFile = file("ExcludedFile.java", "class ExcludedFile {}")
}
}
}
}
val contributor = object : IndexableSetContributor() {
override fun getAdditionalProjectRootsToIndex(project: Project): Set<VirtualFile> =
setOf(additionalProjectRoots.file)
override fun getAdditionalRootsToIndex(): Set<VirtualFile> =
setOf(additionalRoots.file)
}
maskIndexableSetContributors(contributor)
assertIndexableFiles(projectFile.file, appFile.file)
}
@Test
fun `nested content root's excluded file should be indexed after nested content root removal`() {
// no java plugin here, so we use plain text files
val parentContentRootFileName = "ParentContentRootFile.txt"
val nestedContentRootFileName = "NestedContentRootFile.txt"
val excludedFileName = "ExcludedFile.txt"
lateinit var parentContentRootFile: FileSpec
lateinit var nestedContentRoot: ModuleRootSpec
lateinit var nestedContentRootFile: FileSpec
lateinit var excludedDir: DirectorySpec
val module = projectModelRule.createJavaModule("moduleName") {
content("parentContentRoot") {
parentContentRootFile = file(parentContentRootFileName, "class ParentContentRootFile {}")
nestedContentRoot = content("nestedContentRoot") {
nestedContentRootFile = file(nestedContentRootFileName, "class NestedContentRootFile {}")
excludedDir = dir("excluded") {}
}
}
}
ModuleRootModificationUtil.updateExcludedFolders(module, nestedContentRoot.file, emptyList(), listOf(excludedDir.file.url))
val excludedFile = FileSpec(excludedDir.specPath / excludedFileName, "class ExcludedFile {}".toByteArray())
excludedDir.addChild(excludedFileName, excludedFile)
excludedFile.generate(excludedDir.file, excludedFileName)
val fileBasedIndex = FileBasedIndex.getInstance()
assertIndexableFiles(parentContentRootFile.file, nestedContentRootFile.file)
// Currently order of checks masks the fact,
// that called before calls to content-dependent indices on files in question,
// content-independent indices won't return those files
fileBasedIndex.assertHasDataInIndex(nestedContentRootFile.file, IdIndex.NAME, TrigramIndex.INDEX_ID)
fileBasedIndex.assertHasDataInIndex(parentContentRootFile.file, IdIndex.NAME, TrigramIndex.INDEX_ID)
fileBasedIndex.assertNoDataInIndex(excludedFile.file, IdIndex.NAME, TrigramIndex.INDEX_ID)
assertContainsElements(FilenameIndex.getAllFilesByExt(project, "txt", GlobalSearchScope.projectScope(project)),
parentContentRootFile.file, nestedContentRootFile.file)
assertContainsElements(FileTypeIndex.getFiles(PlainTextFileType.INSTANCE, GlobalSearchScope.projectScope(project)),
parentContentRootFile.file, nestedContentRootFile.file)
PsiTestUtil.removeContentEntry(module, nestedContentRoot.file)
assertIndexableFiles(parentContentRootFile.file, nestedContentRootFile.file, excludedFile.file)
fileBasedIndex.assertHasDataInIndex(nestedContentRootFile.file, IdIndex.NAME, TrigramIndex.INDEX_ID)
fileBasedIndex.assertHasDataInIndex(parentContentRootFile.file, IdIndex.NAME, TrigramIndex.INDEX_ID)
fileBasedIndex.assertHasDataInIndex(excludedFile.file, IdIndex.NAME, TrigramIndex.INDEX_ID)
assertContainsElements(FilenameIndex.getAllFilesByExt(project, "txt", GlobalSearchScope.projectScope(project)),
parentContentRootFile.file, nestedContentRootFile.file, excludedFile.file)
assertContainsElements(FileTypeIndex.getFiles(PlainTextFileType.INSTANCE, GlobalSearchScope.projectScope(project)),
parentContentRootFile.file, nestedContentRootFile.file, excludedFile.file)
}
private fun FileBasedIndex.assertHasDataInIndex(file: VirtualFile, vararg indexIds: ID<*, *>) {
for (indexId in indexIds) {
val values = getFileData(indexId, file, project).values
assertTrue("No data is found in $indexId for ${file.name}", !values.isEmpty())
}
}
private fun FileBasedIndex.assertNoDataInIndex(file: VirtualFile, vararg indexIds: ID<*, *>) {
for (indexId in indexIds) {
val values = getFileData(indexId, file, project).values
assertTrue("Some data found in " + indexId + " for " + file.name, values.isEmpty())
}
}
} | platform/platform-tests/testSrc/com/intellij/openapi/roots/impl/indexing/IndexableFilesBeneathExcludedDirectoryTest.kt | 190478978 |
// "Remove variable 'test'" "true"
fun f() {
val <caret>test: Int
} | plugins/kotlin/idea/tests/testData/quickfix/variables/unusedVariableWithoutInitializer.kt | 1747571317 |
// WITH_RUNTIME
fun test(){
listOf(1,2,3).also<caret> { it.forEach{ it + 4 } }.forEach{ it + 5 }
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/simplifyNestedEachInScope/also.kt | 1692223073 |
package com.zhou.android.kotlin
import com.zhou.android.R
import com.zhou.android.common.BaseActivity
import kotlinx.android.synthetic.main.activity_recycler_swipe.*
/**
* Created by zhou on 2020/8/13.
*/
class RecyclerSwipeActivity : BaseActivity() {
override fun setContentView() {
setContentView(R.layout.activity_recycler_swipe)
}
override fun init() {
}
override fun addListener() {
btnReset.setOnClickListener {
recyclerSwipe.reset()
}
}
} | app/src/main/java/com/zhou/android/kotlin/RecyclerSwipeActivity.kt | 3893297472 |
// 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 git4idea.test
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.invokeAndWaitIfNeeded
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.components.service
import com.intellij.openapi.editor.Document
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vcs.*
import com.intellij.openapi.vcs.Executor.cd
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vcs.changes.CommitContext
import com.intellij.openapi.vcs.changes.VcsDirtyScopeManager
import com.intellij.openapi.vcs.ex.PartialLocalLineStatusTracker
import com.intellij.openapi.vcs.impl.LineStatusTrackerManager
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.testFramework.replaceService
import com.intellij.testFramework.runAll
import com.intellij.testFramework.vcs.AbstractVcsTestCase
import com.intellij.util.ui.UIUtil
import com.intellij.vcs.log.VcsFullCommitDetails
import com.intellij.vcs.log.util.VcsLogUtil
import com.intellij.vcs.test.VcsPlatformTest
import git4idea.DialogManager
import git4idea.GitUtil
import git4idea.GitVcs
import git4idea.commands.Git
import git4idea.commands.GitHandler
import git4idea.config.GitExecutableManager
import git4idea.config.GitSaveChangesPolicy
import git4idea.config.GitVcsApplicationSettings
import git4idea.config.GitVcsSettings
import git4idea.log.GitLogProvider
import git4idea.repo.GitRepository
import git4idea.repo.GitRepositoryManager
import git4idea.test.GitPlatformTest.ConfigScope.GLOBAL
import git4idea.test.GitPlatformTest.ConfigScope.SYSTEM
import java.nio.file.Path
abstract class GitPlatformTest : VcsPlatformTest() {
protected lateinit var repositoryManager: GitRepositoryManager
protected lateinit var settings: GitVcsSettings
protected lateinit var appSettings: GitVcsApplicationSettings
protected lateinit var git: TestGitImpl
protected lateinit var vcs: GitVcs
protected lateinit var commitContext: CommitContext
protected lateinit var dialogManager: TestDialogManager
protected lateinit var vcsHelper: MockVcsHelper
protected lateinit var logProvider: GitLogProvider
private lateinit var credentialHelpers: Map<ConfigScope, List<String>>
private var globalSslVerify: Boolean? = null
@Throws(Exception::class)
override fun setUp() {
super.setUp()
dialogManager = service<DialogManager>() as TestDialogManager
vcsHelper = MockVcsHelper(myProject)
project.replaceService(AbstractVcsHelper::class.java, vcsHelper, testRootDisposable)
repositoryManager = GitUtil.getRepositoryManager(project)
git = TestGitImpl()
ApplicationManager.getApplication().replaceService(Git::class.java, git, testRootDisposable)
vcs = GitVcs.getInstance(project)
vcs.doActivate()
commitContext = CommitContext()
settings = GitVcsSettings.getInstance(project)
appSettings = GitVcsApplicationSettings.getInstance()
appSettings.setPathToGit(gitExecutable())
GitExecutableManager.getInstance().testGitExecutableVersionValid(project)
logProvider = findGitLogProvider(project)
assumeSupportedGitVersion(vcs)
addSilently()
removeSilently()
overrideDefaultSaveChangesPolicy()
credentialHelpers = if (hasRemoteGitOperation()) readAndResetCredentialHelpers() else emptyMap()
globalSslVerify = if (hasRemoteGitOperation()) readAndDisableSslVerifyGlobally() else null
}
override fun tearDown() {
runAll(
{ restoreCredentialHelpers() },
{ restoreGlobalSslVerify() },
{ if (::dialogManager.isInitialized) dialogManager.cleanup() },
{ if (::git.isInitialized) git.reset() },
{ if (::settings.isInitialized) settings.appSettings.setPathToGit(null) },
{ super.tearDown() }
)
}
override fun getDebugLogCategories(): Collection<String> {
return super.getDebugLogCategories().plus(listOf("#" + Executor::class.java.name,
"#git4idea",
"#output." + GitHandler::class.java.name))
}
protected open fun hasRemoteGitOperation() = false
protected open fun createRepository(rootDir: String): GitRepository {
return createRepository(project, rootDir)
}
protected open fun getDefaultSaveChangesPolicy() : GitSaveChangesPolicy = GitSaveChangesPolicy.SHELVE
private fun overrideDefaultSaveChangesPolicy() {
settings.saveChangesPolicy = getDefaultSaveChangesPolicy()
}
/**
* Clones the given source repository into a bare parent.git and adds the remote origin.
*/
protected fun prepareRemoteRepo(source: GitRepository, target: Path = testNioRoot.resolve("parent.git"), remoteName: String = "origin"): Path {
cd(testNioRoot)
git("clone --bare '${source.root.path}' $target")
cd(source)
git("remote add $remoteName '$target'")
return target
}
/**
* Creates 3 repositories: a bare "parent" repository, and two clones of it.
*
* One of the clones - "bro" - is outside of the project.
* Another one is inside the project, is registered as a Git root, and is represented by [GitRepository].
*
* Parent and bro are created just inside the [testRoot](myTestRoot).
* The main clone is created at [repoRoot], which is assumed to be inside the project.
*/
protected fun setupRepositories(repoRoot: String, parentName: String, broName: String): ReposTrinity {
val parentRepo = createParentRepo(parentName)
val broRepo = createBroRepo(broName, parentRepo)
val repository = createRepository(project, repoRoot)
cd(repository)
git("remote add origin $parentRepo")
git("push --set-upstream origin master:master")
cd(broRepo)
git("pull")
return ReposTrinity(repository, parentRepo, broRepo)
}
private fun createParentRepo(parentName: String): Path {
cd(testNioRoot)
git("init --bare $parentName.git")
return testNioRoot.resolve("$parentName.git")
}
protected fun createBroRepo(broName: String, parentRepo: Path): Path {
cd(testNioRoot)
git("clone ${parentRepo.fileName} $broName")
cd(broName)
setupDefaultUsername(project)
return testNioRoot.resolve(broName)
}
private fun doActionSilently(op: VcsConfiguration.StandardConfirmation) {
AbstractVcsTestCase.setStandardConfirmation(project, GitVcs.NAME, op, VcsShowConfirmationOption.Value.DO_ACTION_SILENTLY)
}
private fun addSilently() {
doActionSilently(VcsConfiguration.StandardConfirmation.ADD)
}
private fun removeSilently() {
doActionSilently(VcsConfiguration.StandardConfirmation.REMOVE)
}
protected fun installHook(gitDir: Path, hookName: String, hookContent: String) {
val hookFile = gitDir.resolve("hooks/$hookName").toFile()
FileUtil.writeToFile(hookFile, hookContent)
hookFile.setExecutable(true, false)
}
private fun readAndResetCredentialHelpers(): Map<ConfigScope, List<String>> {
val system = readAndResetCredentialHelper(SYSTEM)
val global = readAndResetCredentialHelper(GLOBAL)
return mapOf(SYSTEM to system, GLOBAL to global)
}
private fun readAndResetCredentialHelper(scope: ConfigScope): List<String> {
val values = git("config ${scope.param()} --get-all -z credential.helper", true).split("\u0000").filter { it.isNotBlank() }
git("config ${scope.param()} --unset-all credential.helper", true)
return values
}
private fun restoreCredentialHelpers() {
credentialHelpers.forEach { (scope, values) ->
values.forEach { git("config --add ${scope.param()} credential.helper ${it}", true) }
}
}
private fun readAndDisableSslVerifyGlobally(): Boolean? {
val value = git("config --global --get-all -z http.sslVerify", true)
.split("\u0000")
.singleOrNull { it.isNotBlank() }
?.toBoolean()
git("config --global http.sslVerify false", true)
return value
}
private fun restoreGlobalSslVerify() {
if (globalSslVerify != null) {
git("config --global http.sslVerify ${globalSslVerify}", true)
}
else {
git("config --global --unset http.sslVerify", true)
}
}
protected fun readDetails(hashes: List<String>): List<VcsFullCommitDetails> = VcsLogUtil.getDetails(logProvider, projectRoot, hashes)
protected fun readDetails(hash: String) = readDetails(listOf(hash)).first()
protected fun commit(changes: Collection<Change>) {
val exceptions = tryCommit(changes)
exceptions?.forEach { fail("Exception during executing the commit: " + it.message) }
}
protected fun tryCommit(changes: Collection<Change>): List<VcsException>? {
val exceptions = vcs.checkinEnvironment!!.commit(changes.toList(), "comment", commitContext, mutableSetOf())
updateChangeListManager()
return exceptions
}
protected fun `do nothing on merge`() {
vcsHelper.onMerge {}
}
protected fun `mark as resolved on merge`() {
vcsHelper.onMerge { git("add -u .") }
}
protected fun `assert merge dialog was shown`() {
assertTrue("Merge dialog was not shown", vcsHelper.mergeDialogWasShown())
}
protected fun `assert commit dialog was shown`() {
assertTrue("Commit dialog was not shown", vcsHelper.commitDialogWasShown())
}
protected fun assertNoChanges() {
changeListManager.assertNoChanges()
}
protected fun assertChanges(changes: ChangesBuilder.() -> Unit): List<Change> {
return changeListManager.assertChanges(changes)
}
protected fun assertChangesWithRefresh(changes: ChangesBuilder.() -> Unit): List<Change> {
VcsDirtyScopeManager.getInstance(project).markEverythingDirty()
changeListManager.ensureUpToDate()
return changeListManager.assertChanges(changes)
}
protected fun updateUntrackedFiles(repo: GitRepository) {
repo.untrackedFilesHolder.invalidate()
repo.untrackedFilesHolder.createWaiter().waitFor()
}
protected data class ReposTrinity(val projectRepo: GitRepository, val parent: Path, val bro: Path)
private enum class ConfigScope {
SYSTEM,
GLOBAL;
fun param() = "--${name.toLowerCase()}"
}
protected fun withPartialTracker(file: VirtualFile, newContent: String? = null, task: (Document, PartialLocalLineStatusTracker) -> Unit) {
invokeAndWaitIfNeeded {
val lstm = LineStatusTrackerManager.getInstance(project) as LineStatusTrackerManager
val document = runReadAction { FileDocumentManager.getInstance().getDocument(file)!! }
if (newContent != null) {
runWriteAction {
FileDocumentManager.getInstance().getDocument(file)!!.setText(newContent)
}
changeListManager.waitUntilRefreshed()
UIUtil.dispatchAllInvocationEvents() // ensure `fileStatusesChanged` events are fired
}
lstm.requestTrackerFor(document, this)
try {
val tracker = lstm.getLineStatusTracker(file) as PartialLocalLineStatusTracker
lstm.waitUntilBaseContentsLoaded()
task(document, tracker)
}
finally {
lstm.releaseTrackerFor(document, this)
}
}
}
}
| plugins/git4idea/tests/git4idea/test/GitPlatformTest.kt | 306042153 |
// 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.intellij.plugins.markdown.lang.psi.impl
import com.intellij.extapi.psi.ASTWrapperPsiElement
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.tree.IElementType
import com.intellij.psi.util.elementType
import com.intellij.psi.util.siblings
import org.intellij.plugins.markdown.lang.MarkdownElementTypes
import org.intellij.plugins.markdown.lang.MarkdownTokenTypes
import org.intellij.plugins.markdown.lang.psi.MarkdownPsiElement
import org.intellij.plugins.markdown.util.hasType
class MarkdownImageImpl(node: ASTNode): ASTWrapperPsiElement(node), MarkdownPsiElement {
val exclamationMark: PsiElement?
get() = firstChild
val wholeLink: PsiElement?
get() = findChildByType(MarkdownElementTypes.INLINE_LINK)
val wholeLinkText: PsiElement?
get() = wholeLink?.children?.find { it.hasType(MarkdownElementTypes.LINK_TEXT) }
val wholeLinkTitle: PsiElement?
get() = wholeLink?.children?.find { it.hasType(MarkdownElementTypes.LINK_TITLE) }
val linkDestination: MarkdownLinkDestinationImpl?
get() = wholeLink?.children?.find { it.hasType(MarkdownElementTypes.LINK_DESTINATION) } as? MarkdownLinkDestinationImpl
fun collectLinkDescriptionText(): String? {
return wholeLinkText?.let {
collectTextFromWrappedBlock(it, MarkdownTokenTypes.LBRACKET, MarkdownTokenTypes.RBRACKET)
}
}
fun collectLinkTitleText(): String? {
return wholeLinkTitle?.let {
collectTextFromWrappedBlock(it, MarkdownTokenTypes.DOUBLE_QUOTE, MarkdownTokenTypes.DOUBLE_QUOTE)
}
}
private fun collectTextFromWrappedBlock(element: PsiElement, prefix: IElementType? = null, suffix: IElementType? = null): String? {
val children = element.firstChild?.siblings(withSelf = true)?.toList() ?: return null
val left = when (children.first().elementType) {
prefix -> 1
else -> 0
}
val right = when (children.last().elementType) {
suffix -> children.size - 1
else -> children.size
}
val elements = children.subList(left, right)
val content = elements.joinToString(separator = "") { it.text }
return content.takeIf { it.isNotEmpty() }
}
companion object {
/**
* Useful for determining if some element is an actual image by it's leaf child.
*/
fun getByLeadingExclamationMark(exclamationMark: PsiElement): MarkdownImageImpl? {
if (!exclamationMark.hasType(MarkdownTokenTypes.EXCLAMATION_MARK)) {
return null
}
val image = exclamationMark.parent ?: return null
if (!image.hasType(MarkdownElementTypes.IMAGE) || image.firstChild != exclamationMark) {
return null
}
return image as? MarkdownImageImpl
}
}
}
| plugins/markdown/src/org/intellij/plugins/markdown/lang/psi/impl/MarkdownImageImpl.kt | 2589327716 |
// 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 git4idea.log
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.AppUIExecutor.onUiThread
import com.intellij.openapi.application.impl.coroutineDispatchingContext
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vcs.VcsException
import com.intellij.vcs.log.CommitId
import com.intellij.vcs.log.impl.VcsLogUiProperties
import com.intellij.vcs.log.ui.table.GraphTableModel
import com.intellij.vcs.log.ui.table.VcsLogGraphTable
import com.intellij.vcs.log.ui.table.column.VcsLogColumn
import com.intellij.vcs.log.ui.table.column.isVisible
import kotlinx.coroutines.CoroutineName
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import javax.swing.event.TableModelEvent
import javax.swing.event.TableModelListener
import kotlin.math.min
@Service(Service.Level.PROJECT)
internal class GitCommitSignatureTrackerService {
private val trackers = mutableMapOf<GraphTableModel, GitCommitSignatureTracker>()
fun getCommitSignature(model: GraphTableModel, row: Int): GitCommitSignature? =
trackers[model]?.getCommitSignature(row)
fun ensureTracking(table: VcsLogGraphTable, column: GitCommitSignatureLogColumn) {
if (table.model in trackers) return
val tracker = GitCommitSignatureTracker(table, column)
trackers[table.model] = tracker
Disposer.register(tracker) { trackers -= table.model }
Disposer.register(table, tracker)
tracker.track()
}
companion object {
fun getInstance(project: Project): GitCommitSignatureTrackerService = project.service()
}
}
private val LOG = logger<GitCommitSignatureTracker>()
private const val TRACK_SIZE = 50
private class GitCommitSignatureTracker(
private val table: VcsLogGraphTable,
private val column: GitCommitSignatureLogColumn
) : Disposable {
private val project: Project get() = table.logData.project
private val model: GraphTableModel get() = table.model
private val scope = CoroutineScope(onUiThread().coroutineDispatchingContext())
.also { Disposer.register(this) { it.cancel() } }
private val commitSignatures = mutableMapOf<CommitId, GitCommitSignature>()
fun getCommitSignature(row: Int): GitCommitSignature? {
val commitId = model.getCommitId(row) ?: return null
return commitSignatures[commitId]
}
override fun dispose() = Unit
fun track() {
scope.launch(CoroutineName("Git Commit Signature Tracker - ${table.id}")) {
val trackedEvents =
combine(table.modelChangedFlow(), table.columnVisibilityFlow(column)) { _, isColumnVisible -> isColumnVisible }
trackedEvents.collectLatest { isColumnVisible ->
if (!isColumnVisible) return@collectLatest
update()
}
}
}
private suspend fun update() =
try {
doUpdate()
}
catch (e: VcsException) {
LOG.warn("Failed to load commit signatures", e)
}
@Throws(VcsException::class)
private suspend fun doUpdate() {
val size = min(TRACK_SIZE, table.rowCount)
val rows = IntArray(size) { it }
val rootCommits = model.getCommitIds(rows).groupBy { it.root }
for ((root, commits) in rootCommits) {
val signatures = loadCommitSignatures(project, root, commits.map { it.hash })
commitSignatures.keys.removeIf { it.root == root }
commitSignatures += signatures.mapKeys { (hash, _) -> CommitId(hash, root) }
fireColumnDataChanged()
}
}
private fun fireColumnDataChanged() = table.repaint()
}
@Suppress("EXPERIMENTAL_API_USAGE")
private fun VcsLogGraphTable.modelChangedFlow(): Flow<Unit> =
callbackFlow {
val emit = { offer(Unit) }
val listener = TableModelListener {
if (it.column == TableModelEvent.ALL_COLUMNS) emit()
}
emit() // initial value
model.addTableModelListener(listener)
awaitClose { model.removeTableModelListener(listener) }
}
@Suppress("EXPERIMENTAL_API_USAGE")
private fun VcsLogGraphTable.columnVisibilityFlow(column: VcsLogColumn<*>): Flow<Boolean> {
val flow = callbackFlow {
val emit = { offer(column.isVisible(properties)) }
val listener = object : VcsLogUiProperties.PropertiesChangeListener {
override fun <T> onPropertyChanged(property: VcsLogUiProperties.VcsLogUiProperty<T>) {
emit()
}
}
emit() // initial value
properties.addChangeListener(listener)
awaitClose { properties.removeChangeListener(listener) }
}
return flow.distinctUntilChanged()
} | plugins/git4idea/src/git4idea/log/GitCommitSignatureTrackerService.kt | 3122519456 |
/*
* Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.debugger.evaluate.compilation
import org.jetbrains.kotlin.backend.jvm.FacadeClassSourceShimForFragmentCompilation
import org.jetbrains.kotlin.backend.jvm.JvmGeneratorExtensionsImpl
import org.jetbrains.kotlin.backend.jvm.JvmIrCodegenFactory
import org.jetbrains.kotlin.backend.jvm.serialization.JvmIdSignatureDescriptor
import org.jetbrains.kotlin.codegen.CodegenFactory
import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.config.JVMConfigurationKeys
import org.jetbrains.kotlin.config.languageVersionSettings
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.impl.LocalVariableDescriptor
import org.jetbrains.kotlin.idea.MainFunctionDetector
import org.jetbrains.kotlin.idea.debugger.evaluate.DebuggerFieldPropertyDescriptor
import org.jetbrains.kotlin.idea.debugger.base.util.evaluate.ExecutionContext
import org.jetbrains.kotlin.idea.debugger.evaluate.classLoading.ClassToLoad
import org.jetbrains.kotlin.idea.debugger.evaluate.classLoading.GENERATED_CLASS_NAME
import org.jetbrains.kotlin.idea.debugger.evaluate.classLoading.isEvaluationEntryPoint
import org.jetbrains.kotlin.ir.ObsoleteDescriptorBasedAPI
import org.jetbrains.kotlin.ir.backend.jvm.serialization.JvmDescriptorMangler
import org.jetbrains.kotlin.ir.declarations.IrSimpleFunction
import org.jetbrains.kotlin.ir.declarations.impl.IrFactoryImpl
import org.jetbrains.kotlin.ir.util.NameProvider
import org.jetbrains.kotlin.load.java.descriptors.JavaPropertyDescriptor
import org.jetbrains.kotlin.load.kotlin.toSourceElement
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.KtCodeFragment
import org.jetbrains.kotlin.psi2ir.generators.fragments.EvaluatorFragmentInfo
import org.jetbrains.kotlin.psi2ir.generators.fragments.EvaluatorFragmentParameterInfo
import org.jetbrains.kotlin.psi2ir.generators.fragments.FragmentCompilerSymbolTableDecorator
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.source.PsiSourceFile
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedContainerSource
import org.jetbrains.org.objectweb.asm.*
import org.jetbrains.org.objectweb.asm.ClassReader.SKIP_CODE
class IRFragmentCompilerCodegen : FragmentCompilerCodegen {
override fun initCodegen(
classDescriptor: ClassDescriptor,
methodDescriptor: FunctionDescriptor,
parameterInfo: CodeFragmentParameterInfo
) {
// NO-OP
}
override fun cleanupCodegen() {
// NO-OP
}
override fun configureCompiler(compilerConfiguration: CompilerConfiguration) {
// TODO: Do not understand the implications of DO_NOT_CLEAR_BINDING_CONTEXT,
// but enforced by assertions in JvmIrCodegen
compilerConfiguration.put(JVMConfigurationKeys.DO_NOT_CLEAR_BINDING_CONTEXT, true)
compilerConfiguration.put(JVMConfigurationKeys.IR, true)
}
override fun configureGenerationState(
builder: GenerationState.Builder,
bindingContext: BindingContext,
compilerConfiguration: CompilerConfiguration,
classDescriptor: ClassDescriptor,
methodDescriptor: FunctionDescriptor,
parameterInfo: CodeFragmentParameterInfo
) {
builder.isIrBackend(true)
builder.codegenFactory(
codegenFactory(
bindingContext,
compilerConfiguration,
classDescriptor,
methodDescriptor,
parameterInfo
)
)
}
private fun codegenFactory(
bindingContext: BindingContext,
compilerConfiguration: CompilerConfiguration,
classDescriptor: ClassDescriptor,
methodDescriptor: FunctionDescriptor,
parameterInfo: CodeFragmentParameterInfo
): CodegenFactory {
val mangler = JvmDescriptorMangler(MainFunctionDetector(bindingContext, compilerConfiguration.languageVersionSettings))
val evaluatorFragmentInfo = EvaluatorFragmentInfo(
classDescriptor,
methodDescriptor,
parameterInfo.parameters.map { EvaluatorFragmentParameterInfo(it.targetDescriptor, it.isLValue) }
)
return JvmIrCodegenFactory(
configuration = compilerConfiguration,
phaseConfig = null,
externalMangler = mangler,
externalSymbolTable = FragmentCompilerSymbolTableDecorator(
JvmIdSignatureDescriptor(mangler),
IrFactoryImpl,
evaluatorFragmentInfo,
NameProvider.DEFAULT,
),
jvmGeneratorExtensions = object : JvmGeneratorExtensionsImpl(compilerConfiguration) {
// Top-level declarations in the project being debugged is served to the compiler as
// PSI, not as class files. PSI2IR generate these as "external declarations" and
// here we provide a shim from the PSI structures serving the names of facade classes
// for top level declarations (as the facade classes do not exist in the PSI but are
// created and _named_ during compilation).
override fun getContainerSource(descriptor: DeclarationDescriptor): DeserializedContainerSource? {
val psiSourceFile =
descriptor.toSourceElement.containingFile as? PsiSourceFile ?: return super.getContainerSource(
descriptor
)
return FacadeClassSourceShimForFragmentCompilation(psiSourceFile)
}
@OptIn(ObsoleteDescriptorBasedAPI::class)
override fun isAccessorWithExplicitImplementation(accessor: IrSimpleFunction): Boolean {
return (accessor.descriptor as? PropertyAccessorDescriptor)?.hasBody() == true
}
override fun remapDebuggerFieldPropertyDescriptor(propertyDescriptor: PropertyDescriptor): PropertyDescriptor {
return when (propertyDescriptor) {
is DebuggerFieldPropertyDescriptor -> {
val fieldDescriptor = JavaPropertyDescriptor.create(
propertyDescriptor.containingDeclaration,
propertyDescriptor.annotations,
propertyDescriptor.modality,
propertyDescriptor.visibility,
propertyDescriptor.isVar,
Name.identifier(propertyDescriptor.fieldName.removeSuffix("_field")),
propertyDescriptor.source,
/*isStaticFinal= */ false
)
fieldDescriptor.setType(
propertyDescriptor.type,
propertyDescriptor.typeParameters,
propertyDescriptor.dispatchReceiverParameter,
propertyDescriptor.extensionReceiverParameter,
propertyDescriptor.contextReceiverParameters
)
fieldDescriptor
}
else ->
propertyDescriptor
}
}
},
evaluatorFragmentInfoForPsi2Ir = evaluatorFragmentInfo,
shouldStubAndNotLinkUnboundSymbols = true
)
}
override fun computeFragmentParameters(
executionContext: ExecutionContext,
codeFragment: KtCodeFragment,
bindingContext: BindingContext
): CodeFragmentParameterInfo {
return CodeFragmentParameterAnalyzer(executionContext, codeFragment, bindingContext).analyze().let { analysis ->
// Local functions do not exist as run-time values on the IR backend: they are static functions.
CodeFragmentParameterInfo(
analysis.parameters.filter { it.kind != CodeFragmentParameter.Kind.LOCAL_FUNCTION },
analysis.crossingBounds
)
}
}
override fun extractResult(
methodDescriptor: FunctionDescriptor,
parameterInfo: CodeFragmentParameterInfo,
generationState: GenerationState
): CodeFragmentCompiler.CompilationResult {
val classes: List<ClassToLoad> = collectGeneratedClasses(generationState)
val fragmentClass = classes.single { it.className == GENERATED_CLASS_NAME }
val methodSignature = getMethodSignature(fragmentClass)
val newCaptures: List<CodeFragmentParameter.Smart> = generationState.newFragmentCaptureParameters.map { (name, type, target) ->
val kind = when {
name == "<this>" -> CodeFragmentParameter.Kind.DISPATCH_RECEIVER
target is LocalVariableDescriptor && target.isDelegated -> CodeFragmentParameter.Kind.DELEGATED
else -> CodeFragmentParameter.Kind.ORDINARY
}
val dumb = CodeFragmentParameter.Dumb(kind, name)
CodeFragmentParameter.Smart(dumb, type, target)
}
val processedOldCaptures: List<CodeFragmentParameter.Smart> = parameterInfo.parameters.map {
val target = it.targetDescriptor
val (newName, newDebugName) = when {
target is LocalVariableDescriptor && target.isDelegated -> {
val mangledName = it.name + "\$delegate"
mangledName to mangledName
}
it.name == "" ->
it.name to it.debugString
else ->
it.name to it.name
}
val dumb = CodeFragmentParameter.Dumb(it.dumb.kind, newName, newDebugName)
CodeFragmentParameter.Smart(dumb, it.targetType, it.targetDescriptor)
}
val newParameterInfo =
CodeFragmentParameterInfo(
processedOldCaptures + newCaptures,
parameterInfo.crossingBounds
)
return CodeFragmentCompiler.CompilationResult(classes, newParameterInfo, mapOf(), methodSignature)
}
private fun collectGeneratedClasses(generationState: GenerationState): List<ClassToLoad> {
return generationState.factory.asList()
.filterCodeFragmentClassFiles()
.map {
ClassToLoad(it.internalClassName, it.relativePath, it.asByteArray())
}
}
private fun getMethodSignature(
fragmentClass: ClassToLoad,
): CompiledCodeFragmentData.MethodSignature {
val parameters: MutableList<Type> = mutableListOf()
var returnType: Type? = null
ClassReader(fragmentClass.bytes).accept(object : ClassVisitor(Opcodes.ASM7) {
override fun visitMethod(
access: Int,
name: String?,
descriptor: String?,
signature: String?,
exceptions: Array<out String>?
): MethodVisitor? {
if (name != null && isEvaluationEntryPoint(name)) {
Type.getArgumentTypes(descriptor).forEach { parameters.add(it) }
returnType = Type.getReturnType(descriptor)
}
return null
}
}, SKIP_CODE)
return CompiledCodeFragmentData.MethodSignature(parameters, returnType!!)
}
}
| plugins/kotlin/jvm-debugger/evaluation/src/org/jetbrains/kotlin/idea/debugger/evaluate/compilation/IRFragmentCompilerCodegen.kt | 871651193 |
/*
* Copyright (C) 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 com.example.lunchtray
import androidx.fragment.app.testing.launchFragmentInContainer
import androidx.navigation.Navigation
import androidx.navigation.testing.TestNavHostController
import androidx.test.core.app.ApplicationProvider
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import com.example.lunchtray.ui.order.*
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
/**
* Tests for all navigation flows
*/
@RunWith(AndroidJUnit4::class)
@LargeTest
class NavigationTests : BaseTest() {
/**
* Test navigation from [StartOrderFragment] to [EntreeMenuFragment]
*/
@Test
fun `navigate_to_entree_menu_from_start_order`() {
// Init nav controller
val navController = TestNavHostController(
ApplicationProvider.getApplicationContext())
// Launch StartOrderFragment
val startOrderScenario =
launchFragmentInContainer<StartOrderFragment>(themeResId = R.style.Theme_LunchTray)
// Configure nav controller
startOrderScenario.onFragment{ fragment ->
navController.setGraph(R.navigation.mobile_navigation)
Navigation.setViewNavController(fragment.requireView(), navController)
}
// Click start order
onView(withId(R.id.start_order_btn)).perform(click())
// Check destination is correct
assertEquals(navController.currentDestination?.id, R.id.entreeMenuFragment)
}
/**
* Test navigation from [EntreeMenuFragment] to [StartOrderFragment]
*/
@Test
fun `navigate_to_start_order_from_entree_menu`() {
// Init nav controller
val navController = TestNavHostController(
ApplicationProvider.getApplicationContext())
// Launch EntreeMenuFragment
val entreeMenuScenario =
launchFragmentInContainer<EntreeMenuFragment>(themeResId = R.style.Theme_LunchTray)
// Configure nav controller
entreeMenuScenario.onFragment{ fragment ->
navController.setGraph(R.navigation.mobile_navigation)
// Destination defaults to the home fragment, we have to explicitly set the current
// destination
navController.setCurrentDestination(destId = R.id.entreeMenuFragment)
Navigation.setViewNavController(fragment.requireView(), navController)
}
// Click the cancel button
onView(withId(R.id.cancel_button)).perform(click())
// Check that the destination is correct
assertEquals(navController.currentDestination?.id, R.id.startOrder)
}
/**
* Test navigation from [EntreeMenuFragment] to [SideMenuFragment]
*/
@Test
fun `navigate_to_side_menu_from_entree_menu`() {
// Init nav controller
val navController = TestNavHostController(
ApplicationProvider.getApplicationContext())
// Launch the EntreeMenuFragment
val entreeMenuScenario =
launchFragmentInContainer<EntreeMenuFragment>(themeResId = R.style.Theme_LunchTray)
// Configure nav controller
entreeMenuScenario.onFragment{ fragment ->
navController.setGraph(R.navigation.mobile_navigation)
// Destination defaults to the home fragment, we have to explicitly set the current
// destination
navController.setCurrentDestination(destId = R.id.entreeMenuFragment)
Navigation.setViewNavController(fragment.requireView(), navController)
}
// Click the next button
onView(withId(R.id.next_button)).perform(click())
// Check that the destination is correct
assertEquals(navController.currentDestination?.id, R.id.sideMenuFragment)
}
/**
* Test navigation from [SideMenuFragment] to [StartOrderFragment]
*/
@Test
fun `navigate_to_start_order_from_side_menu`() {
val navController = TestNavHostController(
ApplicationProvider.getApplicationContext())
val sideMenuScenario =
launchFragmentInContainer<SideMenuFragment>(themeResId = R.style.Theme_LunchTray)
sideMenuScenario.onFragment{ fragment ->
navController.setGraph(R.navigation.mobile_navigation)
navController.setCurrentDestination(destId = R.id.sideMenuFragment)
Navigation.setViewNavController(fragment.requireView(), navController)
}
onView(withId(R.id.cancel_button)).perform(click())
assertEquals(navController.currentDestination?.id, R.id.startOrder)
}
/**
* Test navigation from [SideMenuFragment] to [AccompanimentMenuFragment]
*/
@Test
fun `navigate_to_accompaniment_menu_from_side_menu`() {
val navController = TestNavHostController(
ApplicationProvider.getApplicationContext())
val sideMenuScenario =
launchFragmentInContainer<SideMenuFragment>(themeResId = R.style.Theme_LunchTray)
sideMenuScenario.onFragment{ fragment ->
navController.setGraph(R.navigation.mobile_navigation)
navController.setCurrentDestination(destId = R.id.sideMenuFragment)
Navigation.setViewNavController(fragment.requireView(), navController)
}
onView(withId(R.id.next_button)).perform(click())
assertEquals(navController.currentDestination?.id, R.id.accompanimentMenuFragment)
}
/**
* Test navigation from [AccompanimentMenuFragment] to [StartOrderFragment]
*/
@Test
fun `navigate_to_start_order_from_accompaniment_menu`() {
val navController = TestNavHostController(
ApplicationProvider.getApplicationContext())
val accompanimentMenuScenario =
launchFragmentInContainer<AccompanimentMenuFragment>(
themeResId = R.style.Theme_LunchTray)
accompanimentMenuScenario.onFragment{ fragment ->
navController.setGraph(R.navigation.mobile_navigation)
navController.setCurrentDestination(destId = R.id.accompanimentMenuFragment)
Navigation.setViewNavController(fragment.requireView(), navController)
}
onView(withId(R.id.cancel_button)).perform(click())
assertEquals(navController.currentDestination?.id, R.id.startOrder)
}
/**
* Test navigation from [AccompanimentMenuFragment] to [CheckoutFragment]
*/
@Test
fun `navigate_to_checkout_from_accompaniment_menu`() {
val navController = TestNavHostController(
ApplicationProvider.getApplicationContext())
val accompanimentMenuScenario =
launchFragmentInContainer<AccompanimentMenuFragment>(
themeResId = R.style.Theme_LunchTray)
accompanimentMenuScenario.onFragment{ fragment ->
navController.setGraph(R.navigation.mobile_navigation)
navController.setCurrentDestination(destId = R.id.accompanimentMenuFragment)
Navigation.setViewNavController(fragment.requireView(), navController)
}
onView(withId(R.id.next_button)).perform(click())
assertEquals(navController.currentDestination?.id, R.id.checkoutFragment)
}
/**
* Test navigation from [CheckoutFragment] to [StartOrderFragment]
*/
@Test
fun `navigate_to_start_order_from_checkout`() {
val navController = TestNavHostController(
ApplicationProvider.getApplicationContext())
val checkoutScenario =
launchFragmentInContainer<CheckoutFragment>(themeResId = R.style.Theme_LunchTray)
checkoutScenario.onFragment{ fragment ->
navController.setGraph(R.navigation.mobile_navigation)
navController.setCurrentDestination(destId = R.id.checkoutFragment)
Navigation.setViewNavController(fragment.requireView(), navController)
}
onView(withId(R.id.cancel_button)).perform(click())
assertEquals(navController.currentDestination?.id, R.id.startOrder)
}
/**
* Test Navigation from [CheckoutFragment] to [StartOrderFragment]
*/
@Test
fun `navigate_to_start_order_from_checkout_via_submit`() {
val navController = TestNavHostController(
ApplicationProvider.getApplicationContext())
val checkoutScenario =
launchFragmentInContainer<CheckoutFragment>(themeResId = R.style.Theme_LunchTray)
checkoutScenario.onFragment{ fragment ->
navController.setGraph(R.navigation.mobile_navigation)
navController.setCurrentDestination(destId = R.id.checkoutFragment)
Navigation.setViewNavController(fragment.requireView(), navController)
}
onView(withId(R.id.submit_button)).perform(click())
assertEquals(navController.currentDestination?.id, R.id.startOrder)
}
}
| app/src/androidTest/java/com/example/lunchtray/NavigationTests.kt | 2414981805 |
// "Create class 'Foo'" "true"
class A<T>(val n: T) {
fun test() = this.<caret>Foo(2, "2")
} | plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createClass/callExpression/callWithThisReceiverInClass.kt | 4182456288 |
// 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.collaboration.auth.ui.login
import com.intellij.collaboration.async.DisposingMainScope
import com.intellij.collaboration.messages.CollaborationToolsBundle
import com.intellij.collaboration.ui.ExceptionUtil
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.asContextElement
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.wm.IdeFocusManager
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import kotlinx.coroutines.plus
import java.awt.Component
import javax.swing.JComponent
class TokenLoginDialog(
project: Project?, parent: Component?,
private val model: LoginModel,
@NlsContexts.DialogTitle title: String = CollaborationToolsBundle.message("login.dialog.title"),
private val centerPanelSupplier: () -> DialogPanel
) : DialogWrapper(project, parent, false, IdeModalityType.PROJECT) {
private val uiScope = DisposingMainScope(disposable) + ModalityState.stateForComponent(rootPane).asContextElement()
init {
setOKButtonText(CollaborationToolsBundle.message("login.button"))
setTitle(title)
init()
uiScope.launch {
model.loginState.collectLatest { state ->
isOKActionEnabled = state !is LoginModel.LoginState.Connecting
if (state is LoginModel.LoginState.Failed) startTrackingValidation()
if (state is LoginModel.LoginState.Connected) close(OK_EXIT_CODE)
}
}
}
override fun createCenterPanel(): JComponent = centerPanelSupplier()
override fun doOKAction() {
applyFields()
if (!isOKActionEnabled) return
uiScope.launch {
model.login()
}
}
override fun doValidate(): ValidationInfo? {
val loginState = model.loginState.value
if (loginState is LoginModel.LoginState.Failed) {
val errorMessage = ExceptionUtil.getPresentableMessage(loginState.error)
return ValidationInfo(errorMessage).withOKEnabled()
}
return null
}
override fun getPreferredFocusedComponent(): JComponent? {
val focusManager = IdeFocusManager.findInstanceByComponent(contentPanel)
return focusManager.getFocusTargetFor(contentPanel)
}
} | platform/collaboration-tools/src/com/intellij/collaboration/auth/ui/login/TokenLoginDialog.kt | 3957493096 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.editor.Editor
import org.jetbrains.kotlin.builtins.isSuspendFunctionType
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
import org.jetbrains.kotlin.descriptors.impl.AnonymousFunctionDescriptor
import org.jetbrains.kotlin.descriptors.impl.ValueParameterDescriptorImpl
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.core.moveInsideParentheses
import org.jetbrains.kotlin.idea.core.replaced
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.BranchedFoldingUtils
import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.idea.util.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.quoteIfNeeded
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.getTargetFunctionDescriptor
import org.jetbrains.kotlin.resolve.calls.callUtil.getParameterForArgument
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.ErrorType
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeConstructor
import org.jetbrains.kotlin.types.isFlexible
import org.jetbrains.kotlin.types.typeUtil.isTypeParameter
import org.jetbrains.kotlin.types.typeUtil.isUnit
import org.jetbrains.kotlin.types.typeUtil.makeNotNullable
class LambdaToAnonymousFunctionIntention : SelfTargetingIntention<KtLambdaExpression>(
KtLambdaExpression::class.java,
KotlinBundle.lazyMessage("convert.to.anonymous.function"),
KotlinBundle.lazyMessage("convert.lambda.expression.to.anonymous.function")
), LowPriorityAction {
override fun isApplicableTo(element: KtLambdaExpression, caretOffset: Int): Boolean {
val argument = element.getStrictParentOfType<KtValueArgument>()
val call = argument?.getStrictParentOfType<KtCallElement>()
if (call?.getStrictParentOfType<KtFunction>()?.hasModifier(KtTokens.INLINE_KEYWORD) == true) return false
val context = element.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL)
if (call?.getResolvedCall(context)?.getParameterForArgument(argument)?.type?.isSuspendFunctionType == true) return false
val descriptor = context[
BindingContext.DECLARATION_TO_DESCRIPTOR,
element.functionLiteral,
] as? AnonymousFunctionDescriptor ?: return false
if (descriptor.valueParameters.any { it.isDestructuring() || it.type is ErrorType }) return false
val lastElement = element.functionLiteral.arrow ?: element.functionLiteral.lBrace
return caretOffset <= lastElement.endOffset
}
override fun applyTo(element: KtLambdaExpression, editor: Editor?) {
val functionDescriptor = element.functionLiteral.descriptor as? AnonymousFunctionDescriptor ?: return
val resultingFunction = convertLambdaToFunction(element, functionDescriptor) ?: return
val argument = when (val parent = resultingFunction.parent) {
is KtLambdaArgument -> parent
is KtLabeledExpression -> parent.replace(resultingFunction).parent as? KtLambdaArgument
else -> null
} ?: return
argument.moveInsideParentheses(argument.analyze(BodyResolveMode.PARTIAL))
}
private fun ValueParameterDescriptor.isDestructuring() = this is ValueParameterDescriptorImpl.WithDestructuringDeclaration
companion object {
fun convertLambdaToFunction(
lambda: KtLambdaExpression,
functionDescriptor: FunctionDescriptor,
functionName: String = "",
functionParameterName: (ValueParameterDescriptor, Int) -> String = { parameter, _ ->
val parameterName = parameter.name
if (parameterName.isSpecial) "_" else parameterName.asString().quoteIfNeeded()
},
typeParameters: Map<TypeConstructor, KotlinType> = emptyMap(),
replaceElement: (KtNamedFunction) -> KtExpression = { lambda.replaced(it) }
): KtExpression? {
val typeSourceCode = IdeDescriptorRenderers.SOURCE_CODE_TYPES
val functionLiteral = lambda.functionLiteral
val bodyExpression = functionLiteral.bodyExpression ?: return null
val context = bodyExpression.analyze(BodyResolveMode.PARTIAL)
val functionLiteralDescriptor by lazy { functionLiteral.descriptor }
bodyExpression.collectDescendantsOfType<KtReturnExpression>().forEach {
val targetDescriptor = it.getTargetFunctionDescriptor(context)
if (targetDescriptor == functionDescriptor || targetDescriptor == functionLiteralDescriptor) it.labeledExpression?.delete()
}
val psiFactory = KtPsiFactory(lambda)
val function = psiFactory.createFunction(
KtPsiFactory.CallableBuilder(KtPsiFactory.CallableBuilder.Target.FUNCTION).apply {
typeParams()
functionDescriptor.extensionReceiverParameter?.type?.let {
receiver(typeSourceCode.renderType(it))
}
name(functionName)
for ((index, parameter) in functionDescriptor.valueParameters.withIndex()) {
val type = parameter.type.let { if (it.isFlexible()) it.makeNotNullable() else it }
val renderType = typeSourceCode.renderType(
getTypeFromParameters(type, typeParameters)
)
val parameterName = functionParameterName(parameter, index)
param(parameterName, renderType)
}
functionDescriptor.returnType?.takeIf { !it.isUnit() }?.let {
val lastStatement = bodyExpression.statements.lastOrNull()
if (lastStatement != null && lastStatement !is KtReturnExpression) {
val foldableReturns = BranchedFoldingUtils.getFoldableReturns(lastStatement)
if (foldableReturns == null || foldableReturns.isEmpty()) {
lastStatement.replace(psiFactory.createExpressionByPattern("return $0", lastStatement))
}
}
val renderType = typeSourceCode.renderType(
getTypeFromParameters(it, typeParameters)
)
returnType(renderType)
} ?: noReturnType()
blockBody(" " + bodyExpression.text)
}.asString()
)
val result = wrapInParenthesisIfNeeded(replaceElement(function), psiFactory)
ShortenReferences.DEFAULT.process(result)
return result
}
private fun getTypeFromParameters(
type: KotlinType,
typeParameters: Map<TypeConstructor, KotlinType>
): KotlinType {
if (type.isTypeParameter())
return typeParameters[type.constructor] ?: type
return type
}
private fun wrapInParenthesisIfNeeded(expression: KtExpression, psiFactory: KtPsiFactory): KtExpression {
val parent = expression.parent ?: return expression
val grandParent = parent.parent ?: return expression
if (parent is KtCallExpression && grandParent !is KtParenthesizedExpression && grandParent !is KtDeclaration) {
return expression.replaced(psiFactory.createExpressionByPattern("($0)", expression))
}
return expression
}
}
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/LambdaToAnonymousFunctionIntention.kt | 3293685378 |
// OUT_OF_CODE_BLOCK: TRUE
// ERROR: Unresolved reference: foao
class A {
fun foo(): Int = 12
}
class B(val a: A) {
val prop1 get() = a.fo<caret>o()
}
// TODO
// SKIP_ANALYZE_CHECK | plugins/kotlin/idea/tests/testData/codeInsight/outOfBlock/InPropertyAccessorWithInferenceInClass.kt | 271027041 |
// "Create class 'Foo'" "true"
// ERROR: Unresolved reference: Foo
class A<T> internal constructor(val b: B<T>) {
internal fun test() = b.<caret>Foo<Int, String>(2, "2")
} | plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createClass/callExpression/typeArguments/javaClassMemberInner.before.Main.kt | 1229967275 |
package com.jetbrains.packagesearch.intellij.plugin.util
import com.intellij.ui.content.ContentManager
import com.intellij.ui.content.ContentManagerEvent
import com.intellij.ui.content.ContentManagerListener
@Suppress("FunctionName")
internal fun SelectionChangedListener(action: (ContentManagerEvent) -> Unit) = object : ContentManagerListener {
override fun selectionChanged(event: ContentManagerEvent) = action(event)
}
internal fun ContentManager.addSelectionChangedListener(action: (ContentManagerEvent) -> Unit) =
SelectionChangedListener(action).also { addContentManagerListener(it) }
| plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/util/GenericUtils.kt | 548836372 |
import java.io.ByteArrayInputStream
import java.io.IOException
class C {
@Throws(IOException::class)
fun foo() {
ByteArrayInputStream(ByteArray(10)).use { stream -> println(stream.read()) }
}
} | plugins/kotlin/j2k/new/tests/testData/newJ2k/tryWithResource/Simple.kt | 1374132014 |
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.updateSettings.impl
import com.intellij.openapi.updateSettings.UpdateStrategyCustomization
import com.intellij.openapi.util.BuildNumber
import com.intellij.util.containers.MultiMap
import com.intellij.util.graph.InboundSemiGraph
import com.intellij.util.graph.impl.ShortestPathFinder
import org.jetbrains.annotations.ApiStatus
class UpdateStrategy @JvmOverloads constructor(
private val currentBuild: BuildNumber,
private val product: Product? = null,
private val settings: UpdateSettings = UpdateSettings.getInstance(),
private val customization: UpdateStrategyCustomization = UpdateStrategyCustomization.getInstance(),
) {
@Deprecated("Please use `UpdateStrategy(BuildNumber, Product, UpdateSettings)` instead")
@ApiStatus.ScheduledForRemoval(inVersion = "2022.2")
@Suppress("DEPRECATION")
constructor(
currentBuild: BuildNumber,
updates: UpdatesInfo,
settings: UpdateSettings = UpdateSettings.getInstance(),
) : this(
currentBuild,
updates.product,
settings,
)
fun checkForUpdates(): PlatformUpdates {
if (product == null || product.channels.isEmpty()) {
return PlatformUpdates.Empty
}
val selectedChannel = settings.selectedChannelStatus
val ignoredBuilds = settings.ignoredBuildNumbers.toSet()
return product.channels
.asSequence()
.filter { ch -> customization.isChannelApplicableForUpdates(ch, selectedChannel) } // filters out inapplicable channels
.sortedBy { ch -> ch.status } // reorders channels (EAPs first)
.flatMap { ch -> ch.builds.asSequence().map { build -> build to ch } } // maps into a sequence of <build, channel> pairs
.filter { p -> isApplicable(p.first, ignoredBuilds) } // filters out inapplicable builds
.maxWithOrNull(Comparator { p1, p2 -> compareBuilds(p1.first.number, p2.first.number) }) // a build with the max number, preferring the same baseline
?.let { (newBuild, channel) ->
PlatformUpdates.Loaded(
newBuild,
channel,
patches(newBuild, product, currentBuild),
)
} ?: PlatformUpdates.Empty
}
private fun isApplicable(candidate: BuildInfo, ignoredBuilds: Set<String>): Boolean =
customization.isNewerVersion(candidate.number, currentBuild) &&
candidate.number.asStringWithoutProductCode() !in ignoredBuilds &&
candidate.target?.inRange(currentBuild) ?: true
private fun compareBuilds(n1: BuildNumber, n2: BuildNumber): Int {
val preferSameMajorVersion = customization.haveSameMajorVersion(currentBuild, n1).compareTo(customization.haveSameMajorVersion(currentBuild, n2))
return if (preferSameMajorVersion != 0) preferSameMajorVersion else n1.compareTo(n2)
}
private fun patches(newBuild: BuildInfo, product: Product, from: BuildNumber): UpdateChain? {
val single = newBuild.patches.find { it.isAvailable && it.fromBuild.compareTo(from) == 0 }
if (single != null) {
return UpdateChain(listOf(from, newBuild.number), single.size)
}
val selectedChannel = settings.selectedChannelStatus
val upgrades = MultiMap<BuildNumber, BuildNumber>()
val sizes = mutableMapOf<Pair<BuildNumber, BuildNumber>, Int>()
val number = Regex("\\d+")
product.channels
.filter { ch -> customization.canBeUsedForIntermediatePatches(ch, selectedChannel) }
.forEach { channel ->
channel.builds.forEach { build ->
val toBuild = build.number.withoutProductCode()
build.patches.forEach { patch ->
if (patch.isAvailable) {
val fromBuild = patch.fromBuild.withoutProductCode()
upgrades.putValue(toBuild, fromBuild)
if (patch.size != null) {
val maxSize = number.findAll(patch.size).map { it.value.toIntOrNull() }.filterNotNull().maxOrNull()
if (maxSize != null) sizes += (fromBuild to toBuild) to maxSize
}
}
}
}
}
val graph = object : InboundSemiGraph<BuildNumber> {
override fun getNodes() = upgrades.keySet() + upgrades.values()
override fun getIn(n: BuildNumber) = upgrades[n].iterator()
}
val path = ShortestPathFinder(graph).findPath(from.withoutProductCode(), newBuild.number.withoutProductCode())
if (path == null || path.size <= 2) return null
var total = 0
for (i in 1 until path.size) {
val size = sizes[path[i - 1] to path[i]]
if (size == null) {
total = -1
break
}
total += size
}
return UpdateChain(path, if (total > 0) total.toString() else null)
}
}
| platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateStrategy.kt | 4244325619 |
// "Import" "true"
package p
class A {
companion object
}
class B {
companion object
}
open class P {
fun A.Companion.foo() {}
}
open class Q {
fun B.Companion.foo() {}
}
object PObject : P()
object QObject : Q()
fun usage() {
B.<caret>foo()
}
| plugins/kotlin/idea/tests/testData/quickfix/autoImports/callablesDeclaredInClasses/companionObjectExtensionFunctionTwoCandidatesB.kt | 3082082421 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.lang.documentation
import com.intellij.openapi.progress.withJob
import com.intellij.util.AsyncSupplier
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.VisibleForTesting
import java.util.function.Supplier
@VisibleForTesting
data class DocumentationData internal constructor(
val html: @Nls String,
val anchor: String?,
val externalUrl: String?,
val linkUrls: List<String>,
val imageResolver: DocumentationImageResolver?
) : DocumentationResult
internal class AsyncDocumentation(
val supplier: AsyncSupplier<DocumentationResult?>
) : DocumentationResult
internal class ResolvedTarget(
val target: DocumentationTarget,
) : LinkResult
internal class UpdateContent(
val updater: LinkResult.ContentUpdater,
) : LinkResult
internal fun <X> Supplier<X>.asAsyncSupplier(): AsyncSupplier<X> = {
withContext(Dispatchers.IO) {
withJob {
[email protected]()
}
}
}
| platform/lang-impl/src/com/intellij/lang/documentation/classes.kt | 3047737259 |
package com.cognifide.gradle.aem.pkg.tasks.compose
import org.gradle.api.provider.Property
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.Optional
interface BundleInstalled : RepositoryArchive {
@get:Input
@get:Optional
val runMode: Property<String>
}
| src/main/kotlin/com/cognifide/gradle/aem/pkg/tasks/compose/BundleInstalled.kt | 1455087537 |
/*
* Copyright 2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.android.anko
import org.jetbrains.android.anko.config.AnkoFile
import org.jetbrains.android.anko.config.AnkoFile.*
import org.jetbrains.android.anko.config.ConfigurationTune.HELPER_CONSTRUCTORS
import org.jetbrains.android.anko.config.Props
import org.jetbrains.android.anko.config.TargetArtifactType
import org.jetbrains.android.anko.render.*
import org.jetbrains.android.anko.utils.toCamelCase
import java.io.Closeable
import java.io.File
import java.io.PrintWriter
class Writer(private val renderFacade: RenderFacade) {
private val config = renderFacade.config
fun write() {
val versionType = config.getTargetArtifactType()
AnkoFile.values().forEach { file ->
if (config[file] && versionType in file.types && file.shouldBeWritten(config)) {
write(file)
}
}
val staticFilesDir = File("dsl/static/src", when (versionType) {
TargetArtifactType.PLATFORM -> "platform"
else -> config.version.toCamelCase('-', firstCapital = false)
})
if (config.generateStaticFiles) {
staticFilesDir.listFiles()?.forEach { file ->
if (file.isFile) {
file.copyTo(File(config.sourceOutputDirectory, file.name))
}
}
}
}
private fun write(file: AnkoFile): Unit = when (file) {
INTERFACE_WORKAROUNDS_JAVA -> writeInterfaceWorkarounds()
LAYOUTS -> writeLayouts()
LISTENERS -> writeListeners()
PROPERTIES -> writeProperties()
SERVICES -> writeServices()
SQL_PARSER_HELPERS -> writeSqlParserHelpers()
VIEWS -> writeViews()
}
fun writeInterfaceWorkarounds() {
val imports = "package ${config.outputPackage}.workarounds;"
write(AnkoFile.INTERFACE_WORKAROUNDS_JAVA, InterfaceWorkaroundsRenderer::class.java, imports, false)
}
private fun writeLayouts() {
val imports = Props.imports["layouts"] ?: ""
write(AnkoFile.LAYOUTS, LayoutRenderer::class.java, imports)
}
private fun writeListeners() {
write(AnkoFile.LISTENERS, ListenerRenderer::class.java)
}
private fun writeProperties() {
val imports = Props.imports["properties"] ?: ""
write(AnkoFile.PROPERTIES, PropertyRenderer::class.java, imports)
}
private fun writeServices() {
val imports = Props.imports["services"] ?: ""
write(AnkoFile.SERVICES, ServiceRenderer::class.java, imports)
}
private fun writeSqlParserHelpers() {
val imports = Props.imports["sqliteparserhelpers"] ?: ""
write(AnkoFile.SQL_PARSER_HELPERS, SqlParserHelperRenderer::class.java, imports, false)
}
private fun writeViews() {
val allViews = if (config[VIEWS] || config[HELPER_CONSTRUCTORS]) {
renderFacade[ViewRenderer::class.java] + renderFacade[ViewGroupRenderer::class.java]
} else ""
val imports = Props.imports["views"] ?: ""
write(AnkoFile.VIEWS, allViews, imports)
}
private fun write(
subsystem: AnkoFile,
renderer: Class<out Renderer>,
imports: String = "",
generatePackage: Boolean = true)
{
write(subsystem, renderFacade[renderer], imports, generatePackage)
}
private fun write(subsystem: AnkoFile, text: String, imports: String = "", generatePackage: Boolean = true) {
if (text.trim().isEmpty()) return
val file = config.getOutputFile(subsystem)
val dir = file.parentFile
if (!dir.exists()) {
dir.mkdirs()
}
PrintWriter(file).useIt {
if (config.generatePackage && generatePackage) {
val facadeFilename = config.version.toCamelCase('-') + subsystem.name().toLowerCase().toCamelCase()
println("@file:JvmMultifileClass")
println("@file:JvmName(\"${facadeFilename}Kt\")")
println("package ${config.outputPackage}\n")
}
if (config.generateImports) {
if (imports.isNotEmpty()) println(imports)
println()
}
print(text)
}
}
private inline fun <T : Closeable, R> T.useIt(block: T.() -> R) = use { it.block() }
} | dsl/src/org/jetbrains/android/anko/Writer.kt | 1762903851 |
package com.serverless
import com.amazonaws.services.lambda.runtime.Context
import com.amazonaws.services.lambda.runtime.RequestHandler
import com.amazonaws.services.lambda.runtime.events.APIGatewayV2ProxyRequestEvent
import com.amazonaws.services.lambda.runtime.events.APIGatewayV2ProxyResponseEvent
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
class Handler : RequestHandler<APIGatewayV2ProxyRequestEvent, APIGatewayV2ProxyResponseEvent> {
private val mapper = jacksonObjectMapper()
override fun handleRequest(input: APIGatewayV2ProxyRequestEvent?, context: Context): APIGatewayV2ProxyResponseEvent {
val response = APIGatewayV2ProxyResponseEvent()
response.statusCode = 200
response.body = mapper.writeValueAsString(hashMapOf("message" to "Go Serverless v1.x! Your function executed successfully!"))
return response
}
}
| tests/runtimes/java/kotlin/src/main/kotlin/com/serverless/Handler.kt | 3405422769 |
package xyz.nulldev.ts.api.java.impl.downloads
import eu.kanade.tachiyomi.data.database.models.Chapter
import eu.kanade.tachiyomi.data.download.model.Download
import eu.kanade.tachiyomi.source.model.Page
import xyz.nulldev.ts.api.java.model.downloads.DownloadStatus
import xyz.nulldev.ts.api.java.model.downloads.DownloadTask
class DownloadTaskImpl(private val download: Download) : DownloadTask {
override val chapter: Chapter
get() = download.chapter
override val pages: List<Page>?
get() = download.pages
/**
* Download progress, a float between 0 and 1
*/
override val progress: Float
get() {
val pages = pages
// Calculate download progress
val downloadProgressMax: Float
val downloadProgress: Float
if(pages != null) {
downloadProgressMax = pages.size * 100f
downloadProgress = pages
.map { it.progress.toFloat() }
.sum()
} else {
downloadProgressMax = 1f
downloadProgress = 0f
}
return downloadProgress / downloadProgressMax
}
override val status: DownloadStatus
get() = when(download.status) {
Download.NOT_DOWNLOADED -> DownloadStatus.NOT_DOWNLOADED
Download.QUEUE -> DownloadStatus.QUEUE
Download.DOWNLOADING -> DownloadStatus.DOWNLOADING
Download.DOWNLOADED -> DownloadStatus.DOWNLOADED
Download.ERROR -> DownloadStatus.ERROR
else -> throw IllegalStateException("Unknown download status: ${download.status}!")
}
} | TachiServer/src/main/java/xyz/nulldev/ts/api/java/impl/downloads/DownloadTaskImpl.kt | 1005331855 |
@file:Suppress("unused")
package org.maxur.mserv.frame.service.properties
import org.jvnet.hk2.annotations.Contract
import org.maxur.mserv.core.Result
import java.net.URI
/**
* @author myunusov
* @version 1.0
* @since <pre>24.06.2017</pre>
*/
@Contract
abstract class PropertiesFactory {
abstract fun make(uri: URI? = null, rootKey: String? = null): Result<Exception, Properties>
}
| maxur-mserv-core/src/main/kotlin/org/maxur/mserv/frame/service/properties/PropertiesFactory.kt | 1145368258 |
// GENERATED
package com.fkorotkov.kubernetes
import io.fabric8.kubernetes.api.model.LabelSelector as model_LabelSelector
import io.fabric8.kubernetes.api.model.PodAffinityTerm as model_PodAffinityTerm
import io.fabric8.kubernetes.api.model.TopologySpreadConstraint as model_TopologySpreadConstraint
fun model_PodAffinityTerm.`labelSelector`(block: model_LabelSelector.() -> Unit = {}) {
if(this.`labelSelector` == null) {
this.`labelSelector` = model_LabelSelector()
}
this.`labelSelector`.block()
}
fun model_TopologySpreadConstraint.`labelSelector`(block: model_LabelSelector.() -> Unit = {}) {
if(this.`labelSelector` == null) {
this.`labelSelector` = model_LabelSelector()
}
this.`labelSelector`.block()
}
| DSLs/kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/kubernetes/labelSelector.kt | 4281306965 |
package org.maxur.mserv.sample
import org.maxur.mserv.frame.domain.BaseService
import org.maxur.mserv.frame.embedded.WebServer
import org.maxur.mserv.frame.runner.Kotlin
import org.maxur.mserv.frame.runner.hocon
import org.maxur.mserv.frame.service.properties.Properties
import org.maxur.mserv.sample.params.ConfigParams
import org.slf4j.LoggerFactory
/**
* Application Launcher
*
* @author myunusov
* @version 1.0
* @since <pre>12.06.2017</pre>
*/
object Launcher {
private fun log() = LoggerFactory.getLogger(Launcher::class.java)
/**
* Command line entry point. This method kicks off the building of a application object
* and executes it.
*
* @param args - arguments of command.
*/
@JvmStatic
fun main(args: Array<String>) {
Kotlin.runner {
name = ":name"
packages += "org.maxur.mserv.sample"
properties += hocon()
services += rest {
afterStart += this@Launcher::afterWebServiceStart
}
afterStart += this@Launcher::afterStart
beforeStop += { _ -> log().info("Microservice is stopped") }
onError += { exception -> log().error(exception.message, exception) }
}.start()
}
fun afterStart(configParams: ConfigParams, config: Properties, service: BaseService) {
log().info("Properties Source is '${config.sources.get(0).format}'\n")
configParams.log()
log().info("${service.name} is started")
}
fun afterWebServiceStart(service: WebServer) {
log().info("${service.name} is started on ${service.baseUri}\"")
log().info(service.entries().toString())
}
}
| maxur-mserv-sample/src/main/kotlin/org/maxur/mserv/sample/Launcher.kt | 2014208284 |
// 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 mobi.hsz.idea.gitignore.lang.kind
import mobi.hsz.idea.gitignore.file.type.kind.TFFileType
import mobi.hsz.idea.gitignore.lang.IgnoreLanguage
import mobi.hsz.idea.gitignore.util.Icons
/**
* TFLanguage [IgnoreLanguage] definition.
*/
class TFLanguage private constructor() : IgnoreLanguage("Team Foundation", "tfignore", null, Icons.TF) {
companion object {
val INSTANCE = TFLanguage()
}
override val fileType
get() = TFFileType.INSTANCE
override val isVCS
get() = true
}
| src/main/kotlin/mobi/hsz/idea/gitignore/lang/kind/TFLanguage.kt | 3938241450 |
/*
* Copyright 2019 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 im.vector.fragments.roomwidgets
import android.content.Context
import android.text.TextUtils
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.MutableLiveData
import com.airbnb.mvrx.*
import im.vector.Matrix
import im.vector.R
import im.vector.VectorApp
import im.vector.activity.WidgetActivity
import im.vector.ui.arch.LiveEvent
import im.vector.widgets.Widget
import im.vector.widgets.WidgetsManager
import org.matrix.androidsdk.MXSession
import org.matrix.androidsdk.core.Log
import org.matrix.androidsdk.core.callback.ApiCallback
import org.matrix.androidsdk.core.model.MatrixError
import org.matrix.androidsdk.data.Room
import org.matrix.androidsdk.features.integrationmanager.IntegrationManager
import org.matrix.androidsdk.features.terms.TermsNotSignedException
enum class WidgetState {
UNKNOWN,
WIDGET_NOT_ALLOWED,
WIDGET_ALLOWED
}
data class RoomWidgetViewModelState(
val status: WidgetState = WidgetState.UNKNOWN,
val formattedURL: Async<String> = Uninitialized,
val webviewLoadedUrl: Async<String> = Uninitialized,
val widgetName: String = "",
val canManageWidgets: Boolean = false,
val createdByMe: Boolean = false
) : MvRxState
class RoomWidgetViewModel(initialState: RoomWidgetViewModelState, val widget: Widget)
: BaseMvRxViewModel<RoomWidgetViewModelState>(initialState, false) {
companion object : MvRxViewModelFactory<RoomWidgetViewModel, RoomWidgetViewModelState> {
const val NAVIGATE_FINISH = "NAVIGATE_FINISH"
override fun create(viewModelContext: ViewModelContext, state: RoomWidgetViewModelState): RoomWidgetViewModel? {
return (viewModelContext.activity.intent?.extras?.getSerializable(WidgetActivity.EXTRA_WIDGET_ID) as? Widget)?.let {
RoomWidgetViewModel(state, it)
} ?: super.create(viewModelContext, state)
}
override fun initialState(viewModelContext: ViewModelContext): RoomWidgetViewModelState? {
val widget = viewModelContext.activity.intent?.extras?.getSerializable(WidgetActivity.EXTRA_WIDGET_ID) as? Widget
?: return null
val session = Matrix.getInstance(viewModelContext.activity).getSession(widget.sessionId)
return RoomWidgetViewModelState(
widgetName = widget.humanName,
createdByMe = widget.widgetEvent.getSender() == session?.myUserId
)
}
}
var navigateEvent: MutableLiveData<LiveEvent<String>> = MutableLiveData()
var termsNotSignedEvent: MutableLiveData<LiveEvent<TermsNotSignedException>> = MutableLiveData()
var loadWebURLEvent: MutableLiveData<LiveEvent<String>> = MutableLiveData()
var toastMessageEvent: MutableLiveData<LiveEvent<String>> = MutableLiveData()
private var room: Room? = null
var session: MXSession? = null
var widgetsManager: WidgetsManager? = null
/**
* Widget events listener
*/
private val mWidgetListener = WidgetsManager.onWidgetUpdateListener { widget ->
if (TextUtils.equals(widget.widgetId, widget.widgetId)) {
if (!widget.isActive) {
doFinish()
}
}
}
init {
configure()
session?.integrationManager?.addListener(object : IntegrationManager.IntegrationManagerManagerListener {
override fun onIntegrationManagerChange(managerConfig: IntegrationManager) {
refreshPermissionStatus()
}
})
}
fun webviewStartedToLoad(url: String?) = withState {
//Only do it for first load
setState {
copy(webviewLoadedUrl = Loading())
}
}
fun webviewLoadingError(url: String?, reason: String?) = withState {
setState {
copy(webviewLoadedUrl = Fail(Throwable(reason)))
}
}
fun webviewLoadSuccess(url: String?) = withState {
setState {
copy(webviewLoadedUrl = Success(url ?: ""))
}
}
private fun configure() {
val applicationContext = VectorApp.getInstance().applicationContext
val matrix = Matrix.getInstance(applicationContext)
session = matrix.getSession(widget.sessionId)
if (session == null) {
//defensive code
doFinish()
return
}
room = session?.dataHandler?.getRoom(widget.roomId)
if (room == null) {
//defensive code
doFinish()
return
}
widgetsManager = matrix
.getWidgetManagerProvider(session)?.getWidgetManager(applicationContext)
setState {
copy(canManageWidgets = WidgetsManager.checkWidgetPermission(session, room) == null)
}
widgetsManager?.addListener(mWidgetListener)
refreshPermissionStatus(applicationContext)
}
private fun refreshPermissionStatus(applicationContext: Context = VectorApp.getInstance().applicationContext) {
//If it was added by me, consider it as allowed
if (widget.widgetEvent.getSender() == session?.myUserId) {
onWidgetAllowed(applicationContext)
return
}
val isAllowed = session
?.integrationManager
?.isWidgetAllowed(widget.widgetEvent.eventId)
?: false
if (!isAllowed) {
setState {
copy(status = WidgetState.WIDGET_NOT_ALLOWED)
}
} else {
//we can start loading the widget then
onWidgetAllowed(applicationContext)
}
}
fun doCloseWidget(context: Context) {
AlertDialog.Builder(context)
.setMessage(R.string.widget_delete_message_confirmation)
.setPositiveButton(R.string.remove) { _, _ ->
widgetsManager?.closeWidget(session, room, widget.widgetId, object : ApiCallback<Void> {
override fun onSuccess(info: Void?) {
doFinish()
}
private fun onError(errorMessage: String) {
toastMessageEvent.postValue(LiveEvent(errorMessage))
}
override fun onNetworkError(e: Exception) {
onError(e.localizedMessage)
}
override fun onMatrixError(e: MatrixError) {
onError(e.localizedMessage)
}
override fun onUnexpectedError(e: Exception) {
onError(e.localizedMessage)
}
})
}
.setNegativeButton(R.string.cancel, null)
.show()
}
fun doFinish() {
navigateEvent.postValue(LiveEvent(NAVIGATE_FINISH))
}
fun refreshAfterTermsAccepted() {
onWidgetAllowed()
}
private fun onWidgetAllowed(applicationContext: Context = VectorApp.getInstance().applicationContext) {
setState {
copy(
status = WidgetState.WIDGET_ALLOWED,
formattedURL = Loading()
)
}
if (widgetsManager != null) {
widgetsManager!!.getFormattedWidgetUrl(applicationContext, widget, object : ApiCallback<String> {
override fun onSuccess(url: String) {
loadWebURLEvent.postValue(LiveEvent(url))
setState {
//We use a live event to trigger the webview load
copy(
status = WidgetState.WIDGET_ALLOWED,
formattedURL = Success(url)
)
}
}
private fun onError(errorMessage: String) {
setState {
copy(
status = WidgetState.WIDGET_ALLOWED,
formattedURL = Fail(Throwable(errorMessage))
)
}
}
override fun onNetworkError(e: Exception) {
onError(e.localizedMessage)
}
override fun onMatrixError(e: MatrixError) {
onError(e.localizedMessage)
}
override fun onUnexpectedError(e: Exception) {
if (e is TermsNotSignedException) {
termsNotSignedEvent.postValue(LiveEvent(e))
} else {
onError(e.localizedMessage)
}
}
})
} else {
setState {
copy(
status = WidgetState.WIDGET_ALLOWED,
formattedURL = Success(widget.url)
)
}
loadWebURLEvent.postValue(LiveEvent(widget.url))
}
}
fun revokeWidget(onFinished: (() -> Unit)? = null) {
setState {
copy(
status = WidgetState.UNKNOWN
)
}
session?.integrationManager?.setWidgetAllowed(widget.widgetEvent?.eventId
?: "", false, object : ApiCallback<Void?> {
override fun onSuccess(info: Void?) {
onFinished?.invoke()
}
override fun onUnexpectedError(e: Exception) {
Log.e(this::class.java.name, e.message)
}
override fun onNetworkError(e: Exception) {
Log.e(this::class.java.name, e.message)
}
override fun onMatrixError(e: MatrixError) {
Log.e(this::class.java.name, e.message)
}
})
}
override fun onCleared() {
super.onCleared()
widgetsManager?.removeListener(mWidgetListener)
}
} | vector/src/main/java/im/vector/fragments/roomwidgets/RoomWidgetViewModel.kt | 1939571938 |
package trainSimulation
class RailSegment(val railID: Int){
var capacity: Int = 0
var delay: Boolean = false
fun addTrain(){
if(capacity < 3) {
capacity++
}else{
delay = true
}
}
} | src/main/kotlin/trainSimulation/RailSegment.kt | 1147486060 |
// Copyright 2010 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.google.android.stardroid.layers
import android.content.res.AssetManager
import android.content.res.Resources
import com.google.android.stardroid.R
/**
* An implementation of the [AbstractFileBasedLayer] for displaying
* Messier objects.
*
* @author John Taylor
* @author Brent Bryan
*/
class MessierLayer(assetManager: AssetManager, resources: Resources) :
AbstractFileBasedLayer(assetManager, resources, "messier.binary") {
override val layerDepthOrder = 20
// TODO(johntaylor): rename this string id
override val layerNameId = R.string.show_messier_objects_pref
// TODO(brent): Remove this.
override val preferenceId = "source_provider.2"
} | app/src/main/java/com/google/android/stardroid/layers/MessierLayer.kt | 4163086317 |
package com.jcminarro.roundkornerlayout
import android.content.res.TypedArray
import android.graphics.Path
import android.graphics.RectF
import android.os.Build
import android.view.View
internal fun View.updateOutlineProvider(cornersHolder: CornersHolder) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
outlineProvider = RoundOutlineProvider(cornersHolder)
}
}
internal fun View.updateOutlineProvider(cornerRadius: Float) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
outlineProvider = RoundOutlineProvider(cornerRadius)
}
}
internal fun Path.addRoundRectWithRoundCorners(rectF: RectF, cornersHolder: CornersHolder) {
addRoundRectWithRoundCorners(
rectF,
cornersHolder.topLeftCornerRadius,
cornersHolder.topRightCornerRadius,
cornersHolder.bottomRightCornerRadius,
cornersHolder.bottomLeftCornerRadius
)
}
internal fun Path.addRoundRectWithRoundCorners(rectF: RectF,
topLeftCornerRadius: Float,
topRightCornerRadius: Float,
bottomRightCornerRadius: Float,
bottomLeftCornerRadius: Float) {
addRoundRect(
rectF,
floatArrayOf(
topLeftCornerRadius,
topLeftCornerRadius,
topRightCornerRadius,
topRightCornerRadius,
bottomRightCornerRadius,
bottomRightCornerRadius,
bottomLeftCornerRadius,
bottomLeftCornerRadius
),
Path.Direction.CW
)
}
internal fun TypedArray.getCornerRadius(attrCornerRadius: Int,
attrTopLeftCornerRadius: Int,
attrTopRightCornerRadius: Int,
attrBottomRightCornerRadius: Int,
attrBottomLeftCornerRadius: Int
): CornersHolder {
val cornerRadius = getDimension(attrCornerRadius, 0f)
val topLeftCornerRadius = getDimension(attrTopLeftCornerRadius, cornerRadius)
val topRightCornerRadius = getDimension(attrTopRightCornerRadius, cornerRadius)
val bottomRightCornerRadius = getDimension(attrBottomRightCornerRadius, cornerRadius)
val bottomLeftCornerRadius = getDimension(attrBottomLeftCornerRadius, cornerRadius)
return CornersHolder(
topLeftCornerRadius,
topRightCornerRadius,
bottomRightCornerRadius,
bottomLeftCornerRadius
)
}
| roundkornerlayout/src/main/java/com/jcminarro/roundkornerlayout/Extensions.kt | 535127215 |
package nl.deltadak.plep.commands
import javafx.scene.control.ProgressIndicator
import javafx.scene.control.TreeItem
import javafx.scene.control.TreeView
import nl.deltadak.plep.HomeworkTask
import nl.deltadak.plep.database.DatabaseFacade
import nl.deltadak.plep.ui.treeview.TreeViewCleaner
import java.time.LocalDate
/**
* Delete a subtask only.
*/
class DeleteSubtaskCommand(progressIndicator: ProgressIndicator, day: LocalDate, treeViewItemsImmutable: List<List<HomeworkTask>>, index: Int, tree: TreeView<HomeworkTask>) : DeleteCommand(progressIndicator, day, treeViewItemsImmutable, index, tree) {
private val deletedTask: HomeworkTask = treeViewItems.flatten()[index]
/** Index of parent in treeview, only counting parents */
private var parentIndex: Int = -1
/** Index of subtask in the list of children of it's parent */
private var indexWithinParent: Int = -1
/** {@inheritDoc} */
override fun executionHook() {
if (treeViewItems.isEmpty()) {
throw IllegalStateException("cannot delete item from empty treeview")
}
// Remove task from saved state.
for (i in treeViewItems.indices) {
val taskList = treeViewItems[i].toMutableList()
if (taskList.contains(deletedTask)) {
parentIndex = i
// Subtract one because the parent is the first item in the list.
indexWithinParent = taskList.indexOf(deletedTask) - 1
taskList.remove(deletedTask)
treeViewItems[i] = taskList
}
}
// Known to be null when testing.
if (tree.root != null && tree.root.children != null) {
val parent = tree.root.children[parentIndex]
if (parent != null && parent.children.size > 0) {
parent.children.removeAt(indexWithinParent)
DatabaseFacade(progressIndicator).pushData(day, treeViewItems)
TreeViewCleaner().cleanSingleTreeView(tree)
}
}
}
/** {@inheritDoc} */
override fun undoHook() {
if (parentIndex == -1 || indexWithinParent == -1) {
throw IllegalStateException("cannot find the task to re-add")
}
// We add one to the index because the first one in the list is the parent task, and we count from there.
treeViewItems[parentIndex].add(indexWithinParent + 1, deletedTask)
val parent = tree.root.children[parentIndex]
parent.children.add(indexWithinParent, TreeItem(deletedTask))
DatabaseFacade(progressIndicator).pushData(day, treeViewItems)
TreeViewCleaner().cleanSingleTreeView(tree)
}
} | src/main/kotlin/nl/deltadak/plep/commands/DeleteSubtaskCommand.kt | 1753641677 |
/*
* Copyright 2018 Ross Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.moderation.bukkit.command.ticket.list
import com.rpkit.moderation.bukkit.RPKModerationBukkit
import com.rpkit.moderation.bukkit.ticket.RPKTicketProvider
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
import java.time.format.DateTimeFormatter
class TicketListClosedCommand(private val plugin: RPKModerationBukkit): CommandExecutor {
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean {
if (!sender.hasPermission("rpkit.moderation.command.ticket.list.closed")) {
sender.sendMessage(plugin.messages["no-permission-ticket-list-closed"])
}
val ticketProvider = plugin.core.serviceManager.getServiceProvider(RPKTicketProvider::class)
val closedTickets = ticketProvider.getClosedTickets()
sender.sendMessage(plugin.messages["ticket-list-title"])
val dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
closedTickets.forEach { ticket ->
val closeDate = ticket.closeDate
sender.sendMessage(plugin.messages["ticket-list-item", mapOf(
Pair("id", ticket.id.toString()),
Pair("reason", ticket.reason),
Pair("location", "${ticket.location?.world} ${ticket.location?.blockX}, ${ticket.location?.blockY}, ${ticket.location?.blockZ}"),
Pair("issuer", ticket.issuer.name),
Pair("resolver", ticket.resolver?.name?:"none"),
Pair("open-date", dateTimeFormatter.format(ticket.openDate)),
Pair("close-date", if (closeDate == null) "none" else dateTimeFormatter.format(ticket.closeDate)),
Pair("closed", ticket.isClosed.toString())
)])
}
return true
}
} | bukkit/rpk-moderation-bukkit/src/main/kotlin/com/rpkit/moderation/bukkit/command/ticket/list/TicketListClosedCommand.kt | 3585984973 |
/*
* Copyright 2019 Ren Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.players.bukkit.servlet
import com.rpkit.core.web.RPKServlet
import com.rpkit.players.bukkit.RPKPlayersBukkit
import com.rpkit.players.bukkit.profile.RPKProfileProvider
import org.apache.velocity.VelocityContext
import org.apache.velocity.app.Velocity
import java.util.*
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import javax.servlet.http.HttpServletResponse.SC_OK
class ProfilesServlet(private val plugin: RPKPlayersBukkit): RPKServlet() {
override val url = "/profiles/"
override fun doGet(req: HttpServletRequest, resp: HttpServletResponse) {
resp.contentType = "text/html"
resp.status = SC_OK
val templateBuilder = StringBuilder()
val scanner = Scanner(javaClass.getResourceAsStream("/web/profiles.html"))
while (scanner.hasNextLine()) {
templateBuilder.append(scanner.nextLine()).append('\n')
}
scanner.close()
val name = req.getParameter("name")
val profileProvider = plugin.core.serviceManager.getServiceProvider(RPKProfileProvider::class)
val profile = if (name == null) null else profileProvider.getProfile(name)
val velocityContext = VelocityContext()
velocityContext.put("server", plugin.core.web.title)
velocityContext.put("navigationBar", plugin.core.web.navigationBar)
velocityContext.put("activeProfile", profileProvider.getActiveProfile(req))
velocityContext.put("profile", profile)
Velocity.evaluate(velocityContext, resp.writer, "/web/profiles.html", templateBuilder.toString())
}
} | bukkit/rpk-players-bukkit/src/main/kotlin/com/rpkit/players/bukkit/servlet/ProfilesServlet.kt | 355456595 |
/*
* Copyright 2020 Ren Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.drinks.bukkit
import com.rpkit.characters.bukkit.character.RPKCharacterProvider
import com.rpkit.core.bukkit.plugin.RPKBukkitPlugin
import com.rpkit.core.database.Database
import com.rpkit.drinks.bukkit.database.table.RPKDrunkennessTable
import com.rpkit.drinks.bukkit.drink.RPKDrinkProviderImpl
import com.rpkit.drinks.bukkit.listener.PlayerItemConsumeListener
import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider
import org.bstats.bukkit.Metrics
import org.bukkit.potion.PotionEffect
import org.bukkit.potion.PotionEffectType
import org.bukkit.scheduler.BukkitRunnable
class RPKDrinksBukkit: RPKBukkitPlugin() {
override fun onEnable() {
Metrics(this, 4389)
saveDefaultConfig()
val drinkProvider = RPKDrinkProviderImpl(this)
drinkProvider.drinks.forEach { server.addRecipe(it.recipe) }
serviceProviders = arrayOf(
drinkProvider
)
object: BukkitRunnable() {
override fun run() {
val minecraftProfileProvider = core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class)
val characterProvider = core.serviceManager.getServiceProvider(RPKCharacterProvider::class)
server.onlinePlayers.forEach { bukkitPlayer ->
val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(bukkitPlayer) ?: return@forEach
val character = characterProvider.getActiveCharacter(minecraftProfile) ?: return@forEach
val drunkenness = drinkProvider.getDrunkenness(character)
if (drunkenness > 0) {
if (drunkenness > 1000) {
if (config.getBoolean("kill-characters"))
character.isDead = true
characterProvider.updateCharacter(character)
}
if (drunkenness >= 75) {
bukkitPlayer.addPotionEffect(PotionEffect(PotionEffectType.POISON, 1200, drunkenness))
}
if (drunkenness >= 50) {
bukkitPlayer.addPotionEffect(PotionEffect(PotionEffectType.BLINDNESS, 1200, drunkenness))
}
if (drunkenness >= 10) {
bukkitPlayer.addPotionEffect(PotionEffect(PotionEffectType.WEAKNESS, 1200, drunkenness))
}
bukkitPlayer.addPotionEffect(PotionEffect(PotionEffectType.CONFUSION, 1200, drunkenness))
drinkProvider.setDrunkenness(character, drunkenness - 1)
}
}
}
}.runTaskTimer(this, 1200, 1200)
}
override fun registerListeners() {
registerListeners(
PlayerItemConsumeListener(this)
)
}
override fun createTables(database: Database) {
database.addTable(RPKDrunkennessTable(database, this))
}
} | bukkit/rpk-drinks-bukkit/src/main/kotlin/com/rpkit/drinks/bukkit/RPKDrinksBukkit.kt | 483145888 |
package com.petertackage.kotlinoptions.assertions
import com.petertackage.kotlinoptions.None
import com.petertackage.kotlinoptions.Option
import com.petertackage.kotlinoptions.Some
/**
* Creates a new instance of [OptionAssertions] to allow asserting on the properties of the instance under test: [actual].
*/
fun <T : Any> assertThat(actual: Option<T>): OptionAssertions<T> {
return OptionAssertions(actual)
}
/**
* Asserts that the instance under test is [Some].
*/
fun <T : Any> Option<T>.assertIsSome(): Option<T> {
return apply { assertThat(this).isSome() }
}
/**
* Asserts that the instance under test is [None].
*/
fun <T : Any> Option<T>.assertIsNone(): Option<T> {
return apply { assertThat(this).isNone() }
}
/**
* Asserts that the instance under test is [Some] and has the value [expected].
*/
fun <T : Any> Option<T>.assertHasValue(expected: T): Option<T> {
return apply { assertThat(this).hasValue(expected) }
}
/**
* Asserts that the instance under test is [Some] and has the value returned by function [expectedPredicate].
*/
fun <T : Any> Option<T>.assertHasValue(expectedPredicate: (T) -> Boolean): Option<T> {
return apply { assertThat(this).hasValue(expectedPredicate) }
}
class OptionAssertions<T : Any> internal constructor(private val actual: Option<T>) {
/**
* Asserts that the instance under test is [Some].
*/
fun isSome(): OptionAssertions<T> {
return apply {
assert(actual is Some,
{ "Expected: <Some> but was: <None>" })
}
}
/**
* Asserts that the instance under test is [None].
*/
fun isNone(): OptionAssertions<T> {
return apply {
assert(actual is None,
{ "Expected: <None> but was: <Some>" })
}
}
/**
* Asserts that the instance under test is [Some] and has the value [expected].
*/
fun hasValue(expected: T): OptionAssertions<T> {
isSome()
val actualValue: T = actual.getUnsafe()
return apply { assert(expected == actualValue, { "Expected value: <$expected> but was: <$actualValue>" }) }
}
/**
* Asserts that the instance under test is [Some] and has the value returned by function [expectedPredicate].
*/
fun hasValue(expectedPredicate: (T) -> Boolean): OptionAssertions<T> {
isSome()
val actualValue = actual.getUnsafe()
return apply { assert(expectedPredicate(actualValue), { "Expected predicate did not match: <$actualValue>" }) }
}
}
| kotlin-options-assertions/src/main/kotlin/com/petertackage/kotlinoptions/assertions/OptionAssertions.kt | 4285657557 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.