repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
GunoH/intellij-community
|
java/idea-ui/src/com/intellij/jarRepository/repositoryLibrarySynchronizers.kt
|
2
|
5702
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.jarRepository
import com.intellij.openapi.Disposable
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.RootProvider
import com.intellij.openapi.roots.impl.libraries.LibraryEx
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.roots.libraries.LibraryTable
import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar
import com.intellij.workspaceModel.ide.WorkspaceModelChangeListener
import com.intellij.workspaceModel.ide.impl.legacyBridge.library.ProjectLibraryTableBridgeImpl.Companion.libraryMap
import com.intellij.workspaceModel.storage.EntityChange
import com.intellij.workspaceModel.storage.VersionedStorageChange
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.bridgeEntities.*
internal class GlobalChangedRepositoryLibrarySynchronizer(private val queue: LibrarySynchronizationQueue,
private val disposable: Disposable)
: LibraryTable.Listener, RootProvider.RootSetChangedListener {
override fun beforeLibraryRemoved(library: Library) {
if (library is LibraryEx) {
library.rootProvider.removeRootSetChangedListener(this)
queue.revokeSynchronization(library)
}
}
override fun afterLibraryAdded(library: Library) {
if (library is LibraryEx) {
library.rootProvider.addRootSetChangedListener(this, disposable)
queue.requestSynchronization(library)
}
}
override fun rootSetChanged(wrapper: RootProvider) {
for (library in LibraryTablesRegistrar.getInstance().libraryTable.libraries) {
if (library.rootProvider == wrapper) {
if (library is LibraryEx) {
queue.requestSynchronization(library)
}
break
}
}
}
fun installOnExistingLibraries() = getGlobalAndCustomLibraryTables()
.flatMap { it.libraries.asIterable() }
.filterIsInstance<LibraryEx>()
.forEach { it.rootProvider.addRootSetChangedListener(this, disposable) }
companion object {
@JvmStatic
fun getGlobalAndCustomLibraryTables(): List<LibraryTable> {
return LibraryTablesRegistrar.getInstance().customLibraryTables + LibraryTablesRegistrar.getInstance().libraryTable
}
}
}
internal class ChangedRepositoryLibrarySynchronizer(private val project: Project,
private val queue: LibrarySynchronizationQueue) : WorkspaceModelChangeListener {
override fun beforeChanged(event: VersionedStorageChange) {
for (change in event.getChanges(LibraryEntity::class.java)) {
val removed = change as? EntityChange.Removed ?: continue
val library = findLibrary(removed.entity.symbolicId, event.storageBefore)
if (library != null) {
queue.revokeSynchronization(library)
}
}
for (change in event.getChanges(ModuleEntity::class.java)) {
val (oldLibDeps, newLibDeps) = when (change) {
is EntityChange.Added -> continue
is EntityChange.Removed -> change.entity.libraryDependencies() to emptySet()
is EntityChange.Replaced -> change.oldEntity.libraryDependencies() to change.newEntity.libraryDependencies()
}
oldLibDeps
.filterNot { newLibDeps.contains(it) }
.mapNotNull { findLibrary(it, event.storageBefore) }
.forEach { queue.revokeSynchronization(it) }
}
}
override fun changed(event: VersionedStorageChange) {
var libraryReloadRequested = false
for (change in event.getChanges(LibraryEntity::class.java)) {
val entity = when (change) {
is EntityChange.Added -> change.entity
is EntityChange.Replaced -> change.newEntity
is EntityChange.Removed -> null
} ?: continue
val library = findLibrary(entity.symbolicId, event.storageAfter)
if (library != null) {
queue.requestSynchronization(library)
libraryReloadRequested = true
}
}
for (change in event.getChanges(ModuleEntity::class.java)) {
val (oldLibDeps, newLibDeps) = when (change) {
is EntityChange.Removed -> continue
is EntityChange.Added -> emptySet<ModuleDependencyItem.Exportable.LibraryDependency>() to change.entity.libraryDependencies()
is EntityChange.Replaced -> change.oldEntity.libraryDependencies() to change.newEntity.libraryDependencies()
}
newLibDeps.filterNot { oldLibDeps.contains(it) }.mapNotNull { findLibrary(it, event.storageAfter) }.forEach {
queue.requestSynchronization(it)
libraryReloadRequested = true
}
}
if (libraryReloadRequested) {
queue.flush()
}
}
private fun findLibrary(libraryId: LibraryId, storage: EntityStorage): LibraryEx? {
val library = when (val tableId = libraryId.tableId) {
is LibraryTableId.GlobalLibraryTableId ->
LibraryTablesRegistrar.getInstance().getLibraryTableByLevel(tableId.level, project)?.getLibraryByName(libraryId.name)
else -> libraryId.resolve(storage)?.let { storage.libraryMap.getDataByEntity(it) }
}
return library as? LibraryEx
}
private fun findLibrary(libDep: ModuleDependencyItem.Exportable.LibraryDependency, storage: EntityStorage): LibraryEx? =
findLibrary(libDep.library, storage)
private fun ModuleEntity.libraryDependencies(): Set<ModuleDependencyItem.Exportable.LibraryDependency> =
dependencies.filterIsInstance<ModuleDependencyItem.Exportable.LibraryDependency>().toHashSet()
}
|
apache-2.0
|
d21e86f97a8dbdbdf0fda1966b560de8
| 41.879699 | 158 | 0.728166 | 5.072954 | false | false | false | false |
GunoH/intellij-community
|
platform/workspaceModel/codegen/src/com/intellij/workspaceModel/codegen/writer/imports.kt
|
2
|
4100
|
package com.intellij.workspaceModel.codegen.utils
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import kotlin.reflect.*
import kotlin.reflect.jvm.javaMethod
private const val fqnEscape = "#uC03o#"
fun fqn(function: KProperty1<KClass<*>, Collection<Any>>): QualifiedName = function.fqn
fun fqn1(function: KFunction3<EntityStorage, ConnectionId, WorkspaceEntity, WorkspaceEntity?>): QualifiedName = function.fqn
fun fqn2(function: KFunction3<EntityStorage, ConnectionId, WorkspaceEntity, Sequence<Any>>): QualifiedName = function.fqn
fun fqn3(function: KFunction4<EntityStorage, ConnectionId, WorkspaceEntity, WorkspaceEntity?, Unit>): QualifiedName = function.fqn
fun fqn4(function: KFunction4<EntityStorage, ConnectionId, WorkspaceEntity, List<WorkspaceEntity>, Unit>): QualifiedName = function.fqn
fun fqn5(function: KFunction4<EntityStorage, ConnectionId, WorkspaceEntity, Sequence<WorkspaceEntity>, Unit>): QualifiedName = function.fqn
fun fqn6(function: KFunction2<ModifiableWorkspaceEntityBase<*, *>, MutableEntityStorage, Unit>): QualifiedName = function.fqn
fun fqn7(function: KFunction1<Collection<*>, Collection<*>>): QualifiedName = function.fqn
private val KProperty<*>.fqn: QualifiedName
get() {
val declaringClass = this.getter.javaMethod?.declaringClass ?: return "".toQualifiedName()
return fqn(declaringClass.packageName, this.name)
}
private val KFunction<*>.fqn: QualifiedName
get() {
val declaringClass = this.javaMethod?.declaringClass ?: return "".toQualifiedName()
return fqn(declaringClass.packageName, this.name)
}
@JvmInline
value class QualifiedName(val encodedString: String) {
override fun toString(): String {
return encodedString
}
val decoded: String
get() = encodedString.removePrefix(fqnEscape).substringBefore("#").replace("@@", ".")
fun appendInner(innerClassPath: String): QualifiedName = QualifiedName("$encodedString.$innerClassPath")
fun appendSuffix(suffix: String): QualifiedName = QualifiedName("$encodedString$suffix")
}
/**
* Temporary string for adding to imports
*/
fun fqn(packageName: String?, name: String): QualifiedName {
if (packageName.isNullOrEmpty()) return QualifiedName(name)
val outerClassName = name.substringBefore(".")
return QualifiedName("$fqnEscape$packageName@@$outerClassName#$name")
}
fun String.toQualifiedName(): QualifiedName {
val classNameMatch = Regex("\\.[A-Z]").find(this) ?: return QualifiedName(this)
return fqn(substring(0, classNameMatch.range.first), substring(classNameMatch.range.last))
}
val KClass<*>.fqn: QualifiedName
get() = java.fqn
val Class<*>.fqn: QualifiedName
get() {
val name = name
val packageName = name.substringBeforeLast(".")
val className = name.substringAfterLast(".")
.replace('$', '.')
if (className.contains(".")) {
val outerClassName = className.substringBefore(".")
val innerClassPath = className.substringAfter(".")
return fqn(packageName, outerClassName).appendInner(innerClassPath)
}
else {
return fqn(packageName, className)
}
}
class Imports(private val scopeFqn: String?) {
val set = mutableSetOf<String>()
fun findAndRemoveFqns(str: String): String {
val res = StringBuilder()
var p = 0
while (true) {
var s = str.indexOf(fqnEscape, p)
if (s == -1) break
res.append(str, p, s)
s += fqnEscape.length
val e = str.indexOf('#', s)
check(e != -1)
val fqn = str.substring(s, e)
val (packageName, name) = fqn.split("@@")
add(packageName, name)
p = e + 1
}
res.append(str, p, str.length)
return res.toString()
}
fun add(packageName: String, name: String) {
if (packageName != scopeFqn) {
set.add("$packageName.$name")
}
}
fun add(import: String) {
set.add(import)
}
}
|
apache-2.0
|
d1f2d8f519846614f9acb4730d9b3959
| 34.964912 | 139 | 0.725366 | 4.432432 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/parameterInfo/KotlinHighLevelTypeArgumentInfoHandler.kt
|
3
|
5852
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.parameterInfo
import com.intellij.psi.util.parentOfType
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.analyze
import org.jetbrains.kotlin.analysis.api.calls.KtCallableMemberCall
import org.jetbrains.kotlin.analysis.api.components.KtTypeRendererOptions
import org.jetbrains.kotlin.analysis.api.signatures.KtFunctionLikeSignature
import org.jetbrains.kotlin.analysis.api.symbols.KtClassOrObjectSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtNamedClassOrObjectSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtTypeAliasSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtTypeParameterSymbol
import org.jetbrains.kotlin.analysis.api.symbols.markers.KtSymbolWithTypeParameters
import org.jetbrains.kotlin.analysis.api.types.KtClassErrorType
import org.jetbrains.kotlin.analysis.api.types.KtClassType
import org.jetbrains.kotlin.analysis.api.types.KtFlexibleType
import org.jetbrains.kotlin.analysis.api.types.KtNonErrorClassType
import org.jetbrains.kotlin.idea.references.KtSimpleNameReference
import org.jetbrains.kotlin.psi.KtCallElement
import org.jetbrains.kotlin.psi.KtTypeArgumentList
import org.jetbrains.kotlin.psi.KtTypeReference
import org.jetbrains.kotlin.psi.KtUserType
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelector
/**
* Presents type argument info for class type references (e.g., property type in declaration, base class in super types list).
*/
class KotlinHighLevelClassTypeArgumentInfoHandler : KotlinHighLevelTypeArgumentInfoHandlerBase() {
override fun KtAnalysisSession.findParameterOwners(argumentList: KtTypeArgumentList): Collection<KtSymbolWithTypeParameters>? {
val typeReference = argumentList.parentOfType<KtTypeReference>() ?: return null
val ktType = typeReference.getKtType() as? KtClassType ?: return null
return when (ktType) {
is KtNonErrorClassType -> listOfNotNull(ktType.expandedClassSymbol as? KtNamedClassOrObjectSymbol)
is KtClassErrorType -> {
ktType.candidateClassSymbols.mapNotNull { candidateSymbol ->
when (candidateSymbol) {
is KtClassOrObjectSymbol -> candidateSymbol
is KtTypeAliasSymbol -> candidateSymbol.expandedType.expandedClassSymbol
else -> null
} as? KtNamedClassOrObjectSymbol
}
}
}
}
override fun getArgumentListAllowedParentClasses() = setOf(KtUserType::class.java)
}
/**
* Presents type argument info for function calls (including constructor calls).
*/
class KotlinHighLevelFunctionTypeArgumentInfoHandler : KotlinHighLevelTypeArgumentInfoHandlerBase() {
override fun KtAnalysisSession.findParameterOwners(argumentList: KtTypeArgumentList): Collection<KtSymbolWithTypeParameters>? {
val callElement = argumentList.parentOfType<KtCallElement>() ?: return null
// A call element may not be syntactically complete (e.g., missing parentheses: `foo<>`). In that case, `callElement.resolveCall()`
// will NOT return a KtCall because there is no FirFunctionCall there. We find the symbols using the callee name instead.
val reference = callElement.calleeExpression?.references?.singleOrNull() as? KtSimpleNameReference ?: return null
val explicitReceiver = callElement.getQualifiedExpressionForSelector()?.receiverExpression
val fileSymbol = callElement.containingKtFile.getFileSymbol()
val symbols = callElement.collectCallCandidates()
.mapNotNull { (it.candidate as? KtCallableMemberCall<*, *>)?.partiallyAppliedSymbol?.signature }
.filterIsInstance<KtFunctionLikeSignature<*>>()
.filter { filterCandidate(it, callElement, fileSymbol, explicitReceiver) }
// Multiple overloads may have the same type parameters (see Overloads.kt test), so we select the distinct ones.
return symbols.distinctBy { buildPresentation(fetchCandidateInfo(it.symbol), -1).first }.map { it.symbol }
}
override fun getArgumentListAllowedParentClasses() = setOf(KtCallElement::class.java)
}
abstract class KotlinHighLevelTypeArgumentInfoHandlerBase : AbstractKotlinTypeArgumentInfoHandler() {
protected abstract fun KtAnalysisSession.findParameterOwners(argumentList: KtTypeArgumentList): Collection<KtSymbolWithTypeParameters>?
override fun fetchCandidateInfos(argumentList: KtTypeArgumentList): List<CandidateInfo>? {
analyze(argumentList) {
val parameterOwners = findParameterOwners(argumentList) ?: return null
return parameterOwners.map { fetchCandidateInfo(it) }
}
}
protected fun KtAnalysisSession.fetchCandidateInfo(parameterOwner: KtSymbolWithTypeParameters): CandidateInfo {
return CandidateInfo(parameterOwner.typeParameters.map { fetchTypeParameterInfo(it) })
}
private fun KtAnalysisSession.fetchTypeParameterInfo(parameter: KtTypeParameterSymbol): TypeParameterInfo {
val upperBounds = parameter.upperBounds.map {
val isNullableAnyOrFlexibleAny = if (it is KtFlexibleType) {
it.lowerBound.isAny && !it.lowerBound.isMarkedNullable && it.upperBound.isAny && it.upperBound.isMarkedNullable
} else {
it.isAny && it.isMarkedNullable
}
val renderedType = it.render(KtTypeRendererOptions.SHORT_NAMES)
UpperBoundInfo(isNullableAnyOrFlexibleAny, renderedType)
}
return TypeParameterInfo(parameter.name.asString(), parameter.isReified, parameter.variance, upperBounds)
}
}
|
apache-2.0
|
7d023ac194b63ba500b4c6c5710a50d2
| 58.121212 | 158 | 0.759398 | 5.267327 | false | false | false | false |
AsamK/TextSecure
|
app/src/main/java/org/thoughtcrime/securesms/components/settings/app/subscription/SubscriptionsRepository.kt
|
1
|
2229
|
package org.thoughtcrime.securesms.components.settings.app.subscription
import io.reactivex.rxjava3.core.Single
import io.reactivex.rxjava3.schedulers.Schedulers
import org.signal.core.util.money.FiatMoney
import org.thoughtcrime.securesms.badges.Badges
import org.thoughtcrime.securesms.keyvalue.SignalStore
import org.thoughtcrime.securesms.subscription.Subscription
import org.thoughtcrime.securesms.util.PlatformCurrencyUtil
import org.whispersystems.signalservice.api.services.DonationsService
import org.whispersystems.signalservice.api.subscriptions.ActiveSubscription
import org.whispersystems.signalservice.api.subscriptions.SubscriptionLevels
import org.whispersystems.signalservice.internal.ServiceResponse
import java.util.Currency
import java.util.Locale
/**
* Repository which can query for the user's active subscription as well as a list of available subscriptions,
* in the currency indicated.
*/
class SubscriptionsRepository(private val donationsService: DonationsService) {
fun getActiveSubscription(): Single<ActiveSubscription> {
val localSubscription = SignalStore.donationsValues().getSubscriber()
return if (localSubscription != null) {
donationsService.getSubscription(localSubscription.subscriberId)
.subscribeOn(Schedulers.io())
.flatMap(ServiceResponse<ActiveSubscription>::flattenResult)
} else {
Single.just(ActiveSubscription.EMPTY)
}
}
fun getSubscriptions(): Single<List<Subscription>> = donationsService.getSubscriptionLevels(Locale.getDefault())
.subscribeOn(Schedulers.io())
.flatMap(ServiceResponse<SubscriptionLevels>::flattenResult)
.map { subscriptionLevels ->
subscriptionLevels.levels.map { (code, level) ->
Subscription(
id = code,
name = level.name,
badge = Badges.fromServiceBadge(level.badge),
prices = level.currencies.filter {
PlatformCurrencyUtil
.getAvailableCurrencyCodes()
.contains(it.key)
}.map { (currencyCode, price) ->
FiatMoney(price, Currency.getInstance(currencyCode))
}.toSet(),
level = code.toInt()
)
}.sortedBy {
it.level
}
}
}
|
gpl-3.0
|
cb0a6f1aa2e2cfa3b653202ea63f78eb
| 38.803571 | 114 | 0.740691 | 4.742553 | false | false | false | false |
milosmns/Timecrypt
|
Android/app/src/main/java/co/timecrypt/android/activities/LinkDisplayActivity.kt
|
1
|
3751
|
package co.timecrypt.android.activities
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.View
import android.widget.Toast
import co.timecrypt.android.R
import kotlinx.android.synthetic.main.activity_link_display.*
/**
* An activity that handles displaying of the link generated by creating a new Timecrypt message.
*/
class LinkDisplayActivity : AppCompatActivity(), View.OnClickListener, View.OnLongClickListener {
@Suppress("PrivatePropertyName")
private val TAG = LinkDisplayActivity::class.simpleName!!
companion object {
const val KEY_URL = "MESSAGE_URL"
const val KEY_DATE = "MESSAGE_DESTRUCT_DATE"
const val KEY_VIEWS = "MESSAGE_ALLOWED_VIEWS"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// check preconditions, need the message data to continue
val extras = intent.extras
if (extras == null) {
Log.e(TAG, "No bundle provided")
finish()
return
}
val url = extras.getString(KEY_URL, null)
val date = extras.getString(KEY_DATE, null)
val views = extras.getInt(KEY_VIEWS, -1)
if (url == null || date == null || views < 1) {
Log.e(TAG, "Missing bundle date")
finish()
return
}
// all is fine, load the data now
setContentView(R.layout.activity_link_display)
messageUrlDisplay.text = url
messageUrlInfo.text = prepareMessageInfo(date, views)
listOf(messageUrlDisplay, messageUrlCopy, messageUrlShare, buttonNewMessage).forEach {
it.setOnClickListener(this@LinkDisplayActivity)
it.setOnLongClickListener(this@LinkDisplayActivity)
}
}
private fun prepareMessageInfo(date: String, views: Int): String {
val replacementText = resources.getQuantityString(R.plurals.plural_how_many_times, views, views)
return getString(R.string.link_more_info, date, replacementText)
}
override fun onClick(view: View) {
when (view.id) {
messageUrlCopy.id -> {
val clipboard = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
val clip = ClipData.newPlainText(getString(R.string.link_copy_label), messageUrlDisplay.text)
clipboard.primaryClip = clip
Toast.makeText(this, R.string.link_copy_success, Toast.LENGTH_LONG).show()
}
messageUrlShare.id -> {
val i = Intent(Intent.ACTION_SEND)
i.type = "text/plain"
i.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.link_share_content_title))
i.putExtra(Intent.EXTRA_TEXT, messageUrlDisplay.text)
startActivity(Intent.createChooser(i, getString(R.string.link_share_chooser_title)))
}
buttonNewMessage.id -> {
startActivity(Intent(this, CreateMessageActivity::class.java))
finish()
}
messageUrlDisplay.id -> {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(messageUrlDisplay.text.toString())))
finish()
}
}
}
// show hints only for copy and share actions
override fun onLongClick(view: View): Boolean = when (view.id) {
messageUrlCopy.id, messageUrlShare.id -> {
Toast.makeText(this@LinkDisplayActivity, view.contentDescription, Toast.LENGTH_SHORT).show()
true
}
else -> false
}
}
|
apache-2.0
|
961757e9835ce11cedd178516ea56f9f
| 36.888889 | 109 | 0.640896 | 4.492216 | false | false | false | false |
eyneill777/SpacePirates
|
core/src/rustyice/editor/EditorGameView.kt
|
1
|
8137
|
package rustyice.editor
import com.badlogic.gdx.Input
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.g2d.Batch
import com.badlogic.gdx.math.MathUtils
import com.badlogic.gdx.math.Vector2
import com.badlogic.gdx.scenes.scene2d.InputEvent
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener
import com.github.salomonbrys.kodein.instance
import rustyengine.RustyEngine
import rustyice.game.Actor
import rustyice.game.Game
import rustyice.game.tiles.TILE_SIZE
import rustyice.graphics.Camera
import rustyice.graphics.GameDisplay
import rustyice.graphics.drawRect
class EditorGameView(val game: Game, val selectionPane: EditorSelectionPane, val propertyPane: EditorPropertyPane){
val display: GameDisplay
private val editorInput: EditorInput
private val camera: Camera
private var mouseDraging: Boolean = false
private val mouseDownPos: Vector2 = Vector2()
private val mouseDraggedPos: Vector2 = Vector2()
private var selectionActor: Actor? = null
private val selectionDownPos: Vector2 = Vector2()
private val tileSelectStart: Vector2 = Vector2()
private val tileSelectEnd: Vector2 = Vector2()
init {
camera = Camera()
camera.width = 20f
camera.height = 20f
display = GameDisplay()
display.game = game
display.camera = camera
editorInput = EditorInput()
display.addListener(editorInput)
}
fun render(batch: Batch, delta: Float) {
game.currentSection?.finishAddingActors()
if (editorInput.moveUp) {
camera.y += camera.height * delta
}
if (editorInput.moveDown) {
camera.y -= camera.height * delta
}
if (editorInput.moveLeft) {
camera.x -= camera.width * delta
}
if (editorInput.moveRight) {
camera.x += camera.width * delta
}
if (editorInput.zoomIn) {
camera.width *= (1 - 0.75f * delta)
camera.height *= (1 - 0.75f * delta)
}
if (editorInput.zoomOut) {
camera.width *= (1 + 0.75f * delta)
camera.height *= (1 + 0.75f * delta)
}
display.render(batch)
if (selectionPane.isTileMode() && mouseDraging) {
display.fbo!!.begin()
batch.begin()
batch.color = Color.LIGHT_GRAY
batch.drawRect(
tileSelectStart.x * TILE_SIZE,
tileSelectStart.y * TILE_SIZE,
(tileSelectEnd.x - tileSelectStart.x) * TILE_SIZE,
(tileSelectEnd.y - tileSelectStart.y) * TILE_SIZE, 0.1f
)
batch.end()
display.fbo!!.end()
}
}
fun dispose(){
display.dispose()
}
private inner class EditorInput: ClickListener(){
var moveUp = false
var moveDown = false
var moveLeft = false
var moveRight = false
var zoomIn = false
var zoomOut = false
override fun keyDown(event: InputEvent, keycode: Int):Boolean {
when(keycode){
Input.Keys.UP -> moveUp = true
Input.Keys.DOWN -> moveDown = true
Input.Keys.LEFT -> moveLeft = true
Input.Keys.RIGHT -> moveRight = true
Input.Keys.Z -> zoomIn = true
Input.Keys.X -> zoomOut = true
Input.Keys.R -> {
selectionActor?.let{ game.currentSection?.actors?.remove(it) }
selectionActor?.store()
selectionActor = null
}
else -> return false
}
return true
}
override fun keyUp(event: InputEvent, keycode: Int): Boolean {
when (keycode) {
Input.Keys.UP -> moveUp = false
Input.Keys.DOWN -> moveDown = false
Input.Keys.LEFT -> moveLeft = false
Input.Keys.RIGHT -> moveRight = false
Input.Keys.Z -> zoomIn = false
Input.Keys.X -> zoomOut = false
else -> return false
}
return true
}
override fun clicked(event: InputEvent, x: Float, y: Float) {
super.clicked(event, x, y)
event.stage.keyboardFocus = event.listenerActor
if (selectionPane.isActorMode() && selectionPane.hasSelectedActor()) {
val actor = selectionPane.buildSelectedActor()
actor.setPosition(mouseDownPos.x, mouseDownPos.y)
game.currentSection?.addActor(actor)
}
}
override fun touchDown(event: InputEvent, x: Float, y: Float, pointer: Int, button: Int): Boolean {
super.touchDown(event, x, y, pointer, button)
mouseDownPos.set(x, y)
display.stageToSection(mouseDownPos)
val section = game.currentSection
if(section != null) {
if (selectionPane.isActorMode()) {
for (actor in section.actors) {
if (mouseDownPos.x >= actor.x - actor.width / 2 && mouseDownPos.y >= actor.y - actor.height / 2
&& mouseDownPos.x < actor.x + actor.width / 2 && mouseDownPos.y < actor.y + actor.height / 2) {
selectionActor = actor
selectionDownPos.set(actor.x, actor.y)
propertyPane.setSelected(actor)
break
}
}
} else {
val tile = section.tiles.getTileAt(mouseDownPos.x, mouseDownPos.y)
if (tile != null) {
propertyPane.setSelected(tile)
}
}
}
return true
}
override fun touchUp(event: InputEvent, x: Float, y: Float, pointer: Int, button: Int) {
super.touchUp(event, x, y, pointer, button)
selectionActor = null
val section = game.currentSection
if (section != null && selectionPane.hasSelectedTile() && mouseDraging) {
for (i in tileSelectStart.y.toInt() until tileSelectEnd.y.toInt()) {
for (j in tileSelectStart.x.toInt() until tileSelectEnd.x.toInt()) {
section.tiles.setTile(selectionPane.buildSelectedTile(), j, i)
}
}
}
mouseDraging = false
}
override fun touchDragged(event: InputEvent, x: Float, y: Float, pointer: Int) {
super.touchDragged(event, x, y, pointer)
mouseDraging = true
mouseDraggedPos.set(x, y)
display.stageToSection(mouseDraggedPos)
if (selectionPane.isTileMode()) {
if (mouseDownPos.x < mouseDraggedPos.x) {
tileSelectStart.x = tileFloor(mouseDownPos.x)
tileSelectEnd.x = tileCeil(mouseDraggedPos.x)
} else {
tileSelectStart.x = tileFloor(mouseDraggedPos.x)
tileSelectEnd.x = tileCeil(mouseDownPos.x)
}
if (mouseDownPos.y < mouseDraggedPos.y) {
tileSelectStart.y = tileFloor(mouseDownPos.y)
tileSelectEnd.y = tileCeil(mouseDraggedPos.y)
} else {
tileSelectStart.y = tileFloor(mouseDraggedPos.y)
tileSelectEnd.y = tileCeil(mouseDownPos.y)
}
}
selectionActor?.let {
it.x = selectionDownPos.x + mouseDraggedPos.x - mouseDownPos.x
it.y = selectionDownPos.y + mouseDraggedPos.y - mouseDownPos.y
}
}
private fun tileFloor(value: Float): Float{
return MathUtils.floor(value / TILE_SIZE).toFloat()
}
private fun tileCeil(value: Float): Float{
return MathUtils.ceil(value / TILE_SIZE).toFloat()
}
}
}
|
mit
|
383e17427dafe94ee351cd1444cb611d
| 34.225108 | 127 | 0.54627 | 4.538204 | false | false | false | false |
helloworld1/FreeOTPPlus
|
app/src/main/java/org/fedorahosted/freeotp/ui/AddSecretTextWatcher.kt
|
1
|
1314
|
/*
* FreeOTP
*
* Authors: Nathaniel McCallum <[email protected]>
*
* Copyright (C) 2013 Nathaniel McCallum, Red Hat
*
* 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.fedorahosted.freeotp.ui
import android.app.Activity
import android.text.Editable
class AddSecretTextWatcher(activity: Activity) : AddTextWatcher(activity) {
override fun afterTextChanged(s: Editable) {
if (s.isNotEmpty()) {
// Ensure that = is only permitted at the end
var haveData = false
for (i in s.length - 1 downTo 0) {
val c = s[i]
if (c != '=')
haveData = true
else if (haveData)
s.delete(i, i + 1)
}
}
super.afterTextChanged(s)
}
}
|
apache-2.0
|
3415028747441203819f8b9e3fc1c637
| 29.55814 | 75 | 0.633181 | 4.043077 | false | false | false | false |
cfieber/orca
|
orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/handler/ContinueParentStageHandlerTest.kt
|
1
|
8747
|
/*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.q.handler
import com.netflix.spinnaker.orca.ExecutionStatus.*
import com.netflix.spinnaker.orca.ext.beforeStages
import com.netflix.spinnaker.orca.fixture.pipeline
import com.netflix.spinnaker.orca.fixture.stage
import com.netflix.spinnaker.orca.pipeline.model.Execution.ExecutionType.PIPELINE
import com.netflix.spinnaker.orca.pipeline.model.SyntheticStageOwner.STAGE_AFTER
import com.netflix.spinnaker.orca.pipeline.model.SyntheticStageOwner.STAGE_BEFORE
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.orca.q.*
import com.netflix.spinnaker.q.Queue
import com.netflix.spinnaker.spek.and
import com.nhaarman.mockito_kotlin.*
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.dsl.on
import org.jetbrains.spek.api.lifecycle.CachingMode
import org.jetbrains.spek.subject.SubjectSpek
import java.time.Duration
object ContinueParentStageHandlerTest : SubjectSpek<ContinueParentStageHandler>({
val queue: Queue = mock()
val repository: ExecutionRepository = mock()
val retryDelay = Duration.ofSeconds(5)
subject(CachingMode.GROUP) {
ContinueParentStageHandler(queue, repository, retryDelay.toMillis())
}
fun resetMocks() = reset(queue, repository)
listOf(SUCCEEDED, FAILED_CONTINUE).forEach { status ->
describe("running a parent stage after its before stages complete with $status") {
given("other before stages are not yet complete") {
val pipeline = pipeline {
stage {
refId = "1"
type = stageWithSyntheticBefore.type
stageWithSyntheticBefore.buildBeforeStages(this)
stageWithSyntheticBefore.buildTasks(this)
}
}
val message = ContinueParentStage(pipeline.stageByRef("1"), STAGE_BEFORE)
beforeGroup {
pipeline.stageByRef("1<1").status = status
pipeline.stageByRef("1<2").status = RUNNING
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving $message") {
subject.handle(message)
}
it("re-queues the message for later evaluation") {
verify(queue).push(message, retryDelay)
}
}
given("another before stage failed") {
val pipeline = pipeline {
stage {
refId = "1"
type = stageWithSyntheticBefore.type
stageWithSyntheticBefore.buildBeforeStages(this)
stageWithSyntheticBefore.buildTasks(this)
}
}
val message = ContinueParentStage(pipeline.stageByRef("1"), STAGE_BEFORE)
beforeGroup {
pipeline.stageByRef("1<1").status = status
pipeline.stageByRef("1<2").status = TERMINAL
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving $message") {
subject.handle(message)
}
it("does not re-queue the message") {
verifyZeroInteractions(queue)
}
}
given("the parent stage has tasks") {
val pipeline = pipeline {
stage {
refId = "1"
type = stageWithSyntheticBefore.type
stageWithSyntheticBefore.buildBeforeStages(this)
stageWithSyntheticBefore.buildTasks(this)
}
}
val message = ContinueParentStage(pipeline.stageByRef("1"), STAGE_BEFORE)
beforeGroup {
pipeline.stageByRef("1").beforeStages().forEach { it.status = status }
}
and("they have not started yet") {
beforeGroup {
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving $message") {
subject.handle(message)
}
it("runs the parent stage's first task") {
verify(queue).push(StartTask(pipeline.stageByRef("1"), "1"))
}
}
and("they have already started") {
beforeGroup {
pipeline.stageByRef("1").tasks.first().status = RUNNING
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving $message") {
subject.handle(message)
}
it("ignores the message") {
verifyZeroInteractions(queue)
}
}
}
given("the parent stage has no tasks") {
val pipeline = pipeline {
stage {
refId = "1"
type = stageWithSyntheticBeforeAndNoTasks.type
stageWithSyntheticBeforeAndNoTasks.buildBeforeStages(this)
stageWithSyntheticBeforeAndNoTasks.buildTasks(this)
}
}
val message = ContinueParentStage(pipeline.stageByRef("1"), STAGE_BEFORE)
beforeGroup {
pipeline.stageByRef("1").beforeStages().forEach { it.status = status }
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving $message") {
subject.handle(message)
}
it("completes the stage with $status") {
verify(queue).push(CompleteStage(pipeline.stageByRef("1")))
}
}
}
}
listOf(SUCCEEDED, FAILED_CONTINUE).forEach { status ->
describe("running a parent stage after its after stages complete with $status") {
given("other after stages are not yet complete") {
val pipeline = pipeline {
stage {
refId = "1"
type = stageWithParallelAfter.type
stageWithParallelAfter.buildTasks(this)
stageWithParallelAfter.buildAfterStages(this)
}
}
val message = ContinueParentStage(pipeline.stageByRef("1"), STAGE_AFTER)
beforeGroup {
pipeline.stageByRef("1>1").status = status
pipeline.stageByRef("1>2").status = RUNNING
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving $message") {
subject.handle(message)
}
it("re-queues the message for later evaluation") {
verify(queue).push(message, retryDelay)
}
}
given("another after stage failed") {
val pipeline = pipeline {
stage {
refId = "1"
type = stageWithParallelAfter.type
stageWithParallelAfter.buildTasks(this)
stageWithParallelAfter.buildAfterStages(this)
}
}
val message = ContinueParentStage(pipeline.stageByRef("1"), STAGE_AFTER)
beforeGroup {
pipeline.stageByRef("1>1").status = status
pipeline.stageByRef("1>2").status = TERMINAL
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving $message") {
subject.handle(message)
}
it("does nothing") {
verifyZeroInteractions(queue)
}
}
given("all after stages completed") {
val pipeline = pipeline {
stage {
refId = "1"
type = stageWithParallelAfter.type
stageWithParallelAfter.buildTasks(this)
stageWithParallelAfter.buildAfterStages(this)
}
}
val message = ContinueParentStage(pipeline.stageByRef("1"), STAGE_AFTER)
beforeGroup {
pipeline.stageByRef("1>1").status = status
pipeline.stageByRef("1>2").status = SUCCEEDED
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving $message") {
subject.handle(message)
}
it("tells the stage to complete") {
verify(queue).push(CompleteStage(pipeline.stageByRef("1")))
}
}
}
}
})
|
apache-2.0
|
b6d91e171b6598290d5d931ecda4ca3f
| 30.128114 | 86 | 0.62833 | 4.944601 | false | false | false | false |
google/android-fhir
|
datacapture/src/androidTest/java/com/google/android/fhir/datacapture/TestQuestionnaireViewModel.kt
|
1
|
2481
|
/*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.fhir.datacapture
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.viewModelScope
import com.google.android.fhir.datacapture.TestQuestionnaireFragment.Companion.QUESTIONNAIRE_FILE_PATH_KEY
import com.google.android.fhir.datacapture.TestQuestionnaireFragment.Companion.QUESTIONNAIRE_FILE_WITH_VALIDATION_PATH_KEY
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class TestQuestionnaireViewModel(application: Application, private val state: SavedStateHandle) :
AndroidViewModel(application) {
private val backgroundContext = viewModelScope.coroutineContext
private var questionnaireJson: String? = null
private var questionnaireWithValidationJson: String? = null
init {
viewModelScope.launch {
getQuestionnaireJson()
// TODO remove check once all files are added
if (!state.get<String>(QUESTIONNAIRE_FILE_WITH_VALIDATION_PATH_KEY).isNullOrEmpty()) {
getQuestionnaireWithValidationJson()
}
}
}
suspend fun getQuestionnaireJson(): String {
return withContext(backgroundContext) {
if (questionnaireJson == null) {
questionnaireJson = readFileFromAssets(state[QUESTIONNAIRE_FILE_PATH_KEY]!!)
}
questionnaireJson!!
}
}
suspend fun getQuestionnaireWithValidationJson(): String {
return withContext(backgroundContext) {
if (questionnaireWithValidationJson == null) {
questionnaireWithValidationJson =
readFileFromAssets(state[QUESTIONNAIRE_FILE_WITH_VALIDATION_PATH_KEY]!!)
}
questionnaireWithValidationJson!!
}
}
private suspend fun readFileFromAssets(filename: String) =
withContext(backgroundContext) {
javaClass.getResourceAsStream(filename)!!.bufferedReader().use { it.readText() }
}
}
|
apache-2.0
|
86da24c4292cb79c90c2ce2c809b7985
| 36.029851 | 122 | 0.757356 | 4.817476 | false | false | false | false |
code-disaster/lwjgl3
|
modules/lwjgl/core/src/templates/kotlin/core/linux/liburing/templates/io_uring.kt
|
3
|
101060
|
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package core.linux.liburing.templates
import org.lwjgl.generator.*
import core.linux.*
import core.linux.liburing.*
val LibIOURing = "LibIOURing".nativeClass(Module.CORE_LINUX_LIBURING, nativeSubPath = "linux", prefixConstant = "IORING_", prefixMethod = "io_uring_") {
nativeDirective(
"""DISABLE_WARNINGS()
#include "liburing/compat.h"
#include "liburing/io_uring.h"
#include "syscall.h"
ENABLE_WARNINGS()""")
documentation =
"""
Native bindings to ${url("https://github.com/axboe/liburing", "io_uring")}, a Linux-specific API for asynchronous I/O.
It allows the user to submit one or more I/O requests, which are processed asynchronously without blocking the calling process. {@code io_uring} gets
its name from ring buffers which are shared between user space and kernel space. This arrangement allows for efficient I/O, while avoiding the overhead
of copying buffers between them, where possible. This interface makes {@code io_uring} different from other UNIX I/O APIs, wherein, rather than just
communicate between kernel and user space with system calls, ring buffers are used as the main mode of communication. This arrangement has various
performance benefits which are discussed in a separate section below. This man page uses the terms shared buffers, shared ring buffers and queues
interchangeably.
The general programming model you need to follow for io_uring is outlined below
${ul(
"""
Set up shared buffers with #setup() and {@code mmap(2)}, mapping into user space shared buffers for the submission queue (SQ) and the completion
queue (CQ). You place I/O requests you want to make on the SQ, while the kernel places the results of those operations on the CQ.
""",
"""
For every I/O request you need to make (like to read a file, write a file, accept a socket connection, etc), you create a submission queue entry,
or SQE, describe the I/O operation you need to get done and add it to the tail of the submission queue (SQ). Each I/O operation is, in essence, the
equivalent of a system call you would have made otherwise, if you were not using {@code io_uring}. You can add more than one SQE to the queue
depending on the number of operations you want to request.
""",
"After you add one or more SQEs, you need to call #enter() to tell the kernel to dequeue your I/O requests off the SQ and begin processing them.",
"""
For each SQE you submit, once it is done processing the request, the kernel places a completion queue event or CQE at the tail of the completion
queue or CQ. The kernel places exactly one matching CQE in the CQ for every SQE you submit on the SQ. After you retrieve a CQE, minimally, you
might be interested in checking the res field of the CQE structure, which corresponds to the return value of the system call's equivalent, had you
used it directly without using {@code io_uring}. For instance, a read operation under {@code io_uring}, started with the #OP_READ operation, which
issues the equivalent of the {@code read(2)} system call, would return as part of {@code res} what {@code read(2)} would have returned if called
directly, without using {@code io_uring}.
""",
"""
Optionally, #enter() can also wait for a specified number of requests to be processed by the kernel before it returns. If you specified a certain
number of completions to wait for, the kernel would have placed at least those many number of CQEs on the CQ, which you can then readily read,
right after the return from {@code io_uring_enter(2)}.
""",
"""
It is important to remember that I/O requests submitted to the kernel can complete in any order. It is not necessary for the kernel to process one
request after another, in the order you placed them. Given that the interface is a ring, the requests are attempted in order, however that doesn't
imply any sort of ordering on their completion. When more than one request is in flight, it is not possible to determine which one will complete
first. When you dequeue CQEs off the CQ, you should always check which submitted request it corresponds to. The most common method for doing so is
utilizing the {@code user_data} field in the request, which is passed back on the completion side.
"""
)}
Adding to and reading from the queues:
${ul(
"You add SQEs to the tail of the SQ. The kernel reads SQEs off the head of the queue.",
"The kernel adds CQEs to the tail of the CQ. You read CQEs off the head of the queue."
)}
<h3>Submission queue polling</h3>
One of the goals of {@code io_uring} is to provide a means for efficient I/O. To this end, {@code io_uring} supports a polling mode that lets you avoid
the call to #enter(), which you use to inform the kernel that you have queued SQEs on to the SQ. With SQ Polling, {@code io_uring} starts a kernel
thread that polls the submission queue for any I/O requests you submit by adding SQEs. With SQ Polling enabled, there is no need for you to call
{@code io_uring_enter(2)}, letting you avoid the overhead of system calls. A designated kernel thread dequeues SQEs off the SQ as you add them and
dispatches them for asynchronous processing.
<h3>Setting up io_uring</h3>
The main steps in setting up {@code io_uring} consist of mapping in the shared buffers with {@code mmap(2)} calls.
<h3>Submitting I/O requests</h3>
The process of submitting a request consists of describing the I/O operation you need to get done using an {@code io_uring_sqe} structure instance.
These details describe the equivalent system call and its parameters. Because the range of I/O operations Linux supports are very varied and the
{@code io_uring_sqe} structure needs to be able to describe them, it has several fields, some packed into unions for space efficiency.
To submit an I/O request to {@code io_uring}, you need to acquire a submission queue entry (SQE) from the submission queue (SQ), fill it up with
details of the operation you want to submit and call #enter(). If you want to avoid calling {@code io_uring_enter(2)}, you have the option of setting
up Submission Queue Polling.
SQEs are added to the tail of the submission queue. The kernel picks up SQEs off the head of the SQ. The general algorithm to get the next available
SQE and update the tail is as follows.
${codeBlock("""
struct io_uring_sqe *sqe;
unsigned tail, index;
tail = *sqring->tail;
index = tail & (*sqring->ring_mask);
sqe = &sqring->sqes[index];
// fill up details about this I/O request
describe_io(sqe);
// fill the sqe index into the SQ ring array
sqring->array[index] = index;
tail++;
atomic_store_release(sqring->tail, tail);""")}
To get the index of an entry, the application must mask the current tail index with the size mask of the ring. This holds true for both SQs and CQs.
Once the SQE is acquired, the necessary fields are filled in, describing the request. While the CQ ring directly indexes the shared array of CQEs, the
submission side has an indirection array between them. The submission side ring buffer is an index into this array, which in turn contains the index
into the SQEs.
The following code snippet demonstrates how a read operation, an equivalent of a preadv2(2) system call is described by filling up an SQE with the
necessary parameters.
${codeBlock("""
struct iovec iovecs[16];
...
sqe->opcode = IORING_OP_READV;
sqe->fd = fd;
sqe->addr = (unsigned long) iovecs;
sqe->len = 16;
sqe->off = offset;
sqe->flags = 0;""")}
<h4>Memory ordering</h4>
Modern compilers and CPUs freely reorder reads and writes without affecting the program's outcome to optimize performance. Some aspects of this need to
be kept in mind on SMP systems since {@code io_uring} involves buffers shared between kernel and user space. These buffers are both visible and
modifiable from kernel and user space. As heads and tails belonging to these shared buffers are updated by kernel and user space, changes need to be
coherently visible on either side, irrespective of whether a CPU switch took place after the kernel-user mode switch happened. We use memory barriers
to enforce this coherency. Being significantly large subjects on their own, memory barriers are out of scope for further discussion on this man page.
<h4>Letting the kernel know about I/O submissions</h4>
Once you place one or more SQEs on to the SQ, you need to let the kernel know that you've done so. You can do this by calling the #enter() system call.
This system call is also capable of waiting for a specified count of events to complete. This way, you can be sure to find completion events in the
completion queue without having to poll it for events later.
<h3>Reading completion events</h3>
Similar to the submission queue (SQ), the completion queue (CQ) is a shared buffer between the kernel and user space. Whereas you placed submission
queue entries on the tail of the SQ and the kernel read off the head, when it comes to the CQ, the kernel places completion queue events or CQEs on the
tail of the CQ and you read off its head.
Submission is flexible (and thus a bit more complicated) since it needs to be able to encode different types of system calls that take various
parameters. Completion, on the other hand is simpler since we're looking only for a return value back from the kernel. This is easily understood by
looking at the completion queue event structure, ##IOURingCQE.
Here, {@code user_data} is custom data that is passed unchanged from submission to completion. That is, from SQEs to CQEs. This field can be used to
set context, uniquely identifying submissions that got completed. Given that I/O requests can complete in any order, this field can be used to
correlate a submission with a completion. {@code res} is the result from the system call that was performed as part of the submission; its return
value. The {@code flags} field could carry request-specific metadata in the future, but is currently unused.
The general sequence to read completion events off the completion queue is as follows:
${codeBlock("""
unsigned head;
head = *cqring->head;
if (head != atomic_load_acquire(cqring->tail)) {
struct io_uring_cqe *cqe;
unsigned index;
index = head & (cqring->mask);
cqe = &cqring->cqes[index];
// process completed CQE
process_cqe(cqe);
// CQE consumption complete
head++;
}
atomic_store_release(cqring->head, head);""")}
It helps to be reminded that the kernel adds CQEs to the tail of the CQ, while you need to dequeue them off the head. To get the index of an entry at
the head, the application must mask the current head index with the size mask of the ring. Once the CQE has been consumed or processed, the head needs
to be updated to reflect the consumption of the CQE. Attention should be paid to the read and write barriers to ensure successful read and update of
the head.
<h3>io_uring performance</h3>
Because of the shared ring buffers between kernel and user space, {@code io_uring} can be a zero-copy system. Copying buffers to and from becomes
necessary when system calls that transfer data between kernel and user space are involved. But since the bulk of the communication in {@code io_uring}
is via buffers shared between the kernel and user space, this huge performance overhead is completely avoided.
While system calls may not seem like a significant overhead, in high performance applications, making a lot of them will begin to matter. While
workarounds the operating system has in place to deal with Spectre and Meltdown are ideally best done away with, unfortunately, some of these
workarounds are around the system call interface, making system calls not as cheap as before on affected hardware. While newer hardware should not need
these workarounds, hardware with these vulnerabilities can be expected to be in the wild for a long time. While using synchronous programming
interfaces or even when using asynchronous programming interfaces under Linux, there is at least one system call involved in the submission of each
request. In {@code io_uring}, on the other hand, you can batch several requests in one go, simply by queueing up multiple SQEs, each describing an I/O
operation you want and make a single call to #enter(). This is possible due to {@code io_uring}'s shared buffers based design.
While this batching in itself can avoid the overhead associated with potentially multiple and frequent system calls, you can reduce even this overhead
further with Submission Queue Polling, by having the kernel poll and pick up your SQEs for processing as you add them to the submission queue. This
avoids the {@code io_uring_enter(2)} call you need to make to tell the kernel to pick SQEs up. For high-performance applications, this means even
lesser system call overheads.
"""
IntConstant(
"""
If {@code sqe->file_index} is set to this for opcodes that instantiate a new direct descriptor (like {@code openat/openat2/accept}), then io_uring will
allocate an available direct descriptor instead of having the application pass one in.
The picked direct descriptor will be returned in {@code cqe->res}, or {@code -ENFILE} if the space is full.
""",
"FILE_INDEX_ALLOC".."~0"
)
IntConstant("", "MAX_ENTRIES".."4096")
EnumConstant(
"{@code io_uring_sqe->flags} bits",
"IOSQE_FIXED_FILE_BIT".enum("", "0"),
"IOSQE_IO_DRAIN_BIT".enum,
"IOSQE_IO_LINK_BIT".enum,
"IOSQE_IO_HARDLINK_BIT".enum,
"IOSQE_ASYNC_BIT".enum,
"IOSQE_BUFFER_SELECT_BIT".enum,
"IOSQE_CQE_SKIP_SUCCESS_BIT".enum
).noPrefix()
EnumConstant(
"{@code io_uring_sqe->flags} bitfield values",
"IOSQE_FIXED_FILE".enum(
"""
When this flag is specified, {@code fd} is an index into the files array registered with the {@code io_uring} instance (see the #REGISTER_FILES
section of the #register() man page).
Note that this isn't always available for all commands. If used on a command that doesn't support fixed files, the SQE will error with
{@code -EBADF}.
Available since 5.1.
""",
"1 << IOSQE_FIXED_FILE_BIT"),
"IOSQE_IO_DRAIN".enum(
"""
When this flag is specified, the SQE will not be started before previously submitted SQEs have completed, and new SQEs will not be started before
this one completes.
Available since 5.2.
""",
"1 << IOSQE_IO_DRAIN_BIT"
),
"IOSQE_IO_LINK".enum(
"""
When this flag is specified, it forms a link with the next SQE in the submission ring.
That next SQE will not be started before the previous request completes. This, in effect, forms a chain of SQEs, which can be arbitrarily long. The
tail of the chain is denoted by the first SQE that does not have this flag set. Chains are not supported across submission boundaries. Even if the
last SQE in a submission has this flag set, it will still terminate the current chain. This flag has no effect on previous SQE submissions, nor
does it impact SQEs that are outside of the chain tail. This means that multiple chains can be executing in parallel, or chains and individual
SQEs. Only members inside the chain are serialized. A chain of SQEs will be broken, if any request in that chain ends in error. {@code io_uring}
considers any unexpected result an error. This means that, eg, a short read will also terminate the remainder of the chain. If a chain of SQE links
is broken, the remaining unstarted part of the chain will be terminated and completed with {@code -ECANCELED} as the error code.
Available since 5.3.
""",
"1 << IOSQE_IO_LINK_BIT"
),
"IOSQE_IO_HARDLINK".enum(
"""
Like #IOSQE_IO_LINK, but it doesn't sever regardless of the completion result.
Note that the link will still sever if we fail submitting the parent request, hard links are only resilient in the presence of completion results
for requests that did submit correctly. {@code IOSQE_IO_HARDLINK} implies {@code IOSQE_IO_LINK}.
Available since 5.5.
""",
"1 << IOSQE_IO_HARDLINK_BIT"
),
"IOSQE_ASYNC".enum(
"""
Normal operation for {@code io_uring} is to try and issue an sqe as non-blocking first, and if that fails, execute it in an async manner.
To support more efficient overlapped operation of requests that the application knows/assumes will always (or most of the time) block, the
application can ask for an sqe to be issued async from the start.
Available since 5.6.
""",
"1 << IOSQE_ASYNC_BIT"
),
"IOSQE_BUFFER_SELECT".enum(
"""
Used in conjunction with the #OP_PROVIDE_BUFFERS command, which registers a pool of buffers to be used by commands that read or receive data.
When buffers are registered for this use case, and this flag is set in the command, {@code io_uring} will grab a buffer from this pool when the
request is ready to receive or read data. If successful, the resulting CQE will have #CQE_F_BUFFER set in the flags part of the struct, and the
upper #CQE_BUFFER_SHIFT bits will contain the ID of the selected buffers. This allows the application to know exactly which buffer was selected for
the operation. If no buffers are available and this flag is set, then the request will fail with {@code -ENOBUFS} as the error code. Once a buffer
has been used, it is no longer available in the kernel pool. The application must re-register the given buffer again when it is ready to recycle it
(eg has completed using it).
Available since 5.7.
""",
"1 << IOSQE_BUFFER_SELECT_BIT"
),
"IOSQE_CQE_SKIP_SUCCESS".enum(
"""
Don't generate a CQE if the request completes successfully.
If the request fails, an appropriate CQE will be posted as usual and if there is no #IOSQE_IO_HARDLINK, CQEs for all linked requests will be
omitted. The notion of failure/success is {@code opcode} specific and is the same as with breaking chains of #IOSQE_IO_LINK. One special case is
when the request has a linked timeout, then the CQE generation for the linked timeout is decided solely by whether it has
{@code IOSQE_CQE_SKIP_SUCCESS} set, regardless whether it timed out or was cancelled. In other words, if a linked timeout has the flag set, it's
guaranteed to not post a CQE.
The semantics are chosen to accommodate several use cases. First, when all but the last request of a normal link without linked timeouts are marked
with the flag, only one CQE per link is posted. Additionally, it enables supression of CQEs in cases where the side effects of a successfully
executed operation is enough for userspace to know the state of the system. One such example would be writing to a synchronisation file.
This flag is incompatible with #IOSQE_IO_DRAIN. Using both of them in a single ring is undefined behavior, even when they are not used together in
a single request. Currently, after the first request with {@code IOSQE_CQE_SKIP_SUCCESS}, all subsequent requests marked with drain will be failed
at submission time. Note that the error reporting is best effort only, and restrictions may change in the future.
Available since 5.17.
""",
"1 << IOSQE_CQE_SKIP_SUCCESS_BIT"
)
).noPrefix()
EnumConstant(
"{@code io_uring_setup()} flags",
"SETUP_IOPOLL".enum(
"""
Perform busy-waiting for an I/O completion, as opposed to getting notifications via an asynchronous IRQ (Interrupt Request).
The file system (if any) and block device must support polling in order for this to work. Busy-waiting provides lower latency, but may consume more
CPU resources than interrupt driven I/O. Currently, this feature is usable only on a file descriptor opened using the {@code O_DIRECT} flag. When a
read or write is submitted to a polled context, the application must poll for completions on the CQ ring by calling #enter(). It is illegal to mix
and match polled and non-polled I/O on an io_uring instance.
""",
"1 << 0"
),
"SETUP_SQPOLL".enum(
"""
When this flag is specified, a kernel thread is created to perform submission queue polling.
An {@code io_uring} instance configured in this way enables an application to issue I/O without ever context switching into the kernel. By using
the submission queue to fill in new submission queue entries and watching for completions on the completion queue, the application can submit and
reap I/Os without doing a single system call.
If the kernel thread is idle for more than {@code sq_thread_idle} milliseconds, it will set the #SQ_NEED_WAKEUP bit in the flags field of the
struct {@code io_sq_ring}. When this happens, the application must call #enter() to wake the kernel thread. If I/O is kept busy, the kernel thread
will never sleep. An application making use of this feature will need to guard the {@code io_uring_enter()} call with the following code sequence:
${codeBlock("""
// Ensure that the wakeup flag is read after the tail pointer
// has been written. It's important to use memory load acquire
// semantics for the flags read, as otherwise the application
// and the kernel might not agree on the consistency of the
// wakeup flag.
unsigned flags = atomic_load_relaxed(sq_ring->flags);
if (flags & IORING_SQ_NEED_WAKEUP)
io_uring_enter(fd, 0, 0, IORING_ENTER_SQ_WAKEUP);""")}
where {@code sq_ring} is a submission queue ring setup using the struct {@code io_sqring_offsets} described below.
Before version 5.11 of the Linux kernel, to successfully use this feature, the application must register a set of files to be used for IO through
#register() using the #REGISTER_FILES opcode. Failure to do so will result in submitted IO being errored with {@code EBADF}. The presence of this
feature can be detected by the #FEAT_SQPOLL_NONFIXED feature flag. In version 5.11 and later, it is no longer necessary to register files to use
this feature. 5.11 also allows using this as non-root, if the user has the {@code CAP_SYS_NICE} capability.
""",
"1 << 1"
),
"SETUP_SQ_AFF".enum(
"""
If this flag is specified, then the poll thread will be bound to the cpu set in the {@code sq_thread_cpu} field of the struct
{@code io_uring_params}. This flag is only meaningful when #SETUP_SQPOLL is specified. When {@code cgroup} setting {@code cpuset.cpus} changes
(typically in container environment), the bounded cpu set may be changed as well.
""",
"1 << 2"
),
"SETUP_CQSIZE".enum(
"""
Create the completion queue with struct {@code io_uring_params.cq_entries} entries.
The value must be greater than entries, and may be rounded up to the next power-of-two.
""",
"1 << 3"
),
"SETUP_CLAMP".enum(
"""
If this flag is specified, and if entries exceeds #MAX_ENTRIES, then entries will be clamped at {@code IORING_MAX_ENTRIES}.
If the flag #SETUP_SQPOLL is set, and if the value of struct {@code io_uring_params.cq_entries} exceeds {@code IORING_MAX_CQ_ENTRIES}, then it will
be clamped at {@code IORING_MAX_CQ_ENTRIES}.
""",
"1 << 4"
),
"SETUP_ATTACH_WQ".enum(
"""
This flag should be set in conjunction with struct {@code io_uring_params.wq_fd} being set to an existing {@code io_uring} ring file descriptor.
When set, the {@code io_uring} instance being created will share the asynchronous worker thread backend of the specified {@code io_uring} ring,
rather than create a new separate thread pool.
""",
"1 << 5"
),
"SETUP_R_DISABLED".enum(
"""
If this flag is specified, the io_uring ring starts in a disabled state.
In this state, restrictions can be registered, but submissions are not allowed. See #register() for details on how to enable the ring.
Available since 5.10.
""",
"1 << 6"
),
"SETUP_SUBMIT_ALL".enum(
"""
Continue submit on error.
Normally io_uring stops submitting a batch of request, if one of these requests results in an error. This can cause submission of less than what is
expected, if a request ends in error while being submitted. If the ring is created with this flag, #enter() will continue submitting requests even
if it encounters an error submitting a request. CQEs are still posted for errored request regardless of whether or not this flag is set at ring
creation time, the only difference is if the submit sequence is halted or continued when an error is observed.
Available since 5.18.
""",
"1 << 7"
),
"SETUP_COOP_TASKRUN".enum(
"""
Cooperative task running.
By default, io_uring will interrupt a task running in userspace when a completion event comes in. This is to ensure that completions run in a
timely manner. For a lot of use cases, this is overkill and can cause reduced performance from both the inter-processor interrupt used to do this,
the kernel/user transition, the needless interruption of the tasks userspace activities, and reduced batching if completions come in at a rapid
rate. Most applications don't need the forceful interruption, as the events are processed at any kernel/user transition. The exception are setups
where the application uses multiple threads operating on the same ring, where the application waiting on completions isn't the one that submitted
them. For most other use cases, setting this flag will improve performance.
Available since 5.19.
""",
"1 << 8"
),
"SETUP_TASKRUN_FLAG".enum(
"""
Used in conjunction with #SETUP_COOP_TASKRUN, this provides a flag, #SQ_TASKRUN, which is set in the SQ ring {@code flags} whenever completions are
pending that should be processed. liburing will check for this flag even when doing #peek_cqe() and enter the kernel to process them, and
applications can do the same. This makes {@code IORING_SETUP_TASKRUN_FLAG} safe to use even when applications rely on a peek style operation on the
CQ ring to see if anything might be pending to reap.
Available since 5.19.
""",
"1 << 9"
),
"SETUP_SQE128".enum(
"""
If set, io_uring will use 128-byte SQEs rather than the normal 64-byte sized variant.
This is a requirement for using certain request types, as of 5.19 only the #OP_URING_CMD passthrough command for NVMe passthrough needs this.
Available since 5.19.
""",
"1 << 10"
),
"SETUP_CQE32".enum(
"""
If set, io_uring will use 32-byte CQEs rather than the normal 32-byte sized variant.
This is a requirement for using certain request types, as of 5.19 only the #OP_URING_CMD passthrough command for NVMe passthrough needs this.
Available since 5.19.
""",
"1 << 11"
),
"SETUP_SINGLE_ISSUER".enum(
"""
A hint to the kernel that only a single task can submit requests, which is used for internal optimisations.
The kernel enforces the rule, which only affects #enter() calls submitting requests and will fail them with {@code -EEXIST} if the restriction is
violated. The submitter task may differ from the task that created the ring. Note that when #SETUP_SQPOLL is set it is considered that the polling
task is doing all submissions on behalf of the userspace and so it always complies with the rule disregarding how many userspace tasks do
{@code io_uring_enter}.
Available since 5.20.
""",
"1 << 12"
),
"SETUP_DEFER_TASKRUN".enum(
"""
Defer running task work to get events.
By default, io_uring will process all outstanding work at the end of any system call or thread interrupt. This can delay the application from
making other progress. Setting this flag will hint to io_uring that it should defer work until an #enter() call with the #ENTER_GETEVENTS flag set.
This allows the application to request work to run just before it wants to process completions. This flag requires the #SETUP_SINGLE_ISSUER flag to
be set, and also enforces that the call to {@code io_uring_enter} is called from the same thread that submitted requests. Note that if this flag is
set then it is the application's responsibility to periodically trigger work (for example via any of the CQE waiting functions) or else completions
may not be delivered.
Available since 6.1.
""",
"1 << 13"
)
)
EnumConstantByte(
"{@code io_uring_op}",
"OP_NOP".enumByte("Do not perform any I/O. This is useful for testing the performance of the {@code io_uring} implementation itself.", "0"),
"OP_READV".enumByte("Vectored read operation, similar to {@code preadv2(2)}. If the file is not seekable, {@code off} must be set to zero."),
"OP_WRITEV".enumByte("Vectored write operation, similar to {@code pwritev2(2)}. If the file is not seekable, {@code off} must be set to zero."),
"OP_FSYNC".enumByte(
"""
File sync. See also {@code fsync(2)}.
Note that, while I/O is initiated in the order in which it appears inthe submission queue, completions are unordered. For example, an application
which places a write I/O followed by an fsync in the submission queue cannot expect the fsync to apply to the write. The two operations execute in
parallel, so the fsync may complete before the write is issued to the storage. The same is also true for previously issued writes that have not
completed prior to the fsync.
"""
),
"OP_READ_FIXED".enumByte("Read from pre-mapped buffers. See #register() for details on how to setup a context for fixed reads."),
"OP_WRITE_FIXED".enumByte("Write to pre-mapped buffers. See #register() for details on how to setup a context for fixed writes."),
"OP_POLL_ADD".enumByte(
"""
Poll the {@code fd} specified in the submission queue entry for the events specified in the {@code poll_events} field.
Unlike poll or epoll without {@code EPOLLONESHOT}, by default this interface always works in one shot mode. That is, once the poll operation is
completed, it will have to be resubmitted.
If #POLL_ADD_MULTI is set in the SQE {@code len} field, then the poll will work in multi shot mode instead. That means it'll repatedly trigger when
the requested event becomes true, and hence multiple CQEs can be generated from this single SQE. The CQE {@code flags} field will have #CQE_F_MORE
set on completion if the application should expect further CQE entries from the original request. If this flag isn't set on completion, then the
poll request has been terminated and no further events will be generated. This mode is available since 5.13.
If #POLL_UPDATE_EVENTS is set in the SQE {@code len} field, then the request will update an existing poll request with the mask of events passed in
with this request. The lookup is based on the {@code user_data} field of the original SQE submitted, and this values is passed in the {@code addr}
field of the SQE. This mode is available since 5.13.
If #POLL_UPDATE_USER_DATA is set in the SQE {@code len} field, then the request will update the {@code user_data} of an existing poll request based
on the value passed in the {@code off} field. This mode is available since 5.13.
This command works like an {@code asyncpoll(2)} and the completion event result is the returned mask of events. For the variants that update
{@code user_data} or {@code events}, the completion result will be similar to #OP_POLL_REMOVE.
"""
),
"OP_POLL_REMOVE".enumByte(
"""
Remove an existing poll request.
If found, the {@code res} field of the struct {@code io_uring_cqe} will contain 0. If not found, {@code res} will contain {@code -ENOENT}, or
{@code -EALREADY} if the poll request was in the process of completing already.
"""
),
"OP_SYNC_FILE_RANGE".enumByte(
"""
Issue the equivalent of a {@code sync_file_range(2)} on the file descriptor.
The {@code fd} field is the file descriptor to sync, the {@code off} field holds the offset in bytes, the {@code len} field holds the length in
bytes, and the {@code sync_range_flags} field holds the flags for the command. See also {@code sync_file_range(2)} for the general description of
the related system call.
Available since 5.2.
"""
),
"OP_SENDMSG".enumByte(
"""
Issue the equivalent of a {@code sendmsg(2)} system call.
{@code fd} must be set to the socket file descriptor, {@code addr} must contain a pointer to the {@code msghdr} structure, and {@code msg_flags}
holds the flags associated with the system call. See also {@code sendmsg(2)} for the general description of the related system call.
Available since 5.3.
"""
),
"OP_RECVMSG".enumByte(
"""
Works just like #OP_SENDMSG, except for {@code recvmsg(2)} instead. See the description of {@code IORING_OP_SENDMSG}.
Available since 5.3.
"""
),
"OP_TIMEOUT".enumByte(
"""
This command will register a timeout operation.
The {@code addr} field must contain a pointer to a {@code struct timespec64} structure, {@code len} must contain 1 to signify one
{@code timespec64} structure, {@code timeout_flags} may contain #TIMEOUT_ABS for an absolute timeout value, or 0 for a relative timeout.
{@code off} may contain a completion event count. A timeout will trigger a wakeup event on the completion ring for anyone waiting for events. A
timeout condition is met when either the specified timeout expires, or the specified number of events have completed. Either condition will trigger
the event. If set to 0, completed events are not counted, which effectively acts like a timer. {@code io_uring} timeouts use the
{@code CLOCK_MONOTONIC} clock source. The request will complete with {@code -ETIME} if the timeout got completed through expiration of the timer,
or 0 if the timeout got completed through requests completing on their own. If the timeout was cancelled before it expired, the request will
complete with {@code -ECANCELED}.
Available since 5.4.
Since 5.15, this command also supports the following modifiers in {@code timeout_flags}:
${ul(
"""
#TIMEOUT_BOOTTIME: If set, then the clock source used is {@code CLOCK_BOOTTIME} instead of {@code CLOCK_MONOTONIC}. This clock source differs
in that it includes time elapsed if the system was suspend while having a timeout request in-flight.
""",
"#TIMEOUT_REALTIME: If set, then the clock source used is {@code CLOCK_BOOTTIME} instead of {@code CLOCK_MONOTONIC}."
)}
"""
),
"OP_TIMEOUT_REMOVE".enumByte(
"""
If {@code timeout_flags} are zero, then it attempts to remove an existing timeout operation. {@code addr} must contain the {@code user_data} field
of the previously issued timeout operation. If the specified timeout request is found and cancelled successfully, this request will terminate with
a result value of 0. If the timeout request was found but expiration was already in progress, this request will terminate with a result value of
{@code -EBUSY}. If the timeout request wasn't found, the request will terminate with a result value of {@code -ENOENT}.
Available since 5.5.
If {@code timeout_flags} contain #TIMEOUT_UPDATE, instead of removing an existing operation, it updates it. {@code addr} and return values are same
as before. {@code addr2} field must contain a pointer to a {@code struct timespec64} structure. {@code timeout_flags} may also contain
#TIMEOUT_ABS, in which case the value given is an absolute one, not a relative one.
Available since 5.11.
"""
),
"OP_ACCEPT".enumByte(
"""
Issue the equivalent of an {@code accept4(2)} system call.
{@code fd} must be set to the socket file descriptor, {@code addr} must contain the pointer to the {@code sockaddr} structure, and {@code addr2}
must contain a pointer to the {@code socklen_t} {@code addrlen} field. Flags can be passed using the {@code accept_flags} field. See also
{@code accept4(2)} for the general description of the related system call.
Available since 5.5.
If the {@code file_index} field is set to a positive number, the file won't be installed into the normal file table as usual but will be placed
into the fixed file table at index {@code file_index - 1}. In this case, instead of returning a file descriptor, the result will contain either 0
on success or an error. If the index points to a valid empty slot, the installation is guaranteed to not fail. If there is already a file in the
slot, it will be replaced, similar to #OP_FILES_UPDATE. Please note that only {@code io_uring} has access to such files and no other syscall can
use them. See #IOSQE_FIXED_FILE and #REGISTER_FILES.
Available since 5.5.
"""
),
"OP_ASYNC_CANCEL".enumByte(
"""
Attempt to cancel an already issued request.
{@code addr} must contain the {@code user_data} field of the request that should be cancelled. The cancellation request will complete with one of
the following results codes. If found, the {@code res} field of the cqe will contain 0. If not found, {@code res} will contain {@code -ENOENT}. If
found and attempted cancelled, the {@code res} field will contain {@code -EALREADY}. In this case, the request may or may not terminate. In
general, requests that are interruptible (like socket IO) will get cancelled, while disk IO requests cannot be cancelled if already started.
Available since 5.5.
"""
),
"OP_LINK_TIMEOUT".enumByte(
"""
This request must be linked with another request through #IOSQE_IO_LINK which is described below.
Unlike #OP_TIMEOUT, {@code IORING_OP_LINK_TIMEOUT} acts on the linked request, not the completion queue. The format of the command is otherwise
like {@code IORING_OP_TIMEOUT}, except there's no completion event count as it's tied to a specific request. If used, the timeout specified in the
command will cancel the linked command, unless the linked command completes before the timeout. The timeout will complete with {@code -ETIME} if
the timer expired and the linked request was attempted cancelled, or {@code -ECANCELED} if the timer got cancelled because of completion of the
linked request. Like {@code IORING_OP_TIMEOUT} the clock source used is {@code CLOCK_MONOTONIC}.
Available since 5.5.
"""
),
"OP_CONNECT".enumByte(
"""
Issue the equivalent of a {@code connect(2)} system call.
{@code fd} must be set to the socket file descriptor, {@code addr} must contain the const pointer to the {@code sockaddr} structure, and
{@code off} must contain the {@code socklen_t} {@code addrlen} field. See also {@code connect(2)} for the general description of the related system
call.
Available since 5.5.
"""
),
"OP_FALLOCATE".enumByte(
"""
Issue the equivalent of a {@code fallocate(2)} system call.
{@code fd} must be set to the file descriptor, {@code len} must contain the mode associated with the operation, {@code off} must contain the offset
on which to operate, and {@code addr} must contain the length. See also {@code fallocate(2)} for the general description of the related system
call.
Available since 5.6.
"""
),
"OP_OPENAT".enumByte(
"""
Issue the equivalent of a {@code openat(2)} system call.
{@code fd} is the {@code dirfd} argument, {@code addr} must contain a pointer to the {@code *pathname} argument, {@code open_flags} should contain
any flags passed in, and {@code len} is access mode of the file. See also {@code openat(2)} for the general description of the related system call.
Available since 5.6.
If the {@code file_index} field is set to a positive number, the file won't be installed into the normal file table as usual but will be placed
into the fixed file table at index {@code file_index - 1}. In this case, instead of returning a file descriptor, the result will contain either 0
on success or an error. If there is already a file registered at this index, the request will fail with {@code -EBADF}. Only {@code io_uring} has
access to such files and no other syscall can use them. See #IOSQE_FIXED_FILE and #REGISTER_FILES.
Available since 5.15.
"""
),
"OP_CLOSE".enumByte(
"""
Issue the equivalent of a {@code close(2)} system call.
{@code fd} is the file descriptor to be closed. See also {@code close(2)} for the general description of the related system call.
Available since 5.6.
If the {@code file_index} field is set to a positive number, this command can be used to close files that were direct opened through #OP_OPENAT,
#OP_OPENAT2, or #OP_ACCEPT using the {@code io_uring} specific direct descriptors. Note that only one of the descriptor fields may be set. The
direct close feature is available since the 5.15 kernel, where direct descriptors were introduced.
"""
),
"OP_FILES_UPDATE".enumByte(
"""
This command is an alternative to using #REGISTER_FILES_UPDATE which then works in an async fashion, like the rest of the {@code io_uring}
commands.
The arguments passed in are the same. {@code addr} must contain a pointer to the array of file descriptors, {@code len} must contain the length of
the array, and {@code off} must contain the offset at which to operate. Note that the array of file descriptors pointed to in {@code addr} must
remain valid until this operation has completed.
Available since 5.6.
"""
),
"OP_STATX".enumByte(
"""
Issue the equivalent of a {@code statx(2)} system call.
{@code fd} is the {@code dirfd} argument, {@code addr} must contain a pointer to the {@code *pathname} string, {@code statx_flags} is the
{@code flags} argument, {@code len} should be the {@code mask} argument, and {@code off} must contain a pointer to the {@code statxbuf} to be
filled in. See also {@code statx(2)} for the general description of the related system call.
Available since 5.6.
"""
),
"OP_READ".enumByte(
"""
Issue the equivalent of a {@code pread(2)} or {@code pwrite(2)} system call.
{@code fd} is the file descriptor to be operated on, {@code addr} contains the buffer in question, {@code len} contains the length of the IO
operation, and {@code offs} contains the read or write offset. If {@code fd} does not refer to a seekable file, {@code off} must be set to zero.
If {@code offs} is set to -1, the offset will use (and advance) the file position, like the {@code read(2)} and {@code write(2)} system calls.
These are non-vectored versions of the #OP_READV and #OP_WRITEV opcodes. See also {@code read(2)} and {@code write(2)} for the general description
of the related system call.
Available since 5.6.
"""
),
"OP_WRITE".enumByte("See #OP_READ."),
"OP_FADVISE".enumByte(
"""
Issue the equivalent of a {@code posix_fadvise(2)} system call.
{@code fd} must be set to the file descriptor, {@code off} must contain the offset on which to operate, {@code len} must contain the length, and
{@code fadvise_advice} must contain the advice associated with the operation. See also {@code posix_fadvise(2)} for the general description of the
related system call.
Available since 5.6.
"""
),
"OP_MADVISE".enumByte(
"""
Issue the equivalent of a {@code madvise(2)} system call.
{@code addr} must contain the address to operate on, {@code len} must contain the length on which to operate, and {@code fadvise_advice} must
contain the advice associated with the operation. See also {@code madvise(2)} for the general description of the related system call.
Available since 5.6.
"""
),
"OP_SEND".enumByte(
"""
Issue the equivalent of a {@code send(2)} system call.
{@code fd} must be set to the socket file descriptor, {@code addr} must contain a pointer to the buffer, {@code len} denotes the length of the
buffer to send, and {@code msg_flags} holds the flags associated with the system call. See also {@code send(2)} for the general description of the
related system call.
Available since 5.6.
"""
),
"OP_RECV".enumByte(
"""
Works just like #OP_SEND, except for {@code recv(2)} instead. See the description of {@code IORING_OP_SEND}.
Available since 5.6.
"""
),
"OP_OPENAT2".enumByte(
"""
Issue the equivalent of a {@code openat2(2)} system call.
{@code fd} is the {@code dirfd} argument, {@code addr} must contain a pointer to the {@code *pathname} argument, {@code len} should contain the
size of the {@code open_how} structure, and {@code off} should be set to the address of the {@code open_how} structure. See also {@code openat2(2)}
for the general description of the related system call.
Available since 5.6.
If the {@code file_index} field is set to a positive number, the file won't be installed into the normal file table as usual but will be placed
into the fixed file table at index {@code file_index - 1}. In this case, instead of returning a file descriptor, the result will contain either 0
on success or an error. If there is already a file registered at this index, the request will fail with {@code -EBADF}. Only {@code io_uring} has
access to such files and no other syscall can use them. See #IOSQE_FIXED_FILE and #REGISTER_FILES.
Available since 5.15.
"""
),
"OP_EPOLL_CTL".enumByte(
"""
Add, remove or modify entries in the interest list of {@code epoll(7)}. See {@code epoll_ctl(2)} for details of the system call.
{@code fd} holds the file descriptor that represents the epoll instance, {@code addr} holds the file descriptor to add, remove or modify,
{@code len} holds the operation ({@code EPOLL_CTL_ADD}, {@code EPOLL_CTL_DEL}, {@code EPOLL_CTL_MOD}) to perform and, {@code off} holds a pointer
to the {@code epoll_events} structure.
Available since 5.6.
"""
),
"OP_SPLICE".enumByte(
"""
Issue the equivalent of a {@code splice(2)} system call.
{@code splice_fd_in} is the file descriptor to read from, {@code splice_off_in} is an offset to read from, {@code fd} is the file descriptor to
write to, {@code off} is an offset from which to start writing to. A sentinel value of -1 is used to pass the equivalent of a #NULL for the offsets
to {@code splice(2)}. {@code len} contains the number of bytes to copy. {@code splice_flags} contains a bit mask for the flag field associated with
the system call. Please note that one of the file descriptors must refer to a pipe. See also {@code splice(2)} for the general description of the
related system call.
Available since 5.7.
"""
),
"OP_PROVIDE_BUFFERS".enumByte(
"""
This command allows an application to register a group of buffers to be used by commands that read/receive data.
Using buffers in this manner can eliminate the need to separate the poll + read, which provides a convenient point in time to allocate a buffer for
a given request. It's often infeasible to have as many buffers available as pending reads or receive. With this feature, the application can have
its pool of buffers ready in the kernel, and when the file or socket is ready to read/receive data, a buffer can be selected for the operation.
{@code fd} must contain the number of buffers to provide, {@code addr} must contain the starting address to add buffers from, {@code len} must
contain the length of each buffer to add from the range, {@code buf_group} must contain the group ID of this range of buffers, and {@code off} must
contain the starting buffer ID of this range of buffers. With that set, the kernel adds buffers starting with the memory address in {@code addr},
each with a length of {@code len}. Hence the application should provide {@code len * fd} worth of memory in {@code addr}. Buffers are grouped by
the group ID, and each buffer within this group will be identical in size according to the above arguments. This allows the application to provide
different groups of buffers, and this is often used to have differently sized buffers available depending on what the expectations are of the
individual request. When submitting a request that should use a provided buffer, the #IOSQE_BUFFER_SELECT flag must be set, and {@code buf_group}
must be set to the desired buffer group ID where the buffer should be selected from.
Available since 5.7.
"""
),
"OP_REMOVE_BUFFERS".enumByte(
"""
Remove buffers previously registered with #OP_PROVIDE_BUFFERS.
{@code fd} must contain the number of buffers to remove, and {@code buf_group} must contain the buffer group ID from which to remove the buffers.
Available since 5.7.
"""
),
"OP_TEE".enumByte(
"""
Issue the equivalent of a {@code tee(2)} system call.
{@code splice_fd_in} is the file descriptor to read from, {@code fd} is the file descriptor to write to, {@code len} contains the number of bytes
to copy, and {@code splice_flags} contains a bit mask for the flag field associated with the system call. Please note that both of the file
descriptors must refer to a pipe. See also {@code tee(2)} for the general description of the related system call.
Available since 5.8.
"""
),
"OP_SHUTDOWN".enumByte(
"""
Issue the equivalent of a {@code shutdown(2)} system call.
{@code fd} is the file descriptor to the socket being shutdown and {@code len} must be set to the {@code how} argument. No other fields should be
set.
Available since 5.11.
"""
),
"OP_RENAMEAT".enumByte(
"""
Issue the equivalent of a {@code renameat2(2)} system call.
{@code fd} should be set to the {@code olddirfd}, {@code addr} should be set to the {@code oldpath}, {@code len} should be set to the
{@code newdirfd}, {@code addr} should be set to the {@code oldpath}, {@code addr2} should be set to the {@code newpath}, and finally
{@code rename_flags} should be set to the {@code flags} passed in to {@code renameat2(2)}.
Available since 5.11.
"""
),
"OP_UNLINKAT".enumByte(
"""
Issue the equivalent of a {@code unlinkat2(2)} system call.
{@code fd} should be set to the {@code dirfd}, {@code addr} should be set to the {@code pathname}, and {@code unlink_flags} should be set to the
{@code flags} being passed in to {@code unlinkat(2)}.
Available since 5.11.
"""
),
"OP_MKDIRAT".enumByte(
"""
Issue the equivalent of a {@code mkdirat2(2)} system call.
{@code fd} should be set to the {@code dirfd}, {@code addr} should be set to the {@code pathname}, and {@code len} should be set to the
{@code mode} being passed in to {@code mkdirat(2)}.
Available since 5.15.
"""
),
"OP_SYMLINKAT".enumByte(
"""
Issue the equivalent of a {@code symlinkat2(2)} system call.
{@code fd} should be set to the {@code newdirfd}, {@code addr} should be set to the {@code target} and {@code addr2} should be set to the
{@code linkpath} being passed in to {@code symlinkat(2)}.
Available since 5.15.
"""
),
"OP_LINKAT".enumByte(
"""
Issue the equivalent of a {@code linkat2(2)} system call.
{@code fd} should be set to the {@code olddirfd}, {@code addr} should be set to the {@code oldpath}, {@code len} should be set to the
{@code newdirfd}, {@code addr2} should be set to the {@code newpath}, and {@code hardlink_flags} should be set to the {@code flags} being passed in
{@code tolinkat(2)}.
Available since 5.15.
"""
),
"OP_MSG_RING".enumByte(
"""
Send a message to an io_uring.
{@code fd} must be set to a file descriptor of a ring that the application has access to, {@code len} can be set to any 32-bit value that the
application wishes to pass on, and {@code off} should be set any 64-bit value that the application wishes to send. On the target ring, a CQE will
be posted with the {@code res} field matching the {@code len} set, and a {@code user_data} field matching the {@code off} value being passed in.
This request type can be used to either just wake or interrupt anyone waiting for completions on the target ring, or it can be used to pass
messages via the two fields.
Available since 5.18.
"""
),
"OP_FSETXATTR".enumByte,
"OP_SETXATTR".enumByte,
"OP_FGETXATTR".enumByte,
"OP_GETXATTR".enumByte,
"OP_SOCKET".enumByte,
"OP_URING_CMD".enumByte,
"OP_SEND_ZC".enumByte(
"""
Issue the zerocopy equivalent of a {@code send(2)} system call.
Similar to #OP_SEND, but tries to avoid making intermediate copies of data. Zerocopy execution is not guaranteed and it may fall back to copying.
The {@code flags} field of the first {@code "struct io_uring_cqe"} may likely contain #CQE_F_MORE, which means that there will be a second
completion event / notification for the request, with the {@code user_data} field set to the same value. The user must not modify the data buffer
until the notification is posted. The first cqe follows the usual rules and so its {@code res} field will contain the number of bytes sent or a
negative error code. The notification's {@code res} field will be set to zero and the {@code flags} field will contain #CQE_F_NOTIF. The two step
model is needed because the kernel may hold on to buffers for a long time, e.g. waiting for a TCP ACK, and having a separate cqe for request
completions allows userspace to push more data without extra delays. Note, notifications are only responsible for controlling the lifetime of the
buffers, and as such don't mean anything about whether the data has atually been sent out or received by the other end.
{@code fd} must be set to the socket file descriptor, {@code addr} must contain a pointer to the buffer, {@code len} denotes the length of the
buffer to send, and {@code msg_flags} holds the flags associated with the system call. When {@code addr2} is non-zero it points to the address of
the target with {@code addr_len} specifying its size, turning the request into a {@code sendto(2)} system call equivalent.
Available since 6.0.
"""
),
"OP_LAST".enumByte
)
EnumConstant(
"{@code sqe->fsync_flags}",
"FSYNC_DATASYNC".enum("", "1 << 0")
)
EnumConstant(
"{@code sqe->timeout_flags}",
"TIMEOUT_ABS".enum("", "1 << 0"),
"TIMEOUT_UPDATE".enum("", "1 << 1"),
"TIMEOUT_BOOTTIME".enum("", "1 << 2"),
"TIMEOUT_REALTIME".enum("", "1 << 3"),
"LINK_TIMEOUT_UPDATE".enum("", "1 << 4"),
"TIMEOUT_ETIME_SUCCESS".enum("", "1 << 5"),
"TIMEOUT_CLOCK_MASK".enum("", "IORING_TIMEOUT_BOOTTIME | IORING_TIMEOUT_REALTIME"),
"TIMEOUT_UPDATE_MASK".enum("", "IORING_TIMEOUT_UPDATE | IORING_LINK_TIMEOUT_UPDATE")
)
EnumConstant(
"{@code sqe->splice_flags}, extends {@code splice(2)} flags",
"SPLICE_F_FD_IN_FIXED".enum("", "1 << 31")
)
EnumConstant(
"""
{@code POLL_ADD} flags. Note that since {@code sqe->poll_events} is the flag space, the command flags for {@code POLL_ADD} are stored in
{@code sqe->len}.
{@code IORING_POLL_UPDATE}: Update existing poll request, matching {@code sqe->addr} as the old {@code user_data} field.
{@code IORING_POLL_LEVEL}: Level triggered poll.
""",
"POLL_ADD_MULTI".enum(
"Multishot poll. Sets {@code IORING_CQE_F_MORE} if the poll handler will continue to report CQEs on behalf of the same SQE.",
"1 << 0"
),
"POLL_UPDATE_EVENTS".enum("", "1 << 1"),
"POLL_UPDATE_USER_DATA".enum("", "1 << 2"),
"POLL_ADD_LEVEL".enum("", "1 << 3")
)
EnumConstant(
"{@code ASYNC_CANCEL} flags.",
"ASYNC_CANCEL_ALL".enum(
"""
Cancel all requests that match the given criteria, rather than just canceling the first one found.
Available since 5.19.
""",
"1 << 0"
),
"ASYNC_CANCEL_FD".enum(
"""
Match based on the file descriptor used in the original request rather than the {@code user_data}.
This is what #prep_cancel_fd() sets up.
Available since 5.19.
""",
"1 << 1"
),
"ASYNC_CANCEL_ANY".enum(
"""
Match any request in the ring, regardless of {@code user_data} or file descriptor.
Can be used to cancel any pending request in the ring.
Available since 5.19.
""",
"1 << 2"
),
"ASYNC_CANCEL_FD_FIXED".enum("{@code fd} passed in is a fixed descriptor", "1 << 3")
)
EnumConstant(
"{@code send/sendmsg} and {@code recv/recvmsg} flags ({@code sqe->ioprio})",
"RECVSEND_POLL_FIRST".enum(
"""
If set, io_uring will assume the socket is currently empty and attempting to receive data will be unsuccessful.
For this case, io_uring will arm internal poll and trigger a receive of the data when the socket has data to be read. This initial receive attempt
can be wasteful for the case where the socket is expected to be empty, setting this flag will bypass the initial receive attempt and go straight to
arming poll. If poll does indicate that data is ready to be received, the operation will proceed.
Can be used with the CQE #CQE_F_SOCK_NONEMPTY flag, which io_uring will set on CQEs after a {@code recv(2)} or {@code recvmsg(2)} operation. If
set, the socket still had data to be read after the operation completed.
Both these flags are available since 5.19.
""",
"1 << 0"
),
"RECV_MULTISHOT".enum(
"""
Multishot {@code recv}.
Sets #CQE_F_MORE if the handler will continue to report CQEs on behalf of the same SQE.
""",
"1 << 1"
),
"RECVSEND_FIXED_BUF".enum("Use registered buffers, the index is stored in the {@code buf_index} field.", "1 << 2")
)
EnumConstant(
"Accept flags stored in {@code sqe->ioprio}",
"ACCEPT_MULTISHOT".enum("", "1 << 0")
)
EnumConstant(
"#OP_MSG_RING command types, stored in {@code sqe->addr}",
"MSG_DATA".enum("pass {@code sqe->len} as {@code res} and {@code off} as {@code user_data}", "0"),
"MSG_SEND_FD".enum("send a registered fd to another ring")
)
EnumConstant(
"#OP_MSG_RING flags ({@code sqe->msg_ring_flags})",
"MSG_RING_CQE_SKIP".enum("Don't post a CQE to the target ring. Not applicable for #MSG_DATA, obviously.", "1 << 0")
)
EnumConstant(
"{@code cqe->flags}",
"CQE_F_BUFFER".enum("If set, the upper 16 bits are the buffer ID", "1 << 0"),
"CQE_F_MORE".enum("If set, parent SQE will generate more CQE entries", "1 << 1"),
"CQE_F_SOCK_NONEMPTY".enum("If set, more data to read after socket {@code recv}.", "1 << 2"),
"CQE_F_NOTIF".enum("Set for notification CQEs. Can be used to distinct them from sends.", "1 << 3")
)
EnumConstant(
"",
"CQE_BUFFER_SHIFT".enum("", "16")
)
LongConstant(
"Magic offsets for the application to {@code mmap} the data it needs",
"OFF_SQ_RING".."0L",
"OFF_CQ_RING".."0x8000000L",
"OFF_SQES".."0x10000000L",
)
EnumConstant(
"{@code sq_ring->flags}",
"SQ_NEED_WAKEUP".enum("needs {@code io_uring_enter} wakeup", "1 << 0"),
"SQ_CQ_OVERFLOW".enum("CQ ring is overflown", "1 << 1"),
"SQ_TASKRUN".enum("task should enter the kernel", "1 << 2")
)
EnumConstant(
"{@code cq_ring->flags}",
"CQ_EVENTFD_DISABLED".enum("disable {@code eventfd} notifications", "1 << 0")
)
EnumConstant(
"{@code io_uring_enter(2)} flags",
"ENTER_GETEVENTS".enum(
"""
If this flag is set, then the system call will wait for the specificied number of events in {@code min_complete} before returning.
This flag can be set along with {@code to_submit} to both submit and complete events in a single system call.
""",
"1 << 0"
),
"ENTER_SQ_WAKEUP".enum(
"If the ring has been created with #SETUP_SQPOLL, then this flag asks the kernel to wakeup the SQ kernel thread to submit IO.",
"1 << 1"
),
"ENTER_SQ_WAIT".enum(
"""
If the ring has been created with #SETUP_SQPOLL, then the application has no real insight into when the SQ kernel thread has consumed entries from
the SQ ring. This can lead to a situation where the application can no longer get a free SQE entry to submit, without knowing when it one becomes
available as the SQ kernel thread consumes them. If the system call is used with this flag set, then it will wait until at least one entry is free
in the SQ ring.
""",
"1 << 2"
),
"ENTER_EXT_ARG".enum(
"""
Since kernel 5.11, the system calls arguments have been modified to look like the following:
${codeBlock("""
int io_uring_enter(unsigned int fd, unsigned int to_submit,
unsigned int min_complete, unsigned int flags,
const void *arg, size_t argsz);
""")}
which is behaves just like the original definition by default. However, if {@code IORING_ENTER_EXT_ARG} is set, then instead of a {@code sigset_t}
being passed in, a pointer to a struct {@code io_uring_getevents_arg} is used instead and {@code argsz} must be set to the size of this structure.
The definition is ##IOURingGeteventsArg which allows passing in both a signal mask as well as pointer to a struct {@code __kernel_timespec} timeout
value. If {@code ts} is set to a valid pointer, then this time value indicates the timeout for waiting on events. If an application is waiting on
events and wishes to stop waiting after a specified amount of time, then this can be accomplished directly in version 5.11 and newer by using this
feature.
""",
"1 << 3"
),
"ENTER_REGISTERED_RING".enum(
"""
If the ring file descriptor has been registered through use of #REGISTER_RING_FDS, then setting this flag will tell the kernel that the
{@code ring_fd} passed in is the registered ring offset rather than a normal file descriptor.
""",
"1 << 4"
)
)
EnumConstant(
"{@code io_uring_params->features} flags",
"FEAT_SINGLE_MMAP".enum(
"""
If this flag is set, the two SQ and CQ rings can be mapped with a single {@code mmap(2)} call.
The SQEs must still be allocated separately. This brings the necessary {@code mmap(2)} calls down from three to two.
Available since kernel 5.4.
""",
"1 << 0"
),
"FEAT_NODROP".enum(
"""
If this flag is set, {@code io_uring} supports never dropping completion events.
If a completion event occurs and the CQ ring is full, the kernel stores the event internally until such a time that the CQ ring has room for more
entries. If this overflow condition is entered, attempting to submit more IO will fail with the {@code -EBUSY} error value, if it can't flush the
overflown events to the CQ ring. If this happens, the application must reap events from the CQ ring and attempt the submit again.
Available since kernel 5.5.
""",
"1 << 1"
),
"FEAT_SUBMIT_STABLE".enum(
"""
If this flag is set, applications can be certain that any data for async offload has been consumed when the kernel has consumed the SQE.
Available since kernel 5.5.
""",
"1 << 2"
),
"FEAT_RW_CUR_POS".enum(
"""
If this flag is set, applications can specify {@code offset == -1} with {@code IORING_OP_{READV,WRITEV}}, {@code IORING_OP_{READ,WRITE}_FIXED}, and
{@code IORING_OP_{READ,WRITE}} to mean current file position, which behaves like {@code preadv2(2)} and {@code pwritev2(2)} with
{@code offset == -1}.
It'll use (and update) the current file position. This obviously comes with the caveat that if the application has multiple reads or writes in
flight, then the end result will not be as expected. This is similar to threads sharing a file descriptor and doing IO using the current file
position.
Available since kernel 5.6.
""",
"1 << 3"
),
"FEAT_CUR_PERSONALITY".enum(
"""
If this flag is set, then {@code io_uring} guarantees that both sync and async execution of a request assumes the credentials of the task that
called #enter() to queue the requests.
If this flag isn't set, then requests are issued with the credentials of the task that originally registered the {@code io_uring}. If only one task
is using a ring, then this flag doesn't matter as the credentials will always be the same. Note that this is the default behavior, tasks can still
register different personalities through #register() with #REGISTER_PERSONALITY and specify the personality to use in the sqe.
Available since kernel 5.6.
""",
"1 << 4"
),
"FEAT_FAST_POLL".enum(
"""
If this flag is set, then {@code io_uring} supports using an internal poll mechanism to drive data/space readiness.
This means that requests that cannot read or write data to a file no longer need to be punted to an async thread for handling, instead they will
begin operation when the file is ready. This is similar to doing poll + read/write in userspace, but eliminates the need to do so. If this flag is
set, requests waiting on space/data consume a lot less resources doing so as they are not blocking a thread.
Available since kernel 5.7.
""",
"1 << 5"
),
"FEAT_POLL_32BITS".enum(
"""
If this flag is set, the #OP_POLL_ADD command accepts the full 32-bit range of epoll based flags.
Most notably {@code EPOLLEXCLUSIVE} which allows exclusive (waking single waiters) behavior.
Available since kernel 5.9.
""",
"1 << 6"
),
"FEAT_SQPOLL_NONFIXED".enum(
"""
If this flag is set, the #SETUP_SQPOLL feature no longer requires the use of fixed files.
Any normal file descriptor can be used for IO commands without needing registration.
Available since kernel 5.11.
""",
"1 << 7"
),
"FEAT_EXT_ARG".enum(
"""
If this flag is set, then the #enter() system call supports passing in an extended argument instead of just the {@code sigset_t} of earlier
kernels.
This extended argument is of type {@code struct io_uring_getevents_arg} and allows the caller to pass in both a {@code sigset_t} and a timeout
argument for waiting on events. A pointer to this struct must be passed in if #ENTER_EXT_ARG is set in the flags for the enter system call.
Available since kernel 5.11.
""",
"1 << 8"
),
"FEAT_NATIVE_WORKERS".enum(
"""
If this flag is set, {@code io_uring} is using native workers for its async helpers.
Previous kernels used kernel threads that assumed the identity of the original {@code io_uring} owning task, but later kernels will actively create
what looks more like regular process threads instead.
Available since kernel 5.12.
""",
"1 << 9"
),
"FEAT_RSRC_TAGS".enum(
"""
If this flag is set, then {@code io_uring} supports a variety of features related to fixed files and buffers.
In particular, it indicates that registered buffers can be updated in-place, whereas before the full set would have to be unregistered first.
Available since kernel 5.13.
""",
"1 << 10"
),
"FEAT_CQE_SKIP".enum(
"""
If this flag is set, then io_uring supports setting #IOSQE_CQE_SKIP_SUCCESS in the submitted SQE, indicating that no CQE should be generated for
this SQE if it executes normally. If an error happens processing the SQE, a CQE with the appropriate error value will still be generated.
Available since kernel 5.17.
""",
"1 << 11"
),
"FEAT_LINKED_FILE".enum(
"""
If this flag is set, then io_uring supports sane assignment of files for SQEs that have dependencies. For example, if a chain of SQEs are submitted
with #IOSQE_IO_LINK, then kernels without this flag will prepare the file for each link upfront. If a previous link opens a file with a known
index, eg if direct descriptors are used with open or accept, then file assignment needs to happen post execution of that SQE. If this flag is set,
then the kernel will defer file assignment until execution of a given request is started.
Available since kernel 5.17.
""",
"1 << 12"
)
)
EnumConstant(
"#register() {@code opcodes} and arguments",
"REGISTER_BUFFERS".enum(
"""
{@code arg} points to a struct {@code iovec} array of {@code nr_args} entries.
The buffers associated with the {@code iovecs} will be locked in memory and charged against the user's {@code RLIMIT_MEMLOCK} resource limit.
See {@code getrlimit(2)} for more information. Additionally, there is a size limit of 1GiB per buffer. Currently, the buffers must be anonymous,
non-file-backed memory, such as that returned by {@code malloc(3)} or {@code mmap(2)} with the {@code MAP_ANONYMOUS} flag set. It is expected that
this limitation will be lifted in the future. Huge pages are supported as well. Note that the entire huge page will be pinned in the kernel, even
if only a portion of it is used.
After a successful call, the supplied buffers are mapped into the kernel and eligible for I/O. To make use of them, the application must specify
the #OP_READ_FIXED or #OP_WRITE_FIXED {@code opcodes} in the submission queue entry (see the struct {@code io_uring_sqe} definition in #enter()),
and set the {@code buf_index} field to the desired buffer index. The memory range described by the submission queue entry's {@code addr} and
{@code len} fields must fall within the indexed buffer.
It is perfectly valid to setup a large buffer and then only use part of it for an I/O, as long as the range is within the originally mapped region.
An application can increase or decrease the size or number of registered buffers by first unregistering the existing buffers, and then issuing a
new call to {@code io_uring_register()} with the new buffers.
Note that before 5.13 registering buffers would wait for the ring to idle. If the application currently has requests in-flight, the registration
will wait for those to finish before proceeding.
An application need not unregister buffers explicitly before shutting down the io_uring instance.
Available since 5.1.
""",
"0"
),
"UNREGISTER_BUFFERS".enum(
"""
This operation takes no argument, and {@code arg} must be passed as #NULL.
All previously registered buffers associated with the {@code io_uring} instance will be released.
Available since 5.1.
"""
),
"REGISTER_FILES".enum(
"""
Register files for I/O.
{@code arg} contains a pointer to an array of {@code nr_args} file descriptors (signed 32 bit integers). To make use of the registered files, the
#IOSQE_FIXED_FILE flag must be set in the {@code flags} member of the struct {@code io_uring_sqe}, and the {@code fd} member is set to the index of
the file in the file descriptor array.
The file set may be sparse, meaning that the {@code fd} field in the array may be set to -1. See #REGISTER_FILES_UPDATE for how to update files in
place.
Note that before 5.13 registering files would wait for the ring to idle. If the application currently has requests in-flight, the registration will
wait for those to finish before proceeding. See #REGISTER_FILES_UPDATE for how to update an existing set without that limitation.
Files are automatically unregistered when the io_uring instance is torn down. An application needs only unregister if it wishes to register a new
set of fds.
Available since 5.1.
"""
),
"UNREGISTER_FILES".enum(
"""
This operation requires no argument, and {@code arg} must be passed as {@code NULL}.
All previously registered files associated with the {@code io_uring} instance will be unregistered.
Available since 5.1.
"""
),
"REGISTER_EVENTFD".enum(
"""
It's possible to use {@code eventfd(2)} to get notified of completion events on an {@code io_uring} instance. If this is desired, an eventfd file
descriptor can be registered through this operation.
{@code arg} must contain a pointer to the eventfd file descriptor, and {@code nr_args} must be 1.
Available since 5.2.
An application can temporarily disable notifications, coming through the registered eventfd, by setting the #CQ_EVENTFD_DISABLED bit in the
{@code flags} field of the CQ ring.
Available since 5.8.
"""
),
"UNREGISTER_EVENTFD".enum(
"""
Unregister an eventfd file descriptor to stop notifications.
Since only one eventfd descriptor is currently supported, this operation takes no argument, and {@code arg} must be passed as #NULL and
{@code nr_args} must be zero.
Available since 5.2.
"""
),
"REGISTER_FILES_UPDATE".enum(
"""
This operation replaces existing files in the registered file set with new ones, either turning a sparse entry (one where {@code fd} is equal to
-1) into a real one, removing an existing entry (new one is set to -1), or replacing an existing entry with a new existing entry.
{@code arg} must contain a pointer to a struct {@code io_uring_files_update}, which contains an offset on which to start the update, and an array
of file descriptors to use for the update. {@code nr_args} must contain the number of descriptors in the passed in array.
Available since 5.5.
File descriptors can be skipped if they are set to #REGISTER_FILES_SKIP. Skipping an fd will not touch the file associated with the previous fd at
that index.
Available since 5.12.
"""
),
"REGISTER_EVENTFD_ASYNC".enum(
"""
This works just like #REGISTER_EVENTFD, except notifications are only posted for events that complete in an async manner.
This means that events that complete inline while being submitted do not trigger a notification event. The arguments supplied are the same as for
{@code IORING_REGISTER_EVENTFD}.
Available since 5.6.
"""
),
"REGISTER_PROBE".enum(
"""
This operation returns a structure, {@code io_uring_probe}, which contains information about the {@code opcodes} supported by {@code io_uring} on
the running kernel.
{@code arg} must contain a pointer to a struct {@code io_uring_probe}, and {@code nr_args} must contain the size of the ops array in that probe
struct. The {@code ops} array is of the type {@code io_uring_probe_op}, which holds the value of the {@code opcode} and a {@code flags} field. If
the flags field has #IO_URING_OP_SUPPORTED set, then this opcode is supported on the running kernel.
Available since 5.6.
"""
),
"REGISTER_PERSONALITY".enum(
"""
This operation registers credentials of the running application with {@code io_uring}, and returns an id associated with these credentials.
Applications wishing to share a ring between separate users/processes can pass in this credential id in the sqe personality field. If set, that
particular sqe will be issued with these credentials. Must be invoked with {@code arg} set to #NULL and {@code nr_args} set to zero.
Available since 5.6.
"""
),
"UNREGISTER_PERSONALITY".enum(
"""
This operation unregisters a previously registered personality with {@code io_uring}.
{@code nr_args} must be set to the id in question, and {@code arg} must be set to #NULL.
Available since 5.6.
"""
),
"REGISTER_RESTRICTIONS".enum(
"""
{@code arg} points to a struct {@code io_uring_restriction} array of {@code nr_args} entries.
With an entry it is possible to allow an #register() {@code opcode}, or specify which {@code opcode} and flags of the submission queue entry are
allowed, or require certain flags to be specified (these flags must be set on each submission queue entry).
All the restrictions must be submitted with a single {@code io_uring_register()} call and they are handled as an allowlist ({@code opcodes} and
flags not registered, are not allowed).
Restrictions can be registered only if the {@code io_uring} ring started in a disabled state (#SETUP_R_DISABLED must be specified in the call to
#setup()).
Available since 5.10.
"""
),
"REGISTER_ENABLE_RINGS".enum(
"""
This operation enables an {@code io_uring} ring started in a disabled state (#SETUP_R_DISABLED was specified in the call to #setup()).
While the {@code io_uring} ring is disabled, submissions are not allowed and registrations are not restricted. After the execution of this
operation, the {@code io_uring} ring is enabled: submissions and registration are allowed, but they will be validated following the registered
restrictions (if any). This operation takes no argument, must be invoked with {@code arg} set to #NULL and {@code nr_args} set to zero.
Available since 5.10.
"""
),
"REGISTER_FILES2".enum(
"""
Register files for I/O. Similar to #REGISTER_FILES.
{@code arg} points to a struct {@code io_uring_rsrc_register}, and {@code nr_args} should be set to the number of bytes in the structure.
The {@code data} field contains a pointer to an array of {@code nr} file descriptors (signed 32 bit integers). {@code tags} field should either be
0 or or point to an array of {@code nr} "tags" (unsigned 64 bit integers). See #REGISTER_BUFFERS2 for more info on resource tagging.
Note that resource updates, e.g. #REGISTER_FILES_UPDATE, don't necessarily deallocate resources, they might be held until all requests using that
resource complete.
Available since 5.13.
"""
),
"REGISTER_FILES_UPDATE2".enum(
"""
Similar to #REGISTER_FILES_UPDATE, replaces existing files in the registered file set with new ones, either turning a sparse entry (one where fd is
equal to -1) into a real one, removing an existing entry (new one is set to -1), or replacing an existing entry with a new existing entry.
{@code arg} must contain a pointer to a struct {@code io_uring_rsrc_update2}, which contains an offset on which to start the update, and an array
of file descriptors to use for the update stored in data. {@code tags} points to an array of tags. {@code nr} must contain the number of
descriptors in the passed in arrays. See #REGISTER_BUFFERS2 for the resource tagging description.
Available since 5.13.
"""
),
"REGISTER_BUFFERS2".enum(
"""
Register buffers for I/O.
Similar to #REGISTER_BUFFERS but aims to have a more extensible ABI. {@code arg} points to a struct {@code io_uring_rsrc_register}, and
{@code nr_args} should be set to the number of bytes in the structure.
The data field contains a pointer to a struct {@code iovec} array of {@code nr} entries. The {@code tags} field should either be 0, then tagging is
disabled, or point to an array of {@code nr} "tags" (unsigned 64 bit integers). If a tag is zero, then tagging for this particular resource (a
buffer in this case) is disabled. Otherwise, after the resource had been unregistered and it's not used anymore, a CQE will be posted with
{@code user_data} set to the specified tag and all other fields zeroed.
Note that resource updates, e.g. #REGISTER_BUFFERS_UPDATE, don't necessarily deallocate resources by the time it returns, but they might be held
alive until all requests using it complete.
Available since 5.13.
"""
),
"REGISTER_BUFFERS_UPDATE".enum(
"""
Updates registered buffers with new ones, either turning a sparse entry into a real one, or replacing an existing entry.
{@code arg} must contain a pointer to a struct {@code io_uring_rsrc_update2}, which contains an offset on which to start the update, and an array
of struct {@code iovec}. {@code tags} points to an array of tags. {@code nr} must contain the number of descriptors in the passed in arrays. See
#REGISTER_BUFFERS2 for the resource tagging description.
Available since 5.13.
"""
),
"REGISTER_IOWQ_AFF".enum(
"""
By default, async workers created by {@code io_uring} will inherit the CPU mask of its parent.
This is usually all the CPUs in the system, unless the parent is being run with a limited set. If this isn't the desired outcome, the application
may explicitly tell {@code io_uring} what CPUs the async workers may run on.
{@code arg} must point to a {@code cpu_set_t} mask, and {@code nr_args} the byte size of that mask.
Available since 5.14.
"""
),
"UNREGISTER_IOWQ_AFF".enum(
"""
Undoes a CPU mask previously set with #REGISTER_IOWQ_AFF.
Must not have {@code arg} or {@code nr_args} set.
Available since 5.14.
"""
),
"REGISTER_IOWQ_MAX_WORKERS".enum(
"""
By default, {@code io_uring} limits the unbounded workers created to the maximum processor count set by {@code RLIMIT_NPROC} and the bounded
workers is a function of the SQ ring size and the number of CPUs in the system. Sometimes this can be excessive (or too little, for bounded), and
this command provides a way to change the count per ring (per NUMA node) instead.
{@code arg} must be set to an unsigned int pointer to an array of two values, with the values in the array being set to the maximum count of
workers per NUMA node. Index 0 holds the bounded worker count, and index 1 holds the unbounded worker count. On successful return, the passed in
array will contain the previous maximum valyes for each type. If the count being passed in is 0, then this command returns the current maximum
values and doesn't modify the current setting. {@code nr_args} must be set to 2, as the command takes two values.
Available since 5.15.
"""
),
"REGISTER_RING_FDS".enum(
"""
Whenever #enter() is called to submit request or wait for completions, the kernel must grab a reference to the file descriptor. If the application
using io_uring is threaded, the file table is marked as shared, and the reference grab and put of the file descriptor count is more expensive than
it is for a non-threaded application.
Similarly to how io_uring allows registration of files, this allow registration of the ring file descriptor itself. This reduces the overhead of
the {@code io_uring_enter (2)} system call.
{@code arg} must be set to an unsigned int pointer to an array of type {@code struct io_uring_rsrc_register} of {@code nr_args} number of entries.
The {@code data} field of this struct must point to an io_uring file descriptor, and the {@code offset} field can be either {@code -1} or an
explicit offset desired for the registered file descriptor value. If {@code -1} is used, then upon successful return of this system call, the field
will contain the value of the registered file descriptor to be used for future {@code io_uring_enter (2)} system calls.
On successful completion of this request, the returned descriptors may be used instead of the real file descriptor for {@code io_uring_enter (2)},
provided that {@code IORING_ENTER_REGISTERED_RING} is set in the {@code flags} for the system call. This flag tells the kernel that a registered
descriptor is used rather than a real file descriptor.
Each thread or process using a ring must register the file descriptor directly by issuing this request.
The maximum number of supported registered ring descriptors is currently limited to {@code 16}.
Available since 5.18.
"""
),
"UNREGISTER_RING_FDS".enum(
"""
Unregister descriptors previously registered with #REGISTER_RING_FDS.
{@code arg} must be set to an unsigned int pointer to an array of type {@code struct io_uring_rsrc_register} of {@code nr_args} number of entries.
Only the {@code offset} field should be set in the structure, containing the registered file descriptor offset previously returned from
{@code IORING_REGISTER_RING_FDS} that the application wishes to unregister.
Note that this isn't done automatically on ring exit, if the thread or task that previously registered a ring file descriptor isn't exiting. It is
recommended to manually unregister any previously registered ring descriptors if the ring is closed and the task persists. This will free up a
registration slot, making it available for future use.
Available since 5.18.
"""
),
"REGISTER_PBUF_RING".enum("register ring based provide buffer group"),
"UNREGISTER_PBUF_RING".enum("unregister ring based provide buffer group"),
"REGISTER_SYNC_CANCEL".enum("sync cancelation API"),
"REGISTER_FILE_ALLOC_RANGE".enum("register a range of fixed file slots for automatic slot allocation"),
"REGISTER_LAST".enum
)
EnumConstant(
"Register a fully sparse file space, rather than pass in an array of all -1 file descriptors.",
"RSRC_REGISTER_SPARSE".enum("", "1 << 0")
)
EnumConstant(
"{@code io-wq} worker categories",
"IO_WQ_BOUND".enum("", "0"),
"IO_WQ_UNBOUND".enum
).noPrefix()
IntConstant(
"Skip updating fd indexes set to this value in the fd table.",
"REGISTER_FILES_SKIP".."-2"
)
IntConstant(
"",
"IO_URING_OP_SUPPORTED".."1 << 0"
).noPrefix()
EnumConstant(
"{@code io_uring_restriction->opcode} values",
"RESTRICTION_REGISTER_OP".enum("Allow an {@code io_uring_register(2)} opcode", "0"),
"RESTRICTION_SQE_OP".enum("Allow an sqe opcode"),
"RESTRICTION_SQE_FLAGS_ALLOWED".enum("Allow sqe flags"),
"RESTRICTION_SQE_FLAGS_REQUIRED".enum("Require sqe flags (these flags must be set on each submission)"),
"RESTRICTION_LAST".enum("Require sqe flags (these flags must be set on each submission)")
)
SaveErrno..NativeName("__sys_io_uring_setup")..int(
"setup",
"""
The {@code io_uring_setup()} system call sets up a submission queue (SQ) and completion queue (CQ) with at least {@code entries} entries, and returns a
file descriptor which can be used to perform subsequent operations on the {@code io_uring} instance.
The submission and completion queues are shared between userspace and the kernel, which eliminates the need to copy data when initiating and completing
I/O.
Closing the file descriptor returned by {@code io_uring_setup(2)} will free all resources associated with the {@code io_uring} context.
""",
unsigned("entries", ""),
io_uring_params.p("p", "used by the application to pass options to the kernel, and by the kernel to convey information about the ring buffers"),
returnDoc =
"""
a new file descriptor on success.
The application may then provide the file descriptor in a subsequent {@code mmap(2)} call to map the submission and completion queues, or to the
#register() or #enter() system calls.
On error, {@code -1} is returned and {@code errno} is set appropriately.
"""
)
SaveErrno..NativeName("__sys_io_uring_register")..int(
"register",
"""
The {@code io_uring_register()} system call registers resources (e.g. user buffers, files, eventfd, personality, restrictions) for use in an
{@code io_uring} instance referenced by {@code fd}.
Registering files or user buffers allows the kernel to take long term references to internal data structures or create long term mappings of
application memory, greatly reducing per-I/O overhead.
""",
int("fd", "the file descriptor returned by a call to #setup()"),
unsigned("opcode", "", "REGISTER_\\w+"),
nullable..opaque_p("arg", ""),
unsigned("nr_args", ""),
returnDoc = "on success, returns 0. On error, -1 is returned, and {@code errno} is set accordingly."
)
SaveErrno..NativeName("__sys_io_uring_enter2")..int(
"enter2",
"",
int("fd", ""),
unsigned("to_submit", ""),
unsigned("min_complete", ""),
unsigned("flags", ""),
nullable..sigset_t.p("sig", ""),
int("sz", "")
)
SaveErrno..NativeName("__sys_io_uring_enter")..int(
"enter",
"""
{@code io_uring_enter()} is used to initiate and complete I/O using the shared submission and completion queues setup by a call to #setup().
A single call can both submit new I/O and wait for completions of I/O initiated by this call or previous calls to {@code io_uring_enter()}.
If the {@code io_uring} instance was configured for polling, by specifying #SETUP_IOPOLL in the call to {@code io_uring_setup()}, then
{@code min_complete} has a slightly different meaning. Passing a value of 0 instructs the kernel to return any events which are already complete,
without blocking. If {@code min_complete} is a non-zero value, the kernel will still return immediately if any completion events are available. If no
event completions are available, then the call will poll either until one or more completions become available, or until the process has exceeded its
scheduler time slice.
Note that, for interrupt driven I/O (where {@code IORING_SETUP_IOPOLL} was not specified in the call to {@code io_uring_setup()}), an application may
check the completion queue for event completions without entering the kernel at all.
When the system call returns that a certain amount of SQEs have been consumed and submitted, it's safe to reuse SQE entries in the ring. This is true
even if the actual IO submission had to be punted to async context, which means that the SQE may in fact not have been submitted yet. If the kernel
requires later use of a particular SQE entry, it will have made a private copy of it.
""",
int("fd", "the file descriptor returned by #setup()"),
unsigned("to_submit", "the number of I/Os to submit from the submission queue"),
unsigned("min_complete", ""),
unsigned("flags", "", "ENTER_\\w+", LinkMode.BITFIELD),
nullable..sigset_t.p(
"sig",
"""
a pointer to a signal mask (see {@code sigprocmask(2)}); if {@code sig} is not #NULL, {@code io_uring_enter()} first replaces the current signal
mask by the one pointed to by sig, then waits for events to become available in the completion queue, and then restores the original signal mask.
The following {@code io_uring_enter()} call:
${codeBlock("""
ret = io_uring_enter(fd, 0, 1, IORING_ENTER_GETEVENTS, &sig);
""")}
is equivalent to atomically executing the following calls:
${codeBlock("""
pthread_sigmask(SIG_SETMASK, &sig, &orig);
ret = io_uring_enter(fd, 0, 1, IORING_ENTER_GETEVENTS, NULL);
pthread_sigmask(SIG_SETMASK, &orig, NULL);""")}
See the description of {@code pselect(2)} for an explanation of why the {@code sig} parameter is necessary.
"""
),
returnDoc =
"""
the number of I/Os successfully consumed.
This can be zero if {@code to_submit} was zero or if the submission queue was empty. Note that if the ring was created with #SETUP_SQPOLL specified,
then the return value will generally be the same as {@code to_submit} as submission happens outside the context of the system call.
The errors related to a submission queue entry will be returned through a completion queue entry, rather than through the system call itself.
Errors that occur not on behalf of a submission queue entry are returned via the system call directly. On such an error, -1 is returned and
{@code errno} is set appropriately.
"""
)
}
|
bsd-3-clause
|
535a6083f3ab6d3d93bec2e5820cd076
| 54.742416 | 159 | 0.641629 | 4.485774 | false | false | false | false |
google/ground-android
|
ground/src/main/java/com/google/android/ground/persistence/remote/firestore/schema/SubmissionMutationConverter.kt
|
1
|
3101
|
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.ground.persistence.remote.firestore.schema
import com.google.android.ground.model.User
import com.google.android.ground.model.mutation.Mutation
import com.google.android.ground.model.mutation.SubmissionMutation
import com.google.android.ground.model.submission.*
import com.google.android.ground.persistence.remote.DataStoreException
import com.google.android.ground.persistence.remote.firestore.schema.AuditInfoConverter.fromMutationAndUser
import com.google.common.collect.ImmutableList
import com.google.common.collect.ImmutableMap
import com.google.firebase.firestore.FieldValue
import timber.log.Timber
/** Converts between Firestore maps used to merge updates and [SubmissionMutation] instances. */
internal object SubmissionMutationConverter {
const val LOI_ID = "loiId"
private const val JOB_ID = "jobId"
private const val RESPONSES = "responses"
private const val CREATED = "created"
private const val LAST_MODIFIED = "lastModified"
@Throws(DataStoreException::class)
fun toMap(mutation: SubmissionMutation, user: User): ImmutableMap<String, Any> {
val map = ImmutableMap.builder<String, Any>()
val auditInfo = fromMutationAndUser(mutation, user)
when (mutation.type) {
Mutation.Type.CREATE -> {
map.put(CREATED, auditInfo)
map.put(LAST_MODIFIED, auditInfo)
}
Mutation.Type.UPDATE -> map.put(LAST_MODIFIED, auditInfo)
Mutation.Type.DELETE,
Mutation.Type.UNKNOWN ->
throw DataStoreException("Unsupported mutation type: ${mutation.type}")
}
map.put(LOI_ID, mutation.locationOfInterestId)
map.put(JOB_ID, mutation.job!!.id)
map.put(RESPONSES, toMap(mutation.taskDataDeltas))
return map.build()
}
private fun toMap(taskDataDeltas: ImmutableList<TaskDataDelta>): Map<String, Any> {
val map = ImmutableMap.builder<String, Any>()
for (delta in taskDataDeltas) {
delta.newTaskData
.map { obj: TaskData -> toObject(obj) }
.orElse(FieldValue.delete())
?.let { map.put(delta.taskId, it) }
}
return map.build()
}
private fun toObject(taskData: TaskData): Any? =
when (taskData) {
is TextTaskData -> taskData.text
is MultipleChoiceTaskData -> taskData.selectedOptionIds
is NumberTaskData -> taskData.value
is TimeTaskData -> taskData.time
is DateTaskData -> taskData.date
else -> {
Timber.e("Unknown taskData type: %s", taskData.javaClass.name)
null
}
}
}
|
apache-2.0
|
ca3e073a95169a0a921b53241d67a38c
| 36.817073 | 107 | 0.72525 | 4.074901 | false | false | false | false |
theapache64/Mock-API
|
src/com/theah64/mock_api/servlets/DeleteProjectImageServlet.kt
|
1
|
1644
|
package com.theah64.mock_api.servlets
import com.theah64.mock_api.database.Images
import com.theah64.mock_api.utils.APIResponse
import com.theah64.webengine.database.querybuilders.QueryBuilderException
import com.theah64.webengine.utils.PathInfo
import com.theah64.webengine.utils.Request
import org.json.JSONException
import javax.servlet.annotation.WebServlet
import java.io.File
import java.io.IOException
import java.sql.SQLException
@WebServlet(urlPatterns = ["/v1/delete_image"])
class DeleteProjectImageServlet : AdvancedBaseServlet() {
override val isSecureServlet: Boolean
get() = true
override val requiredParameters: Array<String>?
@Throws(Request.RequestException::class)
get() = arrayOf(Images.COLUMN_ID)
@Throws(Request.RequestException::class, IOException::class, JSONException::class, SQLException::class, Request.RequestException::class, PathInfo.PathInfoException::class, QueryBuilderException::class)
override fun doAdvancedPost() {
val imageId = getStringParameter(Images.COLUMN_ID)!!
val projectId = headerSecurity!!.projectId
val filePath = Images.instance.get(Images.COLUMN_ID, imageId, Images.COLUMN_PROJECT_ID, projectId, Images.COLUMN_FILE_PATH)
if (filePath != null) {
val file = File(filePath)
file.delete()
//Delete from db also
Images.instance.delete(Images.COLUMN_ID, imageId, Images.COLUMN_PROJECT_ID, projectId)
writer!!.write(APIResponse("Image deleted", null).response)
} else {
throw Request.RequestException("Invalid request")
}
}
}
|
apache-2.0
|
5564dc0f2db6fc1e66b667e26f315c93
| 36.363636 | 205 | 0.724453 | 4.292428 | false | false | false | false |
anibyl/slounik
|
main/src/main/java/org/anibyl/slounik/data/network/SlounikOrg.kt
|
1
|
7703
|
package org.anibyl.slounik.data.network
import android.content.Context
import android.net.Uri
import com.android.volley.NetworkResponse
import com.android.volley.Response
import com.android.volley.toolbox.HttpHeaderParser
import com.android.volley.toolbox.StringRequest
import org.anibyl.slounik.Notifier
import org.anibyl.slounik.SlounikApplication
import org.anibyl.slounik.data.Article
import org.anibyl.slounik.data.ArticlesCallback
import org.anibyl.slounik.data.ArticlesInfo
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.uiThread
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import org.jsoup.select.Elements
import java.net.URLEncoder
import javax.inject.Inject
/**
* slounik.org website communication.
*
* @author Usievaład Kimajeŭ
* @created 08.04.2015
*/
class SlounikOrg : DictionarySiteCommunicator() {
@Inject lateinit var notifier: Notifier
override val url: String
get() = config.slounikOrgUrl
init {
SlounikApplication.graph.inject(this)
}
override fun loadArticles(wordToSearch: String, context: Context, callback: ArticlesCallback) {
val requestString: String
val builder = Uri.Builder()
builder.scheme("http").authority(url).appendPath("search").appendQueryParameter("search", wordToSearch)
if (preferences.searchInTitles) {
builder.appendQueryParameter("un", "1")
}
requestString = builder.build().toString()
val request = getLoadRequest(requestString, callback)
queue.add(request)
}
override fun loadArticleDescription(article: Article, callback: ArticlesCallback) {
val builder = Uri.Builder()
builder.scheme("http").authority(url).appendPath(article.linkToFullDescription!!.substring(1))
val requestString = builder.build().toString()
val request = getArticleDescriptionLoadRequest(requestString, article, callback)
queue.add(request)
}
override fun enabled(): Boolean {
return preferences.useSlounikOrg
}
private fun getLoadRequest(requestString: String, callback: ArticlesCallback): SlounikOrgRequest {
return SlounikOrgRequest(requestString,
Response.Listener { response ->
doAsync {
val page = Jsoup.parse(response)
val dicsElements = page.select("a.treeSearchDict")
var dicsAmount: Int = dicsElements.size
if (dicsAmount != 0) {
for (e in dicsElements) {
var dicRequestStr: String? = e.attr("href")
if (dicRequestStr != null) {
// Encode cyrillic word.
val startIndex = dicRequestStr.indexOf("search=") + "search=".length
var endIndex = dicRequestStr.indexOf("&", startIndex)
if (endIndex == -1) {
endIndex = dicRequestStr.length - 1
}
dicRequestStr = dicRequestStr.substring(0 until startIndex) +
URLEncoder.encode(
dicRequestStr.substring(startIndex until endIndex),
Charsets.UTF_8.toString()
) +
dicRequestStr.substring(endIndex)
val uri = Uri.Builder()
.scheme("http")
.authority(url)
.appendEncodedPath(dicRequestStr.substring(1))
.build()
val eachDicRequest = getPerDicLoadingRequest(uri.toString(),
object : ArticlesCallback {
override operator fun invoke(info: ArticlesInfo) {
val status = if (--dicsAmount == 0)
ArticlesInfo.Status.SUCCESS
else
ArticlesInfo.Status.IN_PROCESS
notifier.log("Callback invoked, " + (info.articles?.size
?: 0) + " articles added.")
callback.invoke(ArticlesInfo(info.articles, status))
}
})
queue.add(eachDicRequest)
notifier.log("Request added to queue: $eachDicRequest")
}
}
}
uiThread {
if (dicsAmount == 0) {
notifier.log("Callback invoked: no dictionaries.")
callback.invoke(ArticlesInfo(articles = null, status = ArticlesInfo.Status.SUCCESS))
}
}
}
},
Response.ErrorListener { error ->
notifier.log("Error response for $requestString: ${error.message}")
callback.invoke(ArticlesInfo(ArticlesInfo.Status.FAILURE))
})
}
override fun parseElement(element: Element, wordToSearch: String?): Article {
return Article(this).apply {
var elements: Elements? = element.select("a.tsb")
if (elements != null && elements.size != 0) {
val link = elements.first()
title = link.html()
linkToFullDescription = link.attr("href")
if (title != null) {
elements = element.select("a.ts")
if (elements != null && elements.size != 0) {
description = elements.first().html()
}
}
}
if (title == null) {
elements = element.select("b")
if (elements != null && elements.size != 0) {
title = elements.first().html()
if (title != null) {
description = element.html()
}
}
}
if (title != null) {
title = title!!.replace("<u>".toRegex(), "")
title = title!!.replace("</u>".toRegex(), "́")
// Escape all other HTML tags, e.g. second <b>.
title = Jsoup.parse(title).text()
}
elements = element.select("a.la1")
if (elements != null && elements.size != 0) {
dictionary = "$elements.first().html() $url"
}
}
}
private fun getPerDicLoadingRequest(requestString: String, callback: ArticlesCallback): SlounikOrgRequest {
return SlounikOrgRequest(requestString,
Response.Listener { response ->
doAsync {
notifier.log("Response received for $requestString.")
val dicPage = Jsoup.parse(response)
val articleElements = dicPage.select("li#li_poszuk")
var dictionaryTitle: String? = null
val dictionaryTitles = dicPage.select("a.t3")
if (dictionaryTitles != null && dictionaryTitles.size != 0) {
dictionaryTitle = dictionaryTitles.first().html()
}
val list: List<Article> = articleElements.map {
e -> parseElement(e).apply { dictionary = "$dictionaryTitle $url" }
}
uiThread {
callback.invoke(ArticlesInfo(list))
}
}
},
Response.ErrorListener { error ->
notifier.log("Error response for $requestString: ${error.message}")
callback.invoke(ArticlesInfo(ArticlesInfo.Status.FAILURE))
})
}
private fun getArticleDescriptionLoadRequest(
requestString: String,
article: Article,
callback: ArticlesCallback
): SlounikOrgRequest {
return SlounikOrgRequest(requestString,
Response.Listener { response ->
doAsync {
notifier.log("Response received for $requestString.")
val articlePage: Document = Jsoup.parse(response)
val articleElement: Element = articlePage.select("td.n12").first()
val htmlDescription:String = articleElement.html()
val descriptionWithOutExtraSpace: String = htmlDescription.trim { it <= ' ' }
article.fullDescription = htmlDescription.subSequence(0, descriptionWithOutExtraSpace.length)
as String
val list = listOf(article)
uiThread {
callback.invoke(ArticlesInfo(list))
}
}
},
Response.ErrorListener { error ->
notifier.log("Error response for $requestString: ${error.message}")
callback.invoke(ArticlesInfo(ArticlesInfo.Status.FAILURE))
})
}
private class SlounikOrgRequest(
url: String,
listener: Response.Listener<String>,
errorListener: Response.ErrorListener
) : StringRequest(url, listener, errorListener) {
override fun parseNetworkResponse(response: NetworkResponse): Response<String> {
val parsed = String(response.data, Charsets.UTF_8)
return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response))
}
}
}
|
gpl-3.0
|
877b05b6ccd4d2273b9a1189d7296742
| 30.174089 | 108 | 0.671818 | 3.673664 | false | false | false | false |
dahlstrom-g/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/collections/RenameUselessCallFix.kt
|
2
|
1976
|
// 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.inspections.collections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType
class RenameUselessCallFix(val newName: String) : LocalQuickFix {
override fun getName() = KotlinBundle.message("rename.useless.call.fix.text", newName)
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
(descriptor.psiElement as? KtQualifiedExpression)?.let {
val factory = KtPsiFactory(it)
val selectorCallExpression = it.selectorExpression as? KtCallExpression
val calleeExpression = selectorCallExpression?.calleeExpression ?: return
calleeExpression.replaced(factory.createExpression(newName))
selectorCallExpression.renameGivenReturnLabels(factory, calleeExpression.text, newName)
}
}
private fun KtCallExpression.renameGivenReturnLabels(factory: KtPsiFactory, labelName: String, newName: String) {
val lambdaExpression = lambdaArguments.firstOrNull()?.getLambdaExpression() ?: return
val bodyExpression = lambdaExpression.bodyExpression ?: return
bodyExpression.forEachDescendantOfType<KtReturnExpression> {
if (it.getLabelName() != labelName) return@forEachDescendantOfType
it.replaced(
factory.createExpressionByPattern(
"return@$0 $1",
newName,
it.returnedExpression ?: ""
)
)
}
}
}
|
apache-2.0
|
2c8bc629cdd712a06323b0dd48ea9f4b
| 43.931818 | 158 | 0.716093 | 5.443526 | false | false | false | false |
ogarcia/ultrasonic
|
core/subsonic-api/src/main/kotlin/org/moire/ultrasonic/api/subsonic/SubsonicAPIClient.kt
|
1
|
7719
|
package org.moire.ultrasonic.api.subsonic
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.KotlinModule
import com.fasterxml.jackson.module.kotlin.readValue
import java.security.SecureRandom
import java.security.cert.X509Certificate
import java.util.concurrent.TimeUnit.MILLISECONDS
import javax.net.ssl.SSLContext
import javax.net.ssl.X509TrustManager
import okhttp3.OkHttpClient
import okhttp3.ResponseBody
import okhttp3.logging.HttpLoggingInterceptor
import org.moire.ultrasonic.api.subsonic.interceptors.PasswordHexInterceptor
import org.moire.ultrasonic.api.subsonic.interceptors.PasswordMD5Interceptor
import org.moire.ultrasonic.api.subsonic.interceptors.ProxyPasswordInterceptor
import org.moire.ultrasonic.api.subsonic.interceptors.RangeHeaderInterceptor
import org.moire.ultrasonic.api.subsonic.interceptors.VersionInterceptor
import org.moire.ultrasonic.api.subsonic.response.StreamResponse
import org.moire.ultrasonic.api.subsonic.response.SubsonicResponse
import retrofit2.Response
import retrofit2.Retrofit
private const val READ_TIMEOUT = 60_000L
/**
* Subsonic API client that provides api access.
*
* For supported API calls see [SubsonicAPIDefinition].
*
* Client will automatically adjust [protocolVersion] to the current server version on
* doing successful requests.
*
* @author Yahor Berdnikau
*/
class SubsonicAPIClient(
config: SubsonicClientConfiguration,
baseOkClient: OkHttpClient = OkHttpClient.Builder().build()
) {
private val versionInterceptor = VersionInterceptor(config.minimalProtocolVersion)
private val proxyPasswordInterceptor = ProxyPasswordInterceptor(
config.minimalProtocolVersion,
PasswordHexInterceptor(config.password),
PasswordMD5Interceptor(config.password),
config.enableLdapUserSupport
)
/**
* Get currently used protocol version.
*/
var protocolVersion = config.minimalProtocolVersion
private set(value) {
field = value
proxyPasswordInterceptor.apiVersion = field
wrappedApi.currentApiVersion = field
versionInterceptor.protocolVersion = field
}
private val okHttpClient = baseOkClient.newBuilder()
.readTimeout(READ_TIMEOUT, MILLISECONDS)
.apply { if (config.allowSelfSignedCertificate) allowSelfSignedCertificates() }
.addInterceptor { chain ->
// Adds default request params
val originalRequest = chain.request()
val newUrl = originalRequest.url().newBuilder()
.addQueryParameter("u", config.username)
.addQueryParameter("c", config.clientID)
.addQueryParameter("f", "json")
.build()
chain.proceed(originalRequest.newBuilder().url(newUrl).build())
}
.addInterceptor(versionInterceptor)
.addInterceptor(proxyPasswordInterceptor)
.addInterceptor(RangeHeaderInterceptor())
.apply { if (config.debug) addLogging() }
.build()
private val jacksonMapper = ObjectMapper()
.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.registerModule(KotlinModule())
private val retrofit = Retrofit.Builder()
.baseUrl("${config.baseUrl}/rest/")
.client(okHttpClient)
.addConverterFactory(
VersionAwareJacksonConverterFactory.create(
{ protocolVersion = it },
jacksonMapper
)
)
.build()
private val wrappedApi = ApiVersionCheckWrapper(
retrofit.create(SubsonicAPIDefinition::class.java),
config.minimalProtocolVersion
)
val api: SubsonicAPIDefinition get() = wrappedApi
/**
* Convenient method to get cover art from api using item [id] and optional maximum [size].
*
* It detects the response `Content-Type` and tries to parse subsonic error if there is one.
*
* Prefer this method over [SubsonicAPIDefinition.getCoverArt] as this handles error cases.
*/
fun getCoverArt(id: String, size: Long? = null): StreamResponse = handleStreamResponse {
api.getCoverArt(id, size).execute()
}
/**
* Convenient method to get media stream from api using item [id] and optional [maxBitrate].
*
* Optionally also you can provide [offset] that stream should start from.
*
* It detects the response `Content-Type` and tries to parse subsonic error if there is one.
*
* Prefer this method over [SubsonicAPIDefinition.stream] as this handles error cases.
*/
fun stream(id: String, maxBitrate: Int? = null, offset: Long? = null): StreamResponse =
handleStreamResponse {
api.stream(id, maxBitrate, offset = offset).execute()
}
/**
* Convenient method to get user avatar using [username].
*
* It detects the response `Content-Type` and tries to parse subsonic error if there is one.
*
* Prefer this method over [SubsonicAPIDefinition.getAvatar] as this handles error cases.
*/
fun getAvatar(username: String): StreamResponse = handleStreamResponse {
api.getAvatar(username).execute()
}
private inline fun handleStreamResponse(apiCall: () -> Response<ResponseBody>): StreamResponse {
val response = apiCall()
return if (response.isSuccessful) {
val responseBody = response.body()
val contentType = responseBody?.contentType()
if (
contentType != null &&
contentType.type().equals("application", true) &&
contentType.subtype().equals("json", true)
) {
val error = jacksonMapper.readValue<SubsonicResponse>(responseBody.byteStream())
StreamResponse(apiError = error.error, responseHttpCode = response.code())
} else {
StreamResponse(
stream = responseBody?.byteStream(),
responseHttpCode = response.code()
)
}
} else {
StreamResponse(responseHttpCode = response.code())
}
}
/**
* Get stream url.
*
* Calling this method do actual connection to the backend, though not downloading all content.
*
* Consider do not use this method, but [stream] call.
*/
fun getStreamUrl(id: String): String {
val request = api.stream(id).execute()
val url = request.raw().request().url().toString()
if (request.isSuccessful) {
request.body()?.close()
}
return url
}
private fun OkHttpClient.Builder.addLogging() {
val loggingInterceptor = HttpLoggingInterceptor()
loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
this.addInterceptor(loggingInterceptor)
}
@SuppressWarnings("TrustAllX509TrustManager")
private fun OkHttpClient.Builder.allowSelfSignedCertificates() {
val trustManager = object : X509TrustManager {
override fun checkClientTrusted(p0: Array<out X509Certificate>?, p1: String?) {}
override fun checkServerTrusted(p0: Array<out X509Certificate>?, p1: String?) {}
override fun getAcceptedIssuers(): Array<X509Certificate> = emptyArray()
}
val sslContext = SSLContext.getInstance("SSL")
sslContext.init(null, arrayOf(trustManager), SecureRandom())
sslSocketFactory(sslContext.socketFactory, trustManager)
hostnameVerifier { _, _ -> true }
}
}
|
gpl-3.0
|
d27eb298aaeec8f26dc861b28755f28e
| 37.788945 | 100 | 0.678326 | 4.951251 | false | true | false | false |
DreierF/MyTargets
|
shared/src/main/java/de/dreier/mytargets/shared/targets/models/WAField.kt
|
1
|
2239
|
/*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets 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.
*/
package de.dreier.mytargets.shared.targets.models
import android.graphics.Color.WHITE
import de.dreier.mytargets.shared.R
import de.dreier.mytargets.shared.models.Dimension
import de.dreier.mytargets.shared.models.Dimension.Unit.CENTIMETER
import de.dreier.mytargets.shared.models.ETargetType
import de.dreier.mytargets.shared.targets.decoration.CenterMarkDecorator
import de.dreier.mytargets.shared.targets.scoringstyle.ScoringStyle
import de.dreier.mytargets.shared.targets.zone.CircularZone
import de.dreier.mytargets.shared.utils.Color.DARK_GRAY
import de.dreier.mytargets.shared.utils.Color.LEMON_YELLOW
open class WAField internal constructor(id: Long, nameRes: Int) : TargetModelBase(
id = id,
nameRes = nameRes,
zones = listOf(
CircularZone(0.1f, LEMON_YELLOW, DARK_GRAY, 4),
CircularZone(0.2f, LEMON_YELLOW, DARK_GRAY, 4),
CircularZone(0.4f, DARK_GRAY, WHITE, 4),
CircularZone(0.6f, DARK_GRAY, WHITE, 4),
CircularZone(0.8f, DARK_GRAY, WHITE, 4),
CircularZone(1.0f, DARK_GRAY, WHITE, 4)
),
scoringStyles = listOf(
ScoringStyle(true, 5, 5, 4, 3, 2, 1),
ScoringStyle(false, 6, 5, 4, 3, 2, 1)
),
diameters = listOf(
Dimension(20f, CENTIMETER),
Dimension(40f, CENTIMETER),
Dimension(60f, CENTIMETER),
Dimension(80f, CENTIMETER)
),
type = ETargetType.FIELD
) {
constructor() : this(ID, R.string.wa_field)
init {
decorator = CenterMarkDecorator(DARK_GRAY, 10.5f, 4, false)
}
companion object {
const val ID = 13L
}
}
|
gpl-2.0
|
7290d87b5494224f9230cc73d0c0c7a3
| 35.704918 | 82 | 0.664136 | 3.820819 | false | false | false | false |
JuliaSoboleva/SmartReceiptsLibrary
|
app/src/main/java/co/smartreceipts/android/model/impl/columns/categories/CategoryColumnDefinitions.kt
|
2
|
3747
|
package co.smartreceipts.android.model.impl.columns.categories
import androidx.annotation.StringRes
import co.smartreceipts.android.R
import co.smartreceipts.android.model.ActualColumnDefinition
import co.smartreceipts.android.model.Column
import co.smartreceipts.android.model.ColumnDefinitions
import co.smartreceipts.android.model.Keyed
import co.smartreceipts.android.model.comparators.ColumnNameComparator
import co.smartreceipts.android.model.impl.columns.AbstractColumnImpl
import co.smartreceipts.android.model.impl.columns.categories.CategoryColumnDefinitions.ActualDefinition.*
import co.smartreceipts.android.persistence.database.controllers.grouping.results.SumCategoryGroupingResult
import co.smartreceipts.core.sync.model.SyncState
import co.smartreceipts.core.sync.model.impl.DefaultSyncState
import co.smartreceipts.android.workers.reports.ReportResourcesManager
import java.util.*
class CategoryColumnDefinitions(private val reportResourcesManager: ReportResourcesManager,
private val multiCurrency: Boolean,
private val taxEnabled: Boolean) :
ColumnDefinitions<SumCategoryGroupingResult> {
private val actualDefinitions = values()
/**
* Note: Column types must be unique
* Column type must be >= 0
*/
internal enum class ActualDefinition(
override val columnType: Int,
@StringRes override val columnHeaderId: Int
) : ActualColumnDefinition {
NAME(0, R.string.category_name_field),
CODE(1, R.string.category_code_field),
PRICE(2, R.string.category_price_field),
TAX(3, R.string.category_tax_field),
PRICE_EXCHANGED(4, R.string.category_price_exchanged_field);
}
override fun getColumn(
id: Int,
columnType: Int,
syncState: SyncState,
ignoredCustomOrderId: Long,
ignoredUuid: UUID
): Column<SumCategoryGroupingResult> {
for (definition in actualDefinitions) {
if (columnType == definition.columnType) {
return getColumnFromClass(definition, id, syncState)
}
}
throw IllegalArgumentException("Unknown column type: $columnType")
}
override fun getAllColumns(): List<Column<SumCategoryGroupingResult>> {
val columns = ArrayList<AbstractColumnImpl<SumCategoryGroupingResult>>(actualDefinitions.size)
for (definition in actualDefinitions) {
if (definition == PRICE_EXCHANGED && !multiCurrency) {
// don't include PRICE_EXCHANGED definition if all receipts have same currency
continue
} else if (definition == TAX && !taxEnabled) {
// don't include TAX definition if tax field is disabled
continue
} else {
columns.add(getColumnFromClass(definition))
}
}
Collections.sort(columns, ColumnNameComparator(reportResourcesManager))
return ArrayList<Column<SumCategoryGroupingResult>>(columns)
}
override fun getDefaultInsertColumn(): Column<SumCategoryGroupingResult> {
return getColumnFromClass(NAME)
}
private fun getColumnFromClass(
definition: ActualDefinition,
id: Int = Keyed.MISSING_ID,
syncState: SyncState = DefaultSyncState()
): AbstractColumnImpl<SumCategoryGroupingResult> {
return when (definition) {
NAME -> CategoryNameColumn(id, syncState)
CODE -> CategoryCodeColumn(id, syncState)
PRICE -> CategoryPriceColumn(id, syncState)
TAX -> CategoryTaxColumn(id, syncState)
PRICE_EXCHANGED -> CategoryExchangedPriceColumn(id, syncState)
}
}
}
|
agpl-3.0
|
1e78af1081d39cf82b30b9c93d86ebfe
| 39.290323 | 107 | 0.693088 | 4.930263 | false | false | false | false |
paplorinc/intellij-community
|
platform/dvcs-impl/src/com/intellij/dvcs/push/ui/ForcePushAction.kt
|
2
|
3043
|
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.dvcs.push.ui
import com.intellij.dvcs.push.PushSupport
import com.intellij.dvcs.push.PushTarget
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.ui.showOkCancelDialog
import com.intellij.xml.util.XmlStringUtil
class ForcePushAction : PushActionBase() {
override fun actionPerformed(project: Project, ui: VcsPushUi) {
if (confirmForcePush(project, ui)) {
ui.push(true)
}
}
override fun isEnabled(ui: VcsPushUi): Boolean {
return ui.canPush() && getProhibitedTarget(ui) == null
}
override fun getDescription(ui: VcsPushUi, enabled: Boolean): String? {
val prohibitedTarget = getProhibitedTarget(ui)
return if (!enabled && prohibitedTarget != null) {
"Force push to ${prohibitedTarget.presentation} is prohibited"
}
else null
}
private fun confirmForcePush(project: Project, ui: VcsPushUi): Boolean {
val silentForcePushIsNotAllowed = ui.selectedPushSpecs.mapValues { (support, pushInfos) ->
pushInfos.filter { it -> !support.isSilentForcePushAllowed(it.pushSpec.target) }
}.filterValues { it.isNotEmpty() }
if (silentForcePushIsNotAllowed.isEmpty()) return true
// get common target if everything is pushed "synchronously" into a single place
val commonTarget: PushTarget?
val aSupport: PushSupport<*, *, PushTarget>?
if (silentForcePushIsNotAllowed.size > 1) {
aSupport = null
commonTarget = null
}
else {
aSupport = silentForcePushIsNotAllowed.keys.first()
commonTarget = silentForcePushIsNotAllowed[aSupport]!!.map { it.pushSpec.target }.distinct().singleOrNull()
}
val to = if (commonTarget != null) " to <b>${commonTarget.presentation}</b>" else ""
val message = "You're going to force push${to}. It may overwrite commits at the remote. Are you sure you want to proceed?"
val myDoNotAskOption = if (commonTarget != null) MyDoNotAskOptionForPush(aSupport!!, commonTarget) else null
val decision = showOkCancelDialog(title = "Force Push", message = XmlStringUtil.wrapInHtml(message),
okText = "&Force Push",
icon = Messages.getWarningIcon(), doNotAskOption = myDoNotAskOption,
project = project)
return decision == Messages.OK
}
}
private class MyDoNotAskOptionForPush(private val pushSupport: PushSupport<*, *, PushTarget>,
private val commonTarget: PushTarget) : DialogWrapper.DoNotAskOption.Adapter() {
override fun rememberChoice(isSelected: Boolean, exitCode: Int) {
if (exitCode == Messages.OK && isSelected) {
pushSupport.saveSilentForcePushTarget(commonTarget)
}
}
override fun getDoNotShowMessage() = "Don't warn about this target"
}
|
apache-2.0
|
3109f962d98194e1cc47d3c5cb64ad35
| 41.859155 | 140 | 0.697338 | 4.353362 | false | false | false | false |
PaulWoitaschek/MaterialAudiobookPlayer
|
app/src/main/java/de/ph1b/audiobook/features/folderChooser/FolderChooserActivity.kt
|
1
|
5810
|
package de.ph1b.audiobook.features.folderChooser
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.AdapterView
import android.widget.Toast
import androidx.core.view.isVisible
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import de.ph1b.audiobook.R
import de.ph1b.audiobook.features.folderChooser.FolderChooserActivity.Companion.newInstanceIntent
import de.ph1b.audiobook.misc.MultiLineSpinnerAdapter
import de.ph1b.audiobook.misc.PermissionHelper
import de.ph1b.audiobook.misc.Permissions
import de.ph1b.audiobook.misc.color
import de.ph1b.audiobook.misc.drawable
import de.ph1b.audiobook.misc.itemSelections
import de.ph1b.audiobook.misc.tint
import de.ph1b.audiobook.mvp.RxBaseActivity
import kotlinx.android.synthetic.main.activity_folder_chooser.*
import timber.log.Timber
import java.io.File
/**
* Activity for choosing an audiobook folder. If there are multiple SD-Cards, the Activity unifies
* them to a fake-folder structure. We must make sure that this is not choosable. When there are no
* multiple sd-cards, we will directly show the content of the 1 SD Card.
*
*
* Use [newInstanceIntent] to get a new intent with the necessary
* values.
*/
class FolderChooserActivity : RxBaseActivity<FolderChooserView, FolderChooserPresenter>(),
FolderChooserView {
override fun newPresenter() = FolderChooserPresenter()
override fun provideView() = this
override fun showSubFolderWarning(first: String, second: String) {
val message = "${getString(R.string.adding_failed_subfolder)}\n$first\n$second"
Toast.makeText(this, message, Toast.LENGTH_LONG)
.show()
}
private lateinit var adapter: FolderChooserAdapter
private lateinit var spinnerAdapter: MultiLineSpinnerAdapter<File>
private lateinit var permissions: Permissions
private lateinit var permissionHelper: PermissionHelper
override fun getMode() = OperationMode.valueOf(intent.getStringExtra(NI_OPERATION_MODE))
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
permissions = Permissions(this)
permissionHelper = PermissionHelper(this, permissions)
setContentView(R.layout.activity_folder_chooser)
setupToolbar()
// listeners
choose.setOnClickListener { presenter().chooseClicked() }
abort.setOnClickListener { finish() }
upButton.setOnClickListener { onBackPressed() }
// recycler
adapter = FolderChooserAdapter(this, getMode()) {
presenter().fileSelected(it)
}
recycler.layoutManager = LinearLayoutManager(this)
recycler.addItemDecoration(
DividerItemDecoration(
this,
DividerItemDecoration.VERTICAL
)
)
recycler.adapter = adapter
val itemAnimator = recycler.itemAnimator as DefaultItemAnimator
itemAnimator.supportsChangeAnimations = false
// spinner
spinnerAdapter =
MultiLineSpinnerAdapter(toolSpinner, this, color(R.color.textColorPrimary)) { file, _ ->
if (file.absolutePath == FolderChooserPresenter.MARSHMALLOW_SD_FALLBACK) {
getString(R.string.storage_all)
} else {
file.name
}
}
toolSpinner.adapter = spinnerAdapter
toolSpinner.itemSelections {
if (it != AdapterView.INVALID_POSITION) {
Timber.i("spinner selected with position $it and adapter.count ${spinnerAdapter.count}")
val item = spinnerAdapter.getItem(it)
presenter().fileSelected(item)
}
}
}
private fun setupToolbar() {
toolbar.setNavigationIcon(R.drawable.close)
toolbar.setNavigationOnClickListener { super.onBackPressed() }
toolbar.setTitle(R.string.audiobook_folders_title)
toolbar.tint()
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
this.permissions.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
override fun onStart() {
super.onStart()
// permissions
permissionHelper.storagePermission { presenter().gotPermission() }
}
override fun onBackPressed() {
if (!presenter().backConsumed()) {
super.onBackPressed()
}
}
override fun setCurrentFolderText(text: String) {
currentFolder.text = text
}
override fun showNewData(newData: List<File>) {
adapter.newData(newData)
}
override fun setChooseButtonEnabled(chooseEnabled: Boolean) {
choose.isEnabled = chooseEnabled
}
override fun newRootFolders(newFolders: List<File>) {
Timber.i("newRootFolders called with $newFolders")
spinnerGroup.isVisible = newFolders.size > 1
spinnerAdapter.setData(newFolders)
}
/**
* Sets the choose button enabled or disabled, depending on where we are in the hierarchy
*/
override fun setUpButtonEnabled(upEnabled: Boolean) {
upButton.isEnabled = upEnabled
val upIcon = if (upEnabled) drawable(R.drawable.ic_arrow_upward) else null
upButton.setImageDrawable(upIcon)
}
enum class OperationMode {
COLLECTION_BOOK,
SINGLE_BOOK
}
companion object {
private const val NI_OPERATION_MODE = "niOperationMode"
/**
* Generates a new intent with the necessary extras
* @param c The context
* *
* @param operationMode The operation mode for the activity
* *
* @return The new intent
*/
fun newInstanceIntent(c: Context, operationMode: OperationMode): Intent {
val intent = Intent(c, FolderChooserActivity::class.java)
intent.putExtra(NI_OPERATION_MODE, operationMode.name)
return intent
}
}
}
|
lgpl-3.0
|
764e51e2314929a825183d1f63636cde
| 30.576087 | 99 | 0.737177 | 4.465796 | false | false | false | false |
google/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/search/ideaExtensions/DefaultAnnotationMethodKotlinImplicitReferenceSearcher.kt
|
2
|
2787
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.search.ideaExtensions
import com.intellij.openapi.application.QueryExecutorBase
import com.intellij.openapi.application.ReadActionProcessor
import com.intellij.psi.PsiAnnotation
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiReference
import com.intellij.psi.search.searches.MethodReferencesSearch
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.psi.util.PsiUtil
import com.intellij.util.Processor
import org.jetbrains.kotlin.idea.base.util.restrictToKotlinSources
import org.jetbrains.kotlin.idea.references.KtDefaultAnnotationArgumentReference
import org.jetbrains.kotlin.idea.references.KtSimpleNameReference
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.psi.KtAnnotationEntry
import org.jetbrains.kotlin.psi.KtValueArgument
import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypeAndBranch
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
class DefaultAnnotationMethodKotlinImplicitReferenceSearcher :
QueryExecutorBase<PsiReference, MethodReferencesSearch.SearchParameters>(true) {
private val PsiMethod.isDefaultAnnotationMethod: Boolean
get() = PsiUtil.isAnnotationMethod(this) && name == PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME && parameterList.parametersCount == 0
private fun createReferenceProcessor(consumer: Processor<in PsiReference>) = object : ReadActionProcessor<PsiReference>() {
override fun processInReadAction(reference: PsiReference): Boolean {
if (reference !is KtSimpleNameReference) return true
val annotationEntry = reference.expression.getParentOfTypeAndBranch<KtAnnotationEntry> { typeReference } ?: return true
val argument = annotationEntry.valueArguments.singleOrNull() as? KtValueArgument ?: return true
val implicitRef = argument.references.firstIsInstanceOrNull<KtDefaultAnnotationArgumentReference>() ?: return true
return consumer.process(implicitRef)
}
}
override fun processQuery(queryParameters: MethodReferencesSearch.SearchParameters, consumer: Processor<in PsiReference>) {
runReadAction {
val method = queryParameters.method
if (!method.isDefaultAnnotationMethod) return@runReadAction null
val annotationClass = method.containingClass ?: return@runReadAction null
val searchScope = queryParameters.effectiveSearchScope.restrictToKotlinSources()
ReferencesSearch.search(annotationClass, searchScope)
}?.forEach(createReferenceProcessor(consumer))
}
}
|
apache-2.0
|
2b6766448b64a3b425538ee5bc9143b3
| 58.297872 | 158 | 0.796555 | 5.380309 | false | false | false | false |
JetBrains/intellij-community
|
plugins/kotlin/uast/uast-kotlin-idea/src/org/jetbrains/uast/kotlin/generate/KotlinUastCodeGenerationPlugin.kt
|
1
|
25532
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.uast.kotlin.generate
import com.intellij.lang.Language
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.*
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.util.asSafely
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNameSuggester
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.core.*
import org.jetbrains.kotlin.idea.intentions.ImportAllMembersIntention
import org.jetbrains.kotlin.idea.refactoring.fqName.fqName
import org.jetbrains.kotlin.idea.references.KtSimpleNameReference
import org.jetbrains.kotlin.idea.util.getResolutionScope
import org.jetbrains.kotlin.idea.util.resolveToKotlinType
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.references.fe10.KtFe10SimpleNameReference
import org.jetbrains.kotlin.resolve.scopes.utils.findClassifier
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import org.jetbrains.uast.*
import org.jetbrains.uast.generate.UParameterInfo
import org.jetbrains.uast.generate.UastCodeGenerationPlugin
import org.jetbrains.uast.generate.UastElementFactory
import org.jetbrains.uast.kotlin.*
import org.jetbrains.uast.kotlin.internal.KotlinFakeUElement
class KotlinUastCodeGenerationPlugin : UastCodeGenerationPlugin {
override val language: Language
get() = KotlinLanguage.INSTANCE
override fun getElementFactory(project: Project): UastElementFactory =
KotlinUastElementFactory(project)
override fun <T : UElement> replace(oldElement: UElement, newElement: T, elementType: Class<T>): T? {
val oldPsi = oldElement.toSourcePsiFakeAware().singleOrNull() ?: return null
val newPsi = newElement.sourcePsi?.let {
when {
it is KtCallExpression && it.parent is KtQualifiedExpression -> it.parent
else -> it
}
} ?: return null
val psiFactory = KtPsiFactory(oldPsi.project)
val oldParentPsi = oldPsi.parent
val (updOldPsi, updNewPsi) = when {
oldParentPsi is KtStringTemplateExpression && oldParentPsi.entries.size == 1 ->
oldParentPsi to newPsi
oldPsi is KtStringTemplateEntry && newPsi !is KtStringTemplateEntry && newPsi is KtExpression ->
oldPsi to psiFactory.createBlockStringTemplateEntry(newPsi)
oldPsi is KtBlockExpression && newPsi is KtBlockExpression -> {
if (!hasBraces(oldPsi) && hasBraces(newPsi)) {
oldPsi to psiFactory.createLambdaExpression("none", newPsi.statements.joinToString("\n") { "println()" }).bodyExpression!!.also {
it.statements.zip(newPsi.statements).forEach { it.first.replace(it.second) }
}
} else
oldPsi to newPsi
}
else ->
oldPsi to newPsi
}
val replaced = updOldPsi.replace(updNewPsi)?.safeAs<KtElement>()?.let { ShortenReferences.DEFAULT.process(it) }
return when {
newElement.sourcePsi is KtCallExpression && replaced is KtQualifiedExpression -> replaced.selectorExpression
else -> replaced
}?.toUElementOfExpectedTypes(elementType)
}
override fun bindToElement(reference: UReferenceExpression, element: PsiElement): PsiElement? {
val sourcePsi = reference.sourcePsi ?: return null
if (sourcePsi !is KtSimpleNameExpression) return null
return KtFe10SimpleNameReference(sourcePsi)
.bindToElement(element, KtSimpleNameReference.ShorteningMode.FORCED_SHORTENING)
}
override fun shortenReference(reference: UReferenceExpression): UReferenceExpression? {
val sourcePsi = reference.sourcePsi ?: return null
if (sourcePsi !is KtElement) return null
return ShortenReferences.DEFAULT.process(sourcePsi).toUElementOfType()
}
override fun importMemberOnDemand(reference: UQualifiedReferenceExpression): UExpression? {
val ktQualifiedExpression = reference.sourcePsi?.asSafely<KtDotQualifiedExpression>() ?: return null
val selector = ktQualifiedExpression.selectorExpression ?: return null
val ptr = SmartPointerManager.createPointer(selector)
ImportAllMembersIntention().applyTo(ktQualifiedExpression, null)
return ptr.element?.toUElementOfType()
}
override fun initializeField(uField: UField, uParameter: UParameter) {
val uMethod = uParameter.getParentOfType(UMethod::class.java, false) ?: return
val sourcePsi = uMethod.sourcePsi ?: return
if (sourcePsi is KtPrimaryConstructor) {
if (uField.name == uParameter.name) {
val psiElement = uParameter.sourcePsi ?: return
val ktParameter = KtPsiFactory(psiElement.project).createParameter(uField.sourcePsi?.text ?: return)
ktParameter.modifierList?.getModifier(KtTokens.FINAL_KEYWORD)?.delete()
ktParameter.defaultValue?.delete()
ktParameter.equalsToken?.delete()
val psiField = uField.sourcePsi
if (psiField != null) {
val nextSibling = psiField.nextSibling
if (nextSibling is PsiWhiteSpace) {
nextSibling.delete()
}
psiField.delete()
}
psiElement.replace(ktParameter)
}
else {
val property = uField.sourcePsi as? KtProperty ?: return
property.initializer = KtPsiFactory(property.project).createExpression(uParameter.name)
}
return
}
val body = (sourcePsi as? KtDeclarationWithBody)?.bodyBlockExpression ?: return
val ktPsiFactory = KtPsiFactory(sourcePsi)
val assigmentExpression = ktPsiFactory.buildExpression {
if (uField.name == uParameter.name) {
appendFixedText("this.")
}
appendName(Name.identifier(uField.name))
appendFixedText(" = ")
appendName(Name.identifier(uParameter.name))
}
body.addBefore(assigmentExpression, body.rBrace)
}
}
private fun hasBraces(oldPsi: KtBlockExpression): Boolean = oldPsi.lBrace != null && oldPsi.rBrace != null
class KotlinUastElementFactory(project: Project) : UastElementFactory {
private val contextlessPsiFactory = KtPsiFactory(project)
private fun psiFactory(context: PsiElement?): KtPsiFactory {
return if (context != null) KtPsiFactory.contextual(context) else contextlessPsiFactory
}
override fun createQualifiedReference(qualifiedName: String, context: PsiElement?): UQualifiedReferenceExpression? {
return psiFactory(context).createExpression(qualifiedName).let {
when (it) {
is KtDotQualifiedExpression -> KotlinUQualifiedReferenceExpression(it, null)
is KtSafeQualifiedExpression -> KotlinUSafeQualifiedExpression(it, null)
else -> null
}
}
}
override fun createCallExpression(
receiver: UExpression?,
methodName: String,
parameters: List<UExpression>,
expectedReturnType: PsiType?,
kind: UastCallKind,
context: PsiElement?
): UCallExpression? {
if (kind != UastCallKind.METHOD_CALL) return null
val psiFactory = psiFactory(context)
val name = methodName.quoteIfNeeded()
val methodCall = psiFactory.createExpression(
buildString {
if (receiver != null) {
append("a")
receiver.sourcePsi?.nextSibling.safeAs<PsiWhiteSpace>()?.let { whitespaces ->
append(whitespaces.text)
}
append(".")
}
append(name)
append("()")
}
).getPossiblyQualifiedCallExpression() ?: return null
if (receiver != null) {
methodCall.parent.safeAs<KtDotQualifiedExpression>()?.receiverExpression?.replace(wrapULiteral(receiver).sourcePsi!!)
}
val valueArgumentList = methodCall.valueArgumentList
for (parameter in parameters) {
valueArgumentList?.addArgument(psiFactory.createArgument(wrapULiteral(parameter).sourcePsi as KtExpression))
}
if (context !is KtElement) return KotlinUFunctionCallExpression(methodCall, null)
val analyzableMethodCall = psiFactory.getAnalyzableMethodCall(methodCall, context)
if (analyzableMethodCall.canMoveLambdaOutsideParentheses()) {
analyzableMethodCall.moveFunctionLiteralOutsideParentheses()
}
if (expectedReturnType == null) return KotlinUFunctionCallExpression(analyzableMethodCall, null)
val methodCallPsiType = KotlinUFunctionCallExpression(analyzableMethodCall, null).getExpressionType()
if (methodCallPsiType == null || !expectedReturnType.isAssignableFrom(GenericsUtil.eliminateWildcards(methodCallPsiType))) {
val typeParams = (context as? KtElement)?.let { kontext ->
val resolutionFacade = kontext.getResolutionFacade()
(expectedReturnType as? PsiClassType)?.parameters?.map { it.resolveToKotlinType(resolutionFacade) }
}
if (typeParams == null) return KotlinUFunctionCallExpression(analyzableMethodCall, null)
for (typeParam in typeParams) {
val typeParameter = psiFactory.createTypeArgument(typeParam.fqName?.asString().orEmpty())
analyzableMethodCall.addTypeArgument(typeParameter)
}
return KotlinUFunctionCallExpression(analyzableMethodCall, null)
}
return KotlinUFunctionCallExpression(analyzableMethodCall, null)
}
private fun KtPsiFactory.getAnalyzableMethodCall(methodCall: KtCallExpression, context: KtElement): KtCallExpression {
val analyzableElement = ((createExpressionCodeFragment("(null)", context).copy() as KtExpressionCodeFragment)
.getContentElement()!! as KtParenthesizedExpression).expression!!
val isQualified = methodCall.parent is KtQualifiedExpression
return if (isQualified) {
(analyzableElement.replaced(methodCall.parent) as KtQualifiedExpression).lastChild as KtCallExpression
} else {
analyzableElement.replaced(methodCall)
}
}
override fun createCallableReferenceExpression(
receiver: UExpression?,
methodName: String,
context: PsiElement?
): UCallableReferenceExpression? {
val text = receiver?.sourcePsi?.text ?: ""
val callableExpression = psiFactory(context).createCallableReferenceExpression("$text::$methodName") ?: return null
return KotlinUCallableReferenceExpression(callableExpression, null)
}
override fun createStringLiteralExpression(text: String, context: PsiElement?): ULiteralExpression {
return KotlinStringULiteralExpression(psiFactory(context).createExpression(StringUtil.wrapWithDoubleQuote(text)), null)
}
override fun createLongConstantExpression(long: Long, context: PsiElement?): UExpression? {
return when (val literalExpr = psiFactory(context).createExpression(long.toString() + "L")) {
is KtConstantExpression -> KotlinULiteralExpression(literalExpr, null)
is KtPrefixExpression -> KotlinUPrefixExpression(literalExpr, null)
else -> null
}
}
override fun createNullLiteral(context: PsiElement?): ULiteralExpression {
return psiFactory(context).createExpression("null").toUElementOfType()!!
}
@Suppress("UNUSED_PARAMETER")
/*override*/ fun createIntLiteral(value: Int, context: PsiElement?): ULiteralExpression {
return psiFactory(context).createExpression(value.toString()).toUElementOfType()!!
}
private fun KtExpression.ensureBlockExpressionBraces(psiFactory: KtPsiFactory): KtExpression {
if (this !is KtBlockExpression || hasBraces(this)) return this
val blockExpression = psiFactory.createBlock(this.statements.joinToString("\n") { "println()" })
for ((placeholder, statement) in blockExpression.statements.zip(this.statements)) {
placeholder.replace(statement)
}
return blockExpression
}
@Deprecated("use version with context parameter")
fun createIfExpression(condition: UExpression, thenBranch: UExpression, elseBranch: UExpression?): UIfExpression? {
logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter")
return createIfExpression(condition, thenBranch, elseBranch, null)
}
override fun createIfExpression(
condition: UExpression,
thenBranch: UExpression,
elseBranch: UExpression?,
context: PsiElement?
): UIfExpression? {
val conditionPsi = condition.sourcePsi as? KtExpression ?: return null
val thenBranchPsi = thenBranch.sourcePsi as? KtExpression ?: return null
val elseBranchPsi = elseBranch?.sourcePsi as? KtExpression
val psiFactory = psiFactory(context)
return KotlinUIfExpression(
psiFactory.createIf(
conditionPsi,
thenBranchPsi.ensureBlockExpressionBraces(psiFactory),
elseBranchPsi?.ensureBlockExpressionBraces(psiFactory)
),
givenParent = null
)
}
@Deprecated("use version with context parameter")
fun createParenthesizedExpression(expression: UExpression): UParenthesizedExpression? {
logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter")
return createParenthesizedExpression(expression, null)
}
override fun createParenthesizedExpression(expression: UExpression, context: PsiElement?): UParenthesizedExpression? {
val source = expression.sourcePsi ?: return null
val parenthesized = psiFactory(context).createExpression("(${source.text})") as? KtParenthesizedExpression ?: return null
return KotlinUParenthesizedExpression(parenthesized, null)
}
@Deprecated("use version with context parameter")
fun createSimpleReference(name: String): USimpleNameReferenceExpression {
logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter")
return createSimpleReference(name, null)
}
override fun createSimpleReference(name: String, context: PsiElement?): USimpleNameReferenceExpression {
return KotlinUSimpleReferenceExpression(psiFactory(context).createSimpleName(name), null)
}
@Deprecated("use version with context parameter")
fun createSimpleReference(variable: UVariable): USimpleNameReferenceExpression? {
logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter")
return createSimpleReference(variable, null)
}
override fun createSimpleReference(variable: UVariable, context: PsiElement?): USimpleNameReferenceExpression? {
return createSimpleReference(variable.name ?: return null, context)
}
@Deprecated("use version with context parameter")
fun createReturnExpresion(expression: UExpression?, inLambda: Boolean): UReturnExpression {
logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter")
return createReturnExpresion(expression, inLambda, null)
}
override fun createReturnExpresion(expression: UExpression?, inLambda: Boolean, context: PsiElement?): UReturnExpression {
val label = if (inLambda && context != null) getParentLambdaLabelName(context)?.let { "@$it" } ?: "" else ""
val returnExpression = psiFactory(context).createExpression("return$label 1") as KtReturnExpression
val sourcePsi = expression?.sourcePsi
if (sourcePsi != null) {
returnExpression.returnedExpression!!.replace(sourcePsi)
} else {
returnExpression.returnedExpression?.delete()
}
return KotlinUReturnExpression(returnExpression, null)
}
private fun getParentLambdaLabelName(context: PsiElement): String? {
val lambdaExpression = context.getParentOfType<KtLambdaExpression>(false) ?: return null
lambdaExpression.parent.safeAs<KtLabeledExpression>()?.let { return it.getLabelName() }
val callExpression = lambdaExpression.getStrictParentOfType<KtCallExpression>() ?: return null
callExpression.valueArguments.find {
it.getArgumentExpression()?.unpackFunctionLiteral(allowParentheses = false) === lambdaExpression
} ?: return null
return callExpression.getCallNameExpression()?.text
}
@Deprecated("use version with context parameter")
fun createBinaryExpression(
leftOperand: UExpression,
rightOperand: UExpression,
operator: UastBinaryOperator
): UBinaryExpression? {
logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter")
return createBinaryExpression(leftOperand, rightOperand, operator, null)
}
override fun createBinaryExpression(
leftOperand: UExpression,
rightOperand: UExpression,
operator: UastBinaryOperator,
context: PsiElement?
): UBinaryExpression? {
val binaryExpression = joinBinaryExpression(leftOperand, rightOperand, operator, context) ?: return null
return KotlinUBinaryExpression(binaryExpression, null)
}
private fun joinBinaryExpression(
leftOperand: UExpression,
rightOperand: UExpression,
operator: UastBinaryOperator,
context: PsiElement?
): KtBinaryExpression? {
val leftPsi = leftOperand.sourcePsi ?: return null
val rightPsi = rightOperand.sourcePsi ?: return null
val binaryExpression = psiFactory(context).createExpression("a ${operator.text} b") as? KtBinaryExpression ?: return null
binaryExpression.left?.replace(leftPsi)
binaryExpression.right?.replace(rightPsi)
return binaryExpression
}
@Deprecated("use version with context parameter")
fun createFlatBinaryExpression(
leftOperand: UExpression,
rightOperand: UExpression,
operator: UastBinaryOperator
): UPolyadicExpression? {
logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter")
return createFlatBinaryExpression(leftOperand, rightOperand, operator, null)
}
override fun createFlatBinaryExpression(
leftOperand: UExpression,
rightOperand: UExpression,
operator: UastBinaryOperator,
context: PsiElement?
): UPolyadicExpression? {
fun unwrapParentheses(exp: KtExpression?) {
if (exp !is KtParenthesizedExpression) return
if (!KtPsiUtil.areParenthesesUseless(exp)) return
exp.expression?.let { exp.replace(it) }
}
val binaryExpression = joinBinaryExpression(leftOperand, rightOperand, operator, context) ?: return null
unwrapParentheses(binaryExpression.left)
unwrapParentheses(binaryExpression.right)
return psiFactory(context).createExpression(binaryExpression.text).toUElementOfType()!!
}
@Deprecated("use version with context parameter")
fun createBlockExpression(expressions: List<UExpression>): UBlockExpression {
logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter")
return createBlockExpression(expressions, null)
}
override fun createBlockExpression(expressions: List<UExpression>, context: PsiElement?): UBlockExpression {
val sourceExpressions = expressions.flatMap { it.toSourcePsiFakeAware() }
val block = psiFactory(context).createBlock(
sourceExpressions.joinToString(separator = "\n") { "println()" }
)
for ((placeholder, psiElement) in block.statements.zip(sourceExpressions)) {
placeholder.replace(psiElement)
}
return KotlinUBlockExpression(block, null)
}
@Deprecated("use version with context parameter")
fun createDeclarationExpression(declarations: List<UDeclaration>): UDeclarationsExpression {
logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter")
return createDeclarationExpression(declarations, null)
}
override fun createDeclarationExpression(declarations: List<UDeclaration>, context: PsiElement?): UDeclarationsExpression {
return object : KotlinUDeclarationsExpression(null), KotlinFakeUElement {
override var declarations: List<UDeclaration> = declarations
override fun unwrapToSourcePsi(): List<PsiElement> = declarations.flatMap { it.toSourcePsiFakeAware() }
}
}
override fun createLambdaExpression(
parameters: List<UParameterInfo>,
body: UExpression,
context: PsiElement?
): ULambdaExpression? {
val resolutionFacade = (context as? KtElement)?.getResolutionFacade()
val validator = (context as? KtElement)?.let { usedNamesFilter(it) } ?: { true }
val newLambdaStatements = if (body is UBlockExpression) {
body.expressions.flatMap { member ->
when {
member is UReturnExpression -> member.returnExpression?.toSourcePsiFakeAware().orEmpty()
else -> member.toSourcePsiFakeAware()
}
}
} else
listOf(body.sourcePsi!!)
val ktLambdaExpression = psiFactory(context).createLambdaExpression(
parameters.joinToString(", ") { p ->
val ktype = resolutionFacade?.let { p.type?.resolveToKotlinType(it) }
StringBuilder().apply {
append(p.suggestedName ?: ktype?.let { Fe10KotlinNameSuggester.suggestNamesByType(it, validator).firstOrNull() })
?: Fe10KotlinNameSuggester.suggestNameByName("v", validator)
ktype?.fqName?.toString()?.let { append(": ").append(it) }
}
},
newLambdaStatements.joinToString("\n") { "placeholder" }
)
for ((old, new) in ktLambdaExpression.bodyExpression!!.statements.zip(newLambdaStatements)) {
old.replace(new)
}
return ktLambdaExpression.toUElementOfType()!!
}
@Deprecated("use version with context parameter")
fun createLambdaExpression(parameters: List<UParameterInfo>, body: UExpression): ULambdaExpression? {
logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter")
return createLambdaExpression(parameters, body, null)
}
override fun createLocalVariable(
suggestedName: String?,
type: PsiType?,
initializer: UExpression,
immutable: Boolean,
context: PsiElement?
): ULocalVariable {
val resolutionFacade = (context as? KtElement)?.getResolutionFacade()
val validator = (context as? KtElement)?.let { usedNamesFilter(it) } ?: { true }
val ktype = resolutionFacade?.let { type?.resolveToKotlinType(it) }
val function = psiFactory(context).createFunction(
buildString {
append("fun foo() { ")
append(if (immutable) "val" else "var")
append(" ")
append(suggestedName ?: ktype?.let { Fe10KotlinNameSuggester.suggestNamesByType(it, validator).firstOrNull() })
?: Fe10KotlinNameSuggester.suggestNameByName("v", validator)
ktype?.fqName?.toString()?.let { append(": ").append(it) }
append(" = null")
append("}")
}
)
val ktVariable = PsiTreeUtil.findChildOfType(function, KtVariableDeclaration::class.java)!!
val newVariable = ktVariable.initializer!!.replace(initializer.sourcePsi!!).parent
return newVariable.toUElementOfType<UVariable>() as ULocalVariable
}
@Deprecated("use version with context parameter")
fun createLocalVariable(
suggestedName: String?,
type: PsiType?,
initializer: UExpression,
immutable: Boolean
): ULocalVariable {
logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter")
return createLocalVariable(suggestedName, type, initializer, immutable, null)
}
}
private fun usedNamesFilter(context: KtElement): (String) -> Boolean {
val scope = context.getResolutionScope()
return { name: String -> scope.findClassifier(Name.identifier(name), NoLookupLocation.FROM_IDE) == null }
}
|
apache-2.0
|
c3dda43a79ba93374df0039b86202550
| 45.676417 | 149 | 0.687216 | 5.805366 | false | false | false | false |
JetBrains/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ReplaceMapGetOrDefaultIntention.kt
|
1
|
3121
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention
import org.jetbrains.kotlin.idea.inspections.collections.isCalling
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.findDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.util.getType
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.isNullable
class ReplaceMapGetOrDefaultIntention : SelfTargetingRangeIntention<KtDotQualifiedExpression>(
KtDotQualifiedExpression::class.java, KotlinBundle.lazyMessage("replace.with.indexing.and.elvis.operator")
) {
companion object {
private val getOrDefaultFqName = FqName("kotlin.collections.Map.getOrDefault")
}
override fun applicabilityRange(element: KtDotQualifiedExpression): TextRange? {
val callExpression = element.callExpression ?: return null
val calleeExpression = callExpression.calleeExpression ?: return null
if (calleeExpression.text != getOrDefaultFqName.shortName().asString()) return null
val (firstArg, secondArg) = callExpression.arguments() ?: return null
val context = element.analyze(BodyResolveMode.PARTIAL)
if (callExpression.getResolvedCall(context)?.isCalling(getOrDefaultFqName) != true) return null
if (element.receiverExpression.getType(context)?.arguments?.lastOrNull()?.type?.isNullable() == true) return null
setTextGetter(KotlinBundle.lazyMessage("replace.with.0.1.2", element.receiverExpression.text, firstArg.text, secondArg.text))
return calleeExpression.textRange
}
override fun applyTo(element: KtDotQualifiedExpression, editor: Editor?) {
val callExpression = element.callExpression ?: return
val (firstArg, secondArg) = callExpression.arguments() ?: return
val replaced = element.replaced(
KtPsiFactory(element.project).createExpressionByPattern("$0[$1] ?: $2", element.receiverExpression, firstArg, secondArg)
)
replaced.findDescendantOfType<KtArrayAccessExpression>()?.leftBracket?.startOffset?.let {
editor?.caretModel?.moveToOffset(it)
}
}
private fun KtCallExpression.arguments(): Pair<KtExpression, KtExpression>? {
val args = valueArguments
if (args.size != 2) return null
val first = args[0].getArgumentExpression() ?: return null
val second = args[1].getArgumentExpression() ?: return null
return first to second
}
}
|
apache-2.0
|
d74ce95dfc4c1bc5928522a418a167e9
| 51.915254 | 158 | 0.760333 | 4.922713 | false | false | false | false |
google/iosched
|
mobile/src/main/java/com/google/samples/apps/iosched/ui/signin/SignOutDialogFragment.kt
|
1
|
3926
|
/*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.iosched.ui.signin
import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatDialogFragment
import androidx.core.view.isGone
import androidx.databinding.BindingAdapter
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.samples.apps.iosched.databinding.DialogSignOutBinding
import com.google.samples.apps.iosched.shared.data.signin.AuthenticatedUserInfo
import com.google.samples.apps.iosched.ui.signin.SignInNavigationAction.RequestSignOut
import com.google.samples.apps.iosched.util.executeAfter
import com.google.samples.apps.iosched.util.signin.SignInHandler
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import javax.inject.Inject
/**
* Dialog that confirms that a user wishes to sign out.
*/
@AndroidEntryPoint
class SignOutDialogFragment : AppCompatDialogFragment() {
@Inject
lateinit var signInHandler: SignInHandler
private val signInViewModel: SignInViewModel by viewModels()
private lateinit var binding: DialogSignOutBinding
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
// We want to create a dialog, but we also want to use DataBinding for the content view.
// We can do that by making an empty dialog and adding the content later.
return MaterialAlertDialogBuilder(requireContext()).create()
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// In case we are showing as a dialog, use getLayoutInflater() instead.
binding = DialogSignOutBinding.inflate(layoutInflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
lifecycleScope.launch {
lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
signInViewModel.signInNavigationActions.collect { action ->
if (action == RequestSignOut) {
signInHandler.signOut(requireContext())
dismiss()
}
}
}
}
binding.executeAfter {
viewModel = signInViewModel
lifecycleOwner = viewLifecycleOwner
}
if (showsDialog) {
(requireDialog() as AlertDialog).setView(binding.root)
}
}
}
@BindingAdapter("username")
fun setUsername(textView: TextView, userInfo: AuthenticatedUserInfo?) {
val displayName = userInfo?.getDisplayName()
textView.text = displayName
textView.isGone = displayName.isNullOrEmpty()
}
@BindingAdapter("userEmail")
fun setUserEmail(textView: TextView, userInfo: AuthenticatedUserInfo?) {
val email = userInfo?.getEmail()
textView.text = email
textView.isGone = email.isNullOrEmpty()
}
|
apache-2.0
|
fde9f37398f5793336c07241bda36c6e
| 34.690909 | 96 | 0.732298 | 4.889166 | false | false | false | false |
JetBrains/intellij-community
|
plugins/kotlin/uast/uast-kotlin-idea/tests/test/org/jetbrains/uast/test/kotlin/KotlinUastGenerationTest.kt
|
1
|
54324
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.uast.test.kotlin
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.Ref
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiType
import com.intellij.psi.SyntaxTraverser
import com.intellij.psi.util.parentOfType
import com.intellij.testFramework.LightProjectDescriptor
import com.intellij.testFramework.UsefulTestCase
import com.intellij.testFramework.fixtures.JavaCodeInsightTestFixture
import junit.framework.TestCase
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.utils.addToStdlib.cast
import org.jetbrains.uast.*
import org.jetbrains.uast.expressions.UInjectionHost
import org.jetbrains.uast.generate.UParameterInfo
import org.jetbrains.uast.generate.UastCodeGenerationPlugin
import org.jetbrains.uast.generate.refreshed
import org.jetbrains.uast.generate.replace
import org.jetbrains.uast.kotlin.generate.KotlinUastElementFactory
import org.jetbrains.uast.test.env.findElementByTextFromPsi
import org.jetbrains.uast.test.env.findUElementByTextFromPsi
import org.jetbrains.uast.visitor.UastVisitor
import kotlin.test.fail as kfail
class KotlinUastGenerationTest : KotlinLightCodeInsightFixtureTestCase() {
override fun getProjectDescriptor(): LightProjectDescriptor =
KotlinWithJdkAndRuntimeLightProjectDescriptor.getInstance()
private val psiFactory
get() = KtPsiFactory(project)
private val generatePlugin: UastCodeGenerationPlugin
get() = UastCodeGenerationPlugin.byLanguage(KotlinLanguage.INSTANCE)!!
private val uastElementFactory
get() = generatePlugin.getElementFactory(myFixture.project) as KotlinUastElementFactory
fun `test logical and operation with simple operands`() {
val left = psiFactory.createExpression("true").toUElementOfType<UExpression>()
?: kfail("Cannot create left UExpression")
val right = psiFactory.createExpression("false").toUElementOfType<UExpression>()
?: kfail("Cannot create right UExpression")
val expression = uastElementFactory.createBinaryExpression(left, right, UastBinaryOperator.LOGICAL_AND, dummyContextFile())
?: kfail("Cannot create expression")
TestCase.assertEquals("true && false", expression.sourcePsi?.text)
}
fun `test logical and operation with simple operands with parenthesis`() {
val left = psiFactory.createExpression("(true)").toUElementOfType<UExpression>()
?: kfail("Cannot create left UExpression")
val right = psiFactory.createExpression("(false)").toUElementOfType<UExpression>()
?: kfail("Cannot create right UExpression")
val expression = uastElementFactory.createFlatBinaryExpression(left, right, UastBinaryOperator.LOGICAL_AND, dummyContextFile())
?: kfail("Cannot create expression")
TestCase.assertEquals("true && false", expression.sourcePsi?.text)
TestCase.assertEquals("""
UBinaryExpression (operator = &&)
ULiteralExpression (value = true)
ULiteralExpression (value = false)
""".trimIndent(), expression.putIntoFunctionBody().asRecursiveLogString().trim())
}
fun `test logical and operation with simple operands with parenthesis polyadic`() {
val left = psiFactory.createExpression("(true && false)").toUElementOfType<UExpression>()
?: kfail("Cannot create left UExpression")
val right = psiFactory.createExpression("(false)").toUElementOfType<UExpression>()
?: kfail("Cannot create right UExpression")
val expression = uastElementFactory.createFlatBinaryExpression(left, right, UastBinaryOperator.LOGICAL_AND, dummyContextFile())
?: kfail("Cannot create expression")
TestCase.assertEquals("true && false && false", expression.sourcePsi?.text)
TestCase.assertEquals("""
UBinaryExpression (operator = &&)
UBinaryExpression (operator = &&)
ULiteralExpression (value = true)
ULiteralExpression (value = false)
ULiteralExpression (value = false)
""".trimIndent(), expression.asRecursiveLogString().trim())
}
fun `test simple reference creating from variable`() {
val context = dummyContextFile()
val variable = uastElementFactory.createLocalVariable(
"a", PsiType.INT, uastElementFactory.createNullLiteral(context), false, context
)
val reference = uastElementFactory.createSimpleReference(variable, context) ?: kfail("cannot create reference")
TestCase.assertEquals("a", reference.identifier)
}
fun `test simple reference by name`() {
val reference = uastElementFactory.createSimpleReference("a", dummyContextFile())
TestCase.assertEquals("a", reference.identifier)
}
fun `test parenthesised expression`() {
val expression = psiFactory.createExpression("a + b").toUElementOfType<UExpression>()
?: kfail("cannot create expression")
val parenthesizedExpression = uastElementFactory.createParenthesizedExpression(expression, dummyContextFile())
?: kfail("cannot create parenthesized expression")
TestCase.assertEquals("(a + b)", parenthesizedExpression.sourcePsi?.text)
}
fun `test return expression`() {
val expression = psiFactory.createExpression("a + b").toUElementOfType<UExpression>()
?: kfail("Cannot find plugin")
val returnExpression = uastElementFactory.createReturnExpresion(expression, false, dummyContextFile())
TestCase.assertEquals("a + b", returnExpression.returnExpression?.asRenderString())
TestCase.assertEquals("return a + b", returnExpression.sourcePsi?.text)
}
fun `test variable declaration without type`() {
val expression = psiFactory.createExpression("1 + 2").toUElementOfType<UExpression>()
?: kfail("cannot create variable declaration")
val declaration = uastElementFactory.createLocalVariable("a", null, expression, false, dummyContextFile())
TestCase.assertEquals("var a = 1 + 2", declaration.sourcePsi?.text)
}
fun `test variable declaration with type`() {
val expression = psiFactory.createExpression("b").toUElementOfType<UExpression>()
?: kfail("cannot create variable declaration")
val declaration = uastElementFactory.createLocalVariable("a", PsiType.DOUBLE, expression, false, dummyContextFile())
TestCase.assertEquals("var a: kotlin.Double = b", declaration.sourcePsi?.text)
}
fun `test final variable declaration`() {
val expression = psiFactory.createExpression("b").toUElementOfType<UExpression>()
?: kfail("cannot create variable declaration")
val declaration = uastElementFactory.createLocalVariable("a", PsiType.DOUBLE, expression, true, dummyContextFile())
TestCase.assertEquals("val a: kotlin.Double = b", declaration.sourcePsi?.text)
}
fun `test final variable declaration with unique name`() {
val expression = psiFactory.createExpression("b").toUElementOfType<UExpression>()
?: kfail("cannot create variable declaration")
val declaration = uastElementFactory.createLocalVariable("a", PsiType.DOUBLE, expression, true, dummyContextFile())
TestCase.assertEquals("val a: kotlin.Double = b", declaration.sourcePsi?.text)
TestCase.assertEquals("""
ULocalVariable (name = a)
USimpleNameReferenceExpression (identifier = b)
""".trimIndent(), declaration.asRecursiveLogString().trim())
}
fun `test block expression`() {
val statement1 = psiFactory.createExpression("System.out.println()").toUElementOfType<UExpression>()
?: kfail("cannot create statement")
val statement2 = psiFactory.createExpression("System.out.println(2)").toUElementOfType<UExpression>()
?: kfail("cannot create statement")
val block = uastElementFactory.createBlockExpression(listOf(statement1, statement2), dummyContextFile())
TestCase.assertEquals("""
{
System.out.println()
System.out.println(2)
}
""".trimIndent(), block.sourcePsi?.text
)
}
fun `test lambda expression`() {
val statement = psiFactory.createExpression("System.out.println()").toUElementOfType<UExpression>()
?: kfail("cannot create statement")
val lambda = uastElementFactory.createLambdaExpression(
listOf(
UParameterInfo(PsiType.INT, "a"),
UParameterInfo(null, "b")
),
statement,
dummyContextFile()
) ?: kfail("cannot create lambda")
TestCase.assertEquals("{ a: kotlin.Int, b -> System.out.println() }", lambda.sourcePsi?.text)
TestCase.assertEquals("""
ULambdaExpression
UParameter (name = a)
UAnnotation (fqName = org.jetbrains.annotations.NotNull)
UParameter (name = b)
UAnnotation (fqName = null)
UBlockExpression
UQualifiedReferenceExpression
UQualifiedReferenceExpression
USimpleNameReferenceExpression (identifier = System)
USimpleNameReferenceExpression (identifier = out)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0))
UIdentifier (Identifier (println))
USimpleNameReferenceExpression (identifier = println, resolvesTo = null)
""".trimIndent(), lambda.putIntoFunctionBody().asRecursiveLogString().trim())
}
private fun UExpression.putIntoFunctionBody(): UExpression {
val file = myFixture.configureByText("dummyFile.kt", "fun foo() { TODO() }") as KtFile
val ktFunction = file.declarations.single { it.name == "foo" } as KtFunction
val uMethod = ktFunction.toUElementOfType<UMethod>()!!
return runWriteCommand {
uMethod.uastBody.cast<UBlockExpression>().expressions.single().replace(this)!!
}
}
private fun <T : UExpression> T.putIntoVarInitializer(): T {
val file = myFixture.configureByText("dummyFile.kt", "val foo = TODO()") as KtFile
val ktFunction = file.declarations.single { it.name == "foo" } as KtProperty
val uMethod = ktFunction.toUElementOfType<UVariable>()!!
return runWriteCommand {
@Suppress("UNCHECKED_CAST")
generatePlugin.replace(uMethod.uastInitializer!!, this, UExpression::class.java) as T
}
}
private fun <T : UExpression> runWriteCommand(uExpression: () -> T): T {
val result = Ref<T>()
WriteCommandAction.runWriteCommandAction(project) {
result.set(uExpression())
}
return result.get()
}
fun `test lambda expression with explicit types`() {
val statement = psiFactory.createExpression("System.out.println()").toUElementOfType<UExpression>()
?: kfail("cannot create statement")
val lambda = uastElementFactory.createLambdaExpression(
listOf(
UParameterInfo(PsiType.INT, "a"),
UParameterInfo(PsiType.DOUBLE, "b")
),
statement,
dummyContextFile()
) ?: kfail("cannot create lambda")
TestCase.assertEquals("{ a: kotlin.Int, b: kotlin.Double -> System.out.println() }", lambda.sourcePsi?.text)
TestCase.assertEquals("""
ULambdaExpression
UParameter (name = a)
UAnnotation (fqName = org.jetbrains.annotations.NotNull)
UParameter (name = b)
UAnnotation (fqName = org.jetbrains.annotations.NotNull)
UBlockExpression
UQualifiedReferenceExpression
UQualifiedReferenceExpression
USimpleNameReferenceExpression (identifier = System)
USimpleNameReferenceExpression (identifier = out)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0))
UIdentifier (Identifier (println))
USimpleNameReferenceExpression (identifier = println, resolvesTo = null)
""".trimIndent(), lambda.putIntoFunctionBody().asRecursiveLogString().trim())
}
fun `test lambda expression with simplified block body with context`() {
val r = psiFactory.createExpression("return \"10\"").toUElementOfType<UExpression>()
?: kfail("cannot create return")
val block = uastElementFactory.createBlockExpression(listOf(r), dummyContextFile())
val lambda = uastElementFactory.createLambdaExpression(listOf(UParameterInfo(null, "a")), block, dummyContextFile())
?: kfail("cannot create lambda")
TestCase.assertEquals("""{ a -> "10" }""".trimMargin(), lambda.sourcePsi?.text)
TestCase.assertEquals("""
ULambdaExpression
UParameter (name = a)
UAnnotation (fqName = org.jetbrains.annotations.NotNull)
UBlockExpression
UReturnExpression
ULiteralExpression (value = "10")
""".trimIndent(), lambda.putIntoVarInitializer().asRecursiveLogString().trim())
}
fun `test function argument replacement`() {
val file = myFixture.configureByText(
"test.kt", """
fun f(a: Any){}
fun main(){
f(a)
}
""".trimIndent()
)
val expression = file.findUElementByTextFromPsi<UCallExpression>("f(a)")
val newArgument = psiFactory.createExpression("b").toUElementOfType<USimpleNameReferenceExpression>()
?: kfail("cannot create reference")
WriteCommandAction.runWriteCommandAction(project) {
TestCase.assertNotNull(expression.valueArguments[0].replace(newArgument))
}
val updated = expression.refreshed() ?: kfail("cannot update expression")
TestCase.assertEquals("f", updated.methodName)
TestCase.assertTrue(updated.valueArguments[0] is USimpleNameReferenceExpression)
TestCase.assertEquals("b", (updated.valueArguments[0] as USimpleNameReferenceExpression).identifier)
TestCase.assertEquals("""
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (f))
USimpleNameReferenceExpression (identifier = f, resolvesTo = null)
USimpleNameReferenceExpression (identifier = b)
""".trimIndent(), updated.asRecursiveLogString().trim())
}
fun `test suggested name`() {
val expression = psiFactory.createExpression("f(a) + 1").toUElementOfType<UExpression>()
?: kfail("cannot create expression")
val variable = uastElementFactory.createLocalVariable(null, PsiType.INT, expression, true, dummyContextFile())
TestCase.assertEquals("val i: kotlin.Int = f(a) + 1", variable.sourcePsi?.text)
TestCase.assertEquals("""
ULocalVariable (name = i)
UBinaryExpression (operator = +)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (f))
USimpleNameReferenceExpression (identifier = <anonymous class>, resolvesTo = null)
USimpleNameReferenceExpression (identifier = a)
ULiteralExpression (value = 1)
""".trimIndent(), variable.asRecursiveLogString().trim())
}
fun `test method call generation with receiver`() {
val receiver = myFixture.configureByKotlinExpression("receiver.kt", "\"10\"")
val arg1 = myFixture.configureByKotlinExpression("arg1.kt", "1")
val arg2 = myFixture.configureByKotlinExpression("arg2.kt", "2")
val methodCall = uastElementFactory.createCallExpression(
receiver,
"substring",
listOf(arg1, arg2),
null,
UastCallKind.METHOD_CALL
) ?: kfail("cannot create call")
TestCase.assertEquals(""""10".substring(1,2)""", methodCall.uastParent?.sourcePsi?.text)
TestCase.assertEquals("""
UQualifiedReferenceExpression
ULiteralExpression (value = "10")
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 2))
UIdentifier (Identifier (substring))
USimpleNameReferenceExpression (identifier = <anonymous class>, resolvesTo = null)
ULiteralExpression (value = null)
ULiteralExpression (value = null)
""".trimIndent(), methodCall.uastParent?.asRecursiveLogString()?.trim()
)
}
fun `test method call generation without receiver`() {
val arg1 = myFixture.configureByKotlinExpression("arg1.kt", "1")
val arg2 = myFixture.configureByKotlinExpression("arg2.kt", "2")
val methodCall = uastElementFactory.createCallExpression(
null,
"substring",
listOf(arg1, arg2),
null,
UastCallKind.METHOD_CALL
) ?: kfail("cannot create call")
TestCase.assertEquals("""substring(1,2)""", methodCall.sourcePsi?.text)
}
fun `test method call generation with generics restoring`() {
val arrays = psiFactory.createExpression("java.util.Arrays").toUElementOfType<UExpression>()
?: kfail("cannot create receiver")
val methodCall = uastElementFactory.createCallExpression(
arrays,
"asList",
listOf(),
createTypeFromText("java.util.List<java.lang.String>", null),
UastCallKind.METHOD_CALL,
dummyContextFile()
) ?: kfail("cannot create call")
TestCase.assertEquals("java.util.Arrays.asList<kotlin.String>()", methodCall.uastParent?.sourcePsi?.text)
}
fun `test method call generation with generics restoring 2 parameters`() {
val collections = psiFactory.createExpression("java.util.Collections").toUElementOfType<UExpression>()
?: kfail("cannot create receiver")
TestCase.assertEquals("java.util.Collections", collections.asRenderString())
val methodCall = uastElementFactory.createCallExpression(
collections,
"emptyMap",
listOf(),
createTypeFromText(
"java.util.Map<java.lang.String, java.lang.Integer>",
null
),
UastCallKind.METHOD_CALL,
dummyContextFile()
) ?: kfail("cannot create call")
TestCase.assertEquals("emptyMap<kotlin.String,kotlin.Int>()", methodCall.sourcePsi?.text)
TestCase.assertEquals("java.util.Collections.emptyMap<kotlin.String,kotlin.Int>()", methodCall.sourcePsi?.parent?.text)
TestCase.assertEquals(
"""
UQualifiedReferenceExpression
UQualifiedReferenceExpression
UQualifiedReferenceExpression
USimpleNameReferenceExpression (identifier = java)
USimpleNameReferenceExpression (identifier = util)
USimpleNameReferenceExpression (identifier = Collections)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0))
UIdentifier (Identifier (emptyMap))
USimpleNameReferenceExpression (identifier = emptyMap, resolvesTo = null)
""".trimIndent(), methodCall.uastParent?.asRecursiveLogString()?.trim()
)
}
private fun dummyContextFile(): KtFile = myFixture.configureByText("file.kt", "fun foo() {}") as KtFile
fun `test method call generation with generics restoring 1 parameter with 1 existing`() {
val receiver = myFixture.configureByKotlinExpression("receiver.kt", "A")
val arg = myFixture.configureByKotlinExpression("arg.kt", "\"a\"")
val methodCall = uastElementFactory.createCallExpression(
receiver,
"kek",
listOf(arg),
createTypeFromText(
"java.util.Map<java.lang.String, java.lang.Integer>",
null
),
UastCallKind.METHOD_CALL,
dummyContextFile()
) ?: kfail("cannot create call")
TestCase.assertEquals("A.kek<kotlin.String,kotlin.Int>(\"a\")", methodCall.sourcePsi?.parent?.text)
TestCase.assertEquals(
"""
UQualifiedReferenceExpression
USimpleNameReferenceExpression (identifier = A)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (kek))
USimpleNameReferenceExpression (identifier = <anonymous class>, resolvesTo = null)
ULiteralExpression (value = "a")
""".trimIndent(), methodCall.uastParent?.asRecursiveLogString()?.trim()
)
}
fun `test callable reference generation with receiver`() {
val receiver = uastElementFactory.createQualifiedReference("java.util.Arrays", myFixture.file)
?: kfail("failed to create receiver")
val methodReference = uastElementFactory.createCallableReferenceExpression(receiver, "asList", myFixture.file)
?: kfail("failed to create method reference")
TestCase.assertEquals(methodReference.sourcePsi?.text, "java.util.Arrays::asList")
}
fun `test callable reference generation without receiver`() {
val methodReference = uastElementFactory.createCallableReferenceExpression(null, "asList", myFixture.file)
?: kfail("failed to create method reference")
TestCase.assertEquals(methodReference.sourcePsi?.text, "::asList")
}
//not implemented (currently we dont perform resolve in code generating)
fun `ignore method call generation with generics restoring 1 parameter with 1 unused `() {
val aClassFile = myFixture.configureByText(
"A.kt",
"""
object A {
fun <T1, T2, T3> kek(a: T1): Map<T1, T3> {
return TODO();
}
}
""".trimIndent()
)
val a = psiFactory.createExpression("A").toUElementOfType<UExpression>()
?: kfail("cannot create a receiver")
val param = psiFactory.createExpression("\"a\"").toUElementOfType<UExpression>()
?: kfail("cannot create a parameter")
val methodCall = uastElementFactory.createCallExpression(
a,
"kek",
listOf(param),
createTypeFromText(
"java.util.Map<java.lang.String, java.lang.Integer>",
null
),
UastCallKind.METHOD_CALL,
aClassFile
) ?: kfail("cannot create call")
TestCase.assertEquals("A.<String, Object, Integer>kek(\"a\")", methodCall.sourcePsi?.text)
}
fun `test method call generation with generics with context`() {
val file = myFixture.configureByText("file.kt", """
class A {
fun <T> method(): List<T> { TODO() }
}
fun main(){
val a = A()
println(a)
}
""".trimIndent()
) as KtFile
val reference = file.findUElementByTextFromPsi<UElement>("println(a)", strict = true)
.findElementByTextFromPsi<UReferenceExpression>("a")
val callExpression = uastElementFactory.createCallExpression(
reference,
"method",
emptyList(),
createTypeFromText(
"java.util.List<java.lang.Integer>",
null
),
UastCallKind.METHOD_CALL,
context = reference.sourcePsi
) ?: kfail("cannot create method call")
TestCase.assertEquals("a.method<kotlin.Int>()", callExpression.uastParent?.sourcePsi?.text)
TestCase.assertEquals("""
UQualifiedReferenceExpression
USimpleNameReferenceExpression (identifier = a)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0))
UIdentifier (Identifier (method))
USimpleNameReferenceExpression (identifier = method, resolvesTo = null)
""".trimIndent(), callExpression.uastParent?.asRecursiveLogString()?.trim()
)
}
fun `test method call generation without generics with context`() {
val file = myFixture.configureByText("file.kt", """
class A {
fun <T> method(t: T): List<T> { TODO() }
}
fun main(){
val a = A()
println(a)
}
""".trimIndent()
) as KtFile
val reference = file.findUElementByTextFromPsi<UElement>("println(a)")
.findElementByTextFromPsi<UReferenceExpression>("a")
val callExpression = uastElementFactory.createCallExpression(
reference,
"method",
listOf(uastElementFactory.createIntLiteral(1, file)),
createTypeFromText(
"java.util.List<java.lang.Integer>",
null
),
UastCallKind.METHOD_CALL,
context = reference.sourcePsi
) ?: kfail("cannot create method call")
TestCase.assertEquals("a.method(1)", callExpression.uastParent?.sourcePsi?.text)
TestCase.assertEquals("""
UQualifiedReferenceExpression
USimpleNameReferenceExpression (identifier = a)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (method))
USimpleNameReferenceExpression (identifier = method, resolvesTo = null)
ULiteralExpression (value = 1)
""".trimIndent(), callExpression.uastParent?.asRecursiveLogString()?.trim()
)
}
fun `test replace lambda implicit return value`() {
val file = myFixture.configureByText(
"file.kt", """
fun main(){
val a: (Int) -> String = {
println(it)
println(2)
"abc"
}
}
""".trimIndent()
) as KtFile
val uLambdaExpression = file.findUElementByTextFromPsi<UInjectionHost>("\"abc\"")
.getParentOfType<ULambdaExpression>() ?: kfail("cant get lambda")
val expressions = uLambdaExpression.body.cast<UBlockExpression>().expressions
UsefulTestCase.assertSize(3, expressions)
val uReturnExpression = expressions.last() as UReturnExpression
val newStringLiteral = uastElementFactory.createStringLiteralExpression("def", file)
val defReturn = runWriteCommand { uReturnExpression.replace(newStringLiteral) ?: kfail("cant replace") }
val uLambdaExpression2 = defReturn.getParentOfType<ULambdaExpression>() ?: kfail("cant get lambda")
TestCase.assertEquals("{\n println(it)\n println(2)\n \"def\"\n }", uLambdaExpression2.sourcePsi?.text)
TestCase.assertEquals(
"""
ULambdaExpression
UParameter (name = it)
UBlockExpression
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (println))
USimpleNameReferenceExpression (identifier = println, resolvesTo = null)
USimpleNameReferenceExpression (identifier = it)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (println))
USimpleNameReferenceExpression (identifier = println, resolvesTo = null)
ULiteralExpression (value = 2)
UReturnExpression
ULiteralExpression (value = "def")
""".trimIndent(), uLambdaExpression2.asRecursiveLogString().trim()
)
}
private class UserDataChecker {
private val storedData = Any()
private val KEY = Key.create<Any>("testKey")
private lateinit var uniqueStringLiteralText: String
fun store(uElement: UInjectionHost) {
val psiElement = uElement.sourcePsi as KtStringTemplateExpression
uniqueStringLiteralText = psiElement.text
psiElement.putCopyableUserData(KEY, storedData)
}
fun checkUserDataAlive(uElement: UElement) {
val psiElements = uElement.let { SyntaxTraverser.psiTraverser(it.sourcePsi) }
.filter(KtStringTemplateExpression::class.java)
.filter { it.text == uniqueStringLiteralText }.toList()
UsefulTestCase.assertNotEmpty(psiElements)
UsefulTestCase.assertTrue("uElement still should keep the userdata", psiElements.any { storedData === it!!.getCopyableUserData(KEY) })
}
}
fun `test add intermediate returns to lambda`() {
val file = myFixture.configureByText(
"file.kt", """
fun main(){
val a: (Int) -> String = lname@{
println(it)
println(2)
"abc"
}
}
""".trimIndent()
) as KtFile
val aliveChecker = UserDataChecker()
val uLambdaExpression = file.findUElementByTextFromPsi<UInjectionHost>("\"abc\"")
.also(aliveChecker::store)
.getParentOfType<ULambdaExpression>() ?: kfail("cant get lambda")
val oldBlockExpression = uLambdaExpression.body.cast<UBlockExpression>()
UsefulTestCase.assertSize(3, oldBlockExpression.expressions)
val conditionalExit = with(uastElementFactory) {
createIfExpression(
createBinaryExpression(
createSimpleReference("it", uLambdaExpression.sourcePsi),
createIntLiteral(3, uLambdaExpression.sourcePsi),
UastBinaryOperator.GREATER,
uLambdaExpression.sourcePsi
)!!,
createReturnExpresion(
createStringLiteralExpression("exit", uLambdaExpression.sourcePsi), true,
uLambdaExpression.sourcePsi
),
null,
uLambdaExpression.sourcePsi
)!!
}
val newBlockExpression = uastElementFactory.createBlockExpression(
listOf(conditionalExit) + oldBlockExpression.expressions,
uLambdaExpression.sourcePsi
)
aliveChecker.checkUserDataAlive(newBlockExpression)
val uLambdaExpression2 = runWriteCommand {
oldBlockExpression.replace(newBlockExpression) ?: kfail("cant replace")
}.getParentOfType<ULambdaExpression>() ?: kfail("cant get lambda")
aliveChecker.checkUserDataAlive(uLambdaExpression2)
TestCase.assertEquals(
"""
lname@{
if (it > 3) return@lname "exit"
println(it)
println(2)
"abc"
}
""".trimIndent(), uLambdaExpression2.sourcePsi?.parent?.text
)
TestCase.assertEquals(
"""
ULambdaExpression
UParameter (name = it)
UBlockExpression
UIfExpression
UBinaryExpression (operator = >)
USimpleNameReferenceExpression (identifier = it)
ULiteralExpression (value = 3)
UReturnExpression
ULiteralExpression (value = "exit")
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (println))
USimpleNameReferenceExpression (identifier = println, resolvesTo = null)
USimpleNameReferenceExpression (identifier = it)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (println))
USimpleNameReferenceExpression (identifier = println, resolvesTo = null)
ULiteralExpression (value = 2)
UReturnExpression
ULiteralExpression (value = "abc")
""".trimIndent(), uLambdaExpression2.asRecursiveLogString().trim()
)
}
fun `test converting lambda to if`() {
val file = myFixture.configureByText(
"file.kt", """
fun foo(call: (Int) -> String): String = call.invoke(2)
fun main() {
foo {
println(it)
println(2)
"abc"
}
}
}
""".trimIndent()
) as KtFile
val aliveChecker = UserDataChecker()
val uLambdaExpression = file.findUElementByTextFromPsi<UInjectionHost>("\"abc\"")
.also { aliveChecker.store(it) }
.getParentOfType<ULambdaExpression>() ?: kfail("cant get lambda")
val oldBlockExpression = uLambdaExpression.body.cast<UBlockExpression>()
aliveChecker.checkUserDataAlive(oldBlockExpression)
val newLambda = with(uastElementFactory) {
createLambdaExpression(
listOf(UParameterInfo(null, "it")),
createIfExpression(
createBinaryExpression(
createSimpleReference("it", uLambdaExpression.sourcePsi),
createIntLiteral(3, uLambdaExpression.sourcePsi),
UastBinaryOperator.GREATER,
uLambdaExpression.sourcePsi
)!!,
oldBlockExpression,
createReturnExpresion(
createStringLiteralExpression("exit", uLambdaExpression.sourcePsi), true,
uLambdaExpression.sourcePsi
),
uLambdaExpression.sourcePsi
)!!.also {
aliveChecker.checkUserDataAlive(it)
},
uLambdaExpression.sourcePsi
)!!
}
aliveChecker.checkUserDataAlive(newLambda)
val uLambdaExpression2 = runWriteCommand {
uLambdaExpression.replace(newLambda) ?: kfail("cant replace")
}
TestCase.assertEquals(
"""
{ it ->
if (it > 3) {
println(it)
println(2)
"abc"
} else return@foo "exit"
}
""".trimIndent(), uLambdaExpression2.sourcePsi?.parent?.text
)
TestCase.assertEquals(
"""
ULambdaExpression
UParameter (name = it)
UAnnotation (fqName = null)
UBlockExpression
UReturnExpression
UIfExpression
UBinaryExpression (operator = >)
USimpleNameReferenceExpression (identifier = it)
ULiteralExpression (value = 3)
UBlockExpression
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (println))
USimpleNameReferenceExpression (identifier = println, resolvesTo = null)
USimpleNameReferenceExpression (identifier = it)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (println))
USimpleNameReferenceExpression (identifier = println, resolvesTo = null)
ULiteralExpression (value = 2)
ULiteralExpression (value = "abc")
UReturnExpression
ULiteralExpression (value = "exit")
""".trimIndent(), uLambdaExpression2.asRecursiveLogString().trim()
)
aliveChecker.checkUserDataAlive(uLambdaExpression2)
}
fun `test removing unnecessary type parameters while replace`() {
val aClassFile = myFixture.configureByText(
"A.kt",
"""
class A {
fun <T> method():List<T> = TODO()
}
""".trimIndent()
)
val reference = psiFactory.createExpression("a")
.toUElementOfType<UReferenceExpression>() ?: kfail("cannot create reference expression")
val callExpression = uastElementFactory.createCallExpression(
reference,
"method",
emptyList(),
createTypeFromText(
"java.util.List<java.lang.Integer>",
null
),
UastCallKind.METHOD_CALL,
context = aClassFile
) ?: kfail("cannot create method call")
val listAssigment = myFixture.addFileToProject("temp.kt", """
fun foo(kek: List<Int>) {
val list: List<Int> = kek
}
""".trimIndent()).findUElementByTextFromPsi<UVariable>("val list: List<Int> = kek")
WriteCommandAction.runWriteCommandAction(project) {
val methodCall = listAssigment.uastInitializer?.replace(callExpression) ?: kfail("cannot replace!")
// originally result expected be `a.method()` but we expect to clean up type arguments in other plase
TestCase.assertEquals("a.method<Int>()", methodCall.sourcePsi?.parent?.text)
}
}
fun `test create if`() {
val condition = psiFactory.createExpression("true").toUElementOfType<UExpression>()
?: kfail("cannot create condition")
val thenBranch = psiFactory.createBlock("{a(b);}").toUElementOfType<UExpression>()
?: kfail("cannot create then branch")
val elseBranch = psiFactory.createExpression("c++").toUElementOfType<UExpression>()
?: kfail("cannot create else branch")
val ifExpression = uastElementFactory.createIfExpression(condition, thenBranch, elseBranch, dummyContextFile())
?: kfail("cannot create if expression")
TestCase.assertEquals("if (true) {\n { a(b); }\n } else c++", ifExpression.sourcePsi?.text)
}
fun `test qualified reference`() {
val reference = uastElementFactory.createQualifiedReference("java.util.List", myFixture.file)
TestCase.assertEquals("java.util.List", reference?.sourcePsi?.text)
}
fun `test build lambda from returning a variable`() {
val context = dummyContextFile()
val localVariable = uastElementFactory.createLocalVariable("a", null, uastElementFactory.createNullLiteral(context), true, context)
val declarationExpression =
uastElementFactory.createDeclarationExpression(listOf(localVariable), context)
val returnExpression = uastElementFactory.createReturnExpresion(
uastElementFactory.createSimpleReference(localVariable, context), false, context
)
val block = uastElementFactory.createBlockExpression(listOf(declarationExpression, returnExpression), context)
TestCase.assertEquals("""
UBlockExpression
UDeclarationsExpression
ULocalVariable (name = a)
ULiteralExpression (value = null)
UReturnExpression
USimpleNameReferenceExpression (identifier = a)
""".trimIndent(), block.asRecursiveLogString().trim())
val lambda = uastElementFactory.createLambdaExpression(listOf(), block, context) ?: kfail("cannot create lambda expression")
TestCase.assertEquals("{ val a = null\na }", lambda.sourcePsi?.text)
TestCase.assertEquals("""
ULambdaExpression
UBlockExpression
UDeclarationsExpression
ULocalVariable (name = a)
ULiteralExpression (value = null)
UReturnExpression
USimpleNameReferenceExpression (identifier = a)
""".trimIndent(), lambda.putIntoVarInitializer().asRecursiveLogString().trim())
}
fun `test expand oneline lambda`() {
val context = dummyContextFile()
val parameters = listOf(UParameterInfo(PsiType.INT, "a"))
val oneLineLambda = with(uastElementFactory) {
createLambdaExpression(
parameters,
createBinaryExpression(
createSimpleReference("a", context),
createSimpleReference("a", context),
UastBinaryOperator.PLUS, context
)!!, context
)!!
}.putIntoVarInitializer()
val lambdaReturn = (oneLineLambda.body as UBlockExpression).expressions.single()
val lambda = with(uastElementFactory) {
createLambdaExpression(
parameters,
createBlockExpression(
listOf(
createCallExpression(
null,
"println",
listOf(createSimpleReference("a", context)),
PsiType.VOID,
UastCallKind.METHOD_CALL,
context
)!!,
lambdaReturn
),
context
), context
)!!
}
TestCase.assertEquals("{ a: kotlin.Int -> println(a)\na + a }", lambda.sourcePsi?.text)
TestCase.assertEquals("""
ULambdaExpression
UParameter (name = a)
UAnnotation (fqName = org.jetbrains.annotations.NotNull)
UBlockExpression
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (println))
USimpleNameReferenceExpression (identifier = println, resolvesTo = null)
USimpleNameReferenceExpression (identifier = a)
UReturnExpression
UBinaryExpression (operator = +)
USimpleNameReferenceExpression (identifier = a)
USimpleNameReferenceExpression (identifier = a)
""".trimIndent(), lambda.putIntoVarInitializer().asRecursiveLogString().trim())
}
fun `test moving lambda from parenthesis`() {
myFixture.configureByText("myFile.kt", """
fun a(p: (Int) -> Unit) {}
""".trimIndent())
val lambdaExpression = uastElementFactory.createLambdaExpression(
emptyList(),
uastElementFactory.createNullLiteral(null),
null
) ?: kfail("Cannot create lambda")
val callExpression = uastElementFactory.createCallExpression(
null,
"a",
listOf(lambdaExpression),
null,
UastCallKind.METHOD_CALL,
myFixture.file
) ?: kfail("Cannot create method call")
TestCase.assertEquals("""a{ null }""", callExpression.sourcePsi?.text)
}
fun `test saving space after receiver`() {
myFixture.configureByText("myFile.kt", """
fun f() {
a
.b()
.c<caret>()
.d()
}
""".trimIndent())
val receiver =
myFixture.file.findElementAt(myFixture.caretOffset)?.parentOfType<KtDotQualifiedExpression>().toUElementOfType<UExpression>()
?: kfail("Cannot find UExpression")
val callExpression = uastElementFactory.createCallExpression(
receiver,
"e",
listOf(),
null,
UastCallKind.METHOD_CALL,
null
) ?: kfail("Cannot create call expression")
TestCase.assertEquals(
"""
a
.b()
.c()
.e()
""".trimIndent(),
callExpression.sourcePsi?.parentOfType<KtDotQualifiedExpression>()?.text
)
}
fun `test initialize field`() {
val psiFile = myFixture.configureByText("MyClass.kt", """
class My<caret>Class {
var field: String?
fun method(value: String) {
}
}
""".trimIndent())
val uClass =
myFixture.file.findElementAt(myFixture.caretOffset)?.parentOfType<KtClass>().toUElementOfType<UClass>()
?: kfail("Cannot find UClass")
val uField = uClass.fields.firstOrNull() ?: kfail("Cannot find field")
val uParameter = uClass.methods.find { it.name == "method"}?.uastParameters?.firstOrNull() ?: kfail("Cannot find parameter")
WriteCommandAction.runWriteCommandAction(project) { generatePlugin.initializeField(uField, uParameter) }
TestCase.assertEquals("""
class MyClass {
var field: String?
fun method(value: String) {
field = value
}
}
""".trimIndent(), psiFile.text)
}
fun `test initialize field with same name`() {
val psiFile = myFixture.configureByText("MyClass.kt", """
class My<caret>Class {
var field: String?
fun method(field: String) {
}
}
""".trimIndent())
val uClass =
myFixture.file.findElementAt(myFixture.caretOffset)?.parentOfType<KtClass>().toUElementOfType<UClass>()
?: kfail("Cannot find UClass")
val uField = uClass.fields.firstOrNull() ?: kfail("Cannot find field")
val uParameter = uClass.methods.find { it.name == "method"}?.uastParameters?.firstOrNull() ?: kfail("Cannot find parameter")
WriteCommandAction.runWriteCommandAction(project) { generatePlugin.initializeField(uField, uParameter) }
TestCase.assertEquals("""
class MyClass {
var field: String?
fun method(field: String) {
this.field = field
}
}
""".trimIndent(), psiFile.text)
}
fun `test initialize field in constructor`() {
val psiFile = myFixture.configureByText("MyClass.kt", """
class My<caret>Class() {
constructor(value: String): this() {
}
var field: String?
}
""".trimIndent())
val uClass =
myFixture.file.findElementAt(myFixture.caretOffset)?.parentOfType<KtClass>().toUElementOfType<UClass>()
?: kfail("Cannot find UClass")
val uField = uClass.fields.firstOrNull() ?: kfail("Cannot find field")
val uParameter = uClass.methods.find { it.isConstructor && it.uastParameters.isNotEmpty() }?.uastParameters?.firstOrNull()
?: kfail("Cannot find parameter")
WriteCommandAction.runWriteCommandAction(project) { generatePlugin.initializeField(uField, uParameter) }
TestCase.assertEquals("""
class MyClass() {
constructor(value: String): this() {
field = value
}
var field: String?
}
""".trimIndent(), psiFile.text)
}
fun `test initialize field in primary constructor`() {
val psiFile = myFixture.configureByText("MyClass.kt", """
class My<caret>Class(value: String) {
val field: String
}
""".trimIndent())
val uClass =
myFixture.file.findElementAt(myFixture.caretOffset)?.parentOfType<KtClass>().toUElementOfType<UClass>()
?: kfail("Cannot find UClass")
val uField = uClass.fields.firstOrNull() ?: kfail("Cannot find field")
val uParameter = uClass.methods.find { it.uastParameters.isNotEmpty() }?.uastParameters?.firstOrNull() ?: kfail("Cannot find parameter")
WriteCommandAction.runWriteCommandAction(project) { generatePlugin.initializeField(uField, uParameter) }
TestCase.assertEquals("""
class MyClass(value: String) {
val field: String = value
}
""".trimIndent(), psiFile.text)
}
fun `test initialize field in primary constructor with same name`() {
val psiFile = myFixture.configureByText("MyClass.kt", """
class My<caret>Class(field: String) {
private val field: String
}
""".trimIndent())
val uClass =
myFixture.file.findElementAt(myFixture.caretOffset)?.parentOfType<KtClass>().toUElementOfType<UClass>()
?: kfail("Cannot find UClass")
val uField = uClass.fields.firstOrNull() ?: kfail("Cannot find field")
val uParameter = uClass.methods.find { it.uastParameters.isNotEmpty() }?.uastParameters?.firstOrNull() ?: kfail("Cannot find parameter")
WriteCommandAction.runWriteCommandAction(project) { generatePlugin.initializeField(uField, uParameter) }
TestCase.assertEquals("""
class MyClass(private val field: String) {
}
""".trimIndent(), psiFile.text)
}
fun `test initialize field in primary constructor with same name and class body`() {
val psiFile = myFixture.configureByText("MyClass.kt", """
class My<caret>Class(field: String) {
private val field: String
public fun test() {
val i = 0
}
}
""".trimIndent())
val uClass =
myFixture.file.findElementAt(myFixture.caretOffset)?.parentOfType<KtClass>().toUElementOfType<UClass>()
?: kfail("Cannot find UClass")
val uField = uClass.fields.firstOrNull() ?: kfail("Cannot find field")
val uParameter = uClass.methods.find { it.uastParameters.isNotEmpty() }?.uastParameters?.firstOrNull() ?: kfail("Cannot find parameter")
WriteCommandAction.runWriteCommandAction(project) { generatePlugin.initializeField(uField, uParameter) }
TestCase.assertEquals("""
class MyClass(private val field: String) {
public fun test() {
val i = 0
}
}
""".trimIndent(), psiFile.text)
}
fun `test initialize field in primary constructor with leading blank line`() {
val psiFile = myFixture.configureByText("MyClass.kt", """
class My<caret>Class(field: String) {
private val field: String
public fun test() {
val i = 0
}
}
""".trimIndent())
val uClass =
myFixture.file.findElementAt(myFixture.caretOffset)?.parentOfType<KtClass>().toUElementOfType<UClass>()
?: kfail("Cannot find UClass")
val uField = uClass.fields.firstOrNull() ?: kfail("Cannot find field")
val uParameter = uClass.methods.find { it.uastParameters.isNotEmpty() }?.uastParameters?.firstOrNull() ?: kfail("Cannot find parameter")
WriteCommandAction.runWriteCommandAction(project) { generatePlugin.initializeField(uField, uParameter) }
TestCase.assertEquals("""
class MyClass(private val field: String) {
public fun test() {
val i = 0
}
}
""".trimIndent(), psiFile.text)
}
private fun createTypeFromText(s: String, newClass: PsiElement?): PsiType {
return JavaPsiFacade.getElementFactory(myFixture.project).createTypeFromText(s, newClass)
}
private fun JavaCodeInsightTestFixture.configureByKotlinExpression(fileName: String, text: String): UExpression {
val file = configureByText(fileName, "private val x = $text") as KtFile
val property = file.declarations.singleOrNull() as? KtProperty ?: error("Property 'x' is not found in $file")
val initializer = property.initializer ?: error("Property initializer not found in $file")
return initializer.toUElementOfType() ?: error("Initializer '$initializer' is not convertable to UAST")
}
}
// it is a copy of org.jetbrains.uast.UastUtils.asRecursiveLogString with `appendLine` instead of `appendln` to avoid windows related issues
private fun UElement.asRecursiveLogString(render: (UElement) -> String = { it.asLogString() }): String {
val stringBuilder = StringBuilder()
val indent = " "
accept(object : UastVisitor {
private var level = 0
override fun visitElement(node: UElement): Boolean {
stringBuilder.append(indent.repeat(level))
stringBuilder.appendLine(render(node))
level++
return false
}
override fun afterVisitElement(node: UElement) {
super.afterVisitElement(node)
level--
}
})
return stringBuilder.toString()
}
|
apache-2.0
|
8cf218b12b66fba9ac73a01e1ca9e7e4
| 42.563753 | 158 | 0.600287 | 5.711702 | false | true | false | false |
Kiskae/DiscordKt
|
implementation/src/main/kotlin/net/serverpeon/discord/internal/ws/data/inbound/Channels.kt
|
1
|
1765
|
package net.serverpeon.discord.internal.ws.data.inbound
import net.serverpeon.discord.internal.data.EventInput
import net.serverpeon.discord.internal.data.model.ChannelNode
import net.serverpeon.discord.internal.jsonmodels.ChannelModel
import net.serverpeon.discord.internal.jsonmodels.PrivateChannelModel
interface Channels : Event {
interface Create : Channels {
data class Public(val channel: ChannelModel) : Create {
override fun <T : EventInput<T>> accept(visitor: T, handler: EventInput.Handler<T>)
= handler.channelCreate(visitor, this)
}
data class Private(val channel: PrivateChannelModel) : Create {
override fun <T : EventInput<T>> accept(visitor: T, handler: EventInput.Handler<T>)
= handler.channelCreate(visitor, this)
}
}
data class Update(val channel: ChannelModel) : Channels {
override fun <T : EventInput<T>> accept(visitor: T, handler: EventInput.Handler<T>)
= handler.channelUpdate(visitor, this)
}
interface Delete : Channels {
data class Public(val channel: ChannelModel) : Delete, Event.RefHolder<ChannelNode.Public> {
override var value: ChannelNode.Public? = null
override fun <T : EventInput<T>> accept(visitor: T, handler: EventInput.Handler<T>)
= handler.channelDelete(visitor, this)
}
data class Private(val channel: PrivateChannelModel) : Delete, Event.RefHolder<ChannelNode.Private> {
override var value: ChannelNode.Private? = null
override fun <T : EventInput<T>> accept(visitor: T, handler: EventInput.Handler<T>)
= handler.channelDelete(visitor, this)
}
}
}
|
mit
|
7a121081b60c8968e166cef8cd6236ed
| 42.073171 | 109 | 0.664589 | 4.423559 | false | false | false | false |
fluidsonic/fluid-json
|
basic/sources-jvm/implementations/StandardParser.kt
|
1
|
4079
|
package io.fluidsonic.json
internal object StandardParser : JsonParser {
private fun parse(source: JsonReader, expectedType: ExpectedType, withTermination: Boolean) =
source.withTermination(withTermination) { parseUnterminated(source, expectedType) }
override fun parseValueOrNull(source: JsonReader, withTermination: Boolean) =
parse(source, ExpectedType.any, withTermination = withTermination)
override fun parseList(source: JsonReader, withTermination: Boolean) =
parse(source, ExpectedType.list, withTermination = withTermination) as List<*>
@Suppress("UNCHECKED_CAST")
override fun parseMap(source: JsonReader, withTermination: Boolean) =
parse(source, ExpectedType.map, withTermination = withTermination) as Map<String, *>
@Suppress("UNCHECKED_CAST")
private fun parseUnterminated(source: JsonReader, expectedType: ExpectedType): Any? {
var currentList: MutableList<Any?>? = null
var currentKey: String? = null
var currentMap: MutableMap<Any?, Any?>? = null
val parents = mutableListOf<Any>()
val parentKeys = mutableListOf<String>()
when (expectedType) {
ExpectedType.any -> Unit
ExpectedType.list -> source.nextToken == JsonToken.listStart ||
throw JsonException.Schema(
message = "Expected a list, got ${source.nextToken}",
offset = source.offset,
path = source.path
)
ExpectedType.map -> source.nextToken == JsonToken.mapStart ||
throw JsonException.Schema(
message = "Expected a map, got ${source.nextToken}",
offset = source.offset,
path = source.path
)
}
loop@ while (true) {
val value: Any? = when (source.nextToken) {
JsonToken.booleanValue ->
source.readBoolean()
JsonToken.listEnd -> {
source.readListEnd()
val list = currentList
val parentCount = parents.size
if (parentCount > 0) {
val parent = parents.removeAt(parentCount - 1)
if (parent is MutableList<*>) {
currentList = parent as MutableList<Any?>
}
else {
currentList = null
currentMap = parent as MutableMap<Any?, Any?>
}
}
else {
currentList = null
currentMap = null
}
list
}
JsonToken.listStart -> {
source.readListStart()
val list = mutableListOf<Any?>()
if (currentList != null) {
parents += currentList
}
else if (currentMap != null) {
parents += currentMap
currentMap = null
}
currentList = list
continue@loop
}
JsonToken.nullValue
-> source.readNull()
JsonToken.mapEnd -> {
source.readMapEnd()
val map = currentMap
val parentCount = parents.size
if (parentCount > 0) {
val parent = parents.removeAt(parentCount - 1)
if (parent is MutableMap<*, *>) {
currentMap = parent as MutableMap<Any?, Any?>
}
else {
currentList = parent as MutableList<Any?>
currentMap = null
}
}
else {
currentList = null
currentMap = null
}
val parentKeyCount = parentKeys.size
if (parentKeyCount > 0) {
currentKey = parentKeys.removeAt(parentKeyCount - 1)
}
map
}
JsonToken.mapKey -> {
currentKey = source.readMapKey()
continue@loop
}
JsonToken.mapStart -> {
source.readMapStart()
val map = mutableMapOf<Any?, Any?>()
if (currentMap != null) {
parents += currentMap
}
else if (currentList != null) {
parents += currentList
currentList = null
}
if (currentKey != null) {
parentKeys += currentKey
currentKey = null
}
currentMap = map
continue@loop
}
JsonToken.numberValue ->
source.readNumber()
JsonToken.stringValue ->
source.readString()
else ->
throw IllegalStateException("reader is messed up: ${source.nextToken}")
}
when {
currentList != null -> currentList.add(value)
currentMap != null -> currentMap[currentKey] = value
else -> return value
}
}
}
private enum class ExpectedType {
any, list, map
}
}
|
apache-2.0
|
2657d1423138868c2148a368506e1dc0
| 22.442529 | 94 | 0.636921 | 3.910834 | false | false | false | false |
allotria/intellij-community
|
plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/details/GHPRDetailsModelImpl.kt
|
2
|
1010
|
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest.ui.details
import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequest
import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestState
import org.jetbrains.plugins.github.ui.util.SingleValueModel
class GHPRDetailsModelImpl(private val valueModel: SingleValueModel<GHPullRequest>) : GHPRDetailsModel {
override val number: String
get() = valueModel.value.number.toString()
override val title: String
get() = valueModel.value.title
override val description: String
get() = valueModel.value.bodyHTML
override val state: GHPullRequestState
get() = valueModel.value.state
override val isDraft: Boolean
get() = valueModel.value.isDraft
override fun addAndInvokeDetailsChangedListener(listener: () -> Unit) =
valueModel.addAndInvokeValueChangedListener(listener)
}
|
apache-2.0
|
7f99cbacd24e312861034a4a8af54c6c
| 42.956522 | 140 | 0.792079 | 4.334764 | false | false | false | false |
udevbe/westford
|
compositor/src/main/kotlin/org/westford/compositor/x11/X11Seat.kt
|
3
|
8250
|
/*
* Westford Wayland Compositor.
* Copyright (C) 2016 Erik De Rijcke
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.westford.compositor.x11
import com.google.auto.factory.AutoFactory
import com.google.auto.factory.Provided
import org.freedesktop.wayland.shared.WlKeyboardKeyState
import org.freedesktop.wayland.shared.WlPointerAxis
import org.freedesktop.wayland.shared.WlPointerAxis.HORIZONTAL_SCROLL
import org.freedesktop.wayland.shared.WlPointerAxis.VERTICAL_SCROLL
import org.freedesktop.wayland.shared.WlPointerButtonState
import org.westford.compositor.core.Point
import org.westford.compositor.protocol.WlSeat
import org.westford.nativ.libxcb.Libxcb
import org.westford.nativ.libxcb.Libxcb.Companion.XCB_CURSOR_NONE
import org.westford.nativ.libxcb.Libxcb.Companion.XCB_EVENT_MASK_BUTTON_PRESS
import org.westford.nativ.libxcb.Libxcb.Companion.XCB_EVENT_MASK_BUTTON_RELEASE
import org.westford.nativ.libxcb.Libxcb.Companion.XCB_EVENT_MASK_ENTER_WINDOW
import org.westford.nativ.libxcb.Libxcb.Companion.XCB_EVENT_MASK_LEAVE_WINDOW
import org.westford.nativ.libxcb.Libxcb.Companion.XCB_EVENT_MASK_POINTER_MOTION
import org.westford.nativ.libxcb.Libxcb.Companion.XCB_GRAB_MODE_ASYNC
import org.westford.nativ.linux.InputEventCodes.BTN_LEFT
import org.westford.nativ.linux.InputEventCodes.BTN_MIDDLE
import org.westford.nativ.linux.InputEventCodes.BTN_RIGHT
import org.westford.nativ.linux.InputEventCodes.BTN_SIDE
@AutoFactory(className = "PrivateX11SeatFactory",
allowSubclasses = true) class X11Seat(@param:Provided private val libxcb: Libxcb,
@param:Provided private val x11Platform: X11Platform,
val wlSeat: WlSeat) {
fun deliverKey(time: Int,
eventDetail: Short,
pressed: Boolean) {
val wlKeyboardKeyState = wlKeyboardKeyState(pressed)
val key = toLinuxKey(eventDetail)
val wlKeyboard = this.wlSeat.wlKeyboard
wlKeyboard.keyboardDevice.key(wlKeyboard.resources,
time,
key,
wlKeyboardKeyState)
}
private fun wlKeyboardKeyState(pressed: Boolean): WlKeyboardKeyState {
val wlKeyboardKeyState: WlKeyboardKeyState
if (pressed) {
wlKeyboardKeyState = WlKeyboardKeyState.PRESSED
}
else {
wlKeyboardKeyState = WlKeyboardKeyState.RELEASED
}
return wlKeyboardKeyState
}
//convert from X keycodes to input.h keycodes
private fun toLinuxKey(eventDetail: Short): Int = eventDetail - 8
fun deliverButton(window: Int,
buttonTime: Int,
eventDetail: Short,
pressed: Boolean) {
val wlPointerButtonState = wlPointerButtonState(window,
buttonTime,
pressed)
val button = toLinuxButton(eventDetail.toInt())
if (button == 0 && pressed) {
handleScroll(buttonTime,
eventDetail)
}
else if (button != 0) {
val wlPointer = this.wlSeat.wlPointer
val pointerDevice = wlPointer.pointerDevice
pointerDevice.button(wlPointer.resources,
buttonTime,
button,
wlPointerButtonState)
pointerDevice.frame(wlPointer.resources)
}
}
private fun wlPointerButtonState(window: Int,
buttonTime: Int,
pressed: Boolean): WlPointerButtonState {
val wlPointerButtonState: WlPointerButtonState
if (pressed) {
wlPointerButtonState = WlPointerButtonState.PRESSED
this.libxcb.xcb_grab_pointer(this.x11Platform.xcbConnection,
0.toByte(),
window,
(XCB_EVENT_MASK_BUTTON_PRESS or XCB_EVENT_MASK_BUTTON_RELEASE or XCB_EVENT_MASK_POINTER_MOTION or XCB_EVENT_MASK_ENTER_WINDOW or XCB_EVENT_MASK_LEAVE_WINDOW).toShort(),
XCB_GRAB_MODE_ASYNC.toByte(),
XCB_GRAB_MODE_ASYNC.toByte(),
window,
XCB_CURSOR_NONE,
buttonTime)
}
else {
this.libxcb.xcb_ungrab_pointer(this.x11Platform.xcbConnection,
buttonTime)
wlPointerButtonState = WlPointerButtonState.RELEASED
}
return wlPointerButtonState
}
private fun toLinuxButton(eventDetail: Int): Int {
val button: Int
when (eventDetail) {
1 -> button = BTN_LEFT
2 -> button = BTN_MIDDLE
3 -> button = BTN_RIGHT
4, 5, 6, 7 ->
//scroll
button = 0
else -> button = eventDetail + BTN_SIDE - 8
}
return button
}
private fun handleScroll(buttonTime: Int,
eventDetail: Short) {
val wlPointerAxis: WlPointerAxis
val value: Float
val discreteValue: Int
if (eventDetail.toInt() == 4 || eventDetail.toInt() == 5) {
wlPointerAxis = VERTICAL_SCROLL
value = if (eventDetail.toInt() == 4) -DEFAULT_AXIS_STEP_DISTANCE else DEFAULT_AXIS_STEP_DISTANCE
discreteValue = if (eventDetail.toInt() == 4) -1 else 1
}
else {
wlPointerAxis = HORIZONTAL_SCROLL
value = if (eventDetail.toInt() == 6) -DEFAULT_AXIS_STEP_DISTANCE else DEFAULT_AXIS_STEP_DISTANCE
discreteValue = if (eventDetail.toInt() == 6) -1 else 1
}
val wlPointer = this.wlSeat.wlPointer
val pointerDevice = wlPointer.pointerDevice
pointerDevice.axisDiscrete(wlPointer.resources,
wlPointerAxis,
buttonTime,
discreteValue,
value)
pointerDevice.frame(wlPointer.resources)
}
fun deliverMotion(windowId: Int,
time: Int,
x: Int,
y: Int) {
this.x11Platform.renderOutputs.forEach {
if (it.xWindow == windowId) {
val point = toGlobal(it,
x,
y)
val wlPointer = this.wlSeat.wlPointer
val pointerDevice = wlPointer.pointerDevice
pointerDevice.motion(wlPointer.resources,
time,
point.x,
point.y)
pointerDevice.frame(wlPointer.resources)
}
}
}
private fun toGlobal(x11Output: X11Output,
x11WindowX: Int,
x11WindowY: Int): Point {
val globalX = x11Output.x + x11WindowX
val globalY = x11Output.y + x11WindowY
return Point(globalX,
globalY)
}
companion object {
private val DEFAULT_AXIS_STEP_DISTANCE = 10.0f
}
}
|
agpl-3.0
|
46f46f97b98fde84b3e49702cde35ba6
| 39.640394 | 209 | 0.566303 | 4.771544 | false | false | false | false |
leafclick/intellij-community
|
python/src/com/jetbrains/python/run/runAnything/PyConsoleRunAnythingProvider.kt
|
1
|
1230
|
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.run.runAnything
import com.intellij.ide.actions.runAnything.activity.RunAnythingAnActionProvider
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.DataContext
import com.jetbrains.python.console.RunPythonOrDebugConsoleAction
import icons.PythonIcons
import javax.swing.Icon
/**
* @author vlan
*/
class PyConsoleRunAnythingProvider : RunAnythingAnActionProvider<RunPythonOrDebugConsoleAction>() {
override fun getCommand(value: RunPythonOrDebugConsoleAction) = helpCommand
override fun getHelpCommand() = "python"
override fun getHelpGroupTitle(): String? = "Python"
override fun getValues(dataContext: DataContext, pattern: String): Collection<RunPythonOrDebugConsoleAction> {
val action = ActionManager.getInstance().getAction("com.jetbrains.python.console.RunPythonConsoleAction")
return listOfNotNull(action as? RunPythonOrDebugConsoleAction)
}
override fun getHelpIcon(): Icon = PythonIcons.Python.PythonConsole
override fun getHelpDescription(): String = "Runs Python console"
}
|
apache-2.0
|
6e563ded9df82adcfe9bb2795b190812
| 41.448276 | 140 | 0.813821 | 4.86166 | false | false | false | false |
JoachimR/Bible2net
|
app/src/main/java/de/reiss/bible2net/theword/bible/BibleViewModel.kt
|
1
|
1019
|
package de.reiss.bible2net.theword.bible
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import de.reiss.bible2net.theword.architecture.AsyncLoad
import de.reiss.bible2net.theword.architecture.AsyncLoadStatus
import de.reiss.bible2net.theword.model.Bible
class BibleViewModel(private val repository: BibleRepository) : ViewModel() {
var biblesLiveData: MutableLiveData<AsyncLoad<List<Bible>>> = MutableLiveData()
fun bibles() = biblesLiveData.value?.data ?: emptyList()
fun refreshBibles() {
repository.updateBibles(biblesLiveData)
}
fun isLoadingBibles() = biblesLiveData.value?.loadStatus == AsyncLoadStatus.LOADING
class Factory(private val repository: BibleRepository) :
ViewModelProvider.NewInstanceFactory() {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
@Suppress("UNCHECKED_CAST")
return BibleViewModel(repository) as T
}
}
}
|
gpl-3.0
|
b114ed4d3240eaae66b3b353ea427580
| 31.870968 | 87 | 0.745829 | 4.430435 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantElvisReturnNullInspection.kt
|
4
|
2848
|
// 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.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.startOffset
class RedundantElvisReturnNullInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return returnExpressionVisitor(fun(returnExpression: KtReturnExpression) {
if ((returnExpression.returnedExpression?.deparenthesize() as? KtConstantExpression)?.text != KtTokens.NULL_KEYWORD.value) return
val binaryExpression = returnExpression.getStrictParentOfType<KtBinaryExpression>()?.takeIf {
it == it.getStrictParentOfType<KtReturnExpression>()?.returnedExpression?.deparenthesize()
} ?: return
val right = binaryExpression.right?.deparenthesize()?.takeIf { it == returnExpression } ?: return
if (binaryExpression.operationToken == KtTokens.ELSE_KEYWORD) return
if (binaryExpression.left?.resolveToCall()?.resultingDescriptor?.returnType?.isMarkedNullable != true) return
holder.registerProblem(
binaryExpression,
KotlinBundle.message("inspection.redundant.elvis.return.null.descriptor"),
ProblemHighlightType.LIKE_UNUSED_SYMBOL,
TextRange(binaryExpression.operationReference.startOffset, right.endOffset).shiftLeft(binaryExpression.startOffset),
RemoveRedundantElvisReturnNull()
)
})
}
private fun KtExpression.deparenthesize() = KtPsiUtil.deparenthesize(this)
private class RemoveRedundantElvisReturnNull : LocalQuickFix {
override fun getName() = KotlinBundle.message("remove.redundant.elvis.return.null.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val binaryExpression = descriptor.psiElement as? KtBinaryExpression ?: return
val left = binaryExpression.left ?: return
binaryExpression.replace(left)
}
}
}
|
apache-2.0
|
0c5b42338067e19a89ef16f70b22cf5b
| 50.781818 | 158 | 0.747542 | 5.617357 | false | false | false | false |
smmribeiro/intellij-community
|
platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/autoimport/AutoImportTest.kt
|
1
|
48173
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.autoimport
import com.intellij.openapi.externalSystem.autoimport.ExternalSystemProjectTrackerSettings.AutoReloadType.*
import com.intellij.openapi.externalSystem.autoimport.ExternalSystemRefreshStatus.FAILURE
import com.intellij.openapi.externalSystem.autoimport.ExternalSystemRefreshStatus.SUCCESS
import com.intellij.openapi.externalSystem.autoimport.MockProjectAware.RefreshCollisionPassType
import com.intellij.openapi.externalSystem.autoimport.ProjectStatus.ModificationType.EXTERNAL
import com.intellij.openapi.externalSystem.autoimport.ProjectStatus.ModificationType.INTERNAL
import com.intellij.openapi.externalSystem.model.ProjectSystemId
import com.intellij.openapi.externalSystem.util.Parallel.Companion.parallel
import com.intellij.openapi.util.Ref
import com.intellij.testFramework.PlatformTestUtil
import com.intellij.util.AlarmFactory
import org.jetbrains.concurrency.AsyncPromise
import org.junit.Test
import java.io.File
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
class AutoImportTest : AutoImportTestCase() {
@Test
fun `test simple modification tracking`() {
simpleTest("settings.groovy") { settingsFile ->
assertState(refresh = 1, notified = false, event = "register project without cache")
settingsFile.appendString("println 'hello'")
assertState(refresh = 1, notified = true, event = "modification")
scheduleProjectReload()
assertState(refresh = 2, notified = false, event = "project refresh")
settingsFile.replaceString("hello", "hi")
assertState(refresh = 2, notified = true, event = "modification")
settingsFile.replaceString("hi", "hello")
assertState(refresh = 2, notified = false, event = "revert changes")
settingsFile.appendString("\n ")
assertState(refresh = 2, notified = false, event = "empty modification")
settingsFile.replaceString("println", "print ln")
assertState(refresh = 2, notified = true, event = "split token by space")
settingsFile.replaceString("print ln", "println")
assertState(refresh = 2, notified = false, event = "revert modification")
settingsFile.appendString(" ")
assertState(refresh = 2, notified = false, event = "empty modification")
settingsFile.appendString("//It is comment")
assertState(refresh = 2, notified = false, event = "append comment")
settingsFile.insertStringAfter("println", "/*It is comment*/")
assertState(refresh = 2, notified = false, event = "append comment")
settingsFile.insertString(0, "//")
assertState(refresh = 2, notified = true, event = "comment code")
scheduleProjectReload()
assertState(refresh = 3, notified = false, event = "project refresh")
scheduleProjectReload()
assertState(refresh = 3, notified = false, event = "empty project refresh")
}
}
@Test
fun `test modification tracking disabled by ES plugin`() {
val autoImportAwareCondition = Ref.create(true)
testWithDummyExternalSystem("settings.groovy", autoImportAwareCondition = autoImportAwareCondition) { settingsFile ->
assertState(refresh = 1, beforeRefresh = 1, afterRefresh = 1, event = "register project without cache")
settingsFile.appendString("println 'hello'")
assertState(refresh = 1, beforeRefresh = 1, afterRefresh = 1, event = "modification")
scheduleProjectReload()
assertState(refresh = 2, beforeRefresh = 2, afterRefresh = 2, event = "project refresh")
settingsFile.replaceString("hello", "hi")
assertState(refresh = 2, beforeRefresh = 2, afterRefresh = 2, event = "modification")
autoImportAwareCondition.set(false)
scheduleProjectReload()
assertState(refresh = 3, beforeRefresh = 2, afterRefresh = 2, event = "import with inapplicable autoImportAware")
autoImportAwareCondition.set(true)
scheduleProjectReload()
assertState(refresh = 4, beforeRefresh = 3, afterRefresh = 3, event = "empty project refresh")
}
}
@Test
fun `test simple modification tracking in xml`() {
simpleTest("settings.xml") { settingsFile ->
assertState(refresh = 1, notified = false, event = "register project without cache")
settingsFile.replaceContent("""
<element>
<name description="This is a my super name">my-name</name>
</element>
""".trimIndent())
assertState(refresh = 1, notified = true, event = "modification")
scheduleProjectReload()
assertState(refresh = 2, notified = false, event = "refresh project")
settingsFile.replaceString("my-name", "my name")
assertState(refresh = 2, notified = true, event = "replace by space")
settingsFile.replaceString("my name", "my-name")
assertState(refresh = 2, notified = false, event = "revert modification")
settingsFile.replaceString("my-name", "my - name")
assertState(refresh = 2, notified = true, event = "split token by spaces")
settingsFile.replaceString("my - name", "my-name")
assertState(refresh = 2, notified = false, event = "revert modification")
settingsFile.replaceString("my-name", " my-name ")
assertState(refresh = 2, notified = false, event = "expand text token by spaces")
settingsFile.insertStringAfter("</name>", " ")
assertState(refresh = 2, notified = false, event = "append space after tag")
settingsFile.insertStringAfter("</name>", "\n ")
assertState(refresh = 2, notified = false, event = "append empty line in file")
settingsFile.replaceString("</name>", "</n am e>")
assertState(refresh = 2, notified = true, event = "split tag by spaces")
settingsFile.replaceString("</n am e>", "</name>")
assertState(refresh = 2, notified = false, event = "revert modification")
settingsFile.replaceString("</name>", "</ name >")
assertState(refresh = 2, notified = false, event = "expand tag brackets by spaces")
settingsFile.replaceString("=", " = ")
assertState(refresh = 2, notified = false, event = "expand attribute definition")
settingsFile.replaceString("my super name", "my super name")
assertState(refresh = 2, notified = true, event = "expand space inside attribute value")
settingsFile.replaceString("my super name", "my super name")
assertState(refresh = 2, notified = false, event = "revert modification")
settingsFile.insertStringAfter("my super name", " ")
assertState(refresh = 2, notified = true, event = "insert space in end of attribute")
settingsFile.replaceString("my super name \"", "my super name\"")
assertState(refresh = 2, notified = false, event = "revert modification")
}
}
@Test
fun `test unrecognized settings file`() {
simpleTest("settings.elvish") { settingsFile ->
assertState(refresh = 1, notified = false, event = "register project without cache")
settingsFile.appendString("q71Gpj5 .9jR°`N.")
assertState(refresh = 1, notified = true, event = "modification")
scheduleProjectReload()
assertState(refresh = 2, notified = false, event = "project refresh")
settingsFile.replaceString("9jR°`N", "9`B")
assertState(refresh = 2, notified = true, event = "modification")
settingsFile.replaceString("9`B", "9jR°`N")
assertState(refresh = 2, notified = false, event = "revert changes")
settingsFile.appendString(" ")
assertState(refresh = 2, notified = true, event = "unrecognized empty modification")
scheduleProjectReload()
assertState(refresh = 3, notified = false, event = "project refresh")
settingsFile.appendString("//1G iT zt^P1Fp")
assertState(refresh = 3, notified = true, event = "unrecognized comment modification")
scheduleProjectReload()
assertState(refresh = 4, notified = false, event = "project refresh")
}
}
@Test
fun `test deletion tracking`() {
simpleTest("settings.groovy", "println 'hello'") { settingsFile ->
assertState(refresh = 1, notified = false, event = "register project without cache")
settingsFile.delete()
assertState(refresh = 1, notified = true, event = "delete registered settings")
scheduleProjectReload()
assertState(refresh = 2, notified = false, event = "project refresh")
var newSettingsFile = createVirtualFile("settings.groovy")
assertState(refresh = 2, notified = true, event = "create registered settings")
newSettingsFile.replaceContent("println 'hello'")
assertState(refresh = 2, notified = true, event = "modify registered settings")
scheduleProjectReload()
assertState(refresh = 3, notified = false, event = "project refresh")
newSettingsFile.delete()
assertState(refresh = 3, notified = true, event = "delete registered settings")
newSettingsFile = createVirtualFile("settings.groovy")
assertState(refresh = 3, notified = true, event = "create registered settings immediately after deleting")
newSettingsFile.replaceContent("println 'hello'")
assertState(refresh = 3, notified = false, event = "modify registered settings immediately after deleting")
}
}
@Test
fun `test directory deletion tracking`() {
simpleModificationTest {
val directory = findOrCreateDirectory("directory")
createSettingsVirtualFile("directory/settings.txt")
assertState(refresh = 0, notified = true, event = "settings created")
scheduleProjectReload()
assertState(refresh = 1, notified = false, event = "project reloaded")
directory.delete()
assertState(refresh = 1, notified = true, event = "deleted directory with settings")
findOrCreateDirectory("directory")
assertState(refresh = 1, notified = true, event = "deleted directory created without settings")
createSettingsVirtualFile("directory/settings.txt")
assertState(refresh = 1, notified = false, event = "reverted deleted settings")
}
}
@Test
fun `test modification tracking with several settings files`() {
simpleTest("settings.groovy", "println 'hello'") { settingsFile ->
assertState(refresh = 1, notified = false, event = "register project without cache")
val configFile = createVirtualFile("config.groovy")
assertState(refresh = 1, notified = false, event = "create unregistered settings")
configFile.replaceContent("println('hello')")
assertState(refresh = 1, notified = false, event = "modify unregistered settings")
val scriptFile = createSettingsVirtualFile("script.groovy")
assertState(refresh = 1, notified = true, event = "created new settings file")
scriptFile.replaceContent("println('hello')")
assertState(refresh = 1, notified = true, event = "modify settings file")
settingsFile.replaceString("hello", "hi")
assertState(refresh = 1, notified = true, event = "modification")
settingsFile.replaceString("hi", "hello")
assertState(refresh = 1, notified = true, event = "try to revert changes if has other modification")
scheduleProjectReload()
assertState(refresh = 2, notified = false, event = "project refresh")
settingsFile.replaceString("hello", "hi")
assertState(refresh = 2, notified = true, event = "modification")
scriptFile.replaceString("hello", "hi")
assertState(refresh = 2, notified = true, event = "modification")
settingsFile.replaceString("hi", "hello")
assertState(refresh = 2, notified = true, event = "try to revert changes if has other modification")
scriptFile.replaceString("hi", "hello")
assertState(refresh = 2, notified = false, event = "revert changes")
}
}
@Test
fun `test modification tracking with several sub projects`() {
val systemId1 = ProjectSystemId("External System 1")
val systemId2 = ProjectSystemId("External System 2")
val projectId1 = ExternalSystemProjectId(systemId1, projectPath)
val projectId2 = ExternalSystemProjectId(systemId2, projectPath)
val projectAware1 = mockProjectAware(projectId1)
val projectAware2 = mockProjectAware(projectId2)
initialize()
val scriptFile1 = createVirtualFile("script1.groovy")
val scriptFile2 = createVirtualFile("script2.groovy")
projectAware1.registerSettingsFile(scriptFile1.path)
projectAware2.registerSettingsFile(scriptFile2.path)
register(projectAware1)
register(projectAware2)
assertProjectAware(projectAware1, refresh = 1, event = "register project without cache")
assertProjectAware(projectAware2, refresh = 1, event = "register project without cache")
assertNotificationAware(event = "register project without cache")
scriptFile1.appendString("println 1")
assertProjectAware(projectAware1, refresh = 1, event = "modification of first settings")
assertProjectAware(projectAware2, refresh = 1, event = "modification of first settings")
assertNotificationAware(projectId1, event = "modification of first settings")
scriptFile2.appendString("println 2")
assertProjectAware(projectAware1, refresh = 1, event = "modification of second settings")
assertProjectAware(projectAware2, refresh = 1, event = "modification of second settings")
assertNotificationAware(projectId1, projectId2, event = "modification of second settings")
scriptFile1.removeContent()
assertProjectAware(projectAware1, refresh = 1, event = "revert changes at second settings")
assertProjectAware(projectAware2, refresh = 1, event = "revert changes at second settings")
assertNotificationAware(projectId2, event = "revert changes at second settings")
scheduleProjectReload()
assertProjectAware(projectAware1, refresh = 1, event = "project refresh")
assertProjectAware(projectAware2, refresh = 2, event = "project refresh")
assertNotificationAware(event = "project refresh")
scriptFile1.replaceContent("println 'script 1'")
scriptFile2.replaceContent("println 'script 2'")
assertProjectAware(projectAware1, refresh = 1, event = "modification of both settings")
assertProjectAware(projectAware2, refresh = 2, event = "modification of both settings")
assertNotificationAware(projectId1, projectId2, event = "modification of both settings")
scheduleProjectReload()
assertProjectAware(projectAware1, refresh = 2, event = "project refresh")
assertProjectAware(projectAware2, refresh = 3, event = "project refresh")
assertNotificationAware(event = "project refresh")
}
@Test
fun `test project link-unlink`() {
simpleTest("settings.groovy") { settingsFile ->
assertState(refresh = 1, subscribe = 2, unsubscribe = 0, notified = false, event = "register project without cache")
settingsFile.appendString("println 'hello'")
assertState(refresh = 1, subscribe = 2, unsubscribe = 0, notified = true, event = "modification")
removeProjectAware()
assertState(refresh = 1, subscribe = 2, unsubscribe = 2, notified = false, event = "remove project")
registerProjectAware()
assertState(refresh = 2, subscribe = 4, unsubscribe = 2, notified = false, event = "register project without cache")
}
}
@Test
fun `test external modification tracking`() {
simpleTest("settings.groovy") {
var settingsFile = it
assertState(refresh = 1, notified = false, event = "register project without cache")
settingsFile.replaceContentInIoFile("println 'hello'")
assertState(refresh = 2, notified = false, event = "untracked external modification")
settingsFile.replaceString("hello", "hi")
assertState(refresh = 2, notified = true, event = "internal modification")
settingsFile.replaceStringInIoFile("hi", "settings")
assertState(refresh = 2, notified = true, event = "untracked external modification during internal modification")
scheduleProjectReload()
assertState(refresh = 3, notified = false, event = "refresh project")
modification {
assertState(refresh = 3, notified = false, event = "start external modification")
settingsFile.replaceStringInIoFile("settings", "modified settings")
assertState(refresh = 3, notified = false, event = "external modification")
}
assertState(refresh = 4, notified = false, event = "complete external modification")
modification {
assertState(refresh = 4, notified = false, event = "start external modification")
settingsFile.replaceStringInIoFile("modified settings", "simple settings")
assertState(refresh = 4, notified = false, event = "external modification")
settingsFile.replaceStringInIoFile("simple settings", "modified settings")
assertState(refresh = 4, notified = false, event = "revert external modification")
}
assertState(refresh = 4, notified = false, event = "complete external modification")
modification {
assertState(refresh = 4, notified = false, event = "start external modification")
settingsFile.deleteIoFile()
assertState(refresh = 4, notified = false, event = "external deletion")
}
assertState(refresh = 5, notified = false, event = "complete external modification")
modification {
assertState(refresh = 5, notified = false, event = "start external modification")
settingsFile = createIoFile("settings.groovy")
assertState(refresh = 5, notified = false, event = "external creation")
settingsFile.replaceContentInIoFile("println 'settings'")
assertState(refresh = 5, notified = false, event = "external modification")
}
assertState(refresh = 6, notified = false, event = "complete external modification")
modification {
assertState(refresh = 6, notified = false, event = "start first external modification")
settingsFile.replaceStringInIoFile("settings", "hello")
assertState(refresh = 6, notified = false, event = "first external modification")
modification {
assertState(refresh = 6, notified = false, event = "start second external modification")
settingsFile.replaceStringInIoFile("hello", "hi")
assertState(refresh = 6, notified = false, event = "second external modification")
}
assertState(refresh = 6, notified = false, event = "complete second external modification")
}
assertState(refresh = 7, notified = false, event = "complete first external modification")
modification {
assertState(refresh = 7, notified = false, event = "start exte]rnal modification")
settingsFile.replaceStringInIoFile("println", "print")
assertState(refresh = 7, notified = false, event = "external modification")
settingsFile.replaceString("hi", "hello")
assertState(refresh = 7, notified = false, event = "internal modification during external modification")
settingsFile.replaceStringInIoFile("hello", "settings")
assertState(refresh = 7, notified = false, event = "external modification")
}
assertState(refresh = 7, notified = true, event = "complete external modification")
scheduleProjectReload()
assertState(refresh = 8, notified = false, event = "refresh project")
}
}
@Test
fun `test tracker store and restore`() {
var state = simpleTest("settings.groovy") { settingsFile ->
assertState(refresh = 1, notified = false, event = "register project without cache")
settingsFile.replaceContent("println 'hello'")
assertState(refresh = 1, notified = true, event = "modification")
scheduleProjectReload()
assertState(refresh = 2, notified = false, event = "project refresh")
}
state = simpleTest("settings.groovy", state = state) { settingsFile ->
assertState(refresh = 0, notified = false, event = "register project with correct cache")
settingsFile.replaceString("hello", "hi")
assertState(refresh = 0, notified = true, event = "modification")
scheduleProjectReload()
assertState(refresh = 1, notified = false, event = "project refresh")
}
with(File(projectPath, "settings.groovy")) {
writeText(readText().replace("hi", "hello"))
}
state = simpleTest("settings.groovy", state = state) { settingsFile ->
assertState(refresh = 1, notified = false, event = "register project with external modifications")
settingsFile.replaceString("hello", "hi")
assertState(refresh = 1, notified = true, event = "modification")
scheduleProjectReload()
assertState(refresh = 2, notified = false, event = "project refresh")
}
state = simpleTest("settings.groovy", state = state) { settingsFile ->
assertState(refresh = 0, notified = false, event = "register project with correct cache")
settingsFile.replaceString("hi", "hello")
assertState(refresh = 0, notified = true, event = "modification")
}
simpleTest("settings.groovy", state = state) {
assertState(refresh = 1, notified = false, event = "register project with previous modifications")
}
}
fun `test move and rename settings files`() {
simpleTest("settings.groovy") { settingsFile ->
assertState(refresh = 1, notified = false, event = "register project without cache")
registerSettingsFile("script.groovy")
registerSettingsFile("dir/script.groovy")
registerSettingsFile("dir1/script.groovy")
registerSettingsFile("dir/dir1/script.groovy")
var scriptFile = settingsFile.copy("script.groovy")
assertState(refresh = 1, notified = true, event = "copy to registered settings")
scheduleProjectReload()
assertState(refresh = 2, notified = false, event = "project refresh")
scriptFile.delete()
assertState(refresh = 2, notified = true, event = "delete file")
scriptFile = settingsFile.copy("script.groovy")
assertState(refresh = 2, notified = false, event = "revert delete by copy")
val configurationFile = settingsFile.copy("configuration.groovy")
assertState(refresh = 2, notified = false, event = "copy to registered settings")
configurationFile.delete()
assertState(refresh = 2, notified = false, event = "delete file")
val dir = findOrCreateDirectory("dir")
val dir1 = findOrCreateDirectory("dir1")
assertState(refresh = 2, notified = false, event = "create directory")
scriptFile.move(dir)
assertState(refresh = 2, notified = true, event = "move settings to directory")
scriptFile.move(myProjectRoot)
assertState(refresh = 2, notified = false, event = "revert move settings")
scriptFile.move(dir1)
assertState(refresh = 2, notified = true, event = "move settings to directory")
dir1.move(dir)
assertState(refresh = 2, notified = true, event = "move directory with settings to other directory")
scriptFile.move(myProjectRoot)
assertState(refresh = 2, notified = false, event = "revert move settings")
scriptFile.move(dir)
assertState(refresh = 2, notified = true, event = "move settings to directory")
dir.rename("dir1")
assertState(refresh = 2, notified = true, event = "rename directory with settings")
scriptFile.move(myProjectRoot)
assertState(refresh = 2, notified = false, event = "revert move settings")
settingsFile.rename("configuration.groovy")
assertState(refresh = 2, notified = true, event = "rename")
settingsFile.rename("settings.groovy")
assertState(refresh = 2, notified = false, event = "revert rename")
}
}
fun `test document changes between save`() {
simpleTest("settings.groovy") { settingsFile ->
assertState(refresh = 1, notified = false, event = "register project without cache")
val settingsDocument = settingsFile.asDocument()
settingsDocument.replaceContent("println 'hello'")
assertState(refresh = 1, notified = true, event = "change")
scheduleProjectReload()
assertState(refresh = 2, notified = false, event = "refresh project")
settingsDocument.replaceString("hello", "hi")
assertState(refresh = 2, notified = true, event = "change")
settingsDocument.replaceString("hi", "hello")
assertState(refresh = 2, notified = false, event = "revert change")
settingsDocument.replaceString("hello", "hi")
assertState(refresh = 2, notified = true, event = "change")
settingsDocument.save()
assertState(refresh = 2, notified = true, event = "save")
settingsDocument.replaceString("hi", "hello")
assertState(refresh = 2, notified = false, event = "revert change after save")
settingsDocument.save()
assertState(refresh = 2, notified = false, event = "save reverted changes")
}
}
fun `test processing of failure refresh`() {
simpleTest("settings.groovy") { settingsFile ->
assertState(refresh = 1, notified = false, event = "register project without cache")
settingsFile.replaceContentInIoFile("println 'hello'")
assertState(refresh = 2, notified = false, event = "external change")
setRefreshStatus(FAILURE)
settingsFile.replaceStringInIoFile("hello", "hi")
assertState(refresh = 3, notified = true, event = "external change with failure refresh")
scheduleProjectReload()
assertState(refresh = 4, notified = true, event = "failure project refresh")
setRefreshStatus(SUCCESS)
scheduleProjectReload()
assertState(refresh = 5, notified = false, event = "project refresh")
settingsFile.replaceString("hi", "hello")
assertState(refresh = 5, notified = true, event = "modify")
setRefreshStatus(FAILURE)
scheduleProjectReload()
assertState(refresh = 6, notified = true, event = "failure project refresh")
settingsFile.replaceString("hello", "hi")
assertState(refresh = 6, notified = true, event = "try to revert changes after failure refresh")
setRefreshStatus(SUCCESS)
scheduleProjectReload()
assertState(refresh = 7, notified = false, event = "project refresh")
}
}
fun `test files generation during refresh`() {
val systemId = ProjectSystemId("External System")
val projectId = ExternalSystemProjectId(systemId, projectPath)
val projectAware = mockProjectAware(projectId)
initialize()
register(projectAware)
assertProjectAware(projectAware, refresh = 1, event = "register project")
assertNotificationAware(event = "register project")
val settingsFile = createIoFile("project.groovy")
projectAware.onceDuringRefresh {
projectAware.registerSettingsFile(settingsFile.path)
settingsFile.replaceContentInIoFile("println 'generated project'")
}
projectAware.forceReloadProject()
assertProjectAware(projectAware, refresh = 2, event = "registration of settings file during project refresh")
assertNotificationAware(event = "registration of settings file during project refresh")
// modification during refresh
projectAware.onceDuringRefresh {
settingsFile.appendString("println 'hello'")
}
projectAware.forceReloadProject()
assertProjectAware(projectAware, refresh = 3, event = "modification during project refresh")
assertNotificationAware(projectId, event = "modification during project refresh")
}
fun `test disabling of auto-import`() {
var state = simpleTest("settings.groovy") { settingsFile ->
assertState(refresh = 1, autoReloadType = SELECTIVE, notified = false, event = "register project without cache")
setAutoReloadType(NONE)
assertState(refresh = 1, autoReloadType = NONE, notified = false, event = "disable project auto-import")
settingsFile.replaceContentInIoFile("println 'hello'")
assertState(refresh = 1, autoReloadType = NONE, notified = true, event = "modification with disabled auto-import")
}
state = simpleTest("settings.groovy", state = state) { settingsFile ->
// Open modified project with disabled auto-import for external changes
assertState(refresh = 0, autoReloadType = NONE, notified = true, event = "register modified project")
scheduleProjectReload()
assertState(refresh = 1, autoReloadType = NONE, notified = false, event = "refresh project")
// Checkout git branch, that has additional linked project
withLinkedProject("module/settings.groovy") { moduleSettingsFile ->
assertState(refresh = 0, autoReloadType = NONE, notified = true, event = "register project without cache with disabled auto-import")
moduleSettingsFile.replaceContentInIoFile("println 'hello'")
assertState(refresh = 0, autoReloadType = NONE, notified = true, event = "modification with disabled auto-import")
}
assertState(refresh = 1, autoReloadType = NONE, notified = false, event = "remove modified linked project")
setAutoReloadType(SELECTIVE)
assertState(refresh = 1, autoReloadType = SELECTIVE, notified = false, event = "enable auto-import for project without modifications")
setAutoReloadType(NONE)
assertState(refresh = 1, autoReloadType = NONE, notified = false, event = "disable project auto-import")
settingsFile.replaceStringInIoFile("hello", "hi")
assertState(refresh = 1, autoReloadType = NONE, notified = true, event = "modification with disabled auto-import")
setAutoReloadType(SELECTIVE)
assertState(refresh = 2, autoReloadType = SELECTIVE, notified = false, event = "enable auto-import for modified project")
}
simpleTest("settings.groovy", state = state) {
assertState(refresh = 0, autoReloadType = SELECTIVE, notified = false, event = "register project with correct cache")
}
}
@Test
fun `test activation of auto-import`() {
val systemId = ProjectSystemId("External System")
val projectId1 = ExternalSystemProjectId(systemId, projectPath)
val projectId2 = ExternalSystemProjectId(systemId, "$projectPath/sub-project")
val projectAware1 = mockProjectAware(projectId1)
val projectAware2 = mockProjectAware(projectId2)
initialize()
register(projectAware1, activate = false)
assertProjectAware(projectAware1, refresh = 0, event = "register project")
assertNotificationAware(projectId1, event = "register project")
assertActivationStatus(event = "register project")
activate(projectId1)
assertProjectAware(projectAware1, refresh = 1, event = "activate project")
assertNotificationAware(event = "activate project")
assertActivationStatus(projectId1, event = "activate project")
register(projectAware2, activate = false)
assertProjectAware(projectAware1, refresh = 1, event = "register project 2")
assertProjectAware(projectAware2, refresh = 0, event = "register project 2")
assertNotificationAware(projectId2, event = "register project 2")
assertActivationStatus(projectId1, event = "register project 2")
registerSettingsFile(projectAware1, "settings.groovy")
registerSettingsFile(projectAware2, "sub-project/settings.groovy")
val settingsFile1 = createIoFile("settings.groovy")
val settingsFile2 = createIoFile("sub-project/settings.groovy")
assertProjectAware(projectAware1, refresh = 2, event = "externally created both settings files, but project 2 is inactive")
assertProjectAware(projectAware2, refresh = 0, event = "externally created both settings files, but project 2 is inactive")
settingsFile1.replaceContentInIoFile("println 'hello'")
settingsFile2.replaceContentInIoFile("println 'hello'")
assertProjectAware(projectAware1, refresh = 3, event = "externally modified both settings files, but project 2 is inactive")
assertProjectAware(projectAware2, refresh = 0, event = "externally modified both settings files, but project 2 is inactive")
assertNotificationAware(projectId2, event = "externally modified both settings files, but project 2 is inactive")
assertActivationStatus(projectId1, event = "externally modified both settings files, but project 2 is inactive")
settingsFile1.replaceString("hello", "Hello world!")
settingsFile2.replaceString("hello", "Hello world!")
assertProjectAware(projectAware1, refresh = 3, event = "internally modify settings")
assertProjectAware(projectAware2, refresh = 0, event = "internally modify settings")
assertNotificationAware(projectId1, projectId2, event = "internally modify settings")
assertActivationStatus(projectId1, event = "internally modify settings")
scheduleProjectReload()
assertProjectAware(projectAware1, refresh = 4, event = "refresh project")
assertProjectAware(projectAware2, refresh = 1, event = "refresh project")
assertNotificationAware(event = "refresh project")
assertActivationStatus(projectId1, projectId2, event = "refresh project")
}
@Test
fun `test merging of refreshes with different nature`() {
simpleTest("settings.groovy") { settingsFile ->
assertState(1, notified = false, event = "register project without cache")
enableAsyncExecution()
waitForProjectRefresh {
parallel {
thread {
settingsFile.replaceContentInIoFile("println 'hello'")
}
thread {
forceRefreshProject()
}
}
}
assertState(refresh = 2, notified = false, event = "modification")
}
}
@Test
fun `test enabling-disabling internal-external changes importing`() {
simpleModificationTest {
modifySettingsFile(INTERNAL)
assertState(refresh = 0, notified = true, autoReloadType = SELECTIVE, event = "internal modification")
scheduleProjectReload()
assertState(refresh = 1, notified = false, autoReloadType = SELECTIVE, event = "refresh project")
modifySettingsFile(EXTERNAL)
assertState(refresh = 2, notified = false, autoReloadType = SELECTIVE, event = "external modification")
setAutoReloadType(ALL)
modifySettingsFile(INTERNAL)
assertState(refresh = 3, notified = false, autoReloadType = ALL, event = "internal modification with enabled auto-reload")
modifySettingsFile(EXTERNAL)
assertState(refresh = 4, notified = false, autoReloadType = ALL, event = "external modification with enabled auto-reload")
setAutoReloadType(NONE)
modifySettingsFile(INTERNAL)
assertState(refresh = 4, notified = true, autoReloadType = NONE, event = "internal modification with disabled auto-reload")
modifySettingsFile(EXTERNAL)
assertState(refresh = 4, notified = true, autoReloadType = NONE, event = "external modification with disabled auto-reload")
setAutoReloadType(SELECTIVE)
assertState(refresh = 4, notified = true, autoReloadType = SELECTIVE,
event = "enable auto-reload external changes with internal and external modifications")
setAutoReloadType(ALL)
assertState(refresh = 5, notified = false, autoReloadType = ALL, event = "enable auto-reload of any changes")
setAutoReloadType(NONE)
modifySettingsFile(INTERNAL)
assertState(refresh = 5, notified = true, autoReloadType = NONE, event = "internal modification with disabled auto-reload")
modifySettingsFile(EXTERNAL)
assertState(refresh = 5, notified = true, autoReloadType = NONE, event = "external modification with disabled auto-reload")
setAutoReloadType(ALL)
assertState(refresh = 6, notified = false, autoReloadType = ALL, event = "enable auto-reload of any changes")
}
}
@Test
fun `test failure auto-reload with enabled auto-reload of any changes`() {
simpleModificationTest {
setAutoReloadType(ALL)
setRefreshStatus(FAILURE)
modifySettingsFile(INTERNAL)
assertState(refresh = 1, notified = true, autoReloadType = ALL, event = "failure modification with enabled auto-reload")
modifySettingsFile(INTERNAL)
assertState(refresh = 2, notified = true, autoReloadType = ALL, event = "failure modification with enabled auto-reload")
setRefreshStatus(SUCCESS)
scheduleProjectReload()
assertState(refresh = 3, notified = false, autoReloadType = ALL, event = "refresh project")
setRefreshStatus(FAILURE)
onceDuringRefresh {
setRefreshStatus(SUCCESS)
modifySettingsFile(INTERNAL)
}
modifySettingsFile(INTERNAL)
assertState(refresh = 5, notified = false, autoReloadType = ALL, event = "success modification after failure")
}
}
@Test
fun `test up-to-date promise after modifications with enabled auto-import`() {
simpleModificationTest {
for (collisionPassType in RefreshCollisionPassType.values()) {
resetAssertionCounters()
setRefreshCollisionPassType(collisionPassType)
setAutoReloadType(SELECTIVE)
onceDuringRefresh {
modifySettingsFile(EXTERNAL)
}
modifySettingsFile(EXTERNAL)
assertState(refresh = 2, notified = false, autoReloadType = SELECTIVE, event = "auto-reload inside reload ($collisionPassType)")
setAutoReloadType(ALL)
onceDuringRefresh {
modifySettingsFile(INTERNAL)
}
modifySettingsFile(INTERNAL)
assertState(refresh = 4, notified = false, autoReloadType = ALL, event = "auto-reload inside reload ($collisionPassType)")
}
}
}
@Test
fun `test providing explicit reload`() {
simpleModificationTest {
onceDuringRefresh {
assertFalse("implicit reload after external modification", it.isExplicitReload)
}
modifySettingsFile(EXTERNAL)
assertState(refresh = 1, notified = false, event = "external modification")
modifySettingsFile(INTERNAL)
assertState(refresh = 1, notified = true, event = "internal modification")
onceDuringRefresh {
assertTrue("explicit reload after explicit scheduling of project reload", it.isExplicitReload)
}
scheduleProjectReload()
assertState(refresh = 2, notified = false, event = "project reload")
}
}
@Test
fun `test settings files modification partition`() {
simpleTest {
assertState(refresh = 1, notified = false, event = "register project without cache")
val settingsFile1 = createSettingsVirtualFile("settings1.groovy")
val settingsFile2 = createSettingsVirtualFile("settings2.groovy")
val settingsFile3 = createSettingsVirtualFile("settings3.groovy")
assertState(refresh = 1, notified = true, event = "settings files creation")
onceDuringRefresh {
assertFalse(it.hasUndefinedModifications)
assertEquals(pathsOf(), it.settingsFilesContext.updated)
assertEquals(pathsOf(settingsFile1, settingsFile2, settingsFile3), it.settingsFilesContext.created)
assertEquals(pathsOf(), it.settingsFilesContext.deleted)
}
scheduleProjectReload()
assertState(refresh = 2, notified = false, event = "project reload")
settingsFile1.delete()
settingsFile2.appendLine("println 'hello'")
settingsFile3.appendLine("")
assertState(refresh = 2, notified = true, event = "settings files modification")
onceDuringRefresh {
assertFalse(it.hasUndefinedModifications)
assertEquals(pathsOf(settingsFile2), it.settingsFilesContext.updated)
assertEquals(pathsOf(), it.settingsFilesContext.created)
assertEquals(pathsOf(settingsFile1), it.settingsFilesContext.deleted)
}
scheduleProjectReload()
assertState(refresh = 3, notified = false, event = "project reload")
settingsFile2.delete()
settingsFile3.delete()
markDirty()
assertState(refresh = 3, notified = true, event = "settings files deletion")
onceDuringRefresh {
assertTrue(it.hasUndefinedModifications)
assertEquals(pathsOf(), it.settingsFilesContext.updated)
assertEquals(pathsOf(), it.settingsFilesContext.created)
assertEquals(pathsOf(settingsFile2, settingsFile3), it.settingsFilesContext.deleted)
}
scheduleProjectReload()
assertState(refresh = 4, notified = false, event = "project reload")
}
}
@Test
fun `test settings files cache`() {
simpleTest {
assertState(refresh = 1, settingsAccess = 1, notified = false, event = "register project without cache")
resetAssertionCounters()
val settings1File = createSettingsVirtualFile("settings1.groovy")
val settings2File = createSettingsVirtualFile("settings2.groovy")
assertState(refresh = 0, settingsAccess = 2, notified = true, event = "settings files creation")
val configFile1 = createVirtualFile("file1.config")
val configFile2 = createVirtualFile("file2.config")
assertState(refresh = 0, settingsAccess = 4, notified = true, event = "non settings files creation")
scheduleProjectReload()
assertState(refresh = 1, settingsAccess = 5, notified = false, event = "project reload")
configFile1.modify(INTERNAL)
configFile2.modify(INTERNAL)
configFile1.modify(EXTERNAL)
configFile2.modify(EXTERNAL)
assertState(refresh = 1, settingsAccess = 5, notified = false, event = "non settings files modification")
settings1File.modify(INTERNAL)
settings2File.modify(INTERNAL)
assertState(refresh = 1, settingsAccess = 5, notified = true, event = "internal settings files modification")
scheduleProjectReload()
assertState(refresh = 2, settingsAccess = 6, notified = false, event = "project reload")
settings1File.modify(EXTERNAL)
assertState(refresh = 3, settingsAccess = 7, notified = false, event = "external settings file modification")
registerSettingsFile("settings3.groovy")
val settings3File = settings2File.copy("settings3.groovy")
assertState(refresh = 3, settingsAccess = 8, notified = true, event = "copy settings file")
settings1File.modify(INTERNAL)
settings2File.modify(INTERNAL)
settings3File.modify(INTERNAL)
assertState(refresh = 3, settingsAccess = 8, notified = true, event = "internal settings files modification")
scheduleProjectReload()
assertState(refresh = 4, settingsAccess = 9, notified = false, event = "project reload")
settings3File.modify(INTERNAL)
assertState(refresh = 4, settingsAccess = 9, notified = true, event = "internal settings file modification")
settings3File.revert()
assertState(refresh = 4, settingsAccess = 9, notified = false, event = "revert modification in settings file")
registerSettingsFile("settings4.groovy")
configFile1.rename("settings4.groovy")
assertState(refresh = 4, settingsAccess = 10, notified = true, event = "rename config file into settings file")
configFile1.modify(INTERNAL)
assertState(refresh = 4, settingsAccess = 10, notified = true, event = "modify settings file")
configFile1.rename("file1.config")
assertState(refresh = 4, settingsAccess = 11, notified = false, event = "revert config file rename")
registerSettingsFile("my-dir/file1.config")
configFile1.move("my-dir")
assertState(refresh = 4, settingsAccess = 12, notified = true, event = "move config file")
configFile1.modify(INTERNAL)
assertState(refresh = 4, settingsAccess = 12, notified = true, event = "modify config file")
configFile1.move(".")
assertState(refresh = 4, settingsAccess = 13, notified = false, event = "revert config file move")
}
}
@Test
fun `test configuration for unknown file type`() {
simpleTest("unknown") { file ->
assertState(refresh = 1, notified = false, event = "register project without cache")
resetAssertionCounters()
file.replaceContent(byteArrayOf(1, 2, 3))
assertState(refresh = 0, notified = true, event = "modification")
scheduleProjectReload()
assertState(refresh = 1, notified = false, event = "reload")
file.replaceContent(byteArrayOf(1, 2, 3))
assertState(refresh = 1, notified = false, event = "empty modification")
file.replaceContent(byteArrayOf(3, 2, 1))
assertState(refresh = 1, notified = true, event = "modification")
file.replaceContent(byteArrayOf(1, 2, 3))
assertState(refresh = 1, notified = false, event = "revert modification")
}
}
@Test
fun `test reload during reload`() {
simpleModificationTest {
enableAsyncExecution()
val expectedRefreshes = 10
val latch = CountDownLatch(expectedRefreshes)
duringRefresh(expectedRefreshes) {
latch.countDown()
latch.await()
}
beforeRefresh(expectedRefreshes - 1) {
forceRefreshProject()
}
waitForProjectRefresh(expectedRefreshes) {
forceRefreshProject()
}
assertState(refresh = expectedRefreshes, notified = false, event = "reloads")
waitForProjectRefresh {
modifySettingsFile(EXTERNAL)
}
assertState(refresh = expectedRefreshes + 1, notified = false, event = "external modification")
}
}
@Test
fun `test modification during reload`() {
simpleModificationTest {
enableAsyncExecution()
setDispatcherMergingSpan(10)
val expectedRefreshes = 10
duringRefresh(expectedRefreshes - 1) {
modifySettingsFile(EXTERNAL)
}
waitForProjectRefresh(expectedRefreshes) {
modifySettingsFile(EXTERNAL)
}
assertState(refresh = expectedRefreshes, notified = false, event = "reloads")
}
}
@Test
fun `test generation during reload`() {
simpleTest {
assertState(refresh = 1, notified = false, event = "register project without cache")
resetAssertionCounters()
onceDuringRefresh {
createSettingsVirtualFile("settings1.cfg")
}
forceRefreshProject()
assertState(refresh = 1, notified = false, event = "create file during reload")
onceDuringRefresh {
createSettingsVirtualFile("settings2.cfg")
.replaceContent("{ name: project }")
}
forceRefreshProject()
assertState(refresh = 2, notified = false, event = "create file and modify it during reload")
findOrCreateVirtualFile("settings2.cfg")
.appendLine("{ type: Java }")
assertState(refresh = 2, notified = true, event = "internal modification")
}
}
@Test
fun `test merge project reloads`() {
simpleModificationTest {
enableAsyncExecution()
setDispatcherMergingSpan(100)
val alarmFactory = AlarmFactory.getInstance()
val alarm = alarmFactory.create()
repeat(10) { iteration ->
val promise = AsyncPromise<Unit>()
alarm.addRequest({
waitForProjectRefresh {
markDirty()
scheduleProjectReload()
}
promise.setResult(Unit)
}, 500)
waitForProjectRefresh {
modifySettingsFile(EXTERNAL)
}
PlatformTestUtil.waitForPromise(promise, TimeUnit.SECONDS.toMillis(10))
assertState(refresh = iteration + 1, notified = false, event = "project reload")
}
}
}
@Test
fun `test handle explicit settings files list change event`() {
initialize()
setAutoReloadType(ALL)
val settingsFile1 = createVirtualFile("script1.groovy").path
val settingsFile2 = createVirtualFile("script2.groovy").path
val projectAware = mockProjectAware(ExternalSystemProjectId(ProjectSystemId("External System 1"), projectPath))
projectAware.registerSettingsFile(settingsFile1)
register(projectAware)
assertProjectAware(projectAware, refresh = 1, event = "register project")
projectAware.notifySettingsFilesListChanged()
assertProjectAware(projectAware, refresh = 1, event = "handle settings files list change event when nothing actually changed")
projectAware.registerSettingsFile(settingsFile2)
projectAware.notifySettingsFilesListChanged()
assertProjectAware(projectAware, refresh = 2, event = "handle settings files list change event when file added")
}
}
|
apache-2.0
|
37028711eeaae8c5c8b9d86618a7f35b
| 45.229367 | 140 | 0.701412 | 4.660861 | false | true | false | false |
smmribeiro/intellij-community
|
platform/usageView/src/com/intellij/usages/impl/UsageViewStatisticsCollector.kt
|
1
|
7548
|
// 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.usages.impl
import com.intellij.find.FindSettings
import com.intellij.ide.util.scopeChooser.ScopeIdMapper
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.eventLog.validator.ValidationResultType
import com.intellij.internal.statistic.eventLog.validator.rules.EventContext
import com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule
import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector
import com.intellij.lang.Language
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.search.SearchScope
import com.intellij.usageView.UsageInfo
import com.intellij.usages.Usage
import com.intellij.usages.rules.PsiElementUsage
import org.jetbrains.annotations.Nls
import java.util.concurrent.atomic.AtomicInteger
enum class CodeNavigateSource {
ShowUsagesPopup,
FindToolWindow
}
enum class TooManyUsagesUserAction {
Shown,
Aborted,
Continued
}
class UsageViewStatisticsCollector : CounterUsagesCollector() {
override fun getGroup() = GROUP
companion object {
val GROUP = EventLogGroup("usage.view", 4)
private var sessionId = AtomicInteger(0)
private val SESSION_ID = EventFields.Int("id")
private val REFERENCE_CLASS = EventFields.Class("reference_class")
private val USAGE_SHOWN = GROUP.registerEvent("usage.shown", SESSION_ID, REFERENCE_CLASS, EventFields.Language)
private val USAGE_NAVIGATE = GROUP.registerEvent("usage.navigate", SESSION_ID, REFERENCE_CLASS, EventFields.Language)
private val UI_LOCATION = EventFields.Enum("ui_location", CodeNavigateSource::class.java)
private val itemChosen = GROUP.registerEvent("item.chosen", SESSION_ID, UI_LOCATION, EventFields.Language)
const val SCOPE_RULE_ID = "scopeRule"
private val SYMBOL_CLASS = EventFields.Class("symbol")
private val SEARCH_SCOPE = EventFields.StringValidatedByCustomRule("scope", SCOPE_RULE_ID)
private val RESULTS_TOTAL = EventFields.Int("results_total")
private val FIRST_RESULT_TS = EventFields.Long("duration_first_results_ms")
private val TOO_MANY_RESULTS = EventFields.Boolean("too_many_result_warning")
private val searchStarted = GROUP.registerVarargEvent("started", SESSION_ID)
private val searchFinished = GROUP.registerVarargEvent("finished",
SESSION_ID,
SYMBOL_CLASS,
SEARCH_SCOPE,
EventFields.Language,
RESULTS_TOTAL,
FIRST_RESULT_TS,
EventFields.DurationMs,
TOO_MANY_RESULTS,
UI_LOCATION)
private val tabSwitched = GROUP.registerEvent("switch.tab", SESSION_ID)
private val PREVIOUS_SCOPE = EventFields.StringValidatedByCustomRule("previous", SCOPE_RULE_ID)
private val NEW_SCOPE = EventFields.StringValidatedByCustomRule("new", SCOPE_RULE_ID)
private val scopeChanged = GROUP.registerVarargEvent("scope.changed", SESSION_ID, PREVIOUS_SCOPE, NEW_SCOPE, SYMBOL_CLASS)
private val OPEN_IN_FIND_TOOL_WINDOW = GROUP.registerEvent("open.in.tool.window", SESSION_ID)
private val USER_ACTION = EventFields.Enum("userAction", TooManyUsagesUserAction::class.java)
private val tooManyUsagesDialog = GROUP.registerVarargEvent("tooManyResultsDialog",
SESSION_ID,
USER_ACTION,
SYMBOL_CLASS,
SEARCH_SCOPE,
EventFields.Language
)
@JvmStatic
fun logSearchStarted(project: Project?) {
searchStarted.log(project, SESSION_ID.with(sessionId.incrementAndGet()))
}
@JvmStatic
fun logUsageShown(project: Project?, referenceClass: Class<out Any>, language: Language?) {
USAGE_SHOWN.log(project, getSessionId(), referenceClass, language)
}
@JvmStatic
fun logUsageNavigate(project: Project?, usage: Usage) {
UsageReferenceClassProvider.getReferenceClass(usage)?.let {
USAGE_NAVIGATE.log(
project,
getSessionId(),
it,
(usage as? PsiElementUsage)?.element?.language,
)
}
}
@JvmStatic
fun logUsageNavigate(project: Project?, usage: UsageInfo) {
usage.referenceClass?.let {
USAGE_NAVIGATE.log(
project,
getSessionId(),
it,
usage.element?.language,
)
}
}
@JvmStatic
fun logItemChosen(project: Project?, source: CodeNavigateSource, language: Language) = itemChosen.log(project, getSessionId(), source, language)
@JvmStatic
fun logSearchFinished(
project: Project?,
targetClass: Class<*>,
scope: SearchScope?,
language: Language?,
results: Int,
durationFirstResults: Long,
duration: Long,
tooManyResult: Boolean,
source: CodeNavigateSource,
) {
searchFinished.log(project,
SESSION_ID.with(getSessionId()),
SYMBOL_CLASS.with(targetClass),
SEARCH_SCOPE.with(scope?.let { ScopeIdMapper.instance.getScopeSerializationId(it.displayName) }),
EventFields.Language.with(language),
RESULTS_TOTAL.with(results),
FIRST_RESULT_TS.with(durationFirstResults),
EventFields.DurationMs.with(duration),
TOO_MANY_RESULTS.with(tooManyResult),
UI_LOCATION.with(source))
}
@JvmStatic
fun logTabSwitched(project: Project?) = tabSwitched.log(project, getSessionId())
@JvmStatic
fun logScopeChanged(
project: Project?,
previousScope: SearchScope?,
newScope: SearchScope?,
symbolClass: Class<*>,
) {
val scopeIdMapper = ScopeIdMapper.instance
scopeChanged.log(project, SESSION_ID.with(getSessionId()),
PREVIOUS_SCOPE.with(previousScope?.let { scopeIdMapper.getScopeSerializationId(it.displayName) }),
NEW_SCOPE.with(newScope?.let { scopeIdMapper.getScopeSerializationId(it.displayName) }),
SYMBOL_CLASS.with(symbolClass))
}
@JvmStatic
fun logTooManyDialog(
project: Project?,
action: TooManyUsagesUserAction,
targetClass: Class<out PsiElement>?,
@Nls scope: String,
language: Language?,
) {
tooManyUsagesDialog.log(project,
SESSION_ID.with(getSessionId()),
USER_ACTION.with(action),
SYMBOL_CLASS.with(targetClass ?: String::class.java),
SEARCH_SCOPE.with(ScopeIdMapper.instance.getScopeSerializationId(scope)),
EventFields.Language.with(language))
}
@JvmStatic
fun logOpenInFindToolWindow(project: Project?) =
OPEN_IN_FIND_TOOL_WINDOW.log(project, getSessionId())
private fun getSessionId() = if (FindSettings.getInstance().isShowResultsInSeparateView) -1 else sessionId.get()
}
}
class ScopeRuleValidator : CustomValidationRule() {
@Suppress("HardCodedStringLiteral")
override fun doValidate(data: String, context: EventContext): ValidationResultType =
if (ScopeIdMapper.standardNames.contains(data)) ValidationResultType.ACCEPTED else ValidationResultType.REJECTED
override fun acceptRuleId(ruleId: String?): Boolean = ruleId == UsageViewStatisticsCollector.SCOPE_RULE_ID
}
|
apache-2.0
|
683d099c827e584985e785f03152e58e
| 38.11399 | 148 | 0.694886 | 4.599634 | false | false | false | false |
google/intellij-community
|
plugins/ide-features-trainer/src/training/ui/UISettings.kt
|
3
|
4554
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package training.ui
import com.intellij.openapi.components.service
import com.intellij.ui.JBColor
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import java.awt.Color
import java.awt.Font
import javax.swing.border.Border
import javax.swing.border.EmptyBorder
internal class UISettings {
//GENERAL UI SETTINGS
val panelWidth: Int by lazy { JBUI.scale(460) }
//MAIN INSETS
val northInset: Int by lazy { JBUI.scale(20) }
val westInset: Int by lazy { JBUI.scale(24) }
val southInset: Int by lazy { JBUI.scale(24) }
val eastInset: Int by lazy { JBUI.scale(24) }
val learnPanelSideOffset: Int by lazy { JBUI.scale(18) }
val verticalModuleItemInset: Int by lazy { JBUI.scale(8) }
//GAPS
val progressModuleGap: Int by lazy { JBUI.scale(2) }
val expandAndModuleGap: Int by lazy { JBUI.scale(10) }
//FONTS
val plainFont: Font
get() = JBUI.Fonts.label()
val fontSize: Float
get() = plainFont.size2D
val modulesFont: Font
get() = plainFont.deriveFont(Font.BOLD)
fun getFont(relatedUnscaledSize: Int): Font = plainFont.deriveFont(fontSize + JBUI.scale(relatedUnscaledSize))
//COLORS
val transparencyInactiveFactor: Double = 0.3
val defaultTextColor: Color = JBUI.CurrentTheme.Label.foreground()
val lessonLinkColor: Color = JBUI.CurrentTheme.Link.Foreground.ENABLED
val shortcutTextColor: Color = defaultTextColor
val separatorColor: Color = JBColor.namedColor("Button.startBorderColor", 0xC4C4C4, 0x5E6060)
val shortcutBackgroundColor: Color = JBColor.namedColor("Lesson.shortcutBackground", 0xE6EEF7, 0x333638)
val codeForegroundColor: Color = defaultTextColor
val codeBorderColor: Color = JBUI.CurrentTheme.Button.buttonOutlineColorEnd(false)
val inactiveColor: Color = defaultTextColor.addAlpha(transparencyInactiveFactor)
val moduleProgressColor: Color = JBColor.namedColor("Label.infoForeground", 0x808080, 0x8C8C8C)
val shortcutSeparatorColor: Color = moduleProgressColor
val backgroundColor: Color = UIUtil.getTreeBackground()
val completedColor: Color = UIUtil.getLabelSuccessForeground()
val activeTaskBorder: Color = JBColor.namedColor("Component.focusColor", 0x97C3F3, 0x3D6185)
val tooltipBackgroundColor: Color = JBColor.namedColor("Tooltip.Learning.background", 0x1071E8, 0x0E62CF)
val tooltipBorderColor: Color = JBColor.namedColor("Tooltip.Learning.borderColor", 0x1071E8, 0x0E62CF)
val tooltipButtonBackgroundColor: Color = JBColor.namedColor("Tooltip.Learning.spanBackground", 0x0D5CBD, 0x0250B0)
val tooltipButtonForegroundColor: Color = JBColor.namedColor("Tooltip.Learning.spanForeground", 0xF5F5F5)
val tooltipShortcutBackgroundColor: Color = JBColor.namedColor("Tooltip.Learning.spanBackground", 0x0D5CBD, 0x0250B0)
val tooltipShortcutTextColor: Color = JBColor.namedColor("Tooltip.Learning.spanForeground", 0xF5F5F5)
val tooltipTextColor: Color = JBColor.namedColor("Tooltip.Learning.foreground", 0xF5F5F5)
val activeTaskNumberColor: Color = JBColor.namedColor("Lesson.stepNumberForeground", 0x808080, 0xFEFEFE)
val futureTaskNumberColor: Color = activeTaskNumberColor.addAlpha(transparencyInactiveFactor)
val tooltipTaskNumberColor: Color = JBColor.namedColor("Tooltip.Learning.stepNumberForeground", 0x6CA6ED, 0x6A9DDE)
val newContentBackgroundColor: Color = JBColor.namedColor("Lesson.Badge.newLessonBackground", 0x62B543, 0x499C54)
val newContentForegroundColor: Color = JBColor.namedColor("Lesson.Badge.newLessonForeground", 0xFFFFFF, 0xFEFEFE)
//BORDERS
val emptyBorder: Border
get() = EmptyBorder(northInset, westInset, southInset, eastInset)
val lessonHeaderBorder: Border
get() = EmptyBorder(0, JBUI.scale(14) + learnPanelSideOffset, 0, JBUI.scale(14) + learnPanelSideOffset)
val checkmarkShiftBorder: Border
get() = EmptyBorder(0, checkIndent, 0, 0)
val balloonAdditionalBorder: EmptyBorder
get() = EmptyBorder(JBUI.scale(7), JBUI.scale(4), JBUI.scale(7), 0)
val taskParagraphAbove: Int get() = JBUI.scale(24)
val taskInternalParagraphAbove: Int get() = JBUI.scale(12)
val checkIndent: Int get() = JBUI.scale(40)
val numberTaskIndent: Int get() = JBUI.scale(11)
val balloonIndent: Int get() = JBUI.scale(27)
companion object {
fun getInstance(): UISettings = service<UISettings>()
private fun Color.addAlpha(alpha: Double): Color {
return JBColor.lazy { Color(red, green, blue, (255 * alpha).toInt()) }
}
}
}
|
apache-2.0
|
9a42ef2119361ee88248224632f0ad64
| 43.647059 | 120 | 0.770751 | 3.72973 | false | false | false | false |
macoscope/KetchupLunch
|
app/src/main/java/com/macoscope/ketchuplunch/view/lunch/LunchMenuUI.kt
|
1
|
1138
|
package com.macoscope.ketchuplunch.view.lunch
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import com.macoscope.ketchuplunch.R
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersDecoration
import org.jetbrains.anko.AnkoComponent
import org.jetbrains.anko.AnkoContext
import org.jetbrains.anko.frameLayout
import org.jetbrains.anko.matchParent
import org.jetbrains.anko.recyclerview.v7.recyclerView
class LunchMenuUI(val listAdapter: LunchMenuAdapter) : AnkoComponent<Fragment> {
override fun createView(ui: AnkoContext<Fragment>): View {
return with(ui) {
frameLayout() {
lparams(width = matchParent, height = matchParent)
recyclerView {
id = R.id.lunch_menu_list
lparams(width = matchParent, height = matchParent)
layoutManager = LinearLayoutManager(ctx)
adapter = listAdapter
addItemDecoration(StickyRecyclerHeadersDecoration(listAdapter))
}
}
}
}
}
|
apache-2.0
|
761e07665f91a08e1b07eeca83f9cba2
| 36.933333 | 83 | 0.688928 | 4.926407 | false | false | false | false |
jotomo/AndroidAPS
|
app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTargetTest.kt
|
1
|
2790
|
package info.nightscout.androidaps.plugins.general.automation.actions
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R
import info.nightscout.androidaps.plugins.general.automation.elements.InputDuration
import info.nightscout.androidaps.plugins.general.automation.elements.InputTempTarget
import info.nightscout.androidaps.queue.Callback
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito
import org.mockito.Mockito.`when`
import org.powermock.api.mockito.PowerMockito
import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class)
@PrepareForTest(MainApp::class)
class ActionStartTempTargetTest : ActionsTestBase() {
private lateinit var sut: ActionStartTempTarget
@Before
fun setup() {
`when`(resourceHelper.gs(R.string.starttemptarget)).thenReturn("Start temp target")
sut = ActionStartTempTarget(injector)
}
@Test fun friendlyNameTest() {
Assert.assertEquals(R.string.starttemptarget, sut.friendlyName())
}
@Test fun shortDescriptionTest() {
sut.value = InputTempTarget(injector)
sut.value.value = 100.0
sut.duration = InputDuration(injector, 30, InputDuration.TimeUnit.MINUTES)
Assert.assertEquals("Start temp target: 100mg/dl@null(Automation)", sut.shortDescription())
}
@Test fun iconTest() {
Assert.assertEquals(R.drawable.ic_temptarget_high, sut.icon())
}
@Test fun doActionTest() {
`when`(activePlugin.activeTreatments).thenReturn(treatmentsPlugin)
sut.doAction(object : Callback() {
override fun run() {
Assert.assertTrue(result.success)
}
})
Mockito.verify(treatmentsPlugin, Mockito.times(1)).addToHistoryTempTarget(anyObject())
}
@Test fun hasDialogTest() {
Assert.assertTrue(sut.hasDialog())
}
@Test fun toJSONTest() {
sut.value = InputTempTarget(injector)
sut.value.value = 100.0
sut.duration = InputDuration(injector, 30, InputDuration.TimeUnit.MINUTES)
Assert.assertEquals("{\"data\":{\"durationInMinutes\":30,\"units\":\"mg/dl\",\"value\":100},\"type\":\"info.nightscout.androidaps.plugins.general.automation.actions.ActionStartTempTarget\"}", sut.toJSON())
}
@Test fun fromJSONTest() {
sut.fromJSON("{\"value\":100,\"durationInMinutes\":30,\"units\":\"mg/dl\"}")
Assert.assertEquals(Constants.MGDL, sut.value.units)
Assert.assertEquals(100.0, sut.value.value, 0.001)
Assert.assertEquals(30.0, sut.duration.getMinutes().toDouble(), 0.001)
}
}
|
agpl-3.0
|
981201cd9d155efe1a6cf336f6c44921
| 36.716216 | 213 | 0.713978 | 4.298921 | false | true | false | false |
Flank/flank
|
flank-scripts/src/main/kotlin/flank/scripts/cli/assemble/ios/GameLoopExampleCommand.kt
|
1
|
694
|
package flank.scripts.cli.assemble.ios
import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.parameters.options.flag
import com.github.ajalt.clikt.parameters.options.option
import flank.scripts.ops.assemble.ios.buildIosGameLoopExampleCommand
object GameLoopExampleCommand : CliktCommand(
name = "game_loop",
help = "Assemble iOS game loop application"
) {
private val generate: Boolean? by option(help = "Make build")
.flag("-g", default = true)
private val copy: Boolean? by option(help = "Copy output files to tmp")
.flag("-c", default = true)
override fun run() {
buildIosGameLoopExampleCommand(generate, copy)
}
}
|
apache-2.0
|
1e0423301359e0be983ad3811758bb72
| 32.047619 | 75 | 0.724784 | 3.855556 | false | false | false | false |
fabmax/kool
|
kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/gltf/GltfAssetManagerExtensions.kt
|
1
|
3517
|
package de.fabmax.kool.modules.gltf
import de.fabmax.kool.AssetManager
import de.fabmax.kool.KoolException
import de.fabmax.kool.scene.Model
import de.fabmax.kool.util.BufferUtil
import de.fabmax.kool.util.DataStream
import de.fabmax.kool.util.logW
suspend fun AssetManager.loadGltfFile(assetPath: String): GltfFile? {
val file = when {
isGltf(assetPath) -> loadGltf(assetPath)
isBinaryGltf(assetPath) -> loadGlb(assetPath)
else -> null
}
val modelBasePath = if (assetPath.contains('/')) {
assetPath.substring(0, assetPath.lastIndexOf('/'))
} else { "." }
file?.let { m ->
m.buffers.filter { it.uri != null }.forEach {
val uri = it.uri!!
val bufferPath = if (uri.startsWith("data:", true)) { uri } else { "$modelBasePath/$uri" }
it.data = loadAsset(bufferPath)!!
}
m.images.filter { it.uri != null }.forEach { it.uri = "$modelBasePath/${it.uri}" }
m.updateReferences()
}
return file
}
suspend fun AssetManager.loadGltfModel(assetPath: String,
modelCfg: GltfFile.ModelGenerateConfig = GltfFile.ModelGenerateConfig(),
scene: Int = 0): Model? {
return loadGltfFile(assetPath)?.makeModel(modelCfg, scene)
}
private fun isGltf(assetPath: String): Boolean{
return assetPath.endsWith(".gltf", true) || assetPath.endsWith(".gltf.gz", true)
}
private fun isBinaryGltf(assetPath: String): Boolean{
return assetPath.endsWith(".glb", true) || assetPath.endsWith(".glb.gz", true)
}
private suspend fun AssetManager.loadGltf(assetPath: String): GltfFile? {
var data = loadAsset(assetPath)
if (data != null && assetPath.endsWith(".gz", true)) {
data = BufferUtil.inflate(data)
}
return if (data != null) {
GltfFile.fromJson(data.toArray().decodeToString())
} else { null }
}
private suspend fun AssetManager.loadGlb(assetPath: String): GltfFile? {
var data = loadAsset(assetPath) ?: return null
if (assetPath.endsWith(".gz", true)) {
data = BufferUtil.inflate(data)
}
val str = DataStream(data)
// file header
val magic = str.readUInt()
val version = str.readUInt()
//val fileLength = str.readUInt()
str.readUInt()
if (magic != GltfFile.GLB_FILE_MAGIC) {
throw KoolException("Unexpected glTF magic number: $magic (should be ${GltfFile.GLB_FILE_MAGIC} / 'glTF')")
}
if (version != 2) {
logW { "Unexpected glTF version: $version (should be 2) - stuff might not work as expected" }
}
// chunk 0 - JSON content
var chunkLen = str.readUInt()
var chunkType = str.readUInt()
if (chunkType != GltfFile.GLB_CHUNK_MAGIC_JSON) {
throw KoolException("Unexpected chunk type for chunk 0: $chunkType (should be ${GltfFile.GLB_CHUNK_MAGIC_JSON} / 'JSON')")
}
val jsonData = str.readData(chunkLen).toArray()
val model = GltfFile.fromJson(jsonData.decodeToString())
// remaining data chunks
var iChunk = 1
while (str.hasRemaining()) {
chunkLen = str.readUInt()
chunkType = str.readUInt()
if (chunkType == GltfFile.GLB_CHUNK_MAGIC_BIN) {
model.buffers[iChunk-1].data = str.readData(chunkLen)
} else {
logW { "Unexpected chunk type for chunk $iChunk: $chunkType (should be ${GltfFile.GLB_CHUNK_MAGIC_BIN} / ' BIN')" }
str.index += chunkLen
}
iChunk++
}
return model
}
|
apache-2.0
|
592238f93119fd6fe749e8a8b74a0ce8
| 33.821782 | 130 | 0.629229 | 3.826986 | false | false | false | false |
siosio/intellij-community
|
plugins/kotlin/fir-low-level-api/src/org/jetbrains/kotlin/idea/fir/low/level/api/element/builder/FirElementBuilder.kt
|
1
|
6125
|
/*
* Copyright 2010-2020 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.fir.low.level.api.element.builder
import com.intellij.psi.PsiElement
import com.intellij.psi.util.parentsOfType
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.fir.FirElement
import org.jetbrains.kotlin.fir.declarations.FirFile
import org.jetbrains.kotlin.fir.declarations.FirResolvePhase
import org.jetbrains.kotlin.idea.fir.low.level.api.annotations.ThreadSafe
import org.jetbrains.kotlin.idea.fir.low.level.api.file.builder.FirFileBuilder
import org.jetbrains.kotlin.idea.fir.low.level.api.file.builder.ModuleFileCache
import org.jetbrains.kotlin.idea.fir.low.level.api.file.structure.FileStructureCache
import org.jetbrains.kotlin.idea.fir.low.level.api.file.structure.FileStructureElement
import org.jetbrains.kotlin.idea.util.getElementTextInContext
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.isAncestor
import org.jetbrains.kotlin.psi.psiUtil.isObjectLiteral
import org.jetbrains.kotlin.psi2ir.deparenthesize
/**
* Maps [KtElement] to [FirElement]
* Stateless, caches everything into [ModuleFileCache] & [FileStructureCache] passed into the function
*/
@ThreadSafe
internal class FirElementBuilder {
fun getPsiAsFirElementSource(element: KtElement): KtElement {
val deparenthesized = if (element is KtPropertyDelegate) element.deparenthesize() else element
return when {
deparenthesized is KtParenthesizedExpression -> deparenthesized.deparenthesize()
deparenthesized is KtPropertyDelegate -> deparenthesized.expression ?: element
deparenthesized is KtQualifiedExpression && deparenthesized.selectorExpression is KtCallExpression -> {
/*
KtQualifiedExpression with KtCallExpression in selector transformed in FIR to FirFunctionCall expression
Which will have a receiver as qualifier
*/
deparenthesized.selectorExpression ?: error("Incomplete code:\n${element.getElementTextInContext()}")
}
else -> deparenthesized
}
}
fun getOrBuildFirFor(
element: KtElement,
firFileBuilder: FirFileBuilder,
moduleFileCache: ModuleFileCache,
fileStructureCache: FileStructureCache,
): FirElement = when (element) {
is KtFile -> getOrBuildFirForKtFile(element, firFileBuilder, moduleFileCache)
else -> getOrBuildFirForNonKtFileElement(element, fileStructureCache, moduleFileCache)
}
private fun getOrBuildFirForKtFile(ktFile: KtFile, firFileBuilder: FirFileBuilder, moduleFileCache: ModuleFileCache): FirFile =
firFileBuilder.getFirFileResolvedToPhaseWithCaching(
ktFile,
moduleFileCache,
FirResolvePhase.BODY_RESOLVE,
checkPCE = true
)
private fun getOrBuildFirForNonKtFileElement(
element: KtElement,
fileStructureCache: FileStructureCache,
moduleFileCache: ModuleFileCache
): FirElement {
require(element !is KtFile)
val fileStructure = fileStructureCache.getFileStructure(element.containingKtFile, moduleFileCache)
val mappings = fileStructure.getStructureElementFor(element).mappings
val psi = getPsiAsFirElementSource(element)
mappings[psi]?.let { return it }
return psi.getFirOfClosestParent(mappings)?.second
?: error("FirElement is not found for:\n${element.getElementTextInContext()}")
}
@TestOnly
fun getStructureElementFor(
element: KtElement,
moduleFileCache: ModuleFileCache,
fileStructureCache: FileStructureCache,
): FileStructureElement {
val fileStructure = fileStructureCache.getFileStructure(element.containingKtFile, moduleFileCache)
return fileStructure.getStructureElementFor(element)
}
}
private fun KtElement.getFirOfClosestParent(cache: Map<KtElement, FirElement>): Pair<KtElement, FirElement>? {
var current: PsiElement? = this
while (current is KtElement) {
val mappedFir = cache[current]
if (mappedFir != null) {
return current to mappedFir
}
current = current.parent
}
return null
}
// TODO: simplify
internal inline fun PsiElement.getNonLocalContainingOrThisDeclaration(predicate: (KtDeclaration) -> Boolean = { true }): KtNamedDeclaration? {
var container: PsiElement? = this
while (container != null && container !is KtFile) {
if (container is KtNamedDeclaration
&& (container.isNonAnonymousClassOrObject() || container is KtDeclarationWithBody || container is KtProperty || container is KtTypeAlias)
&& container !is KtPrimaryConstructor
&& container.hasFqName()
&& container !is KtEnumEntry
&& container !is KtFunctionLiteral
&& container.containingClassOrObject !is KtEnumEntry
&& predicate(container)
) {
return container
}
container = container.parent
}
return null
}
private fun KtDeclaration.isNonAnonymousClassOrObject() =
this is KtClassOrObject
&& !this.isObjectLiteral()
private fun KtDeclaration.hasFqName(): Boolean =
parentsOfType<KtDeclaration>(withSelf = false).all { it.isNonAnonymousClassOrObject() }
internal fun PsiElement.getNonLocalContainingInBodyDeclarationWith(): KtNamedDeclaration? =
getNonLocalContainingOrThisDeclaration { declaration ->
when (declaration) {
is KtNamedFunction -> declaration.bodyExpression?.isAncestor(this) == true
is KtProperty -> declaration.initializer?.isAncestor(this) == true ||
declaration.getter?.isAncestor(this) == true ||
declaration.setter?.isAncestor(this) == true
else -> false
}
}
|
apache-2.0
|
577ec4a6201ce26d350534e42f4f225d
| 41.832168 | 149 | 0.714939 | 4.971591 | false | false | false | false |
alt236/Bluetooth-LE-Library---Android
|
sample_app/src/main/java/uk/co/alt236/btlescan/ui/details/recyclerview/holder/RssiInfoHolder.kt
|
1
|
826
|
package uk.co.alt236.btlescan.ui.details.recyclerview.holder
import android.view.View
import android.widget.TextView
import uk.co.alt236.btlescan.R
import uk.co.alt236.btlescan.ui.common.recyclerview.BaseViewHolder
import uk.co.alt236.btlescan.ui.details.recyclerview.model.RssiItem
class RssiInfoHolder(itemView: View) : BaseViewHolder<RssiItem>(itemView) {
val firstTimestamp: TextView = itemView.findViewById<View>(R.id.firstTimestamp) as TextView
val firstRssi: TextView = itemView.findViewById<View>(R.id.firstRssi) as TextView
val lastTimestamp: TextView = itemView.findViewById<View>(R.id.lastTimestamp) as TextView
val lastRssi: TextView = itemView.findViewById<View>(R.id.lastRssi) as TextView
val runningAverageRssi: TextView = itemView.findViewById<View>(R.id.runningAverageRssi) as TextView
}
|
apache-2.0
|
b0f482b79948b87d366fda0e44627ae6
| 54.133333 | 103 | 0.806295 | 3.654867 | false | false | false | false |
nadraliev/DsrWeatherApp
|
app/src/main/java/soutvoid/com/DsrWeatherApp/ui/screen/newTrigger/widgets/list/SelectableListItemAdapter.kt
|
1
|
1481
|
package soutvoid.com.DsrWeatherApp.ui.screen.newTrigger.widgets.list
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.TextView
import soutvoid.com.DsrWeatherApp.R
import soutvoid.com.DsrWeatherApp.ui.util.ifNotNullOr
class SelectableListItemAdapter(private val context: Context,
val entries: List<String>): BaseAdapter() {
var selectedPosition = 0
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
var view = convertView.ifNotNullOr(
LayoutInflater.from(context).inflate(R.layout.selectable_list_item, parent, false)
)
view.findViewById<TextView>(R.id.selectable_list_item_text).text = entries[position]
val checkIv = view.findViewById<ImageView>(R.id.factors_list_item_check)
if (position == selectedPosition)
checkIv.visibility = View.VISIBLE
else
checkIv.visibility = View.INVISIBLE
view.findViewById<View>(R.id.selectable_list_item_container).setOnClickListener {
selectedPosition = position
notifyDataSetChanged()
}
return view
}
override fun getItem(p0: Int): Any = entries[p0]
override fun getItemId(p0: Int): Long = p0.toLong()
override fun getCount(): Int = entries.size
}
|
apache-2.0
|
12ef85b33c2972c415e80732713267ca
| 30.531915 | 98 | 0.698177 | 4.50152 | false | false | false | false |
nimakro/tornadofx
|
src/main/java/tornadofx/CSS.kt
|
1
|
64404
|
package tornadofx
import javafx.beans.value.ChangeListener
import javafx.beans.value.ObservableValue
import javafx.css.Styleable
import javafx.geometry.*
import javafx.scene.Cursor
import javafx.scene.ImageCursor
import javafx.scene.Node
import javafx.scene.Parent
import javafx.scene.control.*
import javafx.scene.effect.BlendMode
import javafx.scene.effect.DropShadow
import javafx.scene.effect.Effect
import javafx.scene.effect.InnerShadow
import javafx.scene.layout.*
import javafx.scene.paint.*
import javafx.scene.shape.StrokeLineCap
import javafx.scene.shape.StrokeLineJoin
import javafx.scene.shape.StrokeType
import javafx.scene.text.*
import sun.net.www.protocol.css.Handler
import java.lang.invoke.MethodHandles
import java.net.MalformedURLException
import java.net.URI
import java.net.URL
import java.text.DecimalFormat
import java.text.DecimalFormatSymbols
import java.util.*
import java.util.logging.Level
import java.util.logging.Logger
import kotlin.properties.ReadOnlyProperty
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KClass
import kotlin.reflect.KProperty
interface Rendered {
fun render(): String
}
interface Scoped {
fun toRuleSet(): CssRuleSet
fun append(rule: CssSubRule): CssRuleSet
infix fun and(rule: CssRule) = append(CssSubRule(rule, CssSubRule.Relation.REFINE))
infix fun child(rule: CssRule) = append(CssSubRule(rule, CssSubRule.Relation.CHILD))
infix fun contains(rule: CssRule) = append(CssSubRule(rule, CssSubRule.Relation.DESCENDANT))
infix fun next(rule: CssRule) = append(CssSubRule(rule, CssSubRule.Relation.ADJACENT))
infix fun sibling(rule: CssRule) = append(CssSubRule(rule, CssSubRule.Relation.SIBLING))
}
interface Selectable {
fun toSelection(): CssSelector
}
interface SelectionHolder {
fun addSelection(selection: CssSelection)
fun removeSelection(selection: CssSelection)
operator fun String.invoke(op: CssSelectionBlock.() -> Unit) = toSelector()(op)
operator fun Selectable.invoke(op: CssSelectionBlock.() -> Unit): CssSelection {
val selection = CssSelection(toSelection(), op)
addSelection(selection)
return selection
}
fun select(selector: String, op: CssSelectionBlock.() -> Unit) = selector(op)
fun select(selector: Selectable, vararg selectors: Selectable, op: CssSelectionBlock.() -> Unit) = select(selector, *selectors)(op)
fun select(selector: Selectable, vararg selectors: Selectable) = CssSelector(
*selector.toSelection().rule,
*selectors.flatMap { it.toSelection().rule.asIterable() }.toTypedArray()
)
fun s(selector: String, op: CssSelectionBlock.() -> Unit) = select(selector, op)
fun s(selector: Selectable, vararg selectors: Selectable, op: CssSelectionBlock.() -> Unit) = select(selector, *selectors, op = op)
fun s(selector: Selectable, vararg selectors: Selectable) = select(selector, *selectors)
infix fun Scoped.and(selection: CssSelection) = append(selection, CssSubRule.Relation.REFINE)
infix fun Scoped.child(selection: CssSelection) = append(selection, CssSubRule.Relation.CHILD)
infix fun Scoped.contains(selection: CssSelection) = append(selection, CssSubRule.Relation.DESCENDANT)
infix fun Scoped.next(selection: CssSelection) = append(selection, CssSubRule.Relation.ADJACENT)
infix fun Scoped.sibling(selection: CssSelection) = append(selection, CssSubRule.Relation.SIBLING)
fun Scoped.append(oldSelection: CssSelection, relation: CssSubRule.Relation): CssSelection {
removeSelection(oldSelection)
val ruleSets = oldSelection.selector.rule
if (ruleSets.size > 1) {
Stylesheet.log.warning("Selection has ${ruleSets.size} selectors, but only the first will be used")
}
val selection = CssSelection(CssSelector(toRuleSet().append(ruleSets[0], relation))) { mix(oldSelection.block) }
addSelection(selection)
return selection
}
}
open class Stylesheet(vararg val imports: KClass<out Stylesheet>) : SelectionHolder, Rendered {
companion object {
val log: Logger by lazy { Logger.getLogger("CSS") }
// IDs
val buttonsHbox by cssid()
val colorBarIndicator by cssid()
val colorRectIndicator by cssid()
val settingsPane by cssid()
val spacer1 by cssid()
val spacer2 by cssid()
val spacerBottom by cssid()
val spacerSide by cssid()
// Elements
val star by csselement("*")
// Style classes used by JavaFX
val accordion by cssclass()
val alert by cssclass()
val areaLegendSymbol by cssclass()
val arrow by cssclass()
val arrowButton by cssclass()
val axis by cssclass()
val axisLabel by cssclass()
val axisMinorTickMark by cssclass()
val axisTickMark by cssclass()
val bar by cssclass()
val barChart by cssclass()
val barLegendSymbol by cssclass()
val bottomClass by cssclass("bottom")
val box by cssclass()
val bubbleLegendSymbol by cssclass()
val bullet by cssclass()
val bulletButton by cssclass()
val button by cssclass()
val buttonBar by cssclass()
val calendarGrid by cssclass()
val cell by cssclass()
val centerPill by cssclass()
val chart by cssclass()
val chartAlternativeColumnFill by cssclass()
val chartAlternativeRowFill by cssclass()
val chartAreaSymbol by cssclass()
val chartBar by cssclass()
val chartBubble by cssclass()
val chartContent by cssclass()
val chartHorizontalGridLines by cssclass()
val chartHorizontalZeroLine by cssclass()
val chartLegend by cssclass()
val chartLegendItem by cssclass()
val chartLegendSymbol by cssclass()
val chartLineSymbol by cssclass()
val chartPie by cssclass()
val chartPieLabel by cssclass()
val chartPieLabelLine by cssclass()
val chartPlotBackground by cssclass()
val chartSeriesAreaFill by cssclass()
val chartSeriesAreaLine by cssclass()
val chartSeriesLine by cssclass()
val chartSymbol by cssclass()
val chartTitle by cssclass()
val chartVerticalGridLines by cssclass()
val chartVerticalZeroLine by cssclass()
val checkBox by cssclass()
val checkBoxTableCell by cssclass()
val choiceBox by cssclass()
val choiceDialog by cssclass()
val clippedContainer by cssclass()
val colorInputField by cssclass()
val colorPalette by cssclass()
val colorPaletteRegion by cssclass()
val colorPicker by cssclass()
val colorPickerGrid by cssclass()
val colorPickerLabel by cssclass()
val colorRect by cssclass()
val colorRectBorder by cssclass()
val colorRectPane by cssclass()
val colorSquare by cssclass()
val columnDragHeader by cssclass()
val columnHeader by cssclass()
val columnHeaderBackground by cssclass()
val columnOverlay by cssclass()
val columnResizeLine by cssclass()
val comboBox by cssclass()
val comboBoxBase by cssclass()
val comboBoxPopup by cssclass()
val confirmation by cssclass()
val container by cssclass()
val content by cssclass()
val contextMenu by cssclass()
val controlBox by cssclass()
val controlButtonsTab by cssclass()
val controlsPane by cssclass()
val corner by cssclass()
val currentNewColorGrid by cssclass()
val customcolorControlsBackground by cssclass() // color lowercase intentionally (that's how it is in modena)
val customColorDialog by cssclass()
val dateCell by cssclass()
val datePicker by cssclass()
val datePickerPopup by cssclass()
val dayCell by cssclass()
val dayNameCell by cssclass()
val decrementArrow by cssclass()
val decrementArrowButton by cssclass()
val decrementButton by cssclass()
val defaultColor0 by cssclass()
val defaultColor1 by cssclass()
val defaultColor2 by cssclass()
val defaultColor3 by cssclass()
val defaultColor4 by cssclass()
val defaultColor5 by cssclass()
val defaultColor6 by cssclass()
val defaultColor7 by cssclass()
val detailsButton by cssclass()
val determinateIndicator by cssclass()
val dialogPane by cssclass()
val dot by cssclass()
val edgeToEdge by cssclass()
val emptyTable by cssclass()
val error by cssclass()
val expandableContent by cssclass()
val filler by cssclass()
val firstTitledPane by cssclass()
val floating by cssclass()
val focusIndicator by cssclass()
val formSelectButton by cssclass()
val graphicContainer by cssclass()
val headerPanel by cssclass()
val headersRegion by cssclass()
val hijrahDayCell by cssclass()
val hoverSquare by cssclass()
val htmlEditor by cssclass()
val htmlEditorAlignCenter by cssclass()
val htmlEditorAlignJustify by cssclass()
val htmlEditorAlignLeft by cssclass()
val htmlEditorAlignRight by cssclass()
val htmlEditorBackground by cssclass()
val htmlEditorBold by cssclass()
val htmlEditorBullets by cssclass()
val htmlEditorCopy by cssclass()
val htmlEditorCut by cssclass()
val htmlEditorForeground by cssclass()
val htmlEditorHr by cssclass()
val htmlEditorIndent by cssclass()
val htmlEditorItalic by cssclass()
val htmlEditorNumbers by cssclass()
val htmlEditorOutdent by cssclass()
val htmlEditorPaste by cssclass()
val htmlEditorStrike by cssclass()
val htmlEditorUnderline by cssclass()
val hyperlink by cssclass()
val imageView by cssclass()
val incrementArrow by cssclass()
val incrementArrowButton by cssclass()
val incrementButton by cssclass()
val indexedCell by cssclass()
val indicator by cssclass()
val information by cssclass()
val label by cssclass()
val leftArrow by cssclass()
val leftArrowButton by cssclass()
val leftContainer by cssclass()
val leftPill by cssclass()
val less by cssclass()
val line by cssclass()
val listCell by cssclass()
val listView by cssclass()
val mark by cssclass()
val mediaView by cssclass()
val menu by cssclass()
val menuBar by cssclass()
val menuButton by cssclass()
val menuDownArrow by cssclass()
val menuItem by cssclass()
val menuUpArrow by cssclass()
val mnemonicUnderline by cssclass()
val monthYearPane by cssclass()
val more by cssclass()
val negative by cssclass()
val nestedColumnHeader by cssclass()
val nextMonth by cssclass()
val numberButton by cssclass()
val openButton by cssclass()
val page by cssclass()
val pageInformation by cssclass()
val pagination by cssclass()
val paginationControl by cssclass()
val passwordField by cssclass()
val percentage by cssclass()
val pickerColor by cssclass()
val pickerColorRect by cssclass()
val pieLegendSymbol by cssclass()
val placeholder by cssclass()
val popup by cssclass()
val previousMonth by cssclass()
val progress by cssclass()
val progressBar by cssclass()
val progressBarTableCell by cssclass()
val progressIndicator by cssclass()
val radio by cssclass()
val radioButton by cssclass()
val rightArrow by cssclass()
val rightClass by cssclass("right")
val rightArrowButton by cssclass()
val rightContainer by cssclass()
val rightPill by cssclass()
val root by cssclass()
val scrollArrow by cssclass()
val scrollBar by cssclass()
val scrollPane by cssclass()
val secondaryLabel by cssclass()
val secondaryText by cssclass()
val segment by cssclass()
val segment0 by cssclass()
val segment1 by cssclass()
val segment2 by cssclass()
val segment3 by cssclass()
val segment4 by cssclass()
val segment5 by cssclass()
val segment6 by cssclass()
val segment7 by cssclass()
val segment8 by cssclass()
val segment9 by cssclass()
val segment10 by cssclass()
val segment11 by cssclass()
val selectedClass by cssclass("selected")
val separator by cssclass()
val settingsLabel by cssclass()
val settingsUnit by cssclass()
val sheet by cssclass()
val showHideColumnImage by cssclass()
val showHideColumnsButton by cssclass()
val slider by cssclass()
val sortOrder by cssclass()
val sortOrderDot by cssclass()
val sortOrderDotsContainer by cssclass()
val spinner by cssclass()
val splitArrowsHorizontal by cssclass()
val splitArrowsOnLeftHorizontal by cssclass()
val splitArrowsOnRightHorizontal by cssclass()
val splitArrowsOnLeftVertical by cssclass()
val splitArrowsOnRightVertical by cssclass()
val splitArrowsVertical by cssclass()
val splitButton by cssclass()
val splitMenuButton by cssclass()
val splitPane by cssclass()
val splitPaneDivider by cssclass()
val stackedBarChart by cssclass()
val tab by cssclass()
val tabCloseButton by cssclass()
val tabContentArea by cssclass()
val tabDownButton by cssclass()
val tabHeaderArea by cssclass()
val tabHeaderBackground by cssclass()
val tabLabel by cssclass()
val tableCell by cssclass()
val tableRowCell by cssclass()
val tableView by cssclass()
val tableColumn by cssclass()
val tabPane by cssclass()
val text by cssclass()
val textArea by cssclass()
val textField by cssclass()
val textInput by cssclass()
val textInputDialog by cssclass()
val thumb by cssclass()
val tick by cssclass()
val title by cssclass()
val titledPane by cssclass()
val today by cssclass()
val toggleButton by cssclass()
val toolBar by cssclass()
val toolBarOverflowButton by cssclass()
val tooltip by cssclass()
val track by cssclass()
val transparentPattern by cssclass()
val treeCell by cssclass()
val treeDisclosureNode by cssclass()
val treeTableCell by cssclass()
val treeTableRowCell by cssclass()
val treeTableView by cssclass()
val treeView by cssclass()
val viewport by cssclass()
val virtualFlow by cssclass()
val warning by cssclass()
val webcolorField by cssclass() // color lowercase intentionally (that's how it is in modena)
val webField by cssclass()
val webView by cssclass()
val weekNumberCell by cssclass()
// Style classes used by Form Builder
val form by cssclass()
val fieldset by cssclass()
val legend by cssclass()
val field by cssclass()
val labelContainer by cssclass()
val inputContainer by cssclass()
// DataGrid
val datagrid by cssclass()
val datagridCell by cssclass()
val datagridRow by cssclass()
// Keyboard
val keyboard by cssclass()
val keyboardKey by cssclass()
val keyboardSpacerKey by cssclass()
// Pseudo classes used by JavaFX
val armed by csspseudoclass()
val bottom by csspseudoclass()
val cancel by csspseudoclass()
val cellSelection by csspseudoclass()
val checked by csspseudoclass()
val constrainedResize by csspseudoclass()
val containsFocus by csspseudoclass()
val collapsed by csspseudoclass()
val default by csspseudoclass()
val determinate by csspseudoclass()
val disabled by csspseudoclass()
val editable by csspseudoclass()
val empty by csspseudoclass()
val even by csspseudoclass()
val expanded by csspseudoclass()
val filled by csspseudoclass()
val fitToHeight by csspseudoclass(snakeCase = false)
val fitToWidth by csspseudoclass(snakeCase = false)
val focused by csspseudoclass()
val header by csspseudoclass()
val horizontal by csspseudoclass()
val hover by csspseudoclass()
val indeterminate by csspseudoclass()
val lastVisible by csspseudoclass()
val left by csspseudoclass()
val noHeader by csspseudoclass()
val odd by csspseudoclass()
val openvertically by csspseudoclass() // intentionally single word
val pannable by csspseudoclass()
val pressed by csspseudoclass()
val readonly by csspseudoclass()
val right by csspseudoclass()
val rowSelection by csspseudoclass()
val selected by csspseudoclass()
val showing by csspseudoclass()
val showMnemonics by csspseudoclass()
val top by csspseudoclass()
val vertical by csspseudoclass()
val visited by csspseudoclass()
init {
if (!FX.osgiAvailable) {
detectAndInstallUrlHandler()
}
}
fun importServiceLoadedStylesheets() {
val loader = ServiceLoader.load(Stylesheet::class.java)
for (style in loader) importStylesheet(style.javaClass.kotlin)
}
/**
* Try to retrieve a type safe stylesheet, and force installation of url handler
* if it's missing. This typically happens in environments with atypical class loaders.
*
* Under normal circumstances, the CSS handler that comes with TornadoFX should be picked
* up by the JVM automatically.
*
* If an OSGi environment is detected, the TornadoFX OSGi Activator will install the OSGi
* compatible URL handler instead.
*/
private fun detectAndInstallUrlHandler() {
try {
URL("css://content:64")
} catch (ex: MalformedURLException) {
log.info("Installing CSS url handler, since it was not picked up automatically")
try {
URL.setURLStreamHandlerFactory(Handler.HandlerFactory())
} catch (installFailed: Throwable) {
log.log(Level.WARNING, "Unable to install CSS url handler, type safe stylesheets might not work", ex)
}
}
}
}
val selections = mutableListOf<CssSelection>()
override fun addSelection(selection: CssSelection) {
selections += selection
}
override fun removeSelection(selection: CssSelection) {
selections -= selection
}
override fun render() = imports.joinToString(separator = "\n", postfix = "\n") { "@import url(css://${it.java.name})" } +
selections.joinToString(separator = "") { it.render() }
val base64URL: URL
get() {
val content = Base64.getEncoder().encodeToString(render().toByteArray())
return URL("css://$content:64")
}
val externalForm: String get() = base64URL.toExternalForm()
}
open class PropertyHolder {
companion object {
val selectionScope = ThreadLocal<CssSelectionBlock>()
fun Double.pos(relative: Boolean) = if (relative) "${fiveDigits.format(this * 100)}%" else "${fiveDigits.format(this)}px"
fun <T> toCss(value: T): String = when (value) {
null -> "" // This should only happen in a container (such as box(), Array<>(), Pair())
is MultiValue<*> -> value.elements.joinToString { toCss(it) }
is CssBox<*> -> "${toCss(value.top)} ${toCss(value.right)} ${toCss(value.bottom)} ${toCss(value.left)}"
is FontWeight -> "${value.weight}" // Needs to come before `is Enum<*>`
is Enum<*> -> value.toString().toLowerCase().replace("_", "-")
is Font -> "${if (value.style == "Regular") "normal" else value.style} ${value.size}pt ${toCss(value.family)}"
is Cursor -> if (value is ImageCursor) {
value.image.javaClass.getDeclaredField("url").let {
it.isAccessible = true
it.get(value.image).toString()
}
} else {
value.toString()
}
is URI -> "url(\"${value.toASCIIString()}\")"
is BackgroundPosition -> "${value.horizontalSide} ${value.horizontalPosition.pos(value.isHorizontalAsPercentage)} " +
"${value.verticalSide} ${value.verticalPosition.pos(value.isVerticalAsPercentage)}"
is BackgroundSize -> if (value.isContain) "contain" else if (value.isCover) "cover" else buildString {
append(if (value.width == BackgroundSize.AUTO) "auto" else value.width.pos(value.isWidthAsPercentage))
append(" ")
append(if (value.height == BackgroundSize.AUTO) "auto" else value.height.pos(value.isHeightAsPercentage))
}
is BorderStrokeStyle -> when (value) {
BorderStrokeStyle.NONE -> "none"
BorderStrokeStyle.DASHED -> "dashed"
BorderStrokeStyle.DOTTED -> "dotted"
BorderStrokeStyle.SOLID -> "solid"
else -> buildString {
append("segments(${value.dashArray.joinToString()}) ")
append(toCss(value.type))
append(" line-join ${toCss(value.lineJoin)} ")
if (value.lineJoin == StrokeLineJoin.MITER) {
append(value.miterLimit)
}
append(" line-cap ${toCss(value.lineCap)}")
}
}
is BorderImageSlice -> toCss(value.widths) + if (value.filled) " fill" else ""
is List<*> -> value.joinToString(" ") { toCss(it) }
is Pair<*, *> -> "${toCss(value.first)} ${toCss(value.second)}"
is KClass<*> -> "\"${value.qualifiedName}\""
is CssProperty<*> -> value.name
is Raw -> value.name
is String -> "\"$value\""
is Effect -> when (value) { // JavaFX currently only supports DropShadow and InnerShadow in CSS
is DropShadow -> "dropshadow(${toCss(value.blurType)}, ${value.color.css}, " +
"${value.radius}, ${value.spread}, ${value.offsetX}, ${value.offsetY})"
is InnerShadow -> "innershadow(${toCss(value.blurType)}, ${value.color.css}, " +
"${value.radius}, ${value.choke}, ${value.offsetX}, ${value.offsetY})"
else -> "none"
}
is Color -> value.css
is Paint -> value.toString().replace(Regex("0x[0-9a-f]{8}")) { Color.web(it.groupValues[0]).css }
else -> value.toString()
}
}
val properties = linkedMapOf<String, Pair<Any, ((Any) -> String)?>>()
val unsafeProperties = linkedMapOf<String, Any>()
val mergedProperties: Map<String, Pair<Any, ((Any) -> String)?>> get() = properties + unsafeProperties.mapValues { it.value to null }
// Root
var baseColor: Color by cssprop("-fx-base")
var accentColor: Color by cssprop("-fx-accent")
var focusColor: Paint by cssprop("-fx-focus-color")
var faintFocusColor: Paint by cssprop("-fx-faint-focus-color")
// Font
var font: Font by cssprop("-fx-font")
var fontFamily: String by cssprop("-fx-font-family")
var fontSize: Dimension<Dimension.LinearUnits> by cssprop("-fx-font-size")
var fontStyle: FontPosture by cssprop("-fx-font-style")
var fontWeight: FontWeight by cssprop("-fx-font-weight")
// Node
var blendMode: BlendMode by cssprop("-fx-blend-mode")
var cursor: Cursor by cssprop("-fx-cursor")
var effect: Effect by cssprop("-fx-effect")
var focusTraversable: Boolean by cssprop("-fx-focus-traversable")
var opacity: Double by cssprop("-fx-opacity")
var rotate: Dimension<Dimension.AngularUnits> by cssprop("-fx-rotate")
var scaleX: Number by cssprop("-fx-scale-x")
var scaleY: Number by cssprop("-fx-scale-y")
var scaleZ: Number by cssprop("-fx-scale-z")
var translateX: Dimension<Dimension.LinearUnits> by cssprop("-fx-translate-x")
var translateY: Dimension<Dimension.LinearUnits> by cssprop("-fx-translate-y")
var translateZ: Dimension<Dimension.LinearUnits> by cssprop("-fx-translate-z")
var visibility: FXVisibility by cssprop("visibility") // Intentionally not -fx-visibility
// ImageView
var image: URI by cssprop("-fx-image")
// DialogPane
var graphic: URI by cssprop("-fx-graphic")
// FlowPane
var hgap: Dimension<Dimension.LinearUnits> by cssprop("-fx-hgap")
var vgap: Dimension<Dimension.LinearUnits> by cssprop("-fx-vgap")
var alignment: Pos by cssprop("-fx-alignment")
var columnHAlignment: HPos by cssprop("-fx-column-halignment")
var rowVAlignment: VPos by cssprop("-fx-row-valignment")
var orientation: Orientation by cssprop("-fx-orientation")
// GridPane
var gridLinesVisible: Boolean by cssprop("-fx-grid-lines-visible")
// HBox
var spacing: Dimension<Dimension.LinearUnits> by cssprop("-fx-spacing")
var fillHeight: Boolean by cssprop("-fx-fill-height")
// Region
var backgroundColor: MultiValue<Paint> by cssprop("-fx-background-color")
var backgroundInsets: MultiValue<CssBox<Dimension<Dimension.LinearUnits>>> by cssprop("-fx-background-insets")
var backgroundRadius: MultiValue<CssBox<Dimension<Dimension.LinearUnits>>> by cssprop("-fx-background-radius")
var backgroundImage: MultiValue<URI> by cssprop("-fx-background-image")
var backgroundPosition: MultiValue<BackgroundPosition> by cssprop("-fx-background-position")
var backgroundRepeat: MultiValue<Pair<BackgroundRepeat, BackgroundRepeat>> by cssprop("-fx-background-repeat")
var backgroundSize: MultiValue<BackgroundSize> by cssprop("-fx-background-size")
var borderColor: MultiValue<CssBox<Paint?>> by cssprop("-fx-border-color")
var borderInsets: MultiValue<CssBox<Dimension<Dimension.LinearUnits>>> by cssprop("-fx-border-insets")
var borderRadius: MultiValue<CssBox<Dimension<Dimension.LinearUnits>>> by cssprop("-fx-border-radius")
var borderStyle: MultiValue<BorderStrokeStyle> by cssprop("-fx-border-style")
var borderWidth: MultiValue<CssBox<Dimension<Dimension.LinearUnits>>> by cssprop("-fx-border-width")
var borderImageSource: MultiValue<URI> by cssprop("-fx-border-image-source")
var borderImageInsets: MultiValue<CssBox<Dimension<Dimension.LinearUnits>>> by cssprop("-fx-border-image-insets")
var borderImageRepeat: MultiValue<Pair<BorderRepeat, BorderRepeat>> by cssprop("-fx-border-image-repeat")
var borderImageSlice: MultiValue<BorderImageSlice> by cssprop("-fx-border-image-slice")
var borderImageWidth: CssBox<Dimension<Dimension.LinearUnits>> by cssprop("-fx-border-image-width")
var padding: CssBox<Dimension<Dimension.LinearUnits>> by cssprop("-fx-padding")
var positionShape: Boolean by cssprop("-fx-position-shape")
var scaleShape: Boolean by cssprop("-fx-scale-shape")
var shape: String by cssprop("-fx-shape")
var snapToPixel: Boolean by cssprop("-fx-snap-to-pixel")
var minHeight: Dimension<Dimension.LinearUnits> by cssprop("-fx-min-height")
var prefHeight: Dimension<Dimension.LinearUnits> by cssprop("-fx-pref-height")
var maxHeight: Dimension<Dimension.LinearUnits> by cssprop("-fx-max-height")
var minWidth: Dimension<Dimension.LinearUnits> by cssprop("-fx-min-width")
var prefWidth: Dimension<Dimension.LinearUnits> by cssprop("-fx-pref-width")
var maxWidth: Dimension<Dimension.LinearUnits> by cssprop("-fx-max-width")
// TilePane
var prefRows: Int by cssprop("-fx-pref-rows")
var prefColumns: Int by cssprop("-fx-pref-columns")
var prefTileWidth: Dimension<Dimension.LinearUnits> by cssprop("-fx-pref-tile-width")
var prefTileHeight: Dimension<Dimension.LinearUnits> by cssprop("-fx-pref-tile-height")
var tileAlignment: Pos by cssprop("-fx-tile-alignment")
// VBox
var fillWidth: Boolean by cssprop("-fx-fill-width")
// Shape
var fill: Paint by cssprop("-fx-fill")
var smooth: Boolean by cssprop("-fx-smooth")
var stroke: Paint by cssprop("-fx-stroke")
var strokeType: StrokeType by cssprop("-fx-stroke-type")
var strokeDashArray: List<Dimension<Dimension.LinearUnits>> by cssprop("-fx-stroke-dash-array")
var strokeDashOffset: Dimension<Dimension.LinearUnits> by cssprop("-fx-stroke-dash-offset")
var strokeLineCap: StrokeLineCap by cssprop("-fx-stroke-line-cap")
var strokeLineJoin: StrokeLineJoin by cssprop("-fx-stroke-line-join")
var strokeMiterLimit: Double by cssprop("-fx-stroke-miter-limit")
var strokeWidth: Dimension<Dimension.LinearUnits> by cssprop("-fx-stroke-width")
// Rectangle
var arcHeight: Dimension<Dimension.LinearUnits> by cssprop("-fx-arc-height")
var arcWidth: Dimension<Dimension.LinearUnits> by cssprop("-fx-arc-width")
// Text
var fontSmoothingType: FontSmoothingType by cssprop("-fx-font-smoothing-type")
var strikethrough: Boolean by cssprop("-fx-strikethrough")
var textAlignment: TextAlignment by cssprop("-fx-text-alignment")
var textOrigin: VPos by cssprop("-fx-text-origin")
var underline: Boolean by cssprop("-fx-underline")
// WebView
var contextMenuEnabled: Boolean by cssprop("-fx-context-menu-enabled")
var fontScale: Number by cssprop("-fx-font-scale")
// Cell
var cellSize: Dimension<Dimension.LinearUnits> by cssprop("-fx-cell-size")
// DataGrid Celll
var cellWidth: Dimension<Dimension.LinearUnits> by cssprop("-fx-cell-width")
var cellHeight: Dimension<Dimension.LinearUnits> by cssprop("-fx-cell-height")
var horizontalCellSpacing: Dimension<Dimension.LinearUnits> by cssprop("-fx-horizontal-cell-spacing")
var verticalCellSpacing: Dimension<Dimension.LinearUnits> by cssprop("-fx-vertical-cell-spacing")
var maxCellsInRow: Int by cssprop("-fx-max-cells-in-row")
// ColorPicker
var colorLabelVisible: Boolean by cssprop("-fx-color-label-visible")
// Control
var skin: KClass<*> by cssprop("-fx-skin")
// DatePicker
var showWeekNumbers: Boolean by cssprop("-fx-show-week-numbers")
// Labeled
var textOverrun: OverrunStyle by cssprop("-fx-text-overrun")
var wrapText: Boolean by cssprop("-fx-wrap-text")
var contentDisplay: ContentDisplay by cssprop("-fx-content-display")
var graphicTextGap: Dimension<Dimension.LinearUnits> by cssprop("-fx-graphic-text-gap")
var labelPadding: CssBox<Dimension<Dimension.LinearUnits>> by cssprop("-fx-label-padding")
var textFill: Paint by cssprop("-fx-text-fill")
var ellipsisString: String by cssprop("-fx-ellipsis-string")
// MenuBar
var useSystemMenuBar: Boolean by cssprop("-fx-use-system-menu-bar")
// Pagination
var maxPageIndicatorCount: Int by cssprop("-fx-max-page-indicator-count")
var arrowsVisible: Boolean by cssprop("-fx-arrows-visible")
var tooltipVisible: Boolean by cssprop("-fx-tooltip-visible")
var pageInformationVisible: Boolean by cssprop("-fx-page-information-visible")
var pageInformationAlignment: Side by cssprop("-fx-page-information-alignment")
// ProgressBar
var indeterminateBarLength: Dimension<Dimension.LinearUnits> by cssprop("-fx-indeterminate-bar-length")
var indeterminateBarEscape: Boolean by cssprop("-fx-indeterminate-bar-escape")
var indeterminateBarFlip: Boolean by cssprop("-fx-indeterminate-bar-flip")
var indeterminateBarAnimationTime: Number by cssprop("-fx-indeterminate-bar-animation-time")
// ProgressIndicator
var indeterminateSegmentCount: Int by cssprop("-fx-indeterminate-SegmentCount")
var progressColor: Paint by cssprop("-fx-progress-color")
var spinEnabled: Boolean by cssprop("-fx-spin-enabled")
// ScrollBar
var blockIncrement: Dimension<Dimension.LinearUnits> by cssprop("-fx-block-increment")
var unitIncrement: Dimension<Dimension.LinearUnits> by cssprop("-fx-unit-increment")
// ScrollPane
var fitToWidth: Boolean by cssprop("-fx-fit-to-width")
var fitToHeight: Boolean by cssprop("-fx-fit-to-height")
var pannable: Boolean by cssprop("-fx-pannable")
var hBarPolicy: ScrollPane.ScrollBarPolicy by cssprop("-fx-hbar-policy")
var vBarPolicy: ScrollPane.ScrollBarPolicy by cssprop("-fx-vbar-policy")
// Separator
var hAlignment: HPos by cssprop("-fx-halignment")
var vAlignment: VPos by cssprop("-fx-valignment")
// Slider
var showTickLabels: Boolean by cssprop("-fx-show-tick-labels")
var showTickMarks: Boolean by cssprop("-fx-show-tick-marks")
var majorTickUnit: Double by cssprop("-fx-major-tick-unit")
var minorTickCount: Int by cssprop("-fx-minor-tick-count")
var snapToTicks: Boolean by cssprop("-fx-snap-to-ticks")
// TabPane
var tabMaxHeight: Dimension<Dimension.LinearUnits> by cssprop("-fx-tab-max-height")
var tabMinHeight: Dimension<Dimension.LinearUnits> by cssprop("-fx-tab-min-height")
var tabMaxWidth: Dimension<Dimension.LinearUnits> by cssprop("-fx-tab-max-width")
var tabMinWidth: Dimension<Dimension.LinearUnits> by cssprop("-fx-tab-min-width")
var openTabAnimation: FXTabAnimation by cssprop("-fx-open-tab-animation")
var closeTabAnimation: FXTabAnimation by cssprop("-fx-close-tab-animation")
// TableColumnHeader
var size: Dimension<Dimension.LinearUnits> by cssprop("-fx-size")
// TableView
var fixedCellSize: Dimension<Dimension.LinearUnits> by cssprop("-fx-fixed-cell-size")
// TextArea
var prefColumnCount: Int by cssprop("-fx-pref-column-count")
var prefRowCount: Int by cssprop("-fx-pref-row-count")
var textBoxBorder: Paint by cssprop("-fx-text-box-border")
// TextInputControl
var promptTextFill: Paint by cssprop("-fx-prompt-text-fill")
var highlightFill: Paint by cssprop("-fx-highlight-fill")
var highlightTextFill: Paint by cssprop("-fx-highlight-text-fill")
var displayCaret: Boolean by cssprop("-fx-display-caret")
// TitlePane
var animated: Boolean by cssprop("-fx-animated")
var collapsible: Boolean by cssprop("-fx-collapsible")
// TreeCell
var indent: Dimension<Dimension.LinearUnits> by cssprop("-fx-indent")
// Axis
var side: Side by cssprop("-fx-side")
var tickLength: Dimension<Dimension.LinearUnits> by cssprop("-fx-tick-length")
var tickLabelFont: Font by cssprop("-fx-tick-label-font")
var tickLabelFill: Paint by cssprop("-fx-tick-label-fill")
var tickLabelGap: Dimension<Dimension.LinearUnits> by cssprop("-fx-tick-label-gap")
var tickMarkVisible: Boolean by cssprop("-fx-tick-mark-visible")
var tickLabelsVisible: Boolean by cssprop("-fx-tick-labels-visible")
// BarChar
var barGap: Dimension<Dimension.LinearUnits> by cssprop("-fx-bar-gap")
var categoryGap: Dimension<Dimension.LinearUnits> by cssprop("-fx-category-group")
var barFill: Color by cssprop("-fx-bar-fill")
// CategoryAxis
var startMargin: Dimension<Dimension.LinearUnits> by cssprop("-fx-start-margin")
var endMargin: Dimension<Dimension.LinearUnits> by cssprop("-fx-end-margin")
var gapStartAndEnd: Boolean by cssprop("-fx-gap-start-and-end")
// Chart
var legendSide: Side by cssprop("-fx-legend-side")
var legendVisible: Boolean by cssprop("-fx-legend-visible")
var titleSide: Side by cssprop("-fx-title-side")
// LineChart
var createSymbols: Boolean by cssprop("-fx-create-symbols")
// NumberAxis
var tickUnit: Number by cssprop("-fx-tick-unit")
// PieChart
var clockwise: Boolean by cssprop("-fx-clockwise")
var pieLabelVisible: Boolean by cssprop("-fx-pie-label-visible")
var labelLineLength: Dimension<Dimension.LinearUnits> by cssprop("-fx-label-line-length")
var startAngle: Dimension<Dimension.AngularUnits> by cssprop("-fx-start-angle")
// ValueAxis
var minorTickLength: Dimension<Dimension.LinearUnits> by cssprop("-fx-minor-tick-length")
var minorTickVisible: Boolean by cssprop("-fx-minor-tick-visible")
// XYChart
var alternativeColumnFillVisible: Boolean by cssprop("-fx-alternative-column-fill-visible")
var alternativeRowFillVisible: Boolean by cssprop("-fx-alternative-row-fill-visible")
var horizontalGridLinesVisible: Boolean by cssprop("-fx-horizontal-grid-lines-visible")
var horizontalZeroLineVisible: Boolean by cssprop("-fx-horizontal-zero-line-visible")
var verticalGridLinesVisible: Boolean by cssprop("-fx-vertical-grid-lines-visible")
var verticalZeroLineVisible: Boolean by cssprop("-fx-vertical-zero-line-visible")
infix fun CssProperty<*>.force(value: Any) = unsafe(this, value)
infix fun String.force(value: Any) = unsafe(this, value)
fun unsafe(key: CssProperty<*>, value: Any) = unsafe(key.name, value)
fun unsafe(key: String, value: Any) {
unsafeProperties[key] = value
}
private inline fun <reified V : Any> cssprop(key: String): ReadWriteProperty<PropertyHolder, V> {
return object : ReadWriteProperty<PropertyHolder, V> {
override fun getValue(thisRef: PropertyHolder, property: KProperty<*>): V {
if (!properties.containsKey(key) && MultiValue::class.java.isAssignableFrom(V::class.java))
properties[key] = MultiValue<V>() to null
return properties[key]?.first as V
}
override fun setValue(thisRef: PropertyHolder, property: KProperty<*>, value: V) {
properties[key] = value as Any to properties[key]?.second
}
}
}
@Suppress("UNCHECKED_CAST")
class CssProperty<T>(name: String, val multiValue: Boolean, val renderer: ((T) -> String)? = null) {
val name = name.camelToSnake()
var value: T
get() {
val props = selectionScope.get().properties
if (!props.containsKey(name) && multiValue)
props[name] = MultiValue<T>() to renderer as ((Any) -> String)?
return selectionScope.get().properties[name]?.first as T
}
set(value) {
selectionScope.get().properties.put(name, value as Any to renderer as ((Any) -> String)?)
}
}
infix fun <T : Any> CssProperty<T>.set(value: T) = setProperty(this, value)
fun <T : Any> setProperty(property: CssProperty<T>, value: T) {
properties[property.name] = value to properties[property.name]?.second
}
class Raw(val name: String)
fun raw(name: String) = Raw(name)
}
@Suppress("NAME_SHADOWING")
class CssSelection(val selector: CssSelector, op: CssSelectionBlock.() -> Unit) : Rendered {
val block = CssSelectionBlock(op)
override fun render() = render(emptyList(), CssSubRule.Relation.DESCENDANT)
fun render(parents: List<String>, relation: CssSubRule.Relation): String = buildString {
val ruleStrings = selector.strings(parents, relation)
block.mergedProperties.let {
// TODO: Handle custom renderer
if (it.isNotEmpty()) {
append("${ruleStrings.joinToString()} {\n")
for ((name, value) in it) {
append(" $name: ${value.second?.invoke(value.first) ?: PropertyHolder.toCss(value.first)};\n")
}
append("}\n")
}
}
for ((selection, relation) in block.selections) {
append(selection.render(ruleStrings, relation))
}
}
}
class CssSelector(vararg val rule: CssRuleSet) : Selectable {
companion object {
fun String.merge(other: String, relation: CssSubRule.Relation) = "$this${relation.render()}$other"
fun List<String>.cartesian(parents: List<String>, relation: CssSubRule.Relation) = if (parents.isEmpty()) this else
parents.asSequence().flatMap { parent -> asSequence().map { child -> parent.merge(child, relation) } }.toList()
}
override fun toSelection() = this
fun strings(parents: List<String>, relation: CssSubRule.Relation) = rule.mapEach { render() }.cartesian(parents, relation)
fun simpleRender() = rule.joinToString { it.render() }
}
class CssSelectionBlock(op: CssSelectionBlock.() -> Unit) : PropertyHolder(), SelectionHolder {
val log = Logger.getLogger("ErrorHandler")
val selections = mutableMapOf<CssSelection, CssSubRule.Relation>()
init {
val currentScope = PropertyHolder.selectionScope.get()
PropertyHolder.selectionScope.set(this)
try {
op(this)
} catch (e: Exception) {
// the CSS rule caused an error, do not let the error propagate to
// avoid an infinite loop in the error handler
log.log(Level.WARNING, "CSS rule caused an error", e)
}
PropertyHolder.selectionScope.set(currentScope)
}
override fun addSelection(selection: CssSelection) {
selections[selection] = CssSubRule.Relation.DESCENDANT
}
override fun removeSelection(selection: CssSelection) {
selections.remove(selection)
}
operator fun CssSelectionBlock.unaryPlus() {
[email protected](this)
}
@Deprecated("Use and() instead as it's clearer", ReplaceWith("and(selector, op)"))
fun add(selector: String, op: CssSelectionBlock.() -> Unit) = and(selector, op)
@Deprecated("Use and() instead as it's clearer", ReplaceWith("and(selector, *selectors, op = op)"))
fun add(selector: Selectable, vararg selectors: Selectable, op: CssSelectionBlock.() -> Unit) = and(selector, *selectors, op = op)
private fun addRelation(
relation: CssSubRule.Relation,
selector: Selectable, vararg selectors: Selectable,
op: CssSelectionBlock.() -> Unit
): CssSelection {
val s = select(selector, *selectors, op = op)
selections[s] = relation
return s
}
/**
* [CssSubRule.Relation.REFINE]
*/
fun and(selector: String, op: CssSelectionBlock.() -> Unit) = and(selector.toSelector(), op = op)
/**
* [CssSubRule.Relation.REFINE]
*/
fun and(selector: Selectable, vararg selectors: Selectable, op: CssSelectionBlock.() -> Unit): CssSelection =
addRelation(CssSubRule.Relation.REFINE, selector, *selectors, op = op)
/**
* [CssSubRule.Relation.CHILD]
*/
fun child(selector: String, op: CssSelectionBlock.() -> Unit) = child(selector.toSelector(), op = op)
/**
* [CssSubRule.Relation.CHILD]
*/
fun child(selector: Selectable, vararg selectors: Selectable, op: CssSelectionBlock.() -> Unit): CssSelection =
addRelation(CssSubRule.Relation.CHILD, selector, *selectors, op = op)
/**
* [CssSubRule.Relation.DESCENDANT]
*/
fun contains(selector: String, op: CssSelectionBlock.() -> Unit) = contains(selector.toSelector(), op = op)
/**
* [CssSubRule.Relation.DESCENDANT]
*/
fun contains(selector: Selectable, vararg selectors: Selectable, op: CssSelectionBlock.() -> Unit): CssSelection =
addRelation(CssSubRule.Relation.DESCENDANT, selector, *selectors, op = op)
/**
* [CssSubRule.Relation.ADJACENT]
*/
fun next(selector: String, op: CssSelectionBlock.() -> Unit) = next(selector.toSelector(), op = op)
/**
* [CssSubRule.Relation.ADJACENT]
*/
fun next(selector: Selectable, vararg selectors: Selectable, op: CssSelectionBlock.() -> Unit): CssSelection =
addRelation(CssSubRule.Relation.ADJACENT, selector, *selectors, op = op)
/**
* [CssSubRule.Relation.SIBLING]
*/
fun sibling(selector: String, op: CssSelectionBlock.() -> Unit) = sibling(selector.toSelector(), op = op)
/**
* [CssSubRule.Relation.SIBLING]
*/
fun sibling(selector: Selectable, vararg selectors: Selectable, op: CssSelectionBlock.() -> Unit): CssSelection =
addRelation(CssSubRule.Relation.SIBLING, selector, *selectors, op = op)
@Suppress("UNCHECKED_CAST")
fun mix(mixin: CssSelectionBlock) {
mixin.properties.withEach {
(properties[key]?.first as? MultiValue<Any>)?.addAll(value.first as MultiValue<Any>)
?: run { properties[key] = value }
}
mixin.unsafeProperties.withEach {
(unsafeProperties[key] as? MultiValue<Any>)?.addAll(value as MultiValue<Any>)
?: run { unsafeProperties[key] = value }
}
selections.putAll(mixin.selections)
}
}
fun mixin(op: CssSelectionBlock.() -> Unit) = CssSelectionBlock(op)
class CssRuleSet(val rootRule: CssRule, vararg val subRule: CssSubRule) : Selectable, Scoped, Rendered {
override fun render() = buildString {
append(rootRule.render())
subRule.forEach { append(it.render()) }
}
override fun toRuleSet() = this
override fun toSelection() = CssSelector(this)
override fun append(rule: CssSubRule) = CssRuleSet(rootRule, *subRule, rule)
fun append(ruleSet: CssRuleSet, relation: CssSubRule.Relation)
= CssRuleSet(rootRule, *subRule, CssSubRule(ruleSet.rootRule, relation), *ruleSet.subRule)
}
class CssRule(val prefix: String, name: String, snakeCase: Boolean = true) : Selectable, Scoped, Rendered {
companion object {
fun elem(value: String, snakeCase: Boolean = true) = CssRule("", value.cssValidate(), snakeCase)
fun id(value: String, snakeCase: Boolean = true) = CssRule("#", value.cssValidate(), snakeCase)
fun c(value: String, snakeCase: Boolean = true) = CssRule(".", value.cssValidate(), snakeCase)
fun pc(value: String, snakeCase: Boolean = true) = CssRule(":", value.cssValidate(), snakeCase)
private val name = "\\*|-?[_a-zA-Z][_a-zA-Z0-9-]*" // According to http://stackoverflow.com/a/449000/2094298
private val prefix = "[.#:]?"
private val relation = "[ >+~]?"
private val subRule = "\\s*?($relation)\\s*($prefix)($name)"
val nameRegex = Regex(name)
val subRuleRegex = Regex(subRule)
val ruleSetRegex = Regex("($subRule)+\\s*")
val splitter = Regex("\\s*,\\s*")
val upperCaseRegex = Regex("([A-Z])")
}
val name = if (snakeCase) name.camelToSnake() else name
override fun render() = "$prefix$name"
override fun toRuleSet() = CssRuleSet(this)
override fun toSelection() = toRuleSet().toSelection()
override fun append(rule: CssSubRule) = CssRuleSet(this, rule)
}
class CssSubRule(val rule: CssRule, val relation: Relation) : Rendered {
override fun render() = "${relation.render()}${rule.render()}"
enum class Relation(val symbol: String) : Rendered {
REFINE(""),
CHILD(" > "),
DESCENDANT(" "),
ADJACENT(" + "),
SIBLING(" ~ ");
companion object {
fun of(symbol: String) = when (symbol) {
"" -> REFINE
">" -> CHILD
" " -> DESCENDANT
"+" -> ADJACENT
"~" -> SIBLING
else -> throw IllegalArgumentException("Invalid Css Relation: $symbol")
}
}
override fun render() = symbol
}
}
// Inline CSS
class InlineCss : PropertyHolder(), Rendered {
// TODO: Handle custom renderer
override fun render() = mergedProperties.entries.joinToString(separator = "") {
" ${it.key}: ${it.value.second?.invoke(it.value.first) ?: toCss(it.value.first)};"
}
}
fun Iterable<Node>.style(append: Boolean = false, op: InlineCss.() -> Unit) = withEach { style(append, op) }
fun Styleable.style(append: Boolean = false, op: InlineCss.() -> Unit) {
val setStyleMethod = this.javaClass.methods.firstOrNull { method ->
method.name == "setStyle" && method.returnType == Void.TYPE && method.parameterCount == 1 && method.parameters[0].type == String::class.java
}
setStyleMethod ?: throw IllegalArgumentException("Don't know how to set style for Styleable subclass ${[email protected]}")
val block = InlineCss().apply(op)
val newStyle = if (append && style.isNotBlank())
style + block.render()
else
block.render().trim()
try {
// in Java 9 setStyleMethod.canAccess(this) can be used for checking instead of wrapping this invocation in a try-catch clause
setStyleMethod.invoke(this, newStyle)
} catch (exception: Exception) {
when (exception) {
is IllegalAccessException,
is IllegalArgumentException -> println("Cannot access ${[email protected]}.setStyle(...) through reflection due to insufficient priviledge.")
else -> FX.log.warning("Invocation of ${[email protected]}.setStyle(...) through reflection failed.")
}
throw exception
}
}
// Delegates
fun csselement(value: String? = null, snakeCase: Boolean = value == null) = CssElementDelegate(value, snakeCase)
fun cssid(value: String? = null, snakeCase: Boolean = value == null) = CssIdDelegate(value, snakeCase)
fun cssclass(value: String? = null, snakeCase: Boolean = value == null) = CssClassDelegate(value, snakeCase)
fun csspseudoclass(value: String? = null, snakeCase: Boolean = value == null) = CssPseudoClassDelegate(value, snakeCase)
inline fun <reified T : Any> cssproperty(value: String? = null, noinline renderer: ((T) -> String)? = null) = CssPropertyDelegate(value, MultiValue::class.java.isAssignableFrom(T::class.java), renderer)
class CssElementDelegate(val name: String?, val snakeCase: Boolean = name == null) : ReadOnlyProperty<Any, CssRule> {
override fun getValue(thisRef: Any, property: KProperty<*>) = CssRule.elem(name ?: property.name, snakeCase)
}
class CssIdDelegate(val name: String?, val snakeCase: Boolean = name == null) : ReadOnlyProperty<Any, CssRule> {
override fun getValue(thisRef: Any, property: KProperty<*>) = CssRule.id(name ?: property.name, snakeCase)
}
class CssClassDelegate(val name: String?, val snakeCase: Boolean = name == null) : ReadOnlyProperty<Any, CssRule> {
override fun getValue(thisRef: Any, property: KProperty<*>) = CssRule.c(name ?: property.name, snakeCase)
}
class CssPseudoClassDelegate(val name: String?, val snakeCase: Boolean = name == null) : ReadOnlyProperty<Any, CssRule> {
override fun getValue(thisRef: Any, property: KProperty<*>) = CssRule.pc(name ?: property.name, snakeCase)
}
class CssPropertyDelegate<T : Any>(val name: String?, val multiValue: Boolean, val renderer: ((T) -> String)? = null) : ReadOnlyProperty<Any, PropertyHolder.CssProperty<T>> {
override fun getValue(thisRef: Any, property: KProperty<*>) = PropertyHolder.CssProperty<T>(name ?: property.name, multiValue, renderer)
}
// Dimensions
open class Dimension<T : Enum<T>>(val value: Double, val units: T) {
operator fun unaryPlus() = this
operator fun unaryMinus() = Dimension(-value, units)
operator fun plus(value: Number) = Dimension(this.value + value.toDouble(), units)
operator fun plus(value: Dimension<T>) = safeMath(value, Double::plus)
operator fun minus(value: Number) = Dimension(this.value - value.toDouble(), units)
operator fun minus(value: Dimension<T>) = safeMath(value, Double::minus)
operator fun times(value: Number) = Dimension(this.value * value.toDouble(), units)
operator fun div(value: Number) = Dimension(this.value / value.toDouble(), units)
operator fun rem(value: Number) = Dimension(this.value % value.toDouble(), units)
private fun safeMath(value: Dimension<T>, op: (Double, Double) -> Double) = if (units == value.units)
Dimension(op(this.value, value.value), units)
else
throw IllegalArgumentException("Cannot combine $this and $value: The units do not match")
override fun equals(other: Any?) = other != null && other is Dimension<*> && value == other.value && units == other.units
override fun hashCode() = value.hashCode() * 31 + units.hashCode()
override fun toString() = when (value) {
Double.POSITIVE_INFINITY, Double.MAX_VALUE -> "infinity"
Double.NEGATIVE_INFINITY, Double.MIN_VALUE -> "-infinity"
Double.NaN -> "0$units"
else -> "${fiveDigits.format(value)}$units"
}
enum class AngularUnits { deg, rad, grad, turn }
enum class LinearUnits(val value: String) {
px("px"),
mm("mm"),
cm("cm"),
inches("in"),
pt("pt"),
pc("pc"),
em("em"),
ex("ex"),
percent("%");
override fun toString() = value
}
}
operator fun <T : Enum<T>> Number.plus(value: Dimension<T>) = Dimension(this.toDouble() + value.value, value.units)
operator fun <T : Enum<T>> Number.minus(value: Dimension<T>) = Dimension(this.toDouble() - value.value, value.units)
operator fun <T : Enum<T>> Number.times(value: Dimension<T>) = Dimension(this.toDouble() * value.value, value.units)
val infinity = Dimension(Double.POSITIVE_INFINITY, Dimension.LinearUnits.px)
val Number.px: Dimension<Dimension.LinearUnits> get() = Dimension(this.toDouble(), Dimension.LinearUnits.px)
val Number.mm: Dimension<Dimension.LinearUnits> get() = Dimension(this.toDouble(), Dimension.LinearUnits.mm)
val Number.cm: Dimension<Dimension.LinearUnits> get() = Dimension(this.toDouble(), Dimension.LinearUnits.cm)
val Number.inches: Dimension<Dimension.LinearUnits> get() = Dimension(this.toDouble(), Dimension.LinearUnits.inches)
val Number.pt: Dimension<Dimension.LinearUnits> get() = Dimension(this.toDouble(), Dimension.LinearUnits.pt)
val Number.pc: Dimension<Dimension.LinearUnits> get() = Dimension(this.toDouble(), Dimension.LinearUnits.pc)
val Number.em: Dimension<Dimension.LinearUnits> get() = Dimension(this.toDouble(), Dimension.LinearUnits.em)
val Number.ex: Dimension<Dimension.LinearUnits> get() = Dimension(this.toDouble(), Dimension.LinearUnits.ex)
val Number.percent: Dimension<Dimension.LinearUnits> get() = Dimension(this.toDouble(), Dimension.LinearUnits.percent)
val Number.deg: Dimension<Dimension.AngularUnits> get() = Dimension(this.toDouble(), Dimension.AngularUnits.deg)
val Number.rad: Dimension<Dimension.AngularUnits> get() = Dimension(this.toDouble(), Dimension.AngularUnits.rad)
val Number.grad: Dimension<Dimension.AngularUnits> get() = Dimension(this.toDouble(), Dimension.AngularUnits.grad)
val Number.turn: Dimension<Dimension.AngularUnits> get() = Dimension(this.toDouble(), Dimension.AngularUnits.turn)
// Enums
enum class FXVisibility { VISIBLE, HIDDEN, COLLAPSE, INHERIT; }
enum class FXTabAnimation { GROW, NONE; }
// Misc
val fiveDigits = DecimalFormat("#.#####", DecimalFormatSymbols.getInstance(Locale.ENGLISH))
val Color.css: String get() = "rgba(${(red * 255).toInt()}, ${(green * 255).toInt()}, ${(blue * 255).toInt()}, ${fiveDigits.format(opacity)})"
internal fun String.camelToSnake() = (get(0).toLowerCase() + substring(1)).replace(CssRule.upperCaseRegex, "-$1").toLowerCase()
internal fun String.cssValidate() = if (matches(CssRule.nameRegex)) this else throw IllegalArgumentException("Invalid CSS Name: $this")
internal fun String.toSelector() = CssSelector(*split(CssRule.splitter).map(String::toRuleSet).toTypedArray())
internal fun String.toRuleSet() = if (matches(CssRule.ruleSetRegex)) {
val rules = CssRule.subRuleRegex.findAll(this)
.mapEach { CssSubRule(CssRule(groupValues[2], groupValues[3], false), CssSubRule.Relation.of(groupValues[1])) }
.toList()
CssRuleSet(rules[0].rule, *rules.drop(1).toTypedArray())
} else throw IllegalArgumentException("Invalid CSS Rule Set: $this")
fun loadFont(path: String, size: Number): Font? {
return MethodHandles.lookup().lookupClass().getResourceAsStream(path)?.use { Font.loadFont(it, size.toDouble()) }
}
// Style Class
/**
* Check if this Node has the given type safe css class. Pseudo classes are also supported.
*/
fun Node.hasClass(cssClass: CssRule) = if (cssClass.prefix == ":") hasPseudoClass(cssClass.name) else hasClass(cssClass.name)
/**
* Check if this Node has the given type safe css class. Pseudo classes are also supported.
*/
fun Tab.hasClass(cssClass: CssRule) = if (cssClass.prefix == ":") hasPseudoClass(cssClass.name) else hasClass(cssClass.name)
/**
* Add one or more type safe css classes to this Node. Pseudo classes are also supported.
*/
fun <T : Node> T.addClass(vararg cssClass: CssRule) = apply {
cssClass.withEach {
if (prefix == ":") addPseudoClass(name) else addClass(name)
}
}
/**
* Add one or more type safe css classes to this Tab. Pseudo classes are also supported.
*/
fun <T : Tab> T.addClass(vararg cssClass: CssRule) = apply {
cssClass.withEach {
if (prefix == ":") addPseudoClass(name) else addClass(name)
}
}
/**
* Remove the given given type safe css class(es) from this Node. Pseudo classes are also supported.
*/
fun <T : Node> T.removeClass(vararg cssClass: CssRule) = apply {
cssClass.withEach {
if (prefix == ":") removePseudoClass(name) else removeClass(name)
}
}
/**
* Remove the given given type safe css class(es) from this Tab. Pseudo classes are also supported.
*/
fun <T : Tab> T.removeClass(vararg cssClass: CssRule) = apply {
cssClass.withEach {
if (prefix == ":") removePseudoClass(name) else removeClass(name)
}
}
/**
* Toggle the given type safe css class based on the given predicate. Pseudo classes are also supported.
*/
fun <T : Node> T.toggleClass(cssClass: CssRule, predicate: Boolean) = if (cssClass.prefix == ":") togglePseudoClass(cssClass.name, predicate) else toggleClass(cssClass.name, predicate)
/**
* Toggle the given type safe css class based on the given predicate. Pseudo classes are also supported.
*/
fun <T : Tab> T.toggleClass(cssClass: CssRule, predicate: Boolean) = if (cssClass.prefix == ":") togglePseudoClass(cssClass.name, predicate) else toggleClass(cssClass.name, predicate)
/**
* Toggle the given type safe css class based on the given predicate observable value.
* Whenever the observable value changes, the class is added or removed.
* Pseudo classes are also supported.
*/
fun <T : Node> T.toggleClass(cssClass: CssRule, observablePredicate: ObservableValue<Boolean>) {
toggleClass(cssClass, observablePredicate.value ?: false)
observablePredicate.onChange {
toggleClass(cssClass, it ?: false)
}
}
/**
* Toggle the given type safe css class based on the given predicate observable value.
* Whenever the observable value changes, the class is added or removed.
* Pseudo classes are also supported.
*/
fun <T : Tab> T.toggleClass(cssClass: CssRule, observablePredicate: ObservableValue<Boolean>) {
toggleClass(cssClass, observablePredicate.value ?: false)
observablePredicate.onChange {
toggleClass(cssClass, it ?: false)
}
}
/**
* Add the given type safe css classes to every Node in this Iterable. Pseudo classes are also supported.
*/
fun Iterable<Node>.addClass(vararg cssClass: CssRule) = forEach { node -> cssClass.forEach { node.addClass(it) } }
/**
* Remove the given type safe css classes from every node in this Iterable. Pseudo classes are also supported.
*/
fun Iterable<Node>.removeClass(vararg cssClass: CssRule) = forEach { node -> cssClass.forEach { node.removeClass(it) } }
/**
* Toggle the given type safe css class on every node in this iterable based on the given predicate. Pseudo classes are also supported.
*/
fun Iterable<Node>.toggleClass(cssClass: CssRule, predicate: Boolean) = withEach { toggleClass(cssClass, predicate) }
/**
* Bind this observable type safe css rule to this Node. Pseudo classes are also supported.
*/
fun Node.bindClass(value: ObservableValue<CssRule>): ObservableStyleClass = ObservableStyleClass(this, value)
class ObservableStyleClass(node: Node, val value: ObservableValue<CssRule>) {
val listener: ChangeListener<CssRule>
init {
fun checkAdd(newValue: CssRule?) {
if (newValue != null && !node.hasClass(newValue)) node.addClass(newValue)
}
listener = ChangeListener { observableValue, oldValue, newValue ->
if (oldValue != null) node.removeClass(oldValue)
checkAdd(newValue)
}
checkAdd(value.value)
value.addListener(listener)
}
fun dispose() = value.removeListener(listener)
}
@Suppress("UNCHECKED_CAST")
fun <T : Node> Node.select(selector: Selectable) = lookup(selector.toSelection().simpleRender()) as T
@Suppress("UNCHECKED_CAST")
fun <T : Node> Node.selectAll(selector: Selectable) = (lookupAll(selector.toSelection().simpleRender()) as Set<T>).toList()
fun <T : Node> T.setId(cssId: CssRule) = apply { id = cssId.name }
// Containers
fun <T> box(all: T) = CssBox(all, all, all, all)
fun <T> box(vertical: T, horizontal: T) = CssBox(vertical, horizontal, vertical, horizontal)
fun <T> box(top: T, right: T, bottom: T, left: T) = CssBox(top, right, bottom, left)
data class CssBox<out T>(val top: T, val right: T, val bottom: T, val left: T)
fun c(colorString: String, opacity: Double = 1.0): Color = try {
Color.web(colorString, opacity)
} catch (e: Exception) {
Stylesheet.log.warning("Error parsing color c('$colorString', opacity=$opacity)")
Color.MAGENTA
}
fun c(red: Double, green: Double, blue: Double, opacity: Double = 1.0): Color = try {
Color.color(red, green, blue, opacity)
} catch (e: Exception) {
Stylesheet.log.warning("Error parsing color c(red=$red, green=$green, blue=$blue, opacity=$opacity)")
Color.MAGENTA
}
fun c(red: Int, green: Int, blue: Int, opacity: Double = 1.0): Color = try {
Color.rgb(red, green, blue, opacity)
} catch (e: Exception) {
Stylesheet.log.warning("Error parsing color c(red=$red, green=$green, blue=$blue, opacity=$opacity)")
Color.MAGENTA
}
fun Color.derive(ratio: Double): Color = if (ratio < 0) interpolate(Color(0.0, 0.0, 0.0, opacity), -ratio) else interpolate(Color(1.0, 1.0, 1.0, opacity), ratio)
fun Color.ladder(vararg stops: Stop): Color {
val offset = brightness
val nStops = LinearGradient(0.0, 1.0, 0.0, 1.0, false, CycleMethod.NO_CYCLE, *stops).stops
return if (offset <= 0.0) {
nStops.first().color
} else if (offset >= 1.0) {
nStops.last().color
} else {
val left = nStops.last { it.offset <= offset }
val right = nStops.first { it.offset >= offset }
if (right.offset == left.offset) left.color else left.color.interpolate(right.color, (offset - left.offset) / (right.offset - left.offset))
}
}
/**
* Converts the given Paint to a Background
*/
fun Paint.asBackground(radii: CornerRadii = CornerRadii.EMPTY, insets: Insets = Insets.EMPTY) =
Background(BackgroundFill(this, radii, insets))
fun <T> multi(vararg elements: T) = MultiValue(elements)
class MultiValue<T>(initialElements: Array<out T>? = null) {
val elements = mutableListOf<T>()
init {
if (initialElements != null) elements.addAll(initialElements)
}
operator fun plusAssign(element: T) {
elements.add(element)
}
fun add(element: T) = elements.add(element)
fun add(multivalue: MultiValue<T>) = addAll(multivalue.elements)
fun addAll(list: Iterable<T>) = elements.addAll(list)
fun addAll(vararg element: T) = elements.addAll(element)
}
class BorderImageSlice(val widths: CssBox<Dimension<Dimension.LinearUnits>>, val filled: Boolean = false)
fun Parent.stylesheet(op: Stylesheet.() -> Unit) {
val stylesheet = Stylesheet().apply(op)
stylesheets += stylesheet.base64URL.toExternalForm()
}
/**
* Adds the [stylesheet] to the given parent.
*/
inline fun <T: Stylesheet> Parent.addStylesheet(stylesheet: KClass<T>) = this.stylesheets.add("css://${stylesheet.java.name}")
|
apache-2.0
|
85434ac8001fbfd4912503d082e2907c
| 43.17284 | 202 | 0.671402 | 4.188878 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/JavaToKotlinConverter.kt
|
1
|
16448
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.j2k
import com.intellij.lang.java.JavaLanguage
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.RangeMarker
import com.intellij.openapi.progress.*
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Computable
import com.intellij.openapi.util.NlsContexts
import com.intellij.psi.*
import com.intellij.psi.impl.source.DummyHolder
import com.intellij.refactoring.suggested.range
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.idea.KotlinLanguage
import com.intellij.openapi.application.runReadAction
import org.jetbrains.kotlin.j2k.ast.Element
import org.jetbrains.kotlin.j2k.usageProcessing.ExternalCodeProcessor
import org.jetbrains.kotlin.j2k.usageProcessing.UsageProcessing
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.psiUtil.elementsInRange
import org.jetbrains.kotlin.psi.psiUtil.isAncestor
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import java.util.*
interface PostProcessor {
fun insertImport(file: KtFile, fqName: FqName)
val phasesCount: Int
fun doAdditionalProcessing(
target: JKPostProcessingTarget,
converterContext: ConverterContext?,
onPhaseChanged: ((Int, String) -> Unit)?
)
}
sealed class JKPostProcessingTarget
data class JKPieceOfCodePostProcessingTarget(
val file: KtFile,
val rangeMarker: RangeMarker
) : JKPostProcessingTarget()
data class JKMultipleFilesPostProcessingTarget(
val files: List<KtFile>
) : JKPostProcessingTarget()
fun JKPostProcessingTarget.elements() = when (this) {
is JKPieceOfCodePostProcessingTarget -> runReadAction {
val range = rangeMarker.range ?: return@runReadAction emptyList()
file.elementsInRange(range)
}
is JKMultipleFilesPostProcessingTarget -> files
}
fun JKPostProcessingTarget.files() = when (this) {
is JKPieceOfCodePostProcessingTarget -> listOf(file)
is JKMultipleFilesPostProcessingTarget -> files
}
enum class ParseContext {
TOP_LEVEL,
CODE_BLOCK
}
interface ExternalCodeProcessing {
fun prepareWriteOperation(progress: ProgressIndicator?): (List<KtFile>) -> Unit
}
data class ElementResult(val text: String, val importsToAdd: Set<FqName>, val parseContext: ParseContext)
data class Result(
val results: List<ElementResult?>,
val externalCodeProcessing: ExternalCodeProcessing?,
val converterContext: ConverterContext?
)
data class FilesResult(val results: List<String>, val externalCodeProcessing: ExternalCodeProcessing?)
interface ConverterContext
abstract class JavaToKotlinConverter {
protected abstract fun elementsToKotlin(inputElements: List<PsiElement>, processor: WithProgressProcessor): Result
abstract fun filesToKotlin(
files: List<PsiJavaFile>,
postProcessor: PostProcessor,
progress: ProgressIndicator = EmptyProgressIndicator()
): FilesResult
abstract fun elementsToKotlin(inputElements: List<PsiElement>): Result
}
class OldJavaToKotlinConverter(
private val project: Project,
private val settings: ConverterSettings,
private val services: JavaToKotlinConverterServices
) : JavaToKotlinConverter() {
companion object {
private val LOG = Logger.getInstance(JavaToKotlinConverter::class.java)
}
override fun filesToKotlin(
files: List<PsiJavaFile>,
postProcessor: PostProcessor,
progress: ProgressIndicator
): FilesResult {
val withProgressProcessor = OldWithProgressProcessor(progress, files)
val (results, externalCodeProcessing) = ApplicationManager.getApplication().runReadAction(Computable {
elementsToKotlin(files, withProgressProcessor)
})
val texts = withProgressProcessor.processItems(0.5, results.withIndex()) { pair ->
val (i, result) = pair
try {
val kotlinFile = ApplicationManager.getApplication().runReadAction(Computable {
KtPsiFactory(project).createAnalyzableFile("dummy.kt", result!!.text, files[i])
})
result!!.importsToAdd.forEach { postProcessor.insertImport(kotlinFile, it) }
AfterConversionPass(project, postProcessor).run(kotlinFile, converterContext = null, range = null, onPhaseChanged = null)
kotlinFile.text
} catch (e: ProcessCanceledException) {
throw e
} catch (t: Throwable) {
LOG.error(t)
result!!.text
}
}
return FilesResult(texts, externalCodeProcessing)
}
override fun elementsToKotlin(inputElements: List<PsiElement>, processor: WithProgressProcessor): Result {
try {
val usageProcessings = LinkedHashMap<PsiElement, MutableCollection<UsageProcessing>>()
val usageProcessingCollector: (UsageProcessing) -> Unit = {
usageProcessings.getOrPut(it.targetElement) { ArrayList() }.add(it)
}
fun inConversionScope(element: PsiElement) = inputElements.any { it.isAncestor(element, strict = false) }
val intermediateResults = processor.processItems(0.25, inputElements) { inputElement ->
Converter.create(inputElement, settings, services, ::inConversionScope, usageProcessingCollector).convert()
}.toMutableList()
val results = processor.processItems(0.25, intermediateResults.withIndex()) { pair ->
val (i, result) = pair
intermediateResults[i] = null // to not hold unused objects in the heap
result?.let {
val (text, importsToAdd) = it.codeGenerator(usageProcessings)
ElementResult(text, importsToAdd, it.parseContext)
}
}
val externalCodeProcessing = buildExternalCodeProcessing(usageProcessings, ::inConversionScope)
return Result(results, externalCodeProcessing, null)
} catch (e: ElementCreationStackTraceRequiredException) {
// if we got this exception then we need to turn element creation stack traces on to get better diagnostic
Element.saveCreationStacktraces = true
try {
return elementsToKotlin(inputElements)
} finally {
Element.saveCreationStacktraces = false
}
}
}
override fun elementsToKotlin(inputElements: List<PsiElement>): Result {
return elementsToKotlin(inputElements, OldWithProgressProcessor.DEFAULT)
}
private data class ReferenceInfo(
val reference: PsiReference,
val target: PsiElement,
val file: PsiFile,
val processings: Collection<UsageProcessing>
) {
val depth: Int by lazy(LazyThreadSafetyMode.NONE) { target.parentsWithSelf.takeWhile { it !is PsiFile }.count() }
val offset: Int by lazy(LazyThreadSafetyMode.NONE) { reference.element.textRange.startOffset }
}
private fun buildExternalCodeProcessing(
usageProcessings: Map<PsiElement, Collection<UsageProcessing>>,
inConversionScope: (PsiElement) -> Boolean
): ExternalCodeProcessing? {
if (usageProcessings.isEmpty()) return null
val map: Map<PsiElement, Collection<UsageProcessing>> = usageProcessings.values
.flatten()
.filter { it.javaCodeProcessors.isNotEmpty() || it.kotlinCodeProcessors.isNotEmpty() }
.groupBy { it.targetElement }
if (map.isEmpty()) return null
return object : ExternalCodeProcessing {
override fun prepareWriteOperation(progress: ProgressIndicator?): (List<KtFile>) -> Unit {
if (progress == null) error("Progress should not be null for old J2K")
val refs = ArrayList<ReferenceInfo>()
progress.text = KotlinJ2KBundle.message("text.searching.usages.to.update")
for ((i, entry) in map.entries.withIndex()) {
val psiElement = entry.key
val processings = entry.value
progress.text2 = (psiElement as? PsiNamedElement)?.name ?: ""
progress.checkCanceled()
ProgressManager.getInstance().runProcess(
{
val searchJava = processings.any { it.javaCodeProcessors.isNotEmpty() }
val searchKotlin = processings.any { it.kotlinCodeProcessors.isNotEmpty() }
services.referenceSearcher.findUsagesForExternalCodeProcessing(psiElement, searchJava, searchKotlin)
.filterNot { inConversionScope(it.element) }
.mapTo(refs) { ReferenceInfo(it, psiElement, it.element.containingFile, processings) }
},
ProgressPortionReporter(progress, i / map.size.toDouble(), 1.0 / map.size)
)
}
return { processUsages(refs) }
}
}
}
private fun processUsages(refs: Collection<ReferenceInfo>) {
for (fileRefs in refs.groupBy { it.file }.values) { // group by file for faster sorting
ReferenceLoop@
for ((reference, _, _, processings) in fileRefs.sortedWith(ReferenceComparator)) {
val processors = when (reference.element.language) {
JavaLanguage.INSTANCE -> processings.flatMap { it.javaCodeProcessors }
KotlinLanguage.INSTANCE -> processings.flatMap { it.kotlinCodeProcessors }
else -> continue@ReferenceLoop
}
checkReferenceValid(reference, null)
var references = listOf(reference)
for (processor in processors) {
references = references.flatMap { processor.processUsage(it)?.toList() ?: listOf(it) }
references.forEach { checkReferenceValid(it, processor) }
}
}
}
}
private fun checkReferenceValid(reference: PsiReference, afterProcessor: ExternalCodeProcessor?) {
val element = reference.element
assert(element.isValid && element.containingFile !is DummyHolder) {
"Reference $reference got invalidated" + (if (afterProcessor != null) " after processing with $afterProcessor" else "")
}
}
private object ReferenceComparator : Comparator<ReferenceInfo> {
override fun compare(info1: ReferenceInfo, info2: ReferenceInfo): Int {
val depth1 = info1.depth
val depth2 = info2.depth
if (depth1 != depth2) { // put deeper elements first to not invalidate them when processing ancestors
return -depth1.compareTo(depth2)
}
// process elements with the same deepness from right to left so that right-side of assignments is not invalidated by processing of the left one
return -info1.offset.compareTo(info2.offset)
}
}
}
interface WithProgressProcessor {
fun <TInputItem, TOutputItem> processItems(
fractionPortion: Double,
inputItems: Iterable<TInputItem>,
processItem: (TInputItem) -> TOutputItem
): List<TOutputItem>
fun updateState(fileIndex: Int?, phase: Int, description: String)
fun updateState(phase: Int, subPhase: Int, subPhaseCount: Int, fileIndex: Int?, description: String)
fun <T> process(action: () -> T): T
}
class OldWithProgressProcessor(private val progress: ProgressIndicator?, private val files: List<PsiJavaFile>?) : WithProgressProcessor {
companion object {
val DEFAULT = OldWithProgressProcessor(null, null)
}
private val progressText
@Suppress("DialogTitleCapitalization")
@NlsContexts.ProgressText
get() = KotlinJ2KBundle.message("text.converting.java.to.kotlin")
private val fileCount = files?.size ?: 0
private val fileCountText
@Nls
get() = KotlinJ2KBundle.message("text.files.count.0", fileCount, if (fileCount == 1) 1 else 2)
private var fraction = 0.0
private var pass = 1
override fun <TInputItem, TOutputItem> processItems(
fractionPortion: Double,
inputItems: Iterable<TInputItem>,
processItem: (TInputItem) -> TOutputItem
): List<TOutputItem> {
val outputItems = ArrayList<TOutputItem>()
// we use special process with EmptyProgressIndicator to avoid changing text in our progress by inheritors search inside etc
ProgressManager.getInstance().runProcess(
{
progress?.text = "$progressText ($fileCountText) - ${KotlinJ2KBundle.message("text.pass.of.3", pass)}"
progress?.isIndeterminate = false
for ((i, item) in inputItems.withIndex()) {
progress?.checkCanceled()
progress?.fraction = fraction + fractionPortion * i / fileCount
progress?.text2 = files!![i].virtualFile.presentableUrl
outputItems.add(processItem(item))
}
pass++
fraction += fractionPortion
},
EmptyProgressIndicator()
)
return outputItems
}
override fun <T> process(action: () -> T): T {
throw AbstractMethodError("Should not be called for old J2K")
}
override fun updateState(fileIndex: Int?, phase: Int, description: String) {
throw AbstractMethodError("Should not be called for old J2K")
}
override fun updateState(
phase: Int,
subPhase: Int,
subPhaseCount: Int,
fileIndex: Int?,
description: String
) {
error("Should not be called for old J2K")
}
}
class ProgressPortionReporter(
indicator: ProgressIndicator,
private val start: Double,
private val portion: Double
) : J2KDelegatingProgressIndicator(indicator) {
init {
fraction = 0.0
}
override fun start() {
fraction = 0.0
}
override fun stop() {
fraction = portion
}
override fun setFraction(fraction: Double) {
super.setFraction(start + (fraction * portion))
}
override fun getFraction(): Double {
return (super.getFraction() - start) / portion
}
override fun setText(text: String?) {
}
override fun setText2(text: String?) {
}
}
// Copied from com.intellij.ide.util.DelegatingProgressIndicator
open class J2KDelegatingProgressIndicator(indicator: ProgressIndicator) : WrappedProgressIndicator, StandardProgressIndicator {
protected val delegate: ProgressIndicator = indicator
override fun start() = delegate.start()
override fun stop() = delegate.stop()
override fun isRunning() = delegate.isRunning
override fun cancel() = delegate.cancel()
override fun isCanceled() = delegate.isCanceled
override fun setText(text: String?) {
delegate.text = text
}
override fun getText() = delegate.text
override fun setText2(text: String?) {
delegate.text2 = text
}
override fun getText2() = delegate.text2
override fun getFraction() = delegate.fraction
override fun setFraction(fraction: Double) {
delegate.fraction = fraction
}
override fun pushState() = delegate.pushState()
override fun popState() = delegate.popState()
override fun isModal() = delegate.isModal
override fun getModalityState() = delegate.modalityState
override fun setModalityProgress(modalityProgress: ProgressIndicator?) {
delegate.setModalityProgress(modalityProgress)
}
override fun isIndeterminate() = delegate.isIndeterminate
override fun setIndeterminate(indeterminate: Boolean) {
delegate.isIndeterminate = indeterminate
}
override fun checkCanceled() = delegate.checkCanceled()
override fun getOriginalProgressIndicator() = delegate
override fun isPopupWasShown() = delegate.isPopupWasShown
override fun isShowing() = delegate.isShowing
}
|
apache-2.0
|
186e77d5d85ee04fc894bd638adbf40c
| 36.554795 | 158 | 0.665126 | 5.149656 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/idea/tests/testData/intentions/convertTryFinallyToUseCall/notCloseableClose2.kt
|
8
|
439
|
// IS_APPLICABLE: false
// WITH_STDLIB
import java.io.Closeable
class Resource : Closeable {
fun doStuff(): Unit = println()
@Deprecated(level = DeprecationLevel.HIDDEN, message = "deprecated")
override fun close(): Unit = close(1)
fun close(status: Int = 0): Unit = println(status)
}
fun main() {
val resource = Resource()
<caret>try {
resource.doStuff()
} finally {
resource.close()
}
}
|
apache-2.0
|
6e4adb6ca77b9c984b1be2da583e72b6
| 22.105263 | 72 | 0.626424 | 3.817391 | false | false | false | false |
GunoH/intellij-community
|
plugins/gradle/java/src/config/GradleFileType.kt
|
2
|
1508
|
// 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.plugins.gradle.config
import com.intellij.openapi.fileTypes.FileTypeRegistry
import com.intellij.openapi.fileTypes.LanguageFileType
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiFile
import org.jetbrains.plugins.gradle.util.GradleBundle
import org.jetbrains.plugins.gradle.util.GradleConstants
import org.jetbrains.plugins.groovy.GroovyEnabledFileType
import org.jetbrains.plugins.groovy.GroovyLanguage
import javax.swing.Icon
object GradleFileType : LanguageFileType(GroovyLanguage, true), GroovyEnabledFileType {
override fun getIcon(): Icon = icons.GradleIcons.GradleFile
override fun getName(): String = "Gradle"
override fun getDescription(): String = GradleBundle.message("gradle.filetype.description")
override fun getDisplayName(): String = GradleBundle.message("gradle.filetype.display.name")
override fun getDefaultExtension(): String = GradleConstants.EXTENSION
@JvmStatic
fun isGradleFile(file: VirtualFile) = FileTypeRegistry.getInstance().isFileOfType(file, GradleFileType)
@JvmStatic
fun isGradleFile(file: PsiFile): Boolean {
val virtualFile = file.originalFile.virtualFile ?: return false
return isGradleFile(virtualFile)
}
}
fun VirtualFile?.isGradleFile() = this != null && GradleFileType.isGradleFile(this)
fun PsiFile?.isGradleFile() = this != null && GradleFileType.isGradleFile(this)
|
apache-2.0
|
5e86de17f5b8048be633a2792627c05e
| 46.125 | 120 | 0.80504 | 4.528529 | false | false | false | false |
danesc87/wifi-discloser
|
app/src/main/java/com/nano_bytes/wifi_discloser/adapter/AboutAdapter.kt
|
1
|
1362
|
package com.nano_bytes.wifi_discloser.adapter
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.nano_bytes.wifi_discloser.R
class AboutViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){
var aboutTitle: TextView
var aboutDesc: TextView
init {
aboutTitle = itemView.findViewById(R.id.aboutTitle) as TextView
aboutDesc = itemView.findViewById(R.id.aboutDesc) as TextView
}
}
class AboutAdapter(private val keysArray: ArrayList<String>, private val mapa:
LinkedHashMap<String, String>, private val mContext: Context): RecyclerView.Adapter<AboutViewHolder>(){
private val inflater: LayoutInflater
init {
inflater = LayoutInflater.from(mContext)
}
override fun onBindViewHolder(holder: AboutViewHolder, position: Int) {
holder.aboutTitle.text = keysArray.get(position)
holder.aboutDesc.text = mapa.get(keysArray.get(position))
}
override fun getItemCount(): Int {
return mapa.size
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): AboutViewHolder {
val itemView = inflater.inflate(R.layout.row_about,parent,false)
return AboutViewHolder(itemView)
}
}
|
gpl-3.0
|
3754aab7d13eda8805bc731234d9173b
| 29.288889 | 103 | 0.740822 | 4.229814 | false | false | false | false |
sewerk/Bill-Calculator
|
app/src/main/java/pl/srw/billcalculator/history/HelpHandler.kt
|
1
|
1770
|
package pl.srw.billcalculator.history
import android.app.Activity
import android.content.res.Resources
import android.support.v7.widget.Toolbar
import android.view.View
import com.getkeepsafe.taptargetview.TapTarget
import com.getkeepsafe.taptargetview.TapTargetSequence
import pl.srw.billcalculator.R
import pl.srw.billcalculator.util.analytics.ContentType
import pl.srw.billcalculator.util.analytics.Analytics
import javax.inject.Inject
/**
* Shows help screen for drawer activity
*/
class HelpHandler @Inject constructor(res: Resources) {
private val fabDesc: String = res.getString(R.string.main_help_fab_desc)
private val listDesc: String = res.getString(R.string.main_help_list_desc)
private val swipeDesc: String = res.getString(R.string.main_help_swipe_delete_desc)
private val menuDesc: String = res.getString(R.string.main_help_menu_desc)
private val optionsDesc: String = res.getString(R.string.main_help_options_desc)
fun show(activity: Activity) {
Analytics.contentView(ContentType.HISTORY_HELP)
val toolbar: Toolbar = activity.findViewById(R.id.toolbar)
val fab: View = activity.findViewById(R.id.fab)
val swipeIcon: View = activity.findViewById(R.id.swipe_delete_history_icon)
TapTargetSequence(activity)
.targets(
TapTarget.forView(fab, fabDesc).transparentTarget(true),
TapTarget.forView(swipeIcon, listDesc, swipeDesc),
TapTarget.forToolbarNavigationIcon(toolbar, menuDesc),
TapTarget.forToolbarOverflow(toolbar, optionsDesc)
)
.continueOnCancel(true)
.considerOuterCircleCanceled(true)
.start()
}
}
|
mit
|
ecae4ee93a11fcfe4de6029372953da1
| 40.162791 | 87 | 0.70339 | 4.15493 | false | false | false | false |
jwren/intellij-community
|
platform/platform-impl/src/com/intellij/platform/PlatformProjectOpenProcessor.kt
|
3
|
11067
|
// 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.platform
import com.intellij.ide.impl.OpenProjectTask
import com.intellij.ide.impl.ProjectUtilCore
import com.intellij.ide.impl.TrustedPaths
import com.intellij.ide.lightEdit.LightEditService
import com.intellij.ide.util.PsiNavigationSupport
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ex.ProjectManagerEx
import com.intellij.openapi.roots.ModuleRootModificationUtil
import com.intellij.openapi.startup.StartupManager
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.projectImport.ProjectAttachProcessor
import com.intellij.projectImport.ProjectOpenProcessor
import com.intellij.projectImport.ProjectOpenedCallback
import org.jetbrains.annotations.ApiStatus
import java.nio.file.Files
import java.nio.file.Path
import java.util.*
private val LOG = logger<PlatformProjectOpenProcessor>()
private val EP_NAME = ExtensionPointName<DirectoryProjectConfigurator>("com.intellij.directoryProjectConfigurator")
class PlatformProjectOpenProcessor : ProjectOpenProcessor(), CommandLineProjectOpenProcessor {
enum class Option {
FORCE_NEW_FRAME,
@Suppress("unused")
TEMP_PROJECT
}
companion object {
@JvmField
val PROJECT_OPENED_BY_PLATFORM_PROCESSOR: Key<Boolean> = Key.create("PROJECT_OPENED_BY_PLATFORM_PROCESSOR")
@JvmField
val PROJECT_CONFIGURED_BY_PLATFORM_PROCESSOR: Key<Boolean> = Key.create("PROJECT_CONFIGURED_BY_PLATFORM_PROCESSOR")
@JvmField
val PROJECT_NEWLY_OPENED: Key<Boolean> = Key.create("PROJECT_NEWLY_OPENED")
@JvmField
val PROJECT_LOADED_FROM_CACHE_BUT_HAS_NO_MODULES: Key<Boolean> = Key.create("PROJECT_LOADED_FROM_CACHE_BUT_HAS_NO_MODULES")
fun Project.isOpenedByPlatformProcessor(): Boolean = getUserData(PROJECT_OPENED_BY_PLATFORM_PROCESSOR) == true
fun Project.isConfiguredByPlatformProcessor(): Boolean = getUserData(PROJECT_CONFIGURED_BY_PLATFORM_PROCESSOR) == true
fun Project.isNewProject(): Boolean = getUserData(PROJECT_NEWLY_OPENED) == true
fun Project.isLoadedFromCacheButHasNoModules(): Boolean = getUserData(PROJECT_LOADED_FROM_CACHE_BUT_HAS_NO_MODULES) == true
@JvmStatic
fun getInstance() = getInstanceIfItExists()!!
@JvmStatic
fun getInstanceIfItExists(): PlatformProjectOpenProcessor? {
for (processor in EXTENSION_POINT_NAME.extensionList) {
if (processor is PlatformProjectOpenProcessor) {
return processor
}
}
return null
}
@JvmStatic
@ApiStatus.ScheduledForRemoval
@Deprecated("Use {@link #doOpenProject(Path, OpenProjectTask)} ")
fun doOpenProject(virtualFile: VirtualFile,
projectToClose: Project?,
line: Int,
callback: ProjectOpenedCallback?,
options: EnumSet<Option>): Project? {
val openProjectOptions = OpenProjectTask(forceOpenInNewFrame = Option.FORCE_NEW_FRAME in options,
projectToClose = projectToClose,
callback = callback,
runConfigurators = callback != null,
line = line)
return doOpenProject(Path.of(virtualFile.path), openProjectOptions)
}
@ApiStatus.Internal
@JvmStatic
fun createTempProjectAndOpenFile(file: Path, options: OpenProjectTask): Project? {
val dummyProjectName = file.fileName.toString()
val baseDir = FileUtilRt.createTempDirectory(dummyProjectName, null, true).toPath()
val copy = options.copy(isNewProject = true, projectName = dummyProjectName, runConfigurators = true, preparedToOpen = { module ->
// adding content root for chosen (single) file
ModuleRootModificationUtil.updateModel(module) { model ->
val entries = model.contentEntries
// remove custom content entry created for temp directory
if (entries.size == 1) {
model.removeContentEntry(entries[0])
}
model.addContentEntry(VfsUtilCore.pathToUrl(file.toString()))
}
})
TrustedPaths.getInstance().setProjectPathTrusted(baseDir, true)
val project = ProjectManagerEx.getInstanceEx().openProject(baseDir, copy) ?: return null
openFileFromCommandLine(project, file, copy.line, copy.column)
return project
}
@ApiStatus.Internal
@JvmStatic
fun doOpenProject(file: Path, originalOptions: OpenProjectTask): Project? {
LOG.info("Opening $file")
if (Files.isDirectory(file)) {
return ProjectManagerEx.getInstanceEx().openProject(file, createOptionsToOpenDotIdeaOrCreateNewIfNotExists(file, projectToClose = null))
}
var options = originalOptions
if (LightEditService.getInstance() != null) {
if (LightEditService.getInstance().isForceOpenInLightEditMode) {
val lightEditProject = LightEditService.getInstance().openFile(file, false)
if (lightEditProject != null) {
return lightEditProject
}
}
}
var baseDirCandidate = file.parent
while (baseDirCandidate != null && !Files.exists(baseDirCandidate.resolve(Project.DIRECTORY_STORE_FOLDER))) {
baseDirCandidate = baseDirCandidate.parent
}
val baseDir: Path
// no reasonable directory -> create new temp one or use parent
if (baseDirCandidate == null) {
LOG.info("No project directory found")
if (LightEditService.getInstance() != null) {
if (LightEditService.getInstance().isLightEditEnabled && !LightEditService.getInstance().isPreferProjectMode) {
val lightEditProject = LightEditService.getInstance().openFile(file, true)
if (lightEditProject != null) {
return lightEditProject
}
}
}
if (Registry.`is`("ide.open.file.in.temp.project.dir")) {
return createTempProjectAndOpenFile(file, options)
}
baseDir = file.parent
options = options.copy(isNewProject = !Files.isDirectory(baseDir.resolve(Project.DIRECTORY_STORE_FOLDER)))
}
else {
baseDir = baseDirCandidate
LOG.info("Project directory found: $baseDir")
}
val project = ProjectManagerEx.getInstanceEx().openProject(baseDir, if (baseDir == file) options else options.copy(projectName = file.fileName.toString()))
if (project != null && file != baseDir) {
openFileFromCommandLine(project, file, options.line, options.column)
}
return project
}
@JvmStatic
fun runDirectoryProjectConfigurators(baseDir: Path, project: Project, newProject: Boolean): Module {
project.putUserData(PROJECT_CONFIGURED_BY_PLATFORM_PROCESSOR, true)
val moduleRef = Ref<Module>()
val virtualFile = ProjectUtilCore.getFileAndRefresh(baseDir)!!
EP_NAME.forEachExtensionSafe { configurator ->
fun task() {
configurator.configureProject(project, virtualFile, moduleRef, newProject)
}
if (configurator.isEdtRequired) {
ApplicationManager.getApplication().invokeAndWait {
task()
}
}
else {
task()
}
}
val module = moduleRef.get()
if (module == null) {
LOG.error("No extension configured a module for $baseDir; extensions = ${EP_NAME.extensionList}")
}
return module
}
@JvmStatic
fun attachToProject(project: Project, projectDir: Path, callback: ProjectOpenedCallback?): Boolean =
ProjectAttachProcessor.EP_NAME.findFirstSafe { processor -> processor.attachToProject(project, projectDir, callback) } != null
/**
* If a project file in IDEA format (`.idea` directory or `.ipr` file) exists, opens it and runs configurators if no modules.
* Otherwise, creates a new project using the default project template and runs configurators (something that creates a module)
* (at the moment of creation project file in IDEA format will be removed if any).
* <p>
* This method must be not used in tests.
*
* See `OpenProjectTest`.
*/
@ApiStatus.Internal
@JvmStatic
fun createOptionsToOpenDotIdeaOrCreateNewIfNotExists(projectDir: Path, projectToClose: Project?): OpenProjectTask =
OpenProjectTask(runConfigurators = true,
isNewProject = !ProjectUtilCore.isValidProjectPath(projectDir),
projectToClose = projectToClose,
isRefreshVfsNeeded = !ApplicationManager.getApplication().isUnitTestMode, // doesn't make sense to refresh
useDefaultProjectAsTemplate = true)
}
override fun canOpenProject(file: VirtualFile) = file.isDirectory
override fun isProjectFile(file: VirtualFile) = false
override fun lookForProjectsInDirectory() = false
override fun doOpenProject(virtualFile: VirtualFile, projectToClose: Project?, forceOpenInNewFrame: Boolean): Project? {
val baseDir = virtualFile.toNioPath()
return doOpenProject(baseDir, createOptionsToOpenDotIdeaOrCreateNewIfNotExists(baseDir, projectToClose).copy(forceOpenInNewFrame = forceOpenInNewFrame))
}
override fun openProjectAndFile(file: Path, line: Int, column: Int, tempProject: Boolean): Project? =
// force open in a new frame if temp project
if (tempProject) {
createTempProjectAndOpenFile(file, OpenProjectTask(forceOpenInNewFrame = true, line = line, column = column))
}
else {
doOpenProject(file, OpenProjectTask(line = line, column = column))
}
@Suppress("HardCodedStringLiteral")
override fun getName() = "text editor"
}
private fun openFileFromCommandLine(project: Project, file: Path, line: Int, column: Int) {
StartupManager.getInstance(project).runAfterOpened {
ApplicationManager.getApplication().invokeLater(Runnable {
if (project.isDisposed || !Files.exists(file)) {
return@Runnable
}
val virtualFile = ProjectUtilCore.getFileAndRefresh(file) ?: return@Runnable
val navigatable = if (line > 0) {
OpenFileDescriptor(project, virtualFile, line - 1, column.coerceAtLeast(0))
}
else {
PsiNavigationSupport.getInstance().createNavigatable(project, virtualFile, -1)
}
navigatable.navigate(true)
}, ModalityState.NON_MODAL, project.disposed)
}
}
|
apache-2.0
|
6a4cfb5bde48c8e47910f91f55cd0acd
| 41.72973 | 161 | 0.699377 | 4.953894 | false | true | false | false |
vovagrechka/fucking-everything
|
alraune/alraune/src/main/java/bolone/rp/BoloneRP_GetOperations.kt
|
1
|
1894
|
package bolone.rp
import alraune.*
import alraune.entity.*
import aplight.GelNew
import bolone.BoSite
import vgrechka.*
class BoloneRP_GetOperations(val p: Params) : Dancer<BoloneRP_GetOperations.Result> {
@GelNew class Params {
var orderID: String? = null
var userID: String? = null
var page by place<Int>()
var pageSize by place<Int>()
var ordering by place<Ordering>()
}
class Result(
val pages: Int,
val page: Int,
val items: List<Item>)
class Item(
val operation: Operation,
val time: String,
val site: BoSite
)
override fun dance(): Result {
clog("p", freakingToStringKotlin(p))
// rbBitch("I don't want to serve assholes like you, OK?")
val boobs = PaginationBoobs(UsualPaginationPussy(
itemClass = Operation::class,
pageSize = p.pageSize,
table = tableFor(Operation::class),
shitIntoWhere = {q->
val m = Operation.Meta
run {
var act by once<() -> Unit>()
fun fart(id: String?, col: String) {
if (id != null)
act = {q.text("and $col =", id.toLong())}
}
fart(p.orderID, m.orderId)
fart(p.userID, m.userId)
act()
}
},
shitOrderBy = {shitOrderById(it, p.ordering)}
)).also {
it.fart(_page = p.page)
}
return Result(
pages = boobs.pages,
page = boobs.page,
items = boobs.items.map {Item(
operation = it,
time = TimePile.kievTimeString(it.data.time),
site = BoSite.from(it.data.site)
)}
)
}
}
|
apache-2.0
|
65affc7c22e38ad99823d5088b5f292a
| 21.282353 | 85 | 0.487328 | 4.344037 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/idea/tests/testData/refactoring/copy/copyMultipleDeclarations/before/foo/test.kt
|
13
|
367
|
package foo
class <caret>A {
init {
val a: A = A()
val x: X = X()
b()
c
}
}
class X {
init {
val a: A = A()
val x: X = X()
b()
c
}
}
fun <caret>b() {
val a: A = A()
val x: X = X()
b()
c
}
val <caret>c: Int get() {
val a: A = A()
val x: X = X()
b()
c
}
|
apache-2.0
|
991177396faba42af177847a7ca09176
| 10.151515 | 25 | 0.313351 | 2.65942 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/conversion/copy/ConvertJavaCopyPasteProcessor.kt
|
1
|
14623
|
// 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.conversion.copy
import com.intellij.codeInsight.editorActions.CopyPastePostProcessor
import com.intellij.codeInsight.editorActions.TextBlockTransferableData
import com.intellij.openapi.diagnostic.ControlFlowException
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.RangeMarker
import com.intellij.openapi.module.Module
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.util.ThrowableComputable
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.*
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.actions.JavaToKotlinAction
import org.jetbrains.kotlin.idea.caches.resolve.resolveImportReference
import org.jetbrains.kotlin.idea.codeInsight.KotlinCopyPasteReferenceProcessor
import org.jetbrains.kotlin.idea.codeInsight.KotlinReferenceData
import org.jetbrains.kotlin.idea.configuration.ExperimentalFeatures
import org.jetbrains.kotlin.idea.core.util.range
import org.jetbrains.kotlin.idea.core.util.start
import org.jetbrains.kotlin.idea.editor.KotlinEditorOptions
import org.jetbrains.kotlin.idea.j2k.IdeaJavaToKotlinServices
import org.jetbrains.kotlin.idea.statistics.ConversionType
import org.jetbrains.kotlin.idea.statistics.J2KFusCollector
import org.jetbrains.kotlin.idea.util.ImportInsertHelper
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.idea.util.module
import org.jetbrains.kotlin.j2k.*
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import java.awt.datatransfer.Transferable
import kotlin.system.measureTimeMillis
class ConvertJavaCopyPasteProcessor : CopyPastePostProcessor<TextBlockTransferableData>() {
@Suppress("PrivatePropertyName")
private val LOG = Logger.getInstance(ConvertJavaCopyPasteProcessor::class.java)
override fun extractTransferableData(content: Transferable): List<TextBlockTransferableData> {
try {
if (content.isDataFlavorSupported(CopiedJavaCode.DATA_FLAVOR)) {
return listOf(content.getTransferData(CopiedJavaCode.DATA_FLAVOR) as TextBlockTransferableData)
}
} catch (e: Throwable) {
if (e is ControlFlowException) throw e
LOG.error(e)
}
return listOf()
}
override fun collectTransferableData(
file: PsiFile,
editor: Editor,
startOffsets: IntArray,
endOffsets: IntArray
): List<TextBlockTransferableData> {
if (file !is PsiJavaFile) return listOf()
return listOf(CopiedJavaCode(file.getText()!!, startOffsets, endOffsets))
}
override fun processTransferableData(
project: Project,
editor: Editor,
bounds: RangeMarker,
caretOffset: Int,
indented: Ref<in Boolean>,
values: List<TextBlockTransferableData>
) {
if (DumbService.getInstance(project).isDumb) return
if (!KotlinEditorOptions.getInstance().isEnableJavaToKotlinConversion) return
val data = values.single() as CopiedJavaCode
val document = editor.document
val targetFile = PsiDocumentManager.getInstance(project).getPsiFile(document) as? KtFile ?: return
val useNewJ2k = checkUseNewJ2k(targetFile)
val targetModule = targetFile.module
if (isNoConversionPosition(targetFile, bounds.startOffset)) return
data class Result(
val text: String?,
val referenceData: Collection<KotlinReferenceData>,
val explicitImports: Set<FqName>,
val converterContext: ConverterContext?
)
val dataForConversion = DataForConversion.prepare(data, project)
fun doConversion(): Result {
val result = dataForConversion.elementsAndTexts.convertCodeToKotlin(project, targetModule, useNewJ2k)
val referenceData = buildReferenceData(result.text, result.parseContext, dataForConversion.importsAndPackage, targetFile)
val text = if (result.textChanged) result.text else null
return Result(text, referenceData, result.importsToAdd, result.converterContext)
}
fun insertImports(
bounds: TextRange,
referenceData: Collection<KotlinReferenceData>,
explicitImports: Collection<FqName>
): TextRange? {
if (referenceData.isEmpty() && explicitImports.isEmpty()) return bounds
PsiDocumentManager.getInstance(project).commitDocument(document)
val rangeMarker = document.createRangeMarker(bounds)
rangeMarker.isGreedyToLeft = true
rangeMarker.isGreedyToRight = true
KotlinCopyPasteReferenceProcessor().processReferenceData(project, editor, targetFile, bounds.start, referenceData.toTypedArray())
runWriteAction {
explicitImports.forEach { fqName ->
targetFile.resolveImportReference(fqName).firstOrNull()?.let {
ImportInsertHelper.getInstance(project).importDescriptor(targetFile, it)
}
}
}
return rangeMarker.range
}
var conversionResult: Result? = null
fun doConversionAndInsertImportsIfUnchanged(): Boolean {
conversionResult = doConversion()
if (conversionResult!!.text != null) return false
insertImports(
bounds.range ?: return true,
conversionResult!!.referenceData,
conversionResult!!.explicitImports
)
return true
}
val textLength = data.startOffsets.indices.sumBy { data.endOffsets[it] - data.startOffsets[it] }
// if the text to convert is short enough, try to do conversion without permission from user and skip the dialog if nothing converted
if (textLength < 1000 && doConversionAndInsertImportsIfUnchanged()) return
fun convert() {
if (conversionResult == null && doConversionAndInsertImportsIfUnchanged()) return
val (text, referenceData, explicitImports) = conversionResult!!
text!! // otherwise we should get true from doConversionAndInsertImportsIfUnchanged and return above
val boundsAfterReplace = runWriteAction {
val startOffset = bounds.startOffset
document.replaceString(startOffset, bounds.endOffset, text)
val endOffsetAfterCopy = startOffset + text.length
editor.caretModel.moveToOffset(endOffsetAfterCopy)
TextRange(startOffset, endOffsetAfterCopy)
}
val newBounds = insertImports(boundsAfterReplace, referenceData, explicitImports)
PsiDocumentManager.getInstance(project).commitDocument(document)
runPostProcessing(project, targetFile, newBounds, conversionResult?.converterContext, useNewJ2k)
conversionPerformed = true
}
if (confirmConvertJavaOnPaste(project, isPlainText = false)) {
val conversionTime = measureTimeMillis {
convert()
}
J2KFusCollector.log(
ConversionType.PSI_EXPRESSION,
ExperimentalFeatures.NewJ2k.isEnabled,
conversionTime,
dataForConversion.elementsAndTexts.linesCount(),
filesCount = 1
)
}
}
private fun buildReferenceData(
text: String,
parseContext: ParseContext,
importsAndPackage: String,
targetFile: KtFile
): Collection<KotlinReferenceData> {
var blockStart: Int
var blockEnd: Int
val fileText = buildString {
append(importsAndPackage)
val (contextPrefix, contextSuffix) = when (parseContext) {
ParseContext.CODE_BLOCK -> "fun ${generateDummyFunctionName(text)}() {\n" to "\n}"
ParseContext.TOP_LEVEL -> "" to ""
}
append(contextPrefix)
blockStart = length
append(text)
blockEnd = length
append(contextSuffix)
}
val dummyFile = KtPsiFactory(targetFile.project).createAnalyzableFile("dummy.kt", fileText, targetFile)
val startOffset = blockStart
val endOffset = blockEnd
return KotlinCopyPasteReferenceProcessor().collectReferenceData(dummyFile, intArrayOf(startOffset), intArrayOf(endOffset)).map {
it.copy(startOffset = it.startOffset - startOffset, endOffset = it.endOffset - startOffset)
}
}
private fun generateDummyFunctionName(convertedCode: String): String {
var i = 0
while (true) {
val name = "dummy$i"
if (convertedCode.indexOf(name) < 0) return name
i++
}
}
companion object {
@get:TestOnly
var conversionPerformed: Boolean = false
}
}
internal class ConversionResult(
val text: String,
val parseContext: ParseContext,
val importsToAdd: Set<FqName>,
val textChanged: Boolean,
val converterContext: ConverterContext?
)
internal fun ElementAndTextList.convertCodeToKotlin(project: Project, targetModule: Module?, useNewJ2k: Boolean): ConversionResult {
val converter =
J2kConverterExtension.extension(useNewJ2k).createJavaToKotlinConverter(
project,
targetModule,
ConverterSettings.defaultSettings,
IdeaJavaToKotlinServices
)
val inputElements = toList().filterIsInstance<PsiElement>()
val (results, _, converterContext) =
ProgressManager.getInstance().runProcessWithProgressSynchronously(
ThrowableComputable<Result, Exception> {
runReadAction { converter.elementsToKotlin(inputElements) }
},
JavaToKotlinAction.title,
false,
project
)
val importsToAdd = LinkedHashSet<FqName>()
var resultIndex = 0
val convertedCodeBuilder = StringBuilder()
val originalCodeBuilder = StringBuilder()
var parseContext: ParseContext? = null
this.process(object : ElementsAndTextsProcessor {
override fun processElement(element: PsiElement) {
val originalText = element.text
originalCodeBuilder.append(originalText)
val result = results[resultIndex++]
if (result != null) {
convertedCodeBuilder.append(result.text)
if (parseContext == null) { // use parse context of the first converted element as parse context for the whole text
parseContext = result.parseContext
}
importsToAdd.addAll(result.importsToAdd)
} else { // failed to convert element to Kotlin, insert "as is"
convertedCodeBuilder.append(originalText)
}
}
override fun processText(string: String) {
originalCodeBuilder.append(string)
convertedCodeBuilder.append(string)
}
})
val convertedCode = convertedCodeBuilder.toString()
val originalCode = originalCodeBuilder.toString()
return ConversionResult(
convertedCode,
parseContext ?: ParseContext.CODE_BLOCK,
importsToAdd,
convertedCode != originalCode,
converterContext
)
}
internal fun isNoConversionPosition(file: KtFile, offset: Int): Boolean {
if (offset == 0) return false
val token = file.findElementAt(offset - 1) ?: return true
if (token !is PsiWhiteSpace && token.endOffset != offset) return true // pasting into the middle of token
for (element in token.parentsWithSelf) {
when (element) {
is PsiComment -> return element.node.elementType == KtTokens.EOL_COMMENT || offset != element.endOffset
is KtStringTemplateEntryWithExpression -> return false
is KtStringTemplateExpression -> return true
}
}
return false
}
internal fun confirmConvertJavaOnPaste(project: Project, isPlainText: Boolean): Boolean {
if (KotlinEditorOptions.getInstance().isDonTShowConversionDialog) return true
val dialog = KotlinPasteFromJavaDialog(project, isPlainText)
dialog.show()
return dialog.isOK
}
fun ElementAndTextList.linesCount() =
toList()
.filterIsInstance<PsiElement>()
.sumBy { StringUtil.getLineBreakCount(it.text) }
fun checkUseNewJ2k(targetFile: KtFile): Boolean {
if (targetFile is KtCodeFragment) return false
return ExperimentalFeatures.NewJ2k.isEnabled
}
fun runPostProcessing(
project: Project,
file: KtFile,
bounds: TextRange?,
converterContext: ConverterContext?,
useNewJ2k: Boolean
) {
val postProcessor = J2kConverterExtension.extension(useNewJ2k).createPostProcessor(formatCode = true)
if (useNewJ2k) {
ProgressManager.getInstance().runProcessWithProgressSynchronously(
{
val processor =
J2kConverterExtension.extension(useNewJ2k).createWithProgressProcessor(
ProgressManager.getInstance().progressIndicator!!,
emptyList(),
postProcessor.phasesCount
)
AfterConversionPass(project, postProcessor)
.run(
file,
converterContext,
bounds
) { phase, description ->
processor.updateState(0, phase, description)
}
},
@Suppress("DialogTitleCapitalization") KotlinBundle.message("copy.text.convert.java.to.kotlin.title"),
true,
project
)
} else {
AfterConversionPass(project, postProcessor)
.run(
file,
converterContext,
bounds
)
}
}
|
apache-2.0
|
5d05c389df9bb79eb7489ee46612f343
| 37.484211 | 158 | 0.670109 | 5.397933 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/gradle/gradle-java/tests/test/org/jetbrains/kotlin/idea/codeInsight/gradle/GradleTestRunConfigurationCustomTest.kt
|
5
|
3049
|
// 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.codeInsight.gradle
import com.intellij.platform.externalSystem.testFramework.ExternalSystemTestCase
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.testFramework.runInEdtAndWait
import org.jetbrains.kotlin.gradle.textWithoutTags
import org.jetbrains.kotlin.idea.gradleJava.run.KotlinJvmTestClassGradleConfigurationProducer
import org.jetbrains.kotlin.idea.gradleJava.run.KotlinJvmTestMethodGradleConfigurationProducer
import org.jetbrains.kotlin.idea.run.getConfiguration
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.plugins.gradle.execution.test.runner.TestClassGradleConfigurationProducer
import org.jetbrains.plugins.gradle.execution.test.runner.TestMethodGradleConfigurationProducer
import org.jetbrains.plugins.gradle.tooling.annotation.TargetVersions
import org.junit.Test
class GradleTestRunConfigurationCustomTest16 : KotlinGradleImportingTestCase() {
@Test
@TargetVersions("4.7+")
fun testPreferredConfigurations() {
val files = importProjectFromTestData()
runInEdtAndWait {
runReadAction {
val javaFile = files.first { it.name == "MyTest.java" }
val kotlinFile = files.first { it.name == "MyKotlinTest.kt" }
val javaClassConfiguration = getConfiguration(javaFile, myProject, "MyTest")
assert(javaClassConfiguration.isProducedBy(TestClassGradleConfigurationProducer::class.java))
assert(javaClassConfiguration.configuration.name == "MyTest")
val javaMethodConfiguration = getConfiguration(javaFile, myProject, "testA")
assert(javaMethodConfiguration.isProducedBy(TestMethodGradleConfigurationProducer::class.java))
assert(javaMethodConfiguration.configuration.name == "MyTest.testA")
val kotlinClassConfiguration = getConfiguration(kotlinFile, myProject, "MyKotlinTest")
assert(kotlinClassConfiguration.isProducedBy(KotlinJvmTestClassGradleConfigurationProducer::class.java))
assert(kotlinClassConfiguration.configuration.name == "MyKotlinTest")
val kotlinFunctionConfiguration = getConfiguration(kotlinFile, myProject, "testA")
assert(kotlinFunctionConfiguration.isProducedBy(KotlinJvmTestMethodGradleConfigurationProducer::class.java))
assert(kotlinFunctionConfiguration.configuration.name == "MyKotlinTest.testA")
}
}
}
override fun testDataDirName(): String {
return "testRunConfigurations"
}
override fun createProjectSubFile(relativePath: String, content: String): VirtualFile {
val file = createProjectSubFile(relativePath)
ExternalSystemTestCase.setFileContent(file, textWithoutTags(content), /* advanceStamps = */ false)
return file
}
}
|
apache-2.0
|
87e51fe7df12225b98c4610f137b0f74
| 52.508772 | 158 | 0.75369 | 5.63586 | false | true | false | false |
ianhanniballake/muzei
|
android-client-common/src/main/java/com/google/android/apps/muzei/provider/MuzeiProvider.kt
|
1
|
11720
|
/*
* Copyright 2014 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.
*/
@file:Suppress("DEPRECATION")
package com.google.android.apps.muzei.provider
import android.content.ContentProvider
import android.content.ContentUris
import android.content.ContentValues
import android.content.UriMatcher
import android.database.Cursor
import android.database.DatabaseUtils
import android.database.MatrixCursor
import android.net.Uri
import android.os.Binder
import android.os.ParcelFileDescriptor
import android.provider.BaseColumns
import android.util.Log
import androidx.core.os.UserManagerCompat
import androidx.sqlite.db.SupportSQLiteQueryBuilder
import com.google.android.apps.muzei.api.MuzeiContract
import com.google.android.apps.muzei.room.MuzeiDatabase
import com.google.android.apps.muzei.sync.ProviderManager
import kotlinx.coroutines.runBlocking
import net.nurik.roman.muzei.androidclientcommon.BuildConfig
import java.io.FileNotFoundException
/**
* Provides access to a the most recent artwork
*/
class MuzeiProvider : ContentProvider() {
companion object {
private const val TAG = "MuzeiProvider"
/**
* The incoming URI matches the ARTWORK URI pattern
*/
private const val ARTWORK = 1
/**
* The incoming URI matches the ARTWORK ID URI pattern
*/
private const val ARTWORK_ID = 2
/**
* The incoming URI matches the SOURCE URI pattern
*/
private const val SOURCES = 3
/**
* The incoming URI matches the SOURCE ID URI pattern
*/
private const val SOURCE_ID = 4
/**
* A UriMatcher instance
*/
private val uriMatcher = UriMatcher(UriMatcher.NO_MATCH).apply {
addURI(MuzeiContract.AUTHORITY, MuzeiContract.Artwork.TABLE_NAME,
ARTWORK)
addURI(MuzeiContract.AUTHORITY, "${MuzeiContract.Artwork.TABLE_NAME}/#",
ARTWORK_ID)
addURI(MuzeiContract.AUTHORITY, MuzeiContract.Sources.TABLE_NAME,
SOURCES)
addURI(MuzeiContract.AUTHORITY, "${MuzeiContract.Sources.TABLE_NAME}/#",
SOURCE_ID)
}
}
/**
* An identity all column projection mapping for Artwork
*/
private val allArtworkColumnProjectionMap = mapOf(
BaseColumns._ID to "artwork._id",
"${MuzeiContract.Artwork.TABLE_NAME}.${BaseColumns._ID}" to "artwork._id",
MuzeiContract.Artwork.COLUMN_NAME_PROVIDER_AUTHORITY to
"providerAuthority AS sourceComponentName",
MuzeiContract.Artwork.COLUMN_NAME_IMAGE_URI to "imageUri",
MuzeiContract.Artwork.COLUMN_NAME_TITLE to "title",
MuzeiContract.Artwork.COLUMN_NAME_BYLINE to "byline",
MuzeiContract.Artwork.COLUMN_NAME_ATTRIBUTION to "attribution",
"token" to "NULL AS token",
"viewIntent" to "NULL AS viewIntent",
"metaFont" to "\"\" as metaFont",
MuzeiContract.Artwork.COLUMN_NAME_DATE_ADDED to "date_added",
"${MuzeiContract.Sources.TABLE_NAME}.${BaseColumns._ID}" to
"0 AS \"sources._id\"",
MuzeiContract.Sources.COLUMN_NAME_AUTHORITY to
"providerAuthority AS component_name",
"selected" to "1 AS selected",
MuzeiContract.Sources.COLUMN_NAME_DESCRIPTION to "\"\" AS description",
"network" to "0 AS network",
MuzeiContract.Sources.COLUMN_NAME_SUPPORTS_NEXT_ARTWORK_COMMAND to
"1 AS supports_next_artwork",
"commands" to "NULL AS commands"
)
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int {
throw UnsupportedOperationException("Deletes are not supported")
}
override fun getType(uri: Uri): String? {
// Chooses the MIME type based on the incoming URI pattern
return when (uriMatcher.match(uri)) {
ARTWORK ->
// If the pattern is for artwork, returns the artwork content type.
MuzeiContract.Artwork.CONTENT_TYPE
ARTWORK_ID ->
// If the pattern is for artwork id, returns the artwork content item type.
MuzeiContract.Artwork.CONTENT_ITEM_TYPE
SOURCES ->
// If the pattern is for sources, returns the sources content type.
MuzeiContract.Sources.CONTENT_TYPE
SOURCE_ID ->
// If the pattern is for source id, returns the sources content item type.
MuzeiContract.Sources.CONTENT_ITEM_TYPE
else -> throw IllegalArgumentException("Unknown URI $uri")
}
}
override fun insert(uri: Uri, values: ContentValues?): Uri? {
throw UnsupportedOperationException("Inserts are not supported")
}
/**
* Creates the underlying DatabaseHelper
*
* @see android.content.ContentProvider.onCreate
*/
override fun onCreate(): Boolean {
return true
}
override fun query(
uri: Uri,
projection: Array<String>?,
selection: String?,
selectionArgs: Array<String>?,
sortOrder: String?
): Cursor? {
val context = context ?: return null
if (!UserManagerCompat.isUserUnlocked(context)) {
Log.w(TAG, "Queries are not supported until the user is unlocked")
return null
}
return when(uriMatcher.match(uri)) {
ARTWORK -> queryArtwork(uri, projection, selection, selectionArgs, sortOrder)
ARTWORK_ID -> queryArtwork(uri, projection, selection, selectionArgs, sortOrder)
SOURCES -> querySource(uri, projection)
SOURCE_ID -> querySource(uri, projection)
else -> throw IllegalArgumentException("Unknown URI $uri")
}
}
private fun queryArtwork(
uri: Uri,
projection: Array<String>?,
selection: String?,
selectionArgs: Array<String>?,
sortOrder: String?
): Cursor? {
val context = context ?: return null
val qb = SupportSQLiteQueryBuilder.builder("artwork")
qb.columns(computeColumns(projection, allArtworkColumnProjectionMap))
val provider = ensureBackground {
MuzeiDatabase.getInstance(context).providerDao()
.currentProviderBlocking
}
var finalSelection = provider?.run {
DatabaseUtils.concatenateWhere(selection,
"providerAuthority = \"${provider.authority}\"")
} ?: selection
if (uriMatcher.match(uri) == ARTWORK_ID) {
// If the incoming URI is for a single artwork identified by its ID, appends "_ID = <artworkId>"
// to the where clause, so that it selects that single piece of artwork
finalSelection = DatabaseUtils.concatenateWhere(selection,
"${BaseColumns._ID} = ${uri.lastPathSegment}")
}
qb.selection(finalSelection, selectionArgs)
qb.orderBy(sortOrder ?: "date_added DESC")
return ensureBackground {
MuzeiDatabase.getInstance(context).query(qb.create())
}.apply {
setNotificationUri(context.contentResolver, uri)
}
}
private fun querySource(uri: Uri, projection: Array<String>?): Cursor? {
val context = context ?: return null
val c = MatrixCursor(projection)
val currentProvider = ensureBackground {
MuzeiDatabase.getInstance(context).providerDao()
.currentProviderBlocking
}
currentProvider?.let { provider ->
c.newRow().apply {
add(BaseColumns._ID, 0L)
add(MuzeiContract.Sources.COLUMN_NAME_AUTHORITY, provider.authority)
add("selected", true)
add(MuzeiContract.Sources.COLUMN_NAME_DESCRIPTION, runBlocking {
ProviderManager.getDescription(context, provider.authority)
})
add("network", false)
add(MuzeiContract.Sources.COLUMN_NAME_SUPPORTS_NEXT_ARTWORK_COMMAND,
provider.supportsNextArtwork)
add("commands", null)
}
}
return c.apply { setNotificationUri(context.contentResolver, uri) }
}
private fun computeColumns(projectionIn: Array<String>?, projectionMap: Map<String, String>): Array<String> {
if (projectionIn != null && projectionIn.isNotEmpty()) {
return projectionIn.map { userColumn ->
val column = projectionMap[userColumn]
when {
column != null -> column
userColumn.contains(" AS ") || userColumn.contains(" as ") -> userColumn
else -> throw IllegalArgumentException("Invalid column $userColumn")
}
}.toTypedArray()
}
// Return all columns in projection map.
return projectionMap.values.toTypedArray()
}
@Throws(FileNotFoundException::class)
override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor? {
return when(uriMatcher.match(uri)) {
ARTWORK -> openFileArtwork(uri, mode)
ARTWORK_ID -> openFileArtwork(uri, mode)
else -> throw IllegalArgumentException("Unknown URI $uri")
}
}
@Throws(FileNotFoundException::class)
private fun openFileArtwork(uri: Uri, mode: String): ParcelFileDescriptor? {
val context = context ?: return null
if (!UserManagerCompat.isUserUnlocked(context)) {
val file = DirectBootCache.getCachedArtwork(context)
?: throw FileNotFoundException("No wallpaper was cached for Direct Boot")
return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)
}
val artworkDao = MuzeiDatabase.getInstance(context).artworkDao()
val artwork = ensureBackground {
when (uriMatcher.match(uri)) {
ARTWORK -> artworkDao.currentArtworkBlocking
else -> artworkDao.getArtworkByIdBlocking(ContentUris.parseId(uri))
}
} ?: throw FileNotFoundException("Could not get artwork file for $uri")
val token = Binder.clearCallingIdentity()
try {
return context.contentResolver.openFileDescriptor(artwork.imageUri, mode)
} catch (e: FileNotFoundException) {
if (BuildConfig.DEBUG) {
Log.w(TAG, "Artwork ${artwork.imageUri} with id ${artwork.id} from request for $uri " +
"is no longer valid, deleting: ${e.message}")
}
ensureBackground {
artworkDao.deleteById(artwork.id)
}
throw e
} finally {
Binder.restoreCallingIdentity(token)
}
}
override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>?): Int {
throw UnsupportedOperationException("Updates are not supported")
}
}
|
apache-2.0
|
cc45df0749679b2889774a0eb55f2f17
| 40.708185 | 115 | 0.622952 | 4.959797 | false | false | false | false |
ReactiveX/RxKotlin
|
src/test/kotlin/io/reactivex/rxkotlin/ObservableTest.kt
|
1
|
8514
|
package io.reactivex.rxkotlin
import io.reactivex.Observable
import io.reactivex.observers.LambdaConsumerIntrospection
import io.reactivex.observers.TestObserver
import org.junit.Assert
import org.junit.Assert.*
import org.junit.Ignore
import org.junit.Test
import java.math.BigDecimal
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicReference
class ObservableTest {
@Test fun testCreation() {
val observable = Observable.create<Int> { s ->
s.apply {
onNext(1)
onNext(777)
onComplete()
}
}
assertEquals(listOf(1, 777), observable.toList().blockingGet())
val o0: Observable<Int> = Observable.empty()
val o1: Observable<Int> = listOf(1, 2, 3).toObservable()
val o2: Observable<List<Int>> = Observable.just(listOf(1, 2, 3))
val o3: Observable<Int> = Observable.defer { Observable.create<Int> { s -> s.onNext(1) } }
val o4: Observable<Int> = Array(3) { 0 }.toObservable()
val o5: Observable<Int> = IntArray(3).toObservable()
assertNotNull(o0)
assertNotNull(o1)
assertNotNull(o2)
assertNotNull(o3)
assertNotNull(o4)
assertNotNull(o5)
}
@Test fun testExampleFromReadme() {
val observable = Observable.create<String> { s ->
s.apply {
onNext("H")
onNext("e")
onNext("l")
onNext("")
onNext("l")
onNext("o")
onComplete()
}
}
val result = observable
.filter(String::isNotEmpty)
.reduce(StringBuilder(), StringBuilder::append)
.map { it.toString() }
.blockingGet()
assertEquals("Hello", result)
}
@Test fun iteratorObservable() {
assertEquals(listOf(1, 2, 3), listOf(1, 2, 3).iterator().toObservable().toList().blockingGet())
}
@Test fun intProgressionStep1Empty() {
assertEquals(listOf(1), (1..1).toObservable().toList().blockingGet())
}
@Test fun intProgressionStep1() {
assertEquals((1..10).toList(), (1..10).toObservable().toList().blockingGet())
}
@Test fun intProgressionDownTo() {
assertEquals((1 downTo 10).toList(), (1 downTo 10).toObservable().toList().blockingGet())
}
@Ignore("Too slow")
@Test fun intProgressionOverflow() {
val result = (-10..Integer.MAX_VALUE).toObservable()
.skip(Integer.MAX_VALUE.toLong())
.map { Integer.MAX_VALUE - it }
.toList()
.blockingGet()
assertEquals((0..10).toList().reversed(), result)
}
@Test fun testReduce() {
val result = listOf(1, 2, 3).toObservable().reduce(0) { acc, e -> acc + e }.blockingGet()
assertEquals(6, result)
}
@Test fun `kotlin sequence should produce expected items and observable be able to handle em`() {
generateSequence(0) { it + 1 }.toObservable()
.take(3)
.toList()
.test()
.assertValues(listOf(0, 1, 2))
}
@Test fun `infinite iterable should not hang or produce too many elements`() {
val generated = AtomicInteger()
generateSequence { generated.incrementAndGet() }.toObservable().
take(100).
toList().
subscribe()
assertEquals(100, generated.get())
}
@Test fun testFlatMapSequence() {
assertEquals(
listOf(1, 2, 3, 2, 3, 4, 3, 4, 5),
listOf(1, 2, 3).toObservable().flatMapSequence { listOf(it, it + 1, it + 2).asSequence() }.toList().blockingGet()
)
}
@Test fun testFlatMapIterable() {
assertEquals(
listOf(1, 2, 3),
Observable.just(listOf(1, 2, 3)).flatMapIterable().toList().blockingGet()
)
}
@Test fun testConcatMapIterable() {
assertEquals(
listOf(1, 2, 3, 4),
Observable.just(listOf(1, 2, 3) , listOf(4)).concatMapIterable().toList().blockingGet()
)
}
@Test fun testCombineLatest() {
val list = listOf(1, 2, 3, 2, 3, 4, 3, 4, 5)
assertEquals(list, list.map { Observable.just(it) }.combineLatest { it }.blockingFirst())
}
@Test fun testZip() {
val list = listOf(1, 2, 3, 2, 3, 4, 3, 4, 5)
assertEquals(list, list.map { Observable.just(it) }.zip { it }.blockingFirst())
}
@Test fun testCast() {
val source = Observable.just<Any>(1, 2)
val observable = source.cast<Int>()
observable.test()
.await()
.assertValues(1, 2)
.assertNoErrors()
.assertComplete()
}
@Test fun testCastWithWrongType() {
val source = Observable.just<Any>(1, 2)
val observable = source.cast<String>()
observable.test()
.assertError(ClassCastException::class.java)
}
@Test fun testOfType() {
val source = Observable.just<Number>(BigDecimal.valueOf(15, 1), 2, BigDecimal.valueOf(42), 15)
source.ofType<Int>()
.test()
.await()
.assertValues(2, 15)
.assertNoErrors()
.assertComplete()
source.ofType<BigDecimal>()
.test()
.await()
.assertValues(BigDecimal.valueOf(15, 1), BigDecimal.valueOf(42))
.assertNoErrors()
.assertComplete()
source.ofType<Double>()
.test()
.await()
.assertNoValues()
.assertNoErrors()
.assertComplete()
source.ofType<Comparable<*>>()
.test()
.await()
.assertValues(BigDecimal.valueOf(15, 1), 2, BigDecimal.valueOf(42), 15)
.assertNoErrors()
.assertComplete()
}
@Test
fun testSubscribeBy() {
val first = AtomicReference<String>()
Observable.just("Alpha")
.subscribeBy {
first.set(it)
}
assertTrue(first.get() == "Alpha")
}
@Test
fun testSubscribeByErrorIntrospection() {
val disposable = Observable.just(Unit)
.subscribeBy() as LambdaConsumerIntrospection
assertFalse(disposable.hasCustomOnError())
}
@Test
fun testSubscribeByErrorIntrospectionCustom() {
val disposable = Observable.just(Unit)
.subscribeBy(onError = {}) as LambdaConsumerIntrospection
assertTrue(disposable.hasCustomOnError())
}
@Test
@Ignore("Fix with adding support for LambdaConsumerIntrospection - #151")
fun testSubscribeByErrorIntrospectionDefaultWithOnComplete() {
val disposable = Observable.just(Unit)
.subscribeBy(onComplete = {}) as LambdaConsumerIntrospection
assertFalse(disposable.hasCustomOnError())
}
@Test
fun testBlockingSubscribeBy() {
val first = AtomicReference<String>()
Observable.just("Alpha")
.blockingSubscribeBy {
first.set(it)
}
assertTrue(first.get() == "Alpha")
}
@Test
fun testPairZip() {
val testObserver = TestObserver<Pair<String,Int>>()
Observables.zip(
Observable.just("Alpha", "Beta", "Gamma"),
Observable.range(1,4)
).subscribe(testObserver)
testObserver.assertValues(Pair("Alpha",1), Pair("Beta",2), Pair("Gamma",3))
}
@Test
fun testTripleZip() {
val testObserver = TestObserver<Triple<String,Int,Int>>()
Observables.zip(
Observable.just("Alpha", "Beta", "Gamma"),
Observable.range(1,4),
Observable.just(100,200,300)
).subscribe(testObserver)
testObserver.assertValues(Triple("Alpha",1, 100), Triple("Beta",2, 200), Triple("Gamma",3, 300))
}
@Test fun testConcatAll() {
var counter = 0
(0 until 10)
.map { Observable.just(counter++, counter++, counter++) }
.concatAll()
.toList()
.subscribe { result ->
Assert.assertEquals((0 until 30).toList(), result)
}
}
}
|
apache-2.0
|
044efaeb49e79301ffd551f469f72da2
| 30.072993 | 129 | 0.545924 | 4.557816 | false | true | false | false |
MartinStyk/AndroidApkAnalyzer
|
app/src/main/java/sk/styk/martin/apkanalyzer/ui/dialogs/FancyDialog.kt
|
1
|
3243
|
package sk.styk.martin.apkanalyzer.ui.dialogs
import android.app.Activity
import android.app.Dialog
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.GradientDrawable
import android.view.Window
import android.widget.Button
import android.widget.TextView
import androidx.annotation.ColorRes
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.core.content.ContextCompat
import pl.droidsonroids.gif.GifImageView
import sk.styk.martin.apkanalyzer.R
class FancyDialog(private val activity: Activity) {
interface FancyDialogAction {
fun onPositiveButtonClicked(context: Activity)
fun onNegativeButtonClicked(context: Activity)
}
@StringRes
var title: Int? = null
@StringRes
var message: Int? = null
@StringRes
var positiveBtnText: Int? = null
@StringRes
var negativeBtnText: Int? = null
@ColorRes
var positiveButtonColor: Int = R.color.accent
@ColorRes
var positiveButtonTextColor: Int = R.color.colorWhite
@ColorRes
var negativeButtonColor: Int = R.color.grey_500
@ColorRes
var negativeButtonTextColor: Int = R.color.colorWhite
@DrawableRes
var gifImageResource: Int = 0
var cancelable: Boolean = false
var actionListener: FancyDialogAction = object : FancyDialogAction {
override fun onPositiveButtonClicked(context: Activity) {}
override fun onNegativeButtonClicked(context: Activity) {}
}
private lateinit var dialog: Dialog
fun build(): Dialog {
dialog = Dialog(this.activity).apply {
requestWindowFeature(Window.FEATURE_NO_TITLE)
window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
setCancelable(cancelable)
setContentView(R.layout.dialog_fancy)
}
dialog.findViewById<TextView>(R.id.title).apply {
text = title?.let { activity.getText(it) } ?: ""
}
dialog.findViewById<TextView>(R.id.message).apply {
text = message?.let { activity.getText(it) } ?: ""
}
dialog.findViewById<GifImageView>(R.id.gifImageView).apply {
setImageResource(gifImageResource)
}
dialog.findViewById<Button>(R.id.negativeBtn).apply {
text = negativeBtnText?.let { activity.getText(it) } ?: ""
setTextColor(ContextCompat.getColor(activity, negativeButtonTextColor))
(background as GradientDrawable).setColor(ContextCompat.getColor(activity, negativeButtonColor))
setOnClickListener {
actionListener.onNegativeButtonClicked(activity)
dialog.dismiss()
}
}
dialog.findViewById<Button>(R.id.positiveBtn).apply {
text = positiveBtnText?.let { activity.getText(it) } ?: ""
setTextColor(ContextCompat.getColor(activity, positiveButtonTextColor))
(background as GradientDrawable).setColor(ContextCompat.getColor(activity, positiveButtonColor))
setOnClickListener {
actionListener.onPositiveButtonClicked(activity)
dialog.dismiss()
}
}
return dialog
}
}
|
gpl-3.0
|
5ac6e157da1ee623b771a5bc588ec712
| 35.863636 | 108 | 0.686401 | 4.906203 | false | false | false | false |
sksamuel/ktest
|
kotest-assertions/kotest-assertions-core/src/commonMain/kotlin/io/kotest/matchers/collections/containExactlyInAnyOrder.kt
|
1
|
4740
|
package io.kotest.matchers.collections
import io.kotest.assertions.show.show
import io.kotest.matchers.Matcher
import io.kotest.matchers.MatcherResult
import io.kotest.matchers.neverNullMatcher
import io.kotest.matchers.should
import io.kotest.matchers.shouldNot
/**
* Verifies that the given collection contains all the specified elements and no others, but in any order.
*
* For example, each of the following examples would pass for a collection [1,2,3].
*
* collection.shouldContainExactlyInAnyOrder(1, 2, 3)
* collection.shouldContainExactlyInAnyOrder(3, 2, 1)
* collection.shouldContainExactlyInAnyOrder(2, 1, 3)
*
* Note: Comparison is via the standard Java equals and hash code methods.
*
* From the javadocs for hashcode: If two objects are equal according to the equals(Object) method,
* then calling the hashCode method on each of the two objects must produce the same integer result.
*
*/
infix fun <T> Array<T>.shouldContainExactlyInAnyOrder(expected: Array<T>): Array<T> {
asList().shouldContainExactlyInAnyOrder(expected.asList())
return this
}
/**
* Verifies that the given collection contains all the specified elements and no others, but in any order.
*
* For example, each of the following examples would pass for a collection [1,2,3].
*
* collection.shouldContainExactlyInAnyOrder(1, 2, 3)
* collection.shouldContainExactlyInAnyOrder(3, 2, 1)
* collection.shouldContainExactlyInAnyOrder(2, 1, 3)
*
* Note: Comparison is via the standard Java equals and hash code methods.
*
* From the javadocs for hashcode: If two objects are equal according to the equals(Object) method,
* then calling the hashCode method on each of the two objects must produce the same integer result.
*
*/
infix fun <T, C : Collection<T>> C?.shouldContainExactlyInAnyOrder(expected: C): C? {
this should containExactlyInAnyOrder(expected)
return this
}
/**
* Verifies that the given collection contains all the specified elements and no others, but in any order.
*
* For example, each of the following examples would pass for a collection [1,2,3].
*
* collection.shouldContainExactlyInAnyOrder(1, 2, 3)
* collection.shouldContainExactlyInAnyOrder(3, 2, 1)
* collection.shouldContainExactlyInAnyOrder(2, 1, 3)
*
* Note: Comparison is via the standard Java equals and hash code methods.
*
* From the javadocs for hashcode: If two objects are equal according to the equals(Object) method,
* then calling the hashCode method on each of the two objects must produce the same integer result.
*
*/
fun <T, C : Collection<T>> C?.shouldContainExactlyInAnyOrder(vararg expected: T): C? {
this should containExactlyInAnyOrder(*expected)
return this
}
/**
* Verifies that the given collection contains all the specified elements and no others, but in any order.
*
* For example, each of the following examples would pass for a collection [1,2,3].
*
* collection.shouldContainExactlyInAnyOrder(1, 2, 3)
* collection.shouldContainExactlyInAnyOrder(3, 2, 1)
* collection.shouldContainExactlyInAnyOrder(2, 1, 3)
*
* Note: Comparison is via the standard Java equals and hash code methods.
*
* From the javadocs for hashcode: If two objects are equal according to the equals(Object) method,
* then calling the hashCode method on each of the two objects must produce the same integer result.
*
*/
fun <T> containExactlyInAnyOrder(vararg expected: T): Matcher<Collection<T>?> =
containExactlyInAnyOrder(expected.asList())
infix fun <T> Array<T>.shouldNotContainExactlyInAnyOrder(expected: Array<T>): Array<T> {
asList().shouldNotContainExactlyInAnyOrder(expected.asList())
return this
}
infix fun <T, C : Collection<T>> C?.shouldNotContainExactlyInAnyOrder(expected: C): C? {
this shouldNot containExactlyInAnyOrder(expected)
return this
}
fun <T, C : Collection<T>> C?.shouldNotContainExactlyInAnyOrder(vararg expected: T): C? {
this shouldNot containExactlyInAnyOrder(*expected)
return this
}
/** Assert that a collection contains exactly the given values and nothing else, in any order. */
fun <T, C : Collection<T>> containExactlyInAnyOrder(expected: C): Matcher<C?> = neverNullMatcher { value ->
val valueGroupedCounts: Map<T, Int> = value.groupBy { it }.mapValues { it.value.size }
val expectedGroupedCounts: Map<T, Int> = expected.groupBy { it }.mapValues { it.value.size }
val passed = expectedGroupedCounts.size == valueGroupedCounts.size
&& expectedGroupedCounts.all { valueGroupedCounts[it.key] == it.value }
MatcherResult(
passed,
"Collection should contain ${expected.show().value} in any order, but was ${value.show().value}",
"Collection should not contain exactly ${expected.show().value} in any order"
)
}
|
mit
|
09efd6385c87e7e65537565698c71f22
| 39.862069 | 107 | 0.751266 | 4.26259 | false | true | false | false |
quran/quran_android
|
app/src/main/java/com/quran/labs/androidquran/data/AyahInfoDatabaseProvider.kt
|
2
|
848
|
package com.quran.labs.androidquran.data
import android.content.Context
import com.quran.data.di.ActivityScope
import com.quran.labs.androidquran.util.QuranFileUtils
import javax.inject.Inject
@ActivityScope
class AyahInfoDatabaseProvider @Inject constructor(
private val context: Context,
private val widthParameter: String,
private val quranFileUtils: QuranFileUtils
) {
private var databaseHandler: AyahInfoDatabaseHandler? = null
fun getAyahInfoHandler(): AyahInfoDatabaseHandler? {
if (databaseHandler == null) {
val filename = quranFileUtils.getAyaPositionFileName(widthParameter)
databaseHandler = AyahInfoDatabaseHandler.getAyahInfoDatabaseHandler(
context, filename,
quranFileUtils
)
}
return databaseHandler
}
fun getPageWidth(): Int = widthParameter.substring(1).toInt()
}
|
gpl-3.0
|
369e8f03564ad18dbb442de7f364ef6a
| 29.285714 | 75 | 0.773585 | 4.608696 | false | false | false | false |
hazuki0x0/YuzuBrowser
|
module/search/src/main/java/jp/hazuki/yuzubrowser/search/repository/SearchUrlManager.kt
|
1
|
1927
|
/*
* Copyright (C) 2017-2019 Hazuki
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jp.hazuki.yuzubrowser.search.repository
import android.content.Context
import com.squareup.moshi.Moshi
import jp.hazuki.yuzubrowser.search.domain.ISearchUrlRepository
import jp.hazuki.yuzubrowser.search.model.provider.SearchSettings
import okio.buffer
import okio.sink
import okio.source
import java.io.File
import java.io.IOException
class SearchUrlManager(context: Context, private val moshi: Moshi) : ISearchUrlRepository {
val file = File(context.filesDir, NAME)
override fun load(): SearchSettings {
try {
val items = file.source().buffer().use {
val adapter = moshi.adapter(SearchSettings::class.java)
adapter.fromJson(it)
}
if (items?.items != null) {
return items
}
} catch (e: IOException) {
e.printStackTrace()
}
return SearchSettings(0, 0, listOf())
}
override fun save(settings: SearchSettings) {
try {
file.sink().buffer().use {
val adapter = moshi.adapter(SearchSettings::class.java)
adapter.toJson(it, settings)
}
} catch (e: IOException) {
e.printStackTrace()
}
}
companion object {
private const val NAME = "searchUrl.json"
}
}
|
apache-2.0
|
56582a891cfaf4a592db6079f1e8c7f6
| 30.080645 | 91 | 0.651271 | 4.359729 | false | false | false | false |
seventhroot/elysium
|
bukkit/rpk-travel-bukkit/src/main/kotlin/com/rpkit/travel/bukkit/listener/PlayerInteractListener.kt
|
1
|
1018
|
package com.rpkit.travel.bukkit.listener
import com.rpkit.travel.bukkit.RPKTravelBukkit
import com.rpkit.warp.bukkit.warp.RPKWarpProvider
import org.bukkit.ChatColor.GREEN
import org.bukkit.block.Sign
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.player.PlayerInteractEvent
class PlayerInteractListener(private val plugin: RPKTravelBukkit): Listener {
@EventHandler
fun onPlayerInteractListener(event: PlayerInteractEvent) {
val clickedBlock = event.clickedBlock ?: return
val sign = clickedBlock.state as? Sign ?: return
if (!sign.getLine(0).equals("$GREEN[warp]", ignoreCase = true)) return
val warpProvider = plugin.core.serviceManager.getServiceProvider(RPKWarpProvider::class)
val warp = warpProvider.getWarp(sign.getLine(1))
if (warp != null) {
event.player.teleport(warp.location)
} else {
event.player.sendMessage(plugin.messages["warp-invalid-warp"])
}
}
}
|
apache-2.0
|
41e5b0e534b278b1ca5e25b3b03a94c3
| 35.392857 | 96 | 0.726916 | 4.155102 | false | false | false | false |
addonovan/ftc-ext
|
ftc-ext/src/main/java/com/addonovan/ftcext/hardware/ContinuousToggleServo.kt
|
1
|
6744
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2016 Austin Donovan (addonovan)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.addonovan.ftcext.hardware
import com.qualcomm.robotcore.hardware.Servo
import kotlin.concurrent.thread
/**
* A blend between the [ContinuousServo] and the [ToggleServo]. This
* inherits from a ContinuousServo, rather than a ToggleServo, because
* this functions far differently than a normal ToggleServo does.
*
* How this functions is a little difficult to understand from the
* code; however, it is actually quite simple. When a servo is
* toggled, it will switch to the correct state, and, after
* [ToggleRunTime] milliseconds, it will stop and be in the end state.
* For example, if a servo were toggled on, it would run in
* the direction given by [EngagedDirection] under the status of "Engaging"
* for [ToggleRunTime] milliseconds, then stop under the status of
* "Engaged". When it is next toggled, it will run for [ToggleRunTime]
* milliseconds in the opposite direction of [EngagedDirection] under
* the status of "Disengaging", then it will stop and have the status
* of "Disengaged" until it's toggled next.
*
* @param[servo]
* The servo to create a ContinuousToggleServo from.
*
* @author addonovan
* @since 6/26/16
*
* @see [ToggleServo]
* @see [ContinuousServo]
*/
@Suppress( "unused" )
class ContinuousToggleServo( servo: Servo ) : ContinuousServo( servo )
{
//
// States
//
/**
* The position of a [ContinuousToggleServo].
*
* @param[StringValue]
* The value of the position as a string.
*/
enum class State( val StringValue: String )
{
/** The servo is in its engaged state. */
ENGAGED( "Engaged" ),
/** The servo is moving in its engaged direction. */
ENGAGING( "Engaging" ),
/** The servo is in its disengaged state. */
DISENGAGED( "Disengaged" ),
/** The servo is moving in its disengaged direction. */
DISENGAGING( "Disengaging" );
}
//
// Timing
//
/**
* The amount of time (in milliseconds) to ensure between [toggle] calls go
* through and toggle the position, by default this is 350.
*/
var ToggleDelay: Long = 350;
/**
* The amount of time (in milliseconds) to be running the either direction,
* by default this is 350.
*/
var ToggleRunTime: Long = 350;
/**
* The last time the [toggle] call went through.
*/
private var lastToggle: Long = 0;
//
// Current Positioning
//
/** The backing field for [CurrentPosition]. */
@Volatile
private var _currentPosition = State.ENGAGED;
/**
* The current position of the ToggleServo.
*/
val CurrentPosition: State
get() = _currentPosition;
//
// Positions
//
/**
* The direction to move when the servo is in the "engaging"
* state. When the servo is in the "disengaging" state it will
* move in the opposite direction of this.
*
* @see [State]
*/
var EngagedDirection = Direction.FORWARD;
//
// Toggling
//
/**
* The number of toggle threads we have running. This is incremented when a
* toggling thread starts and decremented when it exits.
*
* @see [dispatchUpdateThread]
*/
@Volatile private var toggleThreadCount = 0;
/**
* Toggles the servo to the opposite state than it's currently in.
*/
fun toggle()
{
// ensure that at least [ToggleDelay] milliseconds have passed since
// this method was last invoked.
if ( System.currentTimeMillis() - lastToggle < ToggleDelay ) return;
// toggle the position
when ( _currentPosition )
{
State.ENGAGED, State.ENGAGING -> toggleOff();
State.DISENGAGED, State.DISENGAGING -> toggleOn();
}
lastToggle = System.currentTimeMillis(); // reset the timer
}
/**
* Moves the servo in the direction of the [EngagedDirection].
*/
fun toggleOn()
{
position =
when ( EngagedDirection )
{
Direction.FORWARD -> 1.0;
Direction.REVERSE -> 0.0;
}
_currentPosition = State.ENGAGING;
dispatchUpdateThread();
}
/**
* Moves the servo in the opposite direction of the [EngagedDirection].
*/
fun toggleOff()
{
position =
when ( EngagedDirection )
{
Direction.FORWARD -> 0.0;
Direction.REVERSE -> 1.0;
}
_currentPosition = State.DISENGAGING;
dispatchUpdateThread();
}
/**
* Dispatches the background thread that will stop the servo after [ToggleRunTime]
* milliseconds have passed, provided no other toggling has occurred.
*/
private fun dispatchUpdateThread()
{
thread {
toggleThreadCount++; // we've just started our thread, after all
Thread.sleep( ToggleRunTime ); // wait for the specified time
// if we're the only running thread, then no other toggling has been going on!
if ( toggleThreadCount == 1 )
{
stop(); // stop all movement
// update the position
if ( _currentPosition == State.ENGAGING ) _currentPosition = State.ENGAGED;
if ( _currentPosition == State.DISENGAGING ) _currentPosition = State.DISENGAGING;
}
toggleThreadCount--; // we're now ended
}.start();
}
}
|
mit
|
a68e139fd66579f3eb8e2eaad9a54094
| 28.709251 | 98 | 0.625297 | 4.390625 | false | false | false | false |
ilya-g/kotlinx.collections.immutable
|
core/commonMain/src/implementations/immutableList/PersistentVectorBuilder.kt
|
1
|
36094
|
/*
* Copyright 2016-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.txt file.
*/
package kotlinx.collections.immutable.implementations.immutableList
import kotlinx.collections.immutable.PersistentList
import kotlinx.collections.immutable.internal.ListImplementation.checkElementIndex
import kotlinx.collections.immutable.internal.ListImplementation.checkPositionIndex
import kotlinx.collections.immutable.internal.MutabilityOwnership
import kotlinx.collections.immutable.internal.assert
import kotlinx.collections.immutable.internal.modCount
internal class PersistentVectorBuilder<E>(private var vector: PersistentList<E>,
private var vectorRoot: Array<Any?>?,
private var vectorTail: Array<Any?>,
internal var rootShift: Int) : AbstractMutableList<E>(), PersistentList.Builder<E> {
private var ownership = MutabilityOwnership()
internal var root = vectorRoot
private set
internal var tail = vectorTail
private set
override var size = vector.size
private set
internal fun getModCount() = modCount
override fun build(): PersistentList<E> {
vector = if (root === vectorRoot && tail === vectorTail) {
vector
} else {
ownership = MutabilityOwnership()
vectorRoot = root
vectorTail = tail
if (root == null) {
if (tail.isEmpty()) {
persistentVectorOf()
} else {
SmallPersistentVector(tail.copyOf(size))
}
} else {
PersistentVector(root!!, tail, size, rootShift)
}
}
return vector
}
private fun rootSize(): Int {
if (size <= MAX_BUFFER_SIZE) {
return 0
}
return rootSize(size)
}
private fun tailSize(size: Int): Int {
if (size <= MAX_BUFFER_SIZE) {
return size
}
return size - rootSize(size)
}
private fun tailSize(): Int {
return tailSize(size)
}
private fun isMutable(buffer: Array<Any?>): Boolean {
return buffer.size == MUTABLE_BUFFER_SIZE && buffer[MUTABLE_BUFFER_SIZE - 1] === ownership
}
/**
* Checks if [buffer] is mutable and returns it or its mutable copy.
*/
private fun makeMutable(buffer: Array<Any?>?): Array<Any?> {
if (buffer == null) {
return mutableBuffer()
}
if (isMutable(buffer)) {
return buffer
}
return buffer.copyInto(mutableBuffer(), endIndex = buffer.size.coerceAtMost(MAX_BUFFER_SIZE))
}
private fun makeMutableShiftingRight(buffer: Array<Any?>, distance: Int): Array<Any?> {
if (isMutable(buffer)) {
return buffer.copyInto(buffer, distance, 0, MAX_BUFFER_SIZE - distance)
}
return buffer.copyInto(mutableBuffer(), distance, 0, MAX_BUFFER_SIZE - distance)
}
private fun mutableBufferWith(element: Any?): Array<Any?> {
val buffer = arrayOfNulls<Any?>(MUTABLE_BUFFER_SIZE)
buffer[0] = element
buffer[MUTABLE_BUFFER_SIZE - 1] = ownership
return buffer
}
private fun mutableBuffer(): Array<Any?> {
val buffer = arrayOfNulls<Any?>(MUTABLE_BUFFER_SIZE)
buffer[MUTABLE_BUFFER_SIZE - 1] = ownership
return buffer
}
override fun add(element: E): Boolean {
modCount += 1
val tailSize = tailSize()
if (tailSize < MAX_BUFFER_SIZE) {
val mutableTail = makeMutable(tail)
mutableTail[tailSize] = element
this.tail = mutableTail
this.size += 1
} else {
val newTail = mutableBufferWith(element)
this.pushFilledTail(root, tail, newTail)
}
return true
}
/**
* Appends the specified entirely filled [tail] as a leaf buffer to the next free position in the [root] trie.
*/
private fun pushFilledTail(root: Array<Any?>?, filledTail: Array<Any?>, newTail: Array<Any?>) = when {
size shr LOG_MAX_BUFFER_SIZE > 1 shl rootShift -> {
// if the root trie is filled entirely, promote it to the next level
this.root = pushTail(mutableBufferWith(root), filledTail, rootShift + LOG_MAX_BUFFER_SIZE)
this.tail = newTail
this.rootShift += LOG_MAX_BUFFER_SIZE
this.size += 1
}
root == null -> {
this.root = filledTail
this.tail = newTail
this.size += 1
}
else -> {
this.root = pushTail(root, filledTail, rootShift)
this.tail = newTail
this.size += 1
}
}
/**
* Appends the specified entirely filled [tail] as a leaf buffer to the next free position in the [root] trie.
* The trie must not be filled entirely.
*/
private fun pushTail(root: Array<Any?>?, tail: Array<Any?>, shift: Int): Array<Any?> {
val index = indexSegment(size - 1, shift)
val mutableRoot = makeMutable(root)
if (shift == LOG_MAX_BUFFER_SIZE) {
mutableRoot[index] = tail
} else {
@Suppress("UNCHECKED_CAST")
mutableRoot[index] = pushTail(mutableRoot[index] as Array<Any?>?, tail, shift - LOG_MAX_BUFFER_SIZE)
}
return mutableRoot
}
override fun addAll(elements: Collection<E>): Boolean {
if (elements.isEmpty()) {
return false
}
modCount++
val tailSize = tailSize()
val elementsIterator = elements.iterator()
if (MAX_BUFFER_SIZE - tailSize >= elements.size) {
// there is enough space in tail, add all elements to it
tail = copyToBuffer(makeMutable(tail), tailSize, elementsIterator)
size += elements.size
} else {
val buffersSize = (elements.size + tailSize - 1) / MAX_BUFFER_SIZE
val buffers = arrayOfNulls<Array<Any?>?>(buffersSize)
// fill remained space of tail
buffers[0] = copyToBuffer(makeMutable(tail), tailSize, elementsIterator)
// fill other buffers
for (index in 1 until buffersSize) {
buffers[index] = copyToBuffer(mutableBuffer(), 0, elementsIterator)
}
// add buffers to the root, rootShift is updated appropriately there
@Suppress("UNCHECKED_CAST")
root = pushBuffersIncreasingHeightIfNeeded(root, rootSize(), buffers as Array<Array<Any?>>)
// create new tail and copy remained elements there
tail = copyToBuffer(mutableBuffer(), 0, elementsIterator)
size += elements.size
}
return true
}
private fun copyToBuffer(buffer: Array<Any?>, bufferIndex: Int, sourceIterator: Iterator<Any?>): Array<Any?> {
var index = bufferIndex
while (index < MAX_BUFFER_SIZE && sourceIterator.hasNext()) {
buffer[index++] = sourceIterator.next()
}
return buffer
}
/**
* Adds all buffers from [buffers] as leaf nodes to the [root].
* If the [root] has less available leaves for the buffers, height of the trie is increased.
*
* Returns root of the resulting trie.
*/
private fun pushBuffersIncreasingHeightIfNeeded(root: Array<Any?>?, rootSize: Int, buffers: Array<Array<Any?>>): Array<Any?> {
val buffersIterator = buffers.iterator()
var mutableRoot = when {
rootSize shr LOG_MAX_BUFFER_SIZE < 1 shl rootShift ->
// if the root trie is not filled entirely, fill it
pushBuffers(root, rootSize, rootShift, buffersIterator)
else ->
// root is filled entirely, make it mutable
makeMutable(root)
}
// here root is filled entirely or/and all buffers are already placed
while (buffersIterator.hasNext()) {
// some buffers left, so root is filled entirely. promote root to the next level
rootShift += LOG_MAX_BUFFER_SIZE
mutableRoot = mutableBufferWith(mutableRoot)
pushBuffers(mutableRoot, 1 shl rootShift, rootShift, buffersIterator)
}
return mutableRoot
}
/**
* Adds buffers from the [buffersIterator] as leaf nodes.
* As the result [root] is entirely filled, or all buffers are added.
*
* Returns the resulting root.
*/
private fun pushBuffers(root: Array<Any?>?, rootSize: Int, shift: Int, buffersIterator: Iterator<Array<Any?>>): Array<Any?> {
check(buffersIterator.hasNext())
check(shift >= 0)
if (shift == 0) {
return buffersIterator.next()
}
val mutableRoot = makeMutable(root)
var index = indexSegment(rootSize, shift)
@Suppress("UNCHECKED_CAST")
mutableRoot[index] =
pushBuffers(mutableRoot[index] as Array<Any?>?, rootSize, shift - LOG_MAX_BUFFER_SIZE, buffersIterator)
while (++index < MAX_BUFFER_SIZE && buffersIterator.hasNext()) {
@Suppress("UNCHECKED_CAST")
mutableRoot[index] =
pushBuffers(mutableRoot[index] as Array<Any?>?, 0, shift - LOG_MAX_BUFFER_SIZE, buffersIterator)
}
return mutableRoot
}
override fun add(index: Int, element: E) {
checkPositionIndex(index, size)
if (index == size) {
add(element)
return
}
modCount += 1
val rootSize = rootSize()
if (index >= rootSize) {
insertIntoTail(root, index - rootSize, element)
return
}
val elementCarry = ObjectRef(null)
val newRest = insertIntoRoot(root!!, rootShift, index, element, elementCarry)
@Suppress("UNCHECKED_CAST")
insertIntoTail(newRest, 0, elementCarry.value as E)
}
private fun insertIntoTail(root: Array<Any?>?, index: Int, element: E) {
val tailSize = tailSize()
val mutableTail = makeMutable(tail)
if (tailSize < MAX_BUFFER_SIZE) {
tail.copyInto(mutableTail, index + 1, index, tailSize)
mutableTail[index] = element
this.root = root
this.tail = mutableTail
this.size += 1
} else {
val lastElement = tail[MAX_BUFFER_SIZE_MINUS_ONE]
tail.copyInto(mutableTail, index + 1, index, MAX_BUFFER_SIZE_MINUS_ONE)
mutableTail[index] = element
pushFilledTail(root, mutableTail, mutableBufferWith(lastElement))
}
}
/**
* Insert the specified [element] into the [root] trie at the specified trie [index].
*
* [elementCarry] contains the last element of this trie that was popped out by the insertion operation.
*
* @return new root trie or this modified trie, if it's already mutable
*/
private fun insertIntoRoot(root: Array<Any?>, shift: Int, index: Int, element: Any?, elementCarry: ObjectRef): Array<Any?> {
val bufferIndex = indexSegment(index, shift)
if (shift == 0) {
elementCarry.value = root[MAX_BUFFER_SIZE_MINUS_ONE]
val mutableRoot = root.copyInto(makeMutable(root), bufferIndex + 1, bufferIndex, MAX_BUFFER_SIZE_MINUS_ONE)
mutableRoot[bufferIndex] = element
return mutableRoot
}
val mutableRoot = makeMutable(root)
val lowerLevelShift = shift - LOG_MAX_BUFFER_SIZE
@Suppress("UNCHECKED_CAST")
mutableRoot[bufferIndex] =
insertIntoRoot(mutableRoot[bufferIndex] as Array<Any?>, lowerLevelShift, index, element, elementCarry)
for (i in bufferIndex + 1 until MAX_BUFFER_SIZE) {
if (mutableRoot[i] == null) break
@Suppress("UNCHECKED_CAST")
mutableRoot[i] =
insertIntoRoot(mutableRoot[i] as Array<Any?>, lowerLevelShift, 0, elementCarry.value, elementCarry)
}
return mutableRoot
}
override fun addAll(index: Int, elements: Collection<E>): Boolean {
checkPositionIndex(index, size)
if (index == size) {
return addAll(elements)
}
if (elements.isEmpty()) {
return false
}
modCount++
val unaffectedElementsCount = (index shr LOG_MAX_BUFFER_SIZE) shl LOG_MAX_BUFFER_SIZE
val buffersSize = (size - unaffectedElementsCount + elements.size - 1) / MAX_BUFFER_SIZE
if (buffersSize == 0) {
assert(index >= rootSize())
val startIndex = index and MAX_BUFFER_SIZE_MINUS_ONE
val endIndex = (index + elements.size - 1) and MAX_BUFFER_SIZE_MINUS_ONE // inclusive
// Copy the unaffected tail prefix and shift the affected tail suffix to the end
val newTail = tail.copyInto(makeMutable(tail), endIndex + 1, startIndex, tailSize())
// Copy the specified elements to the new tail
copyToBuffer(newTail, startIndex, elements.iterator())
tail = newTail
size += elements.size
return true
}
val buffers = arrayOfNulls<Array<Any?>?>(buffersSize)
val tailSize = tailSize()
val newTailSize = tailSize(size + elements.size)
val newTail: Array<Any?>
when {
index >= rootSize() -> {
newTail = mutableBuffer()
splitToBuffers(elements, index, tail, tailSize, buffers, buffersSize, newTail)
}
newTailSize > tailSize -> {
val rightShift = newTailSize - tailSize
newTail = makeMutableShiftingRight(tail, rightShift)
insertIntoRoot(elements, index, rightShift, buffers, buffersSize, newTail)
}
else -> {
newTail = tail.copyInto(mutableBuffer(), 0, tailSize - newTailSize, tailSize)
val rightShift = MAX_BUFFER_SIZE - (tailSize - newTailSize)
val lastBuffer = makeMutableShiftingRight(tail, rightShift)
buffers[buffersSize - 1] = lastBuffer
insertIntoRoot(elements, index, rightShift, buffers, buffersSize - 1, lastBuffer)
}
}
@Suppress("UNCHECKED_CAST")
root = pushBuffersIncreasingHeightIfNeeded(root, unaffectedElementsCount, buffers as Array<Array<Any?>>)
tail = newTail
size += elements.size
return true
}
/**
* Inserts the [elements] into the [root] at the given [index].
*
* Affected elements are copied to the [buffers] split into [nullBuffers] buffers.
* Elements that do not fit [nullBuffers] buffers are copied to the [nextBuffer].
*/
private fun insertIntoRoot(
elements: Collection<E>,
index: Int,
rightShift: Int,
buffers: Array<Array<Any?>?>,
nullBuffers: Int,
nextBuffer: Array<Any?>
) {
checkNotNull(root)
val startLeafIndex = index shr LOG_MAX_BUFFER_SIZE
val startLeaf = shiftLeafBuffers(startLeafIndex, rightShift, buffers, nullBuffers, nextBuffer)
val lastLeafIndex = (rootSize() shr LOG_MAX_BUFFER_SIZE) - 1
val newNullBuffers = nullBuffers - (lastLeafIndex - startLeafIndex)
val newNextBuffer = if (newNullBuffers < nullBuffers) buffers[newNullBuffers]!! else nextBuffer
splitToBuffers(elements, index, startLeaf, MAX_BUFFER_SIZE, buffers, newNullBuffers, newNextBuffer)
}
/**
* Shifts elements in the [root] to the right by the given [rightShift] position starting from the end.
*
* Shifting stops when elements of the leaf at [startLeafIndex] are reached.
* Last elements whose indexes become bigger than [rootSize] are copied to the [nextBuffer].
* Shifted leaves are stored in the [buffers] starting from the given [nullBuffers] index.
*
* Returns leaf at the [startLeafIndex].
*/
private fun shiftLeafBuffers(
startLeafIndex: Int,
rightShift: Int,
buffers: Array<Array<Any?>?>,
nullBuffers: Int,
nextBuffer: Array<Any?>
): Array<Any?> {
checkNotNull(root)
val leafCount = rootSize() shr LOG_MAX_BUFFER_SIZE
val leafBufferIterator = leafBufferIterator(leafCount) // start from the last leaf
var bufferIndex = nullBuffers
var buffer = nextBuffer
while (leafBufferIterator.previousIndex() != startLeafIndex) {
val currentBuffer = leafBufferIterator.previous()
currentBuffer.copyInto(buffer, 0, MAX_BUFFER_SIZE - rightShift, MAX_BUFFER_SIZE)
buffer = makeMutableShiftingRight(currentBuffer, rightShift)
buffers[--bufferIndex] = buffer
}
return leafBufferIterator.previous()
}
/**
* Inserts [elements] into [startBuffer] of size [startBufferSize] and splits the result into [nullBuffers] buffers.
*
* Elements that do not fit [nullBuffers] buffers are copied to the [nextBuffer].
*/
private fun splitToBuffers(
elements: Collection<E>,
index: Int,
startBuffer: Array<Any?>,
startBufferSize: Int,
buffers: Array<Array<Any?>?>,
nullBuffers: Int,
nextBuffer: Array<Any?>
) {
check(nullBuffers >= 1)
val firstBuffer = makeMutable(startBuffer)
buffers[0] = firstBuffer
var newNextBuffer = nextBuffer
var newNullBuffers = nullBuffers
val startBufferStartIndex = index and MAX_BUFFER_SIZE_MINUS_ONE
val endBufferEndIndex = (index + elements.size - 1) and MAX_BUFFER_SIZE_MINUS_ONE // inclusive
val elementsToShift = startBufferSize - startBufferStartIndex
if (endBufferEndIndex + elementsToShift < MAX_BUFFER_SIZE) {
firstBuffer.copyInto(newNextBuffer, endBufferEndIndex + 1, startBufferStartIndex, startBufferSize)
} else {
val toCopyToLast = endBufferEndIndex + elementsToShift - MAX_BUFFER_SIZE + 1
if (nullBuffers == 1) {
newNextBuffer = firstBuffer
} else {
newNextBuffer = mutableBuffer()
buffers[--newNullBuffers] = newNextBuffer
}
firstBuffer.copyInto(nextBuffer, 0, startBufferSize - toCopyToLast, startBufferSize)
firstBuffer.copyInto(newNextBuffer, endBufferEndIndex + 1, startBufferStartIndex, startBufferSize - toCopyToLast)
}
val elementsIterator = elements.iterator()
copyToBuffer(firstBuffer, startBufferStartIndex, elementsIterator)
for (i in 1 until newNullBuffers) {
buffers[i] = copyToBuffer(mutableBuffer(), 0, elementsIterator)
}
copyToBuffer(newNextBuffer, 0, elementsIterator)
}
override fun get(index: Int): E {
checkElementIndex(index, size)
val buffer = bufferFor(index)
@Suppress("UNCHECKED_CAST")
return buffer[index and MAX_BUFFER_SIZE_MINUS_ONE] as E
}
private fun bufferFor(index: Int): Array<Any?> {
if (rootSize() <= index) {
return tail
}
var buffer = root!!
var shift = rootShift
while (shift > 0) {
@Suppress("UNCHECKED_CAST")
buffer = buffer[indexSegment(index, shift)] as Array<Any?>
shift -= LOG_MAX_BUFFER_SIZE
}
return buffer
}
override fun removeAt(index: Int): E {
checkElementIndex(index, size)
modCount += 1
val rootSize = rootSize()
if (index >= rootSize) {
@Suppress("UNCHECKED_CAST")
return removeFromTailAt(root, rootSize, rootShift, index - rootSize) as E
}
val elementCarry = ObjectRef(tail[0])
val newRoot = removeFromRootAt(root!!, rootShift, index, elementCarry)
removeFromTailAt(newRoot, rootSize, rootShift, 0)
@Suppress("UNCHECKED_CAST")
return elementCarry.value as E
}
private fun removeFromTailAt(root: Array<Any?>?, rootSize: Int, shift: Int, index: Int): Any? {
val tailSize = size - rootSize
assert(index < tailSize)
val removedElement: Any?
if (tailSize == 1) {
removedElement = tail[0]
pullLastBufferFromRoot(root, rootSize, shift)
} else {
removedElement = tail[index]
val mutableTail = tail.copyInto(makeMutable(tail), index, index + 1, tailSize)
mutableTail[tailSize - 1] = null
this.root = root
this.tail = mutableTail
this.size = rootSize + tailSize - 1
this.rootShift = shift
}
return removedElement
}
/**
* Removes element from trie at the specified trie [index].
*
* [tailCarry] on input contains the first element of the adjacent trie to fill the last vacant element with.
* [tailCarry] on output contains the first element of this trie.
*
* @return the new root of the trie.
*/
private fun removeFromRootAt(root: Array<Any?>, shift: Int, index: Int, tailCarry: ObjectRef): Array<Any?> {
val bufferIndex = indexSegment(index, shift)
if (shift == 0) {
val removedElement = root[bufferIndex]
val mutableRoot = root.copyInto(makeMutable(root), bufferIndex, bufferIndex + 1, MAX_BUFFER_SIZE)
mutableRoot[MAX_BUFFER_SIZE - 1] = tailCarry.value
tailCarry.value = removedElement
return mutableRoot
}
var bufferLastIndex = MAX_BUFFER_SIZE_MINUS_ONE
if (root[bufferLastIndex] == null) {
bufferLastIndex = indexSegment(rootSize() - 1, shift)
}
val mutableRoot = makeMutable(root)
val lowerLevelShift = shift - LOG_MAX_BUFFER_SIZE
for (i in bufferLastIndex downTo bufferIndex + 1) {
@Suppress("UNCHECKED_CAST")
mutableRoot[i] = removeFromRootAt(mutableRoot[i] as Array<Any?>, lowerLevelShift, 0, tailCarry)
}
@Suppress("UNCHECKED_CAST")
mutableRoot[bufferIndex] =
removeFromRootAt(mutableRoot[bufferIndex] as Array<Any?>, lowerLevelShift, index, tailCarry)
return mutableRoot
}
/**
* Extracts the last entirely filled leaf buffer from the trie of this vector and makes it a tail in this
*
* Used when there are no elements left in current tail.
*
* Requires the trie to contain at least one leaf buffer.
*/
private fun pullLastBufferFromRoot(root: Array<Any?>?, rootSize: Int, shift: Int) {
if (shift == 0) {
this.root = null
this.tail = root ?: emptyArray()
this.size = rootSize
this.rootShift = shift
return
}
val tailCarry = ObjectRef(null)
val newRoot = pullLastBuffer(root!!, shift, rootSize, tailCarry)!!
@Suppress("UNCHECKED_CAST")
this.tail = tailCarry.value as Array<Any?>
this.size = rootSize
// check if the new root contains only one element
if (newRoot[1] == null) {
// demote the root trie to the lower level
@Suppress("UNCHECKED_CAST")
this.root = newRoot[0] as Array<Any?>?
this.rootShift = shift - LOG_MAX_BUFFER_SIZE
} else {
this.root = newRoot
this.rootShift = shift
}
}
/**
* Extracts the last leaf buffer from trie and returns new trie without it or `null` if there's no more leaf elements in this trie.
*
* [tailCarry] on output contains the extracted leaf buffer.
*/
private fun pullLastBuffer(root: Array<Any?>, shift: Int, rootSize: Int, tailCarry: ObjectRef): Array<Any?>? {
val bufferIndex = indexSegment(rootSize - 1, shift)
val newBufferAtIndex = if (shift == LOG_MAX_BUFFER_SIZE) {
tailCarry.value = root[bufferIndex]
null
} else {
@Suppress("UNCHECKED_CAST")
pullLastBuffer(root[bufferIndex] as Array<Any?>, shift - LOG_MAX_BUFFER_SIZE, rootSize, tailCarry)
}
if (newBufferAtIndex == null && bufferIndex == 0) {
return null
}
val mutableRoot = makeMutable(root)
mutableRoot[bufferIndex] = newBufferAtIndex
return mutableRoot
}
override fun removeAll(elements: Collection<E>): Boolean {
return removeAllWithPredicate { elements.contains(it) }
}
fun removeAllWithPredicate(predicate: (E) -> Boolean): Boolean {
val anyRemoved = removeAll(predicate)
if (anyRemoved) {
modCount++
}
return anyRemoved
}
// Does not update `modCount`.
private fun removeAll(predicate: (E) -> Boolean): Boolean {
val tailSize = tailSize()
val bufferRef = ObjectRef(null)
if (root == null) {
return removeAllFromTail(predicate, tailSize, bufferRef) != tailSize
}
val leafIterator = leafBufferIterator(0)
var bufferSize = MAX_BUFFER_SIZE
// skip unaffected leaves
while (bufferSize == MAX_BUFFER_SIZE && leafIterator.hasNext()) {
bufferSize = removeAll(predicate, leafIterator.next(), MAX_BUFFER_SIZE, bufferRef)
}
// if no elements from the root match the predicate, check the tail
if (bufferSize == MAX_BUFFER_SIZE) {
assert(!leafIterator.hasNext())
val newTailSize = removeAllFromTail(predicate, tailSize, bufferRef)
if (newTailSize == 0) {
// all elements of the tail was removed, pull the last leaf from the root to make it the tail
pullLastBufferFromRoot(root, size, rootShift)
}
return newTailSize != tailSize
}
// handle affected leaves reusing mutable ones
val unaffectedElementsCount = leafIterator.previousIndex() shl LOG_MAX_BUFFER_SIZE
val buffers = mutableListOf<Array<Any?>>()
val recyclableBuffers = mutableListOf<Array<Any?>>()
while (leafIterator.hasNext()) {
val leaf = leafIterator.next()
bufferSize = recyclableRemoveAll(predicate, leaf, MAX_BUFFER_SIZE, bufferSize, bufferRef, recyclableBuffers, buffers)
}
// handle the tail
val newTailSize = recyclableRemoveAll(predicate, tail, tailSize, bufferSize, bufferRef, recyclableBuffers, buffers)
@Suppress("UNCHECKED_CAST")
val newTail = bufferRef.value as Array<Any?>
newTail.fill(null, newTailSize, MAX_BUFFER_SIZE)
// build the root
val newRoot = if (buffers.isEmpty()) root!! else pushBuffers(root, unaffectedElementsCount, rootShift, buffers.iterator())
val newRootSize = unaffectedElementsCount + (buffers.size shl LOG_MAX_BUFFER_SIZE)
root = retainFirst(newRoot, newRootSize)
tail = newTail
size = newRootSize + newTailSize
return true
}
/**
* Retains first [size] elements of the [root].
*
* If the height of the root is bigger than needed to store [size] elements, it's decreased.
*/
private fun retainFirst(root: Array<Any?>, size: Int): Array<Any?>? {
check(size and MAX_BUFFER_SIZE_MINUS_ONE == 0)
if (size == 0) {
rootShift = 0
return null
}
val lastIndex = size - 1
var newRoot = root
while (lastIndex shr rootShift == 0) {
rootShift -= LOG_MAX_BUFFER_SIZE
@Suppress("UNCHECKED_CAST")
newRoot = root[0] as Array<Any?>
}
return nullifyAfter(newRoot, lastIndex, rootShift)
}
/**
* Nullifies nodes cells after the specified [index].
*
* Used to prevent memory leaks after reusing nodes.
*/
private fun nullifyAfter(root: Array<Any?>, index: Int, shift: Int): Array<Any?> {
check(shift >= 0)
if (shift == 0) {
// the `root` is a leaf buffer.
// As leaf buffers can't be filled partially, return the `root` as is.
return root
}
val lastIndex = indexSegment(index, shift)
@Suppress("UNCHECKED_CAST")
val newChild = nullifyAfter(root[lastIndex] as Array<Any?>, index, shift - LOG_MAX_BUFFER_SIZE)
var newRoot = root
if (lastIndex < MAX_BUFFER_SIZE_MINUS_ONE && newRoot[lastIndex + 1] != null) {
if (isMutable(newRoot)) {
newRoot.fill(null, lastIndex + 1, MAX_BUFFER_SIZE)
}
newRoot = newRoot.copyInto(mutableBuffer(), 0, 0, lastIndex + 1)
}
if (newChild !== newRoot[lastIndex]) {
newRoot = makeMutable(newRoot)
newRoot[lastIndex] = newChild
}
return newRoot
}
/**
* Copies elements of the [tail] buffer of size [tailSize] that do not match the given [predicate] to a new buffer.
*
* If the [tail] is mutable, it is reused to store non-matching elements.
* If non of the elements match the [predicate], no buffers are created and elements are not copied.
* [bufferRef] stores the newly created buffer, or the [tail] if a new buffer was not created.
*
* Returns the filled size of the buffer stored in the [bufferRef].
*/
private fun removeAllFromTail(predicate: (E) -> Boolean, tailSize: Int, bufferRef: ObjectRef): Int {
val newTailSize = removeAll(predicate, tail, tailSize, bufferRef)
if (newTailSize == tailSize) {
assert(bufferRef.value === tail)
return tailSize
}
@Suppress("UNCHECKED_CAST")
val newTail = bufferRef.value as Array<Any?>
newTail.fill(null, newTailSize, tailSize)
tail = newTail
size -= tailSize - newTailSize
return newTailSize
}
/**
* Copies elements of the given [buffer] of size [bufferSize] that do not match the given [predicate] to a new buffer.
*
* If the [buffer] is mutable, it is reused to store non-matching elements.
* If non of the elements match the [predicate], no buffers are created and elements are not copied.
* [bufferRef] stores the newly created buffer, or the [buffer] if a new buffer was not created.
*
* Returns the filled size of the buffer stored in the [bufferRef].
*/
private fun removeAll(
predicate: (E) -> Boolean,
buffer: Array<Any?>,
bufferSize: Int,
bufferRef: ObjectRef
): Int {
var newBuffer = buffer
var newBufferSize = bufferSize
var anyRemoved = false
for (index in 0 until bufferSize) {
@Suppress("UNCHECKED_CAST")
val element = buffer[index] as E
if (predicate(element)) {
if (!anyRemoved) {
newBuffer = makeMutable(buffer)
newBufferSize = index
anyRemoved = true
}
} else if (anyRemoved) {
newBuffer[newBufferSize++] = element
}
}
bufferRef.value = newBuffer
return newBufferSize
}
/**
* Copied elements of the given [buffer] of size [bufferSize] that do not match the given [predicate]
* to the buffer stored in the given [bufferRef] starting at [toBufferSize].
*
* If the buffer gets filled entirely, it is added to [buffers] and a new buffer is created or
* reused from the [recyclableBuffers] to hold the rest of the non-matching elements.
* [bufferRef] stores the newly created buffer if a new buffer was created.
*
* Returns the filled size of the buffer stored in the [bufferRef].
*/
private fun recyclableRemoveAll(
predicate: (E) -> Boolean,
buffer: Array<Any?>,
bufferSize: Int,
toBufferSize: Int,
bufferRef: ObjectRef,
recyclableBuffers: MutableList<Array<Any?>>,
buffers: MutableList<Array<Any?>>
): Int {
if (isMutable(buffer)) {
recyclableBuffers.add(buffer)
}
@Suppress("UNCHECKED_CAST")
val toBuffer = bufferRef.value as Array<Any?>
var newToBuffer = toBuffer
var newToBufferSize = toBufferSize
for (index in 0 until bufferSize) {
@Suppress("UNCHECKED_CAST")
val element = buffer[index] as E
if (!predicate(element)) {
if (newToBufferSize == MAX_BUFFER_SIZE) {
newToBuffer = if (recyclableBuffers.isNotEmpty()) {
recyclableBuffers.removeAt(recyclableBuffers.size - 1)
} else {
mutableBuffer()
}
newToBufferSize = 0
}
newToBuffer[newToBufferSize++] = element
}
}
bufferRef.value = newToBuffer
if (toBuffer !== bufferRef.value) {
buffers.add(toBuffer)
}
return newToBufferSize
}
override fun set(index: Int, element: E): E {
// TODO: Should list[i] = list[i] make it mutable?
checkElementIndex(index, size)
if (rootSize() <= index) {
val mutableTail = makeMutable(tail)
// Creating new tail implies structural change.
if (mutableTail !== tail) { modCount++ }
val tailIndex = index and MAX_BUFFER_SIZE_MINUS_ONE
val oldElement = mutableTail[tailIndex]
mutableTail[tailIndex] = element
this.tail = mutableTail
@Suppress("UNCHECKED_CAST")
return oldElement as E
}
val oldElementCarry = ObjectRef(null)
this.root = setInRoot(root!!, rootShift, index, element, oldElementCarry)
@Suppress("UNCHECKED_CAST")
return oldElementCarry.value as E
}
private fun setInRoot(root: Array<Any?>, shift: Int, index: Int, e: E, oldElementCarry: ObjectRef): Array<Any?> {
val bufferIndex = indexSegment(index, shift)
val mutableRoot = makeMutable(root)
if (shift == 0) {
// Creating new leaf implies structural change.
// Actually, while descending to this leaf several nodes could be recreated.
// However, this builder is exclusive owner of this leaf iff it is exclusive owner of all leaf's ancestors.
// Hence, checking recreation of this leaf is enough to determine if a structural change occurred.
if (mutableRoot !== root) { modCount++ }
oldElementCarry.value = mutableRoot[bufferIndex]
mutableRoot[bufferIndex] = e
return mutableRoot
}
@Suppress("UNCHECKED_CAST")
mutableRoot[bufferIndex] =
setInRoot(mutableRoot[bufferIndex] as Array<Any?>, shift - LOG_MAX_BUFFER_SIZE, index, e, oldElementCarry)
return mutableRoot
}
override fun iterator(): MutableIterator<E> {
return this.listIterator()
}
override fun listIterator(): MutableListIterator<E> {
return this.listIterator(0)
}
override fun listIterator(index: Int): MutableListIterator<E> {
checkPositionIndex(index, size)
return PersistentVectorMutableIterator(this, index)
}
private fun leafBufferIterator(index: Int): ListIterator<Array<Any?>> {
checkNotNull(root)
val leafCount = rootSize() shr LOG_MAX_BUFFER_SIZE
checkPositionIndex(index, leafCount)
if (rootShift == 0) {
return SingleElementListIterator(root!!, index)
}
val trieHeight = rootShift / LOG_MAX_BUFFER_SIZE
return TrieIterator(root!!, index, leafCount, trieHeight)
}
}
|
apache-2.0
|
c4dab1c440674e0f8afde639de238a9c
| 35.421796 | 135 | 0.599989 | 4.480387 | false | false | false | false |
BlueBoxWare/LibGDXPlugin
|
src/main/kotlin/com/gmail/blueboxware/libgdxplugin/filetypes/json/structureView/GdxJsonStructureViewElement.kt
|
1
|
2850
|
package com.gmail.blueboxware.libgdxplugin.filetypes.json.structureView
import com.gmail.blueboxware.libgdxplugin.filetypes.json.psi.*
import com.gmail.blueboxware.libgdxplugin.utils.childOfType
import com.intellij.ide.structureView.StructureViewTreeElement
import com.intellij.ide.structureView.StructureViewTreeElement.EMPTY_ARRAY
import com.intellij.ide.util.treeView.smartTree.TreeElement
import com.intellij.navigation.ItemPresentation
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiTreeUtil
import javax.swing.Icon
/*
* Copyright 2019 Blue Box Ware
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
class GdxJsonStructureViewElement(val element: GdxJsonElement) : StructureViewTreeElement {
override fun navigate(requestFocus: Boolean) = element.navigate(requestFocus)
override fun canNavigate(): Boolean = element.canNavigate()
override fun getValue(): PsiElement = element
override fun canNavigateToSource(): Boolean = element.canNavigateToSource()
override fun getPresentation(): ItemPresentation = element.presentation ?: object : ItemPresentation {
override fun getLocationString(): String? = null
override fun getIcon(unused: Boolean): Icon? = null
override fun getPresentableText(): String? = element.text
}
override fun getChildren(): Array<out TreeElement> {
var value: GdxJsonElement? = null
when (element) {
is GdxJsonFile -> value = element.childOfType<GdxJsonValue>()?.value
is GdxJsonProperty -> value = element.value?.value
is GdxJsonJobject, is GdxJsonArray -> value = element
}
if (value is GdxJsonJobject) {
return value.propertyList.map { GdxJsonStructureViewElement(it) }.toTypedArray()
} else if (value is GdxJsonArray) {
return value.valueList.mapNotNull { it.value }.mapNotNull {
if (it is GdxJsonJobject && it.propertyList.isNotEmpty()) {
GdxJsonStructureViewElement(it)
} else if (it is GdxJsonArray && PsiTreeUtil.findChildOfType(it, GdxJsonProperty::class.java) != null) {
GdxJsonStructureViewElement(it)
} else {
null
}
}.toTypedArray()
}
return EMPTY_ARRAY
}
}
|
apache-2.0
|
cbc024cb33e5730eb4f2cd405071dc20
| 37 | 120 | 0.702105 | 4.965157 | false | false | false | false |
holgerbrandl/kscript
|
src/main/kotlin/kscript/app/util/UriUtils.kt
|
1
|
936
|
package kscript.app.util
import java.net.HttpURLConnection
import java.net.URI
import java.net.URL
object UriUtils {
fun isUrl(string: String): Boolean {
val normalizedString = string.lowercase().trim()
return normalizedString.startsWith("http://") || normalizedString.startsWith("https://")
}
fun isUrl(uri: URI) = uri.scheme.equals("http") || uri.scheme.equals("https")
fun isRegularFile(uri: URI) = uri.scheme.startsWith("file")
fun resolveRedirects(url: URL): URL {
val con: HttpURLConnection = url.openConnection() as HttpURLConnection
con.instanceFollowRedirects = false
con.connect()
if (con.responseCode == HttpURLConnection.HTTP_MOVED_PERM || con.responseCode == HttpURLConnection.HTTP_MOVED_TEMP) {
val redirectUrl = URL(con.getHeaderField("Location"))
return resolveRedirects(redirectUrl)
}
return url
}
}
|
mit
|
f5e1090625722f8668261c46a913a926
| 31.275862 | 125 | 0.674145 | 4.457143 | false | false | false | false |
OpenConference/OpenConference-android
|
app/src/main/java/com/openconference/sessiondetails/SessionDetailsFragment.kt
|
1
|
7964
|
package com.openconference.sessiondetails
import android.graphics.drawable.AnimatedVectorDrawable
import android.os.Bundle
import android.support.annotation.StringRes
import android.support.design.widget.CollapsingToolbarLayout
import android.support.design.widget.FloatingActionButton
import android.support.design.widget.Snackbar
import android.support.v4.content.res.ResourcesCompat
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.Toolbar
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.OvershootInterpolator
import android.widget.TextView
import com.hannesdorfmann.adapterdelegates2.AdapterDelegatesManager
import com.hannesdorfmann.adapterdelegates2.ListDelegationAdapter
import com.hannesdorfmann.fragmentargs.FragmentArgs
import com.hannesdorfmann.fragmentargs.annotation.Arg
import com.hannesdorfmann.fragmentargs.annotation.FragmentWithArgs
import com.hannesdorfmann.mosby.mvp.viewstate.MvpViewStateFragment
import com.openconference.Navigator
import com.openconference.R
import com.openconference.model.Session
import com.openconference.sessiondetails.presentationmodel.SessionDetail
import com.openconference.sessiondetails.presentationmodel.SessionDetailItem
import com.openconference.util.applicationComponent
import com.openconference.util.findView
import com.openconference.util.layoutInflater
import com.openconference.util.lce.LceAnimatable
import com.openconference.util.lce.LceViewState
import com.openconference.util.picasso.PicassoScrollListener
import com.squareup.picasso.Picasso
import javax.inject.Inject
/**
* Displays the details of a Session
*
* @author Hannes Dorfmann
*/
@FragmentWithArgs
open class SessionDetailsFragment : SessionDetailsView, LceAnimatable<SessionDetail>, MvpViewStateFragment<SessionDetailsView, SessionDetailsPresenter>() {
@Arg lateinit var session: Session
override lateinit var content_view: View
override lateinit var errorView: TextView
override lateinit var loadingView: View
override lateinit var emptyView: View
protected lateinit var recyclerView: RecyclerView
protected lateinit var adapter: ListDelegationAdapter<List<SessionDetailItem>>
protected lateinit var component: SessionDetailsComponent
protected lateinit var toolbar: Toolbar
protected lateinit var collapsingToolbar: CollapsingToolbarLayout
protected lateinit var title: TextView
protected lateinit var fab: FloatingActionButton
lateinit var sessionDetails: SessionDetail
private var runningFirstTime = true
@Inject protected lateinit var navigator: Navigator
@Inject protected lateinit var picasso: Picasso
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
FragmentArgs.inject(this)
retainInstance = true
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
component = DaggerSessionDetailsComponent.builder()
.applicationComponent(applicationComponent())
.sessionDetailsModule(SessionDetailsModule(activity))
.build()
component.inject(this)
return inflater.inflate(R.layout.fragment_session_details,
container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
content_view = view.findView(R.id.contentView)
errorView = view.findView(R.id.errorView)
emptyView = view.findView(R.id.emptyView)
recyclerView = view.findView(R.id.recyclerView)
loadingView = view.findView(R.id.loadingView)
toolbar = view.findView(R.id.toolbar)
collapsingToolbar = view.findView(R.id.collapsingToolbar)
title = view.findView(R.id.title)
fab = view.findView(R.id.fab)
fab.setOnClickListener {
val animTime = resources.getInteger(R.integer.add_to_schedule_duration)
val animatedDrawable = fab.drawable as AnimatedVectorDrawable
animatedDrawable.start()
fab.isClickable = false
// TODO is there really no better way to listen for callbacks?
fab.postDelayed({
if (sessionDetails.inMySchedule) {
presenter.removeSessionFromSchedule(sessionDetails.session)
} else {
presenter.addSessionToSchedule(sessionDetails.session)
}
}, animTime + 100L)
}
toolbar.setNavigationOnClickListener { activity.finish() }
// toolbar.title = session.title()
title.text = session.title()
adapter = createAdapter()
recyclerView.adapter = adapter
recyclerView.layoutManager = LinearLayoutManager(activity)
recyclerView.addOnScrollListener(PicassoScrollListener(picasso))
}
fun createAdapter(): ListDelegationAdapter<List<SessionDetailItem>> {
val inflater = layoutInflater()
return ListDelegationAdapter(
AdapterDelegatesManager<List<SessionDetailItem>>()
.addDelegate(DetailsDateAdapterDelegate(inflater))
.addDelegate(DetailsDescriptionAdapterDelegate(inflater))
.addDelegate(DetailsLocationAdapterDelegate(inflater))
.addDelegate(DetailsSeparatorAdapterDelegate(inflater))
.addDelegate(DetailsSpeakerAdapterDelegate(inflater, picasso,
{ navigator.showSpeakerDetails(it) }))
)
}
override fun getViewState(): LceViewState<SessionDetail>? = super.getViewState() as LceViewState<SessionDetail>?
override fun showLoading() {
super.showLoading()
fab.visibility = View.GONE
}
override fun showError(@StringRes errorRes: Int) {
super.showError(errorRes)
fab.visibility = View.GONE
}
override fun showContent(data: SessionDetail) {
this.sessionDetails = data
adapter.items = data.detailsItems
adapter.notifyDataSetChanged()
setFabDrawable()
fab.isClickable = true
if (!isRestoringViewState && runningFirstTime) {
runningFirstTime = false // Only animate on first appearance
fab.scaleX = 0f
fab.scaleY = 0f
fab.visibility = View.VISIBLE
fab.animate().scaleX(1f).scaleY(1f).setInterpolator(OvershootInterpolator()).setStartDelay(
1000).start()
} else {
fab.visibility = View.VISIBLE
}
super.showContent(data)
}
override fun isDataEmpty(data: SessionDetail): Boolean = data.detailsItems.isEmpty()
private inline fun loadData() = presenter.loadSession(session.id());
override fun onNewViewStateInstance() = loadData()
override fun createPresenter(): SessionDetailsPresenter = component.sessionDetailsPresenter()
override fun createViewState(): LceViewState<SessionDetailsView> = LceViewState()
override fun showSessionAddedToSchedule() {
Snackbar.make(content_view, R.string.session_details_added_to_schedule,
Snackbar.LENGTH_LONG).show()
}
override fun showErrorWhileAddingSessionToSchedule() {
Snackbar.make(content_view, R.string.error_session_details_added_to_schedule,
Snackbar.LENGTH_LONG).show()
fab.isClickable = true
setFabDrawable()
}
override fun showSessionRemovedFromSchedule() {
// Not needed
}
override fun showErrorWhileRemovingSessionFromSchedule() {
Snackbar.make(content_view, R.string.error_session_details_removed_from_schedule,
Snackbar.LENGTH_LONG).show()
fab.isClickable = true
setFabDrawable()
}
private inline fun setFabDrawable() {
val drawable = fab.drawable as AnimatedVectorDrawable
drawable.stop()
if (sessionDetails.inMySchedule) {
fab.setImageDrawable(
ResourcesCompat.getDrawable(resources, R.drawable.avd_remove_from_schedule,
activity.theme)!!.mutate().constantState.newDrawable())
} else {
fab.setImageDrawable(
ResourcesCompat.getDrawable(resources, R.drawable.avd_add_to_schedule,
activity.theme)!!.mutate().constantState.newDrawable())
}
}
}
|
apache-2.0
|
842b0bf632d5789057939b5695f23977
| 35.369863 | 155 | 0.764063 | 4.826667 | false | false | false | false |
bubelov/coins-android
|
app/src/main/java/com/bubelov/coins/repository/rate/Coinbase.kt
|
1
|
1254
|
package com.bubelov.coins.repository.rate
import com.bubelov.coins.api.rates.CoinbaseApi
import com.bubelov.coins.model.CurrencyPair
import com.bubelov.coins.repository.Result
import com.google.gson.Gson
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
class Coinbase(gson: Gson) : ExchangeRatesSource {
override val name = "Coinbase"
val api: CoinbaseApi = Retrofit.Builder()
.baseUrl("https://api.coinbase.com/v2/")
.addConverterFactory(GsonConverterFactory.create(gson))
.build()
.create(CoinbaseApi::class.java)
override fun getCurrencyPairs(): Collection<CurrencyPair> {
return listOf(CurrencyPair.BTC_USD, CurrencyPair.BTC_EUR, CurrencyPair.BTC_GBP)
}
override suspend fun getExchangeRate(pair: CurrencyPair): Result<Double> {
if (pair == CurrencyPair.BTC_USD || pair == CurrencyPair.BTC_EUR || pair == CurrencyPair.BTC_GBP) {
return try {
val result = api.getExchangeRates()
Result.Success(result.data.rates.getValue(pair.quoteCurrency))
} catch (e: Exception) {
Result.Error(e)
}
} else {
throw IllegalArgumentException()
}
}
}
|
unlicense
|
c7110f31521a33c8bf54fd3de961fe66
| 34.857143 | 107 | 0.671451 | 4.111475 | false | false | false | false |
facebook/fresco
|
samples/showcase/src/main/java/com/facebook/fresco/samples/showcase/vito/renderer/RendererExampleDrawable.kt
|
2
|
1312
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.fresco.samples.showcase.vito.renderer
import android.graphics.Canvas
import android.graphics.ColorFilter
import android.graphics.Matrix
import android.graphics.Paint
import android.graphics.PixelFormat
import android.graphics.drawable.Drawable
import com.facebook.fresco.vito.renderer.ImageDataModel
import com.facebook.fresco.vito.renderer.ImageRenderer
import com.facebook.fresco.vito.renderer.Shape
open class RendererExampleDrawable(
private val imageDataModel: ImageDataModel,
private val shape: Shape,
private val transformationMatrix: Matrix? = null,
private var imageColorFilter: ColorFilter? = null,
) : Drawable() {
override fun draw(canvas: Canvas) {
ImageRenderer.createImageDataModelRenderCommand(
imageDataModel,
shape,
Paint(Paint.ANTI_ALIAS_FLAG).apply { colorFilter = imageColorFilter },
transformationMatrix)(canvas)
}
override fun setAlpha(alpha: Int) = Unit
override fun setColorFilter(colorFilter: ColorFilter?) {
imageColorFilter = colorFilter
}
override fun getOpacity(): Int = PixelFormat.TRANSLUCENT
}
|
mit
|
17a1030a331b9b5269a0f37d062e7b55
| 31 | 78 | 0.768293 | 4.477816 | false | false | false | false |
soeminnminn/EngMyanDictionary
|
app/src/main/java/com/s16/engmyan/activity/DetailsActivity.kt
|
1
|
7415
|
package com.s16.engmyan.activity
import android.content.Context
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.google.android.material.snackbar.Snackbar
import com.s16.app.BackStackActivity
import com.s16.engmyan.Constants
import com.s16.engmyan.R
import com.s16.engmyan.data.DbManager
import com.s16.engmyan.data.DefinitionItem
import com.s16.engmyan.data.DefinitionModel
import com.s16.engmyan.data.FavoriteItem
import com.s16.engmyan.fragments.DetailsFragment
import com.s16.engmyan.utils.DefinitionBuilder
import com.s16.engmyan.utils.MenuItemToggle
import com.s16.engmyan.utils.TextToSpeechHelper
import com.s16.engmyan.utils.UIManager
import kotlinx.android.synthetic.main.activity_details.*
import kotlinx.coroutines.*
import java.lang.Exception
class DetailsActivity : BackStackActivity(),
DefinitionBuilder.OnWordLinkClickListener {
private var recordId: Long = 0
private val menuFavorite = MenuItemToggle(true).apply {
setIcon(R.drawable.ic_favorite_off)
setTitle(R.string.action_favorite)
setIconChecked(R.drawable.ic_favorite_on)
setTitleChecked(R.string.action_favorite_remove)
}
private val menuPicture = MenuItemToggle()
private lateinit var menuSound : MenuItem
private lateinit var model: DefinitionModel
private lateinit var textToSpeech: TextToSpeechHelper
private var uiScope = CoroutineScope(Dispatchers.Main)
private var backgroundScope = CoroutineScope(Dispatchers.IO)
private var favoriteJob: Job? = null
private var historyJob: Job? = null
private var linkClickJob: Job? = null
private val context: Context
get() = this
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_details)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
recordId = intent.getLongExtra(Constants.ARG_PARAM_ID, 0)
textToSpeech = TextToSpeechHelper(this)
textToSpeech.onTextToSpeechListener = object: TextToSpeechHelper.OnTextToSpeechListener {
override fun onTextToSpeechInit(enabled: Boolean) {
if (::menuSound.isInitialized) {
menuSound.isVisible = enabled
}
}
}
model = ViewModelProvider(this).get(DefinitionModel::class.java)
model.data.observe(
this, Observer<DefinitionItem> { item ->
saveHistory(item)
title = item.word ?: ""
menuFavorite.setCheck(item.isFavorite)
menuPicture.isVisible = item.hasImage
textToSpeech.text = item.word ?: ""
}
)
if (savedInstanceState == null) {
createNewFragment(R.id.detailsContainer, DetailsFragment.newInstance(recordId), "details_$recordId")
}
model.fetch(recordId)
}
override fun onDestroy() {
textToSpeech.shutdown()
favoriteJob?.cancel()
historyJob?.cancel()
linkClickJob?.cancel()
super.onDestroy()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.details, menu)
return true
}
override fun onPrepareOptionsMenu(menu: Menu): Boolean {
menuFavorite.menuItem = menu.findItem(R.id.action_favorite)
menuPicture.menuItem = menu.findItem(R.id.action_picture)
menuSound = menu.findItem(R.id.action_sound)
if (::textToSpeech.isInitialized) {
menuSound.isVisible = textToSpeech.isEnabled
}
return super.onPrepareOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
android.R.id.home -> {
onBackPressed()
true
}
R.id.action_favorite -> {
performFavorite(item.isChecked)
true
}
R.id.action_sound -> {
performSpeak()
true
}
R.id.action_picture -> {
performPicture()
true
}
else -> super.onOptionsItemSelected(item)
}
}
override fun onBackPressed() {
if (getTopFragment<DetailsFragment>()?.onBackPressed() == true) {
return
}
super.onBackPressed()
}
override fun onBackStackChanged(activeFragment: Fragment) {
activeFragment.arguments?.let { args ->
recordId = args.getLong(Constants.ARG_PARAM_ID, 0)
model.fetch(recordId)
}
}
override fun onWordLinkClick(word: String) {
linkClickJob = uiScope.launch {
val id = withContext(Dispatchers.IO) {
val searchWord = word.replace("'", "''")
.replace("%", "").replace("_", "").trim()
try {
val provider = DbManager(context).provider()
provider.queryId(searchWord)
} catch (e: Exception) {
e.printStackTrace()
-1L
}
}
if (::model.isInitialized && id > 0L) {
recordId = id
addNewFragment(R.id.detailsContainer, DetailsFragment.newInstance(recordId), "details_$recordId")
model.fetch(recordId)
}
}
}
private fun performFavorite(isFavorite: Boolean) {
val item = FavoriteItem(word = "$title", refId = recordId, timestamp = System.currentTimeMillis())
favoriteJob = uiScope.launch {
val provider = DbManager(context).provider()
val result = withContext(Dispatchers.IO) {
try {
if (isFavorite) {
provider.deleteFavoriteByRef(recordId)
0L
} else {
provider.insertFavorite(item)
}
} catch (e: Exception) {
e.printStackTrace()
-1L
}
}
try {
val topFav = provider.queryTopFavorites()
UIManager.createShortcuts(context, topFav)
} catch (e: Exception) {
e.printStackTrace()
}
if (result == 0L) {
Snackbar.make(detailsRoot, getText(R.string.remove_favorites_message), Snackbar.LENGTH_LONG).show()
} else if (result > 0L) {
Snackbar.make(detailsRoot, getText(R.string.add_favorites_message), Snackbar.LENGTH_LONG).show()
}
}
}
private fun performSpeak() {
textToSpeech.speak()
}
private fun performPicture() {
getTopFragment<DetailsFragment>()?.togglePicture()
}
private fun saveHistory(item: DefinitionItem) {
historyJob = backgroundScope.launch {
try {
val provider = DbManager(context).provider()
provider.createHistory(item.word ?: "", item.id)
} catch (e: Exception) {
e.printStackTrace()
}
}
}
}
|
gpl-2.0
|
937bcbb4f7834f03ca3174e2ae896b0f
| 31.379913 | 115 | 0.595819 | 4.852749 | false | false | false | false |
tangying91/profit
|
src/main/java/org/profit/server/handler/HttpServerHandler.kt
|
1
|
4083
|
package org.profit.server.handler
import io.netty.buffer.Unpooled
import io.netty.channel.ChannelFutureListener
import io.netty.channel.ChannelHandler.Sharable
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.SimpleChannelInboundHandler
import io.netty.handler.codec.http.*
import io.netty.util.CharsetUtil
import org.profit.app.Actions
import org.profit.server.handler.communication.RequestMessage
import org.profit.server.handler.communication.exception.InvalidActionException
import org.profit.server.handler.communication.exception.InvalidParamException
import org.slf4j.LoggerFactory
/**
* @author TangYing
*/
@Sharable
class HttpServerHandler : SimpleChannelInboundHandler<FullHttpRequest>() {
private val staticFileHandler = HttpStaticFileHandler()
@Throws(Exception::class)
override fun channelRead0(ctx: ChannelHandlerContext, request: FullHttpRequest) {
if (request.method !== HttpMethod.GET) {
sendError(ctx, HttpResponseStatus.FORBIDDEN)
return
}
val decoder = QueryStringDecoder(request.uri)
val parameters = decoder.parameters()
val path = decoder.path()
if (!path.endsWith(actionSuffix)) {
staticFileHandler.handleStaticFile(ctx, request)
return
}
// Action request
val actionUri = getActionUri(path)
val actionName = actionUri.replace(actionSuffix.toRegex(), "")
if (actionName.contains("_")) {
try {
val action = Actions.INSTANCE.interpretCommand(actionName)
if (action == null) {
sendError(ctx, HttpResponseStatus.FORBIDDEN)
return
}
// Execute action
val requestMessage = RequestMessage(parameters)
action.execute(ctx, requestMessage)
} catch (ipe: InvalidParamException) {
LOG.error("InvalidParamException. {}", ipe.message)
sendError(ctx, HttpResponseStatus.FORBIDDEN)
} catch (iae: InvalidActionException) {
LOG.error("InvalidActionException. {}", iae.message)
sendError(ctx, HttpResponseStatus.FORBIDDEN)
}
return
}
// Sya forbidden
sendError(ctx, HttpResponseStatus.FORBIDDEN)
}
@Throws(Exception::class)
override fun channelReadComplete(ctx: ChannelHandlerContext) {
ctx.flush()
}
@Throws(Exception::class)
override fun exceptionCaught(ctx: ChannelHandlerContext, cause: Throwable) {
cause.printStackTrace()
ctx.close()
}
/**
* Get action URL
*
* @param uri
* @return
*/
protected fun getActionUri(uri: String): String {
val baseUri = getBaseUri(uri)
return uri.substring(uri.indexOf(baseUri) + baseUri.length)
}
/**
* Get base URL
*
* @param uri
* @return
*/
protected fun getBaseUri(uri: String): String {
val idx = uri.indexOf("/", 1)
return if (idx == -1) {
"/"
} else {
uri.substring(0, idx)
}
}
companion object {
private val LOG = LoggerFactory.getLogger(HttpServerHandler::class.java)
private const val actionSuffix = ".action"
/**
* Send error status
*
* @param ctx
* @param status
*/
private fun sendError(ctx: ChannelHandlerContext, status: HttpResponseStatus) {
val response: FullHttpResponse = DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, Unpooled.copiedBuffer("Failure: $status\r\n", CharsetUtil.UTF_8))
response.headers()[HttpHeaders.Names.CONTENT_TYPE] = "text/plain; charset=UTF-8"
// Close the connection as soon as the error message is sent.
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE)
}
}
}
|
apache-2.0
|
ab821e612835247a5c66513f22fd5429
| 33.833333 | 164 | 0.614744 | 4.814858 | false | false | false | false |
nsnikhil/Notes
|
app/src/main/java/com/nrs/nsnik/notes/util/FileUtil.kt
|
1
|
8077
|
/*
* Notes Copyright (C) 2018 Nikhil Soni
* This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
* This is free software, and you are welcome to redistribute it
* under certain conditions; type `show c' for details.
*
* The hypothetical commands `show w' and `show c' should show the appropriate
* parts of the General Public License. Of course, your program's commands
* might be different; for a GUI interface, you would use an "about box".
*
* You should also get your employer (if you work as a programmer) or school,
* if any, to sign a "copyright disclaimer" for the program, if necessary.
* For more information on this, and how to apply and follow the GNU GPL, see
* <http://www.gnu.org/licenses/>.
*
* The GNU General Public License does not permit incorporating your program
* into proprietary programs. If your program is a subroutine library, you
* may consider it more useful to permit linking proprietary applications with
* the library. If this is what you want to do, use the GNU Lesser General
* Public License instead of this License. But first, please read
* <http://www.gnu.org/philosophy/why-not-lgpl.html>.
*/
package com.nrs.nsnik.notes.util
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import androidx.lifecycle.MutableLiveData
import com.nrs.nsnik.notes.dagger.qualifiers.RootFolder
import com.nrs.nsnik.notes.dagger.scopes.ApplicationScope
import com.nrs.nsnik.notes.data.NoteEntity
import io.reactivex.Completable
import io.reactivex.CompletableObserver
import io.reactivex.Single
import io.reactivex.SingleObserver
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.internal.operators.completable.CompletableFromCallable
import io.reactivex.schedulers.Schedulers
import okio.Buffer
import okio.ByteString
import okio.Okio
import timber.log.Timber
import java.io.*
import java.util.concurrent.Callable
import javax.inject.Inject
@ApplicationScope
class FileUtil @Inject
internal constructor(@param:ApplicationScope @param:RootFolder val rootFolder: File) {
@Throws(IOException::class)
internal fun saveNote(noteEntity: NoteEntity, fileName: String) {
val completable: Completable = CompletableFromCallable(Callable {
val file = File(rootFolder, fileName)
val sink = Okio.buffer(Okio.sink(file))
sink.write(serialize(noteEntity))
sink.close()
}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
completable.subscribe(object : CompletableObserver {
override fun onComplete() {
Timber.d("Note Saved")
}
override fun onSubscribe(d: Disposable) {
}
override fun onError(e: Throwable) {
Timber.d(e)
}
})
}
@Throws(IOException::class)
fun saveImage(image: Bitmap, fileName: String) {
val completable: Completable = CompletableFromCallable(Callable {
val file = File(rootFolder, fileName)
val sink = Okio.buffer(Okio.sink(file))
val stream = ByteArrayOutputStream()
image.compress(Bitmap.CompressFormat.PNG, 100, stream)
sink.write(stream.toByteArray())
sink.close()
}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
completable.subscribe(object : CompletableObserver {
override fun onComplete() {
Timber.d("Image Saved")
}
override fun onSubscribe(d: Disposable) {
}
override fun onError(e: Throwable) {
Timber.d(e)
}
})
}
@Throws(IOException::class)
fun getImage(fileName: String): Bitmap {
val file = File(rootFolder, fileName)
val source = Okio.buffer(Okio.source(file))
val byteArray = source.readByteArray()
return BitmapFactory.decodeByteArray(byteArray, 0, byteArray.size)
}
fun deleteNote(fileName: String) {
val single: Single<Boolean> = Single.fromCallable(Callable {
val file = File(rootFolder, fileName)
if (file.exists()) return@Callable file.delete()
return@Callable false
}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
single.subscribe(object : SingleObserver<Boolean> {
override fun onSuccess(t: Boolean) {
Timber.d(t.toString())
}
override fun onSubscribe(d: Disposable) {
}
override fun onError(e: Throwable) {
Timber.d(e)
}
})
}
fun deleteNoteImages(fileName: List<String>) {
val single: Single<Boolean> = Single.fromCallable(Callable {
var allDeleted: Boolean = false
fileName.forEach {
val file = File(rootFolder, it)
if (file.exists()) allDeleted = file.delete()
}
return@Callable allDeleted
}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
single.subscribe(object : SingleObserver<Boolean> {
override fun onSuccess(t: Boolean) {
Timber.d(t.toString())
}
override fun onSubscribe(d: Disposable) {
}
override fun onError(e: Throwable) {
Timber.d(e)
}
})
}
fun deleteNoteAudio(fileName: List<String>) {
val single: Single<Boolean> = Single.fromCallable(Callable {
var allDeleted: Boolean = false
fileName.forEach {
val file = File(rootFolder, it)
if (file.exists()) allDeleted = file.delete()
}
return@Callable allDeleted
}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
single.subscribe(object : SingleObserver<Boolean> {
override fun onSuccess(t: Boolean) {
Timber.d(t.toString())
}
override fun onSubscribe(d: Disposable) {
}
override fun onError(e: Throwable) {
Timber.d(e)
}
})
}
fun deleteNoteResources(noteEntity: NoteEntity) {
if (noteEntity.imageList != null) deleteNoteImages(noteEntity.imageList!!)
if (noteEntity.audioList != null) deleteNoteAudio(noteEntity.audioList!!)
if (noteEntity.fileName != null) deleteNote(noteEntity.fileName!!)
}
@Throws(Exception::class)
fun getLiveNote(fileName: String): MutableLiveData<NoteEntity> {
val liveNote = MutableLiveData<NoteEntity>()
val single: Single<NoteEntity> = Single.fromCallable(Callable {
val file = File(rootFolder, fileName)
val source = Okio.buffer(Okio.source(file))
val entity = deSerialize(source.readByteString())
source.close()
return@Callable entity
}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
single.subscribe(object : SingleObserver<NoteEntity> {
override fun onSuccess(t: NoteEntity) {
liveNote.value = t
}
override fun onSubscribe(d: Disposable) {
}
override fun onError(e: Throwable) {
Timber.d(e)
}
})
return liveNote
}
@Throws(IOException::class)
private fun serialize(noteEntity: NoteEntity): ByteString {
val buffer = Buffer()
val stream = ObjectOutputStream(buffer.outputStream())
stream.writeObject(noteEntity)
stream.flush()
return buffer.readByteString()
}
@Throws(Exception::class)
private fun deSerialize(data: ByteString): NoteEntity {
val buffer = Buffer().write(data)
val stream = ObjectInputStream(buffer.inputStream())
return stream.readObject() as NoteEntity
}
}
|
gpl-3.0
|
7907c7ae46ec7f476f4aa09e6874c537
| 34.738938 | 86 | 0.635013 | 4.717874 | false | false | false | false |
AlmasB/FXGL
|
fxgl/src/main/kotlin/com/almasb/fxgl/app/scene/LoadingScene.kt
|
1
|
2005
|
/*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package com.almasb.fxgl.app.scene
import com.almasb.fxgl.dsl.FXGL
import javafx.concurrent.Task
import javafx.scene.control.ProgressBar
import javafx.scene.paint.Color
import javafx.scene.shape.Rectangle
import javafx.scene.text.Text
/**
* Loading scene to be used during loading tasks.
*
* @author Almas Baimagambetov (AlmasB) ([email protected])
*/
abstract class LoadingScene : FXGLScene() {
fun pushNewTask(task: Runnable) {
pushNewTask(object : Task<Void?>() {
override fun call(): Void? {
task.run()
return null
}
})
}
fun pushNewTask(task: Task<*>) {
task.setOnSucceeded {
controller.gotoPlay()
}
bind(task)
FXGL.getExecutor().execute(task)
}
/**
* Bind to listen for updates of given background loading task.
*
* @param task the loading task
*/
protected open fun bind(task: Task<*>) { }
}
class FXGLLoadingScene : LoadingScene() {
private val progress = ProgressBar()
private val text = Text()
init {
with(progress) {
setPrefSize(appWidth - 200.0, 10.0)
translateX = 100.0
translateY = appHeight - 100.0
}
with(text) {
font = FXGL.getUIFactoryService().newFont(24.0)
fill = Color.WHITE
}
FXGL.centerTextBind(
text,
appWidth / 2.0,
appHeight * 4 / 5.0
)
contentRoot.children.addAll(
Rectangle(appWidth.toDouble(), appHeight.toDouble(), Color.rgb(0, 0, 10)),
progress,
text
)
}
override fun bind(task: Task<*>) {
progress.progressProperty().bind(task.progressProperty())
text.textProperty().bind(task.messageProperty())
}
}
|
mit
|
ceeffd26d8b06e47cf1105cd5e8dbb7b
| 22.880952 | 90 | 0.572569 | 4.212185 | false | false | false | false |
joseph-roque/BowlingCompanion
|
app/src/main/java/ca/josephroque/bowlingcompanion/teams/list/TeamListFragment.kt
|
1
|
3347
|
package ca.josephroque.bowlingcompanion.teams.list
import android.os.Bundle
import android.preference.PreferenceManager
import android.support.v7.app.AlertDialog
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import ca.josephroque.bowlingcompanion.R
import ca.josephroque.bowlingcompanion.bowlers.Bowler
import ca.josephroque.bowlingcompanion.common.fragments.ListFragment
import ca.josephroque.bowlingcompanion.teams.Team
import ca.josephroque.bowlingcompanion.utils.Preferences
import kotlinx.coroutines.experimental.CommonPool
import kotlinx.coroutines.experimental.Deferred
import kotlinx.coroutines.experimental.async
/**
* Copyright (C) 2018 Joseph Roque
*
* A fragment representing a list of Teams.
*/
class TeamListFragment : ListFragment<Team, TeamRecyclerViewAdapter>() {
companion object {
@Suppress("unused")
private const val TAG = "TeamListFragment"
fun newInstance(): TeamListFragment {
return TeamListFragment()
}
}
override val emptyViewImage = R.drawable.empty_view_teams
override val emptyViewText = R.string.empty_view_teams
// MARK: Lifecycle functions
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
setHasOptionsMenu(true)
return super.onCreateView(inflater, container, savedInstanceState)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.fragment_teams, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.action_sort_by -> {
showSortByDialog()
true
}
else -> super.onOptionsItemSelected(item)
}
}
// MARK: BaseFragment
override fun updateToolbarTitle() {
// Intentionally left blank
}
// MARK: ListFragment
override fun fetchItems(): Deferred<MutableList<Team>> {
context?.let {
return Team.fetchAll(it)
}
return async(CommonPool) {
mutableListOf<Team>()
}
}
override fun buildAdapter(): TeamRecyclerViewAdapter {
val adapter = TeamRecyclerViewAdapter(emptyList(), this)
adapter.swipeable = true
adapter.longPressable = true
return adapter
}
// MARK: Private functions
private fun showSortByDialog() {
context?.let {
AlertDialog.Builder(it)
.setTitle(it.resources.getString(R.string.sort_items))
.setItems(R.array.team_sort_options) { _, which: Int ->
val order = Bowler.Companion.Sort.fromInt(which)
order?.let { sort ->
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.putInt(Preferences.TEAM_SORT_ORDER, sort.ordinal)
.apply()
refreshList()
}
}
.show()
}
}
}
|
mit
|
640ffff8f3015f77f44b4f7a13cd91c8
| 30.575472 | 116 | 0.633702 | 5.165123 | false | false | false | false |
sxend/FrameworkBenchmarks
|
frameworks/Kotlin/kooby/src/main/kotlin/kooby/App.kt
|
1
|
4751
|
package kooby
import com.fasterxml.jackson.databind.ObjectMapper
import io.jooby.BadRequestException
import io.jooby.Context
import io.jooby.ExecutionMode.EVENT_LOOP
import io.jooby.MediaType.JSON
import io.jooby.hikari.HikariModule
import io.jooby.json.JacksonModule
import io.jooby.require
import io.jooby.rocker.Rockerby
import io.jooby.runApp
import java.util.*
import java.util.concurrent.ThreadLocalRandom
import javax.sql.DataSource
private const val SELECT_WORLD = "select * from world where id=?"
private const val DB_ROWS = 10000
private const val MESSAGE = "Hello, World!"
private val MESSAGE_BYTES = MESSAGE.toByteArray(Charsets.UTF_8)
data class Message(val message: String = MESSAGE)
class World(val id: Int, var randomNumber: Int)
data class Fortune(val id: Int, var message: String)
fun main(args: Array<String>) {
runApp(args, EVENT_LOOP) {
/** Server options (netty only): */
serverOptions {
singleLoop = true
}
/** JSON: */
install(JacksonModule())
val mapper = require(ObjectMapper::class)
/** Database: */
install(HikariModule())
val ds = require(DataSource::class)
/** Template engine: */
install(Rockerby())
get("/plaintext") {
ctx.send(MESSAGE_BYTES)
}
get("/json") {
ctx.setResponseType(JSON)
ctx.send(mapper.writeValueAsBytes(Message()))
}
/** Go blocking : */
dispatch {
/** Single query: */
get("/db") {
val rnd = ThreadLocalRandom.current()
val result = ds.connection.use { conn ->
conn.prepareStatement(SELECT_WORLD).use { statement ->
statement.setInt(1, nextRandom(rnd))
statement.executeQuery().use { rs ->
rs.next()
World(rs.getInt(1), rs.getInt(2))
}
}
}
ctx.setResponseType(JSON)
ctx.send(mapper.writeValueAsBytes(result))
}
/** Multiple query: */
get("/queries") {
val rnd = ThreadLocalRandom.current()
val queries = ctx.queries()
val result = ArrayList<World>(queries)
ds.connection.use { conn ->
conn.prepareStatement(SELECT_WORLD).use { statement ->
for (i in 1..queries) {
statement.setInt(1, nextRandom(rnd))
statement.executeQuery().use { rs ->
while (rs.next()) {
result += World(rs.getInt(1), rs.getInt(2))
}
}
}
}
}
ctx.setResponseType(JSON)
ctx.send(mapper.writeValueAsBytes(result))
}
/** Updates: */
get("/updates") {
val queries = ctx.queries()
val result = ArrayList<World>(queries)
val rnd = ThreadLocalRandom.current()
val updateSql = StringJoiner(
", ",
"UPDATE world SET randomNumber = temp.randomNumber FROM (VALUES ",
" ORDER BY 1) AS temp(id, randomNumber) WHERE temp.id = world.id")
ds.connection.use { connection ->
connection.prepareStatement(SELECT_WORLD).use { statement ->
for (i in 1..queries) {
statement.setInt(1, nextRandom(rnd))
statement.executeQuery().use { rs ->
rs.next()
result += World(rs.getInt("id"), rs.getInt("randomNumber"))
}
// prepare update query
updateSql.add("(?, ?)")
}
}
connection.prepareStatement(updateSql.toString()).use { statement ->
var i = 0
for (world in result) {
world.randomNumber = nextRandom(rnd)
statement.setInt(++i, world.id)
statement.setInt(++i, world.randomNumber)
}
statement.executeUpdate()
}
}
ctx.setResponseType(JSON)
ctx.send(mapper.writeValueAsBytes(result))
}
/** Fortunes: */
get("/fortunes") {
val fortunes = ArrayList<Fortune>()
ds.connection.use { connection ->
connection.prepareStatement("select * from fortune").use { stt ->
stt.executeQuery().use { rs ->
while (rs.next()) {
fortunes += Fortune(rs.getInt("id"), rs.getString("message"))
}
}
}
}
fortunes.add(Fortune(0, "Additional fortune added at request time."))
fortunes.sortBy { it.message }
/** render view: */
views.fortunes.template(fortunes)
}
}
}
}
private fun nextRandom(rnd: Random): Int {
return rnd.nextInt(DB_ROWS) + 1
}
fun Context.queries() = try {
this.query("queries").intValue(1).coerceIn(1, 500)
} catch (x: BadRequestException) {
1
}
|
bsd-3-clause
|
340a5c6f471df479c52f3a8ae89009bb
| 27.279762 | 78 | 0.571248 | 4.264811 | false | false | false | false |
nfrankel/kaadin
|
kaadin-core/src/test/kotlin/ch/frankel/kaadin/datainput/NativeSelectTest.kt
|
1
|
3729
|
/*
* Copyright 2016 Nicolas Fränkel
*
* 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 ch.frankel.kaadin.datainput
import ch.frankel.kaadin.*
import com.vaadin.data.util.*
import com.vaadin.ui.*
import org.assertj.core.api.Assertions.assertThat
import org.testng.annotations.Test
class NativeSelectTest {
@Test
fun `native select should be added to layout`() {
val layout = horizontalLayout {
nativeSelect()
}
assertThat(layout.componentCount).isEqualTo(1)
val component = layout.getComponent(0)
assertThat(component).isNotNull.isInstanceOf(NativeSelect::class.java)
}
@Test(dependsOnMethods = ["native select should be added to layout"])
fun `native select elements can be initialized via varargs`() {
val layout = horizontalLayout {
nativeSelect("caption", "One", "Two", "Three")
}
val component = layout.getComponent(0) as NativeSelect
assertThat(component.size()).isEqualTo(3)
}
@Test(dependsOnMethods = ["native select should be added to layout"])
fun `native select elements can be initialized via collection`() {
val layout = horizontalLayout {
nativeSelect(options = arrayListOf("One", "Two", "Three"))
}
val component = layout.getComponent(0) as NativeSelect
assertThat(component.size()).isEqualTo(3)
}
@Test(dependsOnMethods = ["native select should be added to layout"])
fun `native select elements can be initialized via property`() {
val container = BeanItemContainer(String::class.java).apply {
addAll(arrayListOf("One", "Two", "Three"))
}
val layout = horizontalLayout {
nativeSelect(dataSource = container)
}
val component = layout.getComponent(0) as NativeSelect
assertThat(component.size()).isEqualTo(3)
}
@Test(dependsOnMethods = ["native select should be added to layout"])
fun `native select caption can be initialized`() {
val caption = "caption"
val layout = horizontalLayout {
nativeSelect(caption)
}
val component = layout.getComponent(0) as NativeSelect
assertThat(component.caption).isEqualTo(caption)
}
@Test(dependsOnMethods = ["native select should be added to layout"])
fun `native select should be configurable`() {
val layout = horizontalLayout {
nativeSelect {
disallowNewItems()
disallowNullSelection()
}
}
val component = layout.getComponent(0) as NativeSelect
assertThat(component.isNewItemsAllowed).isFalse
assertThat(component.isNullSelectionAllowed).isFalse
}
@Test(dependsOnMethods = ["native select should be added to layout"])
fun `native select value change listener can be initialized`() {
val data = "dummy"
val layout = horizontalLayout {
nativeSelect(onValueChange = { this.data = data })
}
val component = layout.getComponent(0) as NativeSelect
val id = component.addItem()
component.select(id)
assertThat(layout.data).isEqualTo(data)
}
}
|
apache-2.0
|
10045d8553821aeda5a6d1dc4434e8a3
| 36.29 | 78 | 0.661481 | 4.755102 | false | true | false | false |
shyiko/ktlint
|
ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/MultiLineIfElseRule.kt
|
1
|
3101
|
package com.pinterest.ktlint.ruleset.experimental
import com.pinterest.ktlint.core.Rule
import com.pinterest.ktlint.core.ast.ElementType.ELSE
import com.pinterest.ktlint.core.ast.ElementType.ELSE_KEYWORD
import com.pinterest.ktlint.core.ast.ElementType.LBRACE
import com.pinterest.ktlint.core.ast.ElementType.RBRACE
import com.pinterest.ktlint.core.ast.ElementType.RPAR
import com.pinterest.ktlint.core.ast.ElementType.THEN
import com.pinterest.ktlint.core.ast.isPartOfComment
import com.pinterest.ktlint.core.ast.isWhiteSpaceWithoutNewline
import com.pinterest.ktlint.core.ast.prevLeaf
import org.jetbrains.kotlin.com.intellij.lang.ASTNode
import org.jetbrains.kotlin.com.intellij.psi.PsiWhiteSpace
import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafPsiElement
import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.PsiWhiteSpaceImpl
import org.jetbrains.kotlin.psi.KtBlockExpression
import org.jetbrains.kotlin.psi.psiUtil.leaves
/**
* https://kotlinlang.org/docs/reference/coding-conventions.html#formatting-control-flow-statements
*
* TODO: if, for, when branch, do, while
*/
class MultiLineIfElseRule : Rule("multiline-if-else") {
override fun visit(
node: ASTNode,
autoCorrect: Boolean,
emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit
) {
if (node.elementType == THEN || node.elementType == ELSE) {
if (!node.treePrev.textContains('\n')) { // if (...) <statement>
return
}
if (node.firstChildNode?.firstChildNode?.elementType != LBRACE) {
emit(node.firstChildNode.startOffset, "Missing { ... }", true)
if (autoCorrect) {
autocorrect(node)
}
}
}
}
private fun autocorrect(node: ASTNode) {
val prevLeaves =
node.leaves(forward = false).takeWhile { it.elementType !in listOf(RPAR, ELSE_KEYWORD) }.toList().reversed()
val nextLeaves =
node.leaves(forward = true).takeWhile { it.isWhiteSpaceWithoutNewline() || it.isPartOfComment() }.toList()
val rightBraceIndent = node.treeParent
.prevLeaf { it is PsiWhiteSpace && it.textContains('\n') }?.text.orEmpty()
.let { "\n${it.substringAfterLast("\n")}" }
(node.treePrev as LeafPsiElement).rawReplaceWithText(" ")
KtBlockExpression(null).apply {
val previousChild = node.firstChildNode
node.replaceChild(node.firstChildNode, this)
addChild(LeafPsiElement(LBRACE, "{"))
prevLeaves.forEach(::addChild)
addChild(previousChild)
nextLeaves.forEach(::addChild)
addChild(PsiWhiteSpaceImpl(rightBraceIndent))
addChild(LeafPsiElement(RBRACE, "}"))
}
// Make sure else starts on same line as newly inserted right brace
if (node.elementType == THEN && node.treeNext?.treeNext?.elementType == ELSE_KEYWORD) {
node.treeParent.replaceChild(node.treeNext, PsiWhiteSpaceImpl(" "))
}
}
}
|
mit
|
1b47fe4ba1d38b7728da1851b08602a3
| 42.069444 | 120 | 0.676233 | 4.367606 | false | false | false | false |
zametki/zametki
|
src/main/java/com/github/zametki/ajax/UpdateNoteAjaxCall.kt
|
1
|
1095
|
package com.github.zametki.ajax
import com.github.zametki.Context
import com.github.zametki.UserSession
import com.github.zametki.annotation.MountPath
import com.github.zametki.annotation.Post
import com.github.zametki.model.Zametka
import com.github.zametki.model.ZametkaId
@Post
@MountPath("/ajax/update-note")
class UpdateNoteAjaxCall : BaseAjaxCall() {
override fun getResponseText(): String {
val userId = UserSession.get().userId ?: return permissionError()
val zId = ZametkaId(getParameter("noteId").toInt(-1))
val z = Context.getZametkaDbi().getById(zId)
if (z == null || z.userId != userId) {
return error("No user note found with id: " + zId.intValue)
}
val text = getParameter("text").toString("")
if (text.length < Zametka.MIN_CONTENT_LEN || text.length > Zametka.MAX_CONTENT_LEN) {
return error("Illegal text length: " + text.length)
}
z.content = text
Context.getZametkaDbi().update(z)
return AjaxApiUtils.getNotesAndGroupsAsResponse(userId, z.groupId)
}
}
|
apache-2.0
|
a22bae99310d4a678e99f90576f01843
| 35.5 | 93 | 0.680365 | 3.910714 | false | false | false | false |
jitsi/jitsi-videobridge
|
rtp/src/main/kotlin/org/jitsi/rtp/rtcp/RtcpByePacket.kt
|
1
|
2853
|
/*
* Copyright @ 2018 - present 8x8, 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 org.jitsi.rtp.rtcp
import org.jitsi.rtp.extensions.bytearray.getInt
import org.jitsi.rtp.extensions.unsigned.toPositiveLong
/**
* An [RtcpByePacket] cannot be changed once it has been created, so we
* parse the fields once (lazily) and store them.
* TODO: technically it COULD be changed, since anyone can change the buffer.
* can we enforce immutability?
*
* https://tools.ietf.org/html/rfc3550#section-6.6
*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |V=2|P| SC | PT=BYE=203 | length |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | SSRC/CSRC |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* : ... :
* +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
* (opt) | length | reason for leaving ...
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
class RtcpByePacket(
buffer: ByteArray,
offset: Int,
length: Int
) : RtcpPacket(buffer, offset, length) {
val ssrcs: List<Long> by lazy {
val ssrcStartOffset = offset + 4
(0 until reportCount)
.map { buffer.getInt(ssrcStartOffset + it * 4) }
.map(Int::toPositiveLong)
.toList()
}
val reason: String? by lazy {
val headerAndSsrcsLengthBytes = RtcpHeader.SIZE_BYTES + (reportCount - 1) * 4
val hasReason = headerAndSsrcsLengthBytes < length
if (hasReason) {
val reasonLengthOffset = offset + headerAndSsrcsLengthBytes
val reasonLength = buffer[reasonLengthOffset].toInt()
val reasonStr = String(buffer, reasonLengthOffset + 1, reasonLength)
reasonStr
} else {
null
}
}
override fun clone(): RtcpByePacket = RtcpByePacket(cloneBuffer(0), 0, length)
companion object {
const val PT: Int = 203
}
}
|
apache-2.0
|
75e4c3557fab519f10e67f634912796d
| 37.554054 | 85 | 0.508587 | 4.158892 | false | false | false | false |
lefevre00/baby
|
app/src/main/java/com/example/michael/myapplication/services/ParentService.kt
|
1
|
2861
|
package com.example.michael.myapplication.services
import android.content.Intent
import android.net.nsd.NsdManager
import android.net.nsd.NsdManager.RegistrationListener
import android.net.nsd.NsdServiceInfo
import android.os.Binder
import android.os.IBinder
import timber.log.Timber
import java.net.ServerSocket
class ParentService : GenericService() {
companion object {
val SERVICE_NAME = "Parents"
}
// Binder given to clients
private val mBinder = ParentServiceBinder()
inner class ParentServiceBinder : Binder() {
val service: ParentService
get() = this@ParentService
}
override fun onBind(intent: Intent): IBinder? {
return mBinder
}
override fun onCreate() {
super.onCreate()
Timber.d("ParentService started")
}
override fun onDestroy() {
super.onDestroy()
Timber.d("ParentService destroyed")
}
private var mRegistrationListener: RegistrationListener? = null
override fun onStart() {
val serviceInfo = NsdServiceInfo()
serviceInfo.serviceName = SERVICE_NAME
serviceInfo.serviceType = SERVICE_TYPE
serviceInfo.port = ServerSocket(0).localPort
mNsdManager.registerService(serviceInfo, NsdManager.PROTOCOL_DNS_SD, createRegistrationListener())
}
override fun isRunning(): Boolean {
return mRegistrationListener != null
}
private fun createRegistrationListener(): RegistrationListener? {
return object : NsdManager.RegistrationListener {
override fun onServiceRegistered(serviceInfo: NsdServiceInfo) {
Timber.d("${serviceInfo.serviceName} registred on port ${serviceInfo.port}")
mRegistrationListener = this
broadcastManager.sendBroadcast(Intent(getStartAction()))
}
override fun onRegistrationFailed(serviceInfo: NsdServiceInfo,
errorCode: Int) {
Timber.w("Registration of service ${serviceInfo.serviceName} failed")
}
override fun onServiceUnregistered(serviceInfo: NsdServiceInfo) {
Timber.d("${serviceInfo.serviceName} unregistred")
mRegistrationListener = null
broadcastManager.sendBroadcast(Intent(getStopAction()))
}
override fun onUnregistrationFailed(serviceInfo: NsdServiceInfo,
errorCode: Int) {
Timber.w("Unregistration failed for service ${serviceInfo.serviceName}")
}
}
}
override fun onStop() {
if (mRegistrationListener != null) {
mNsdManager.unregisterService(mRegistrationListener)
}
}
override fun getName(): String {
return SERVICE_NAME
}
}
|
gpl-3.0
|
2181beed42104d19c27907a3ca2224f5
| 30.450549 | 106 | 0.641384 | 5.501923 | false | false | false | false |
Magneticraft-Team/Magneticraft
|
src/main/kotlin/com/cout970/magneticraft/api/internal/energy/ElectricConnection.kt
|
2
|
1949
|
package com.cout970.magneticraft.api.internal.energy
import com.cout970.magneticraft.api.energy.IElectricConnection
import com.cout970.magneticraft.api.energy.IElectricNode
import com.cout970.magneticraft.misc.vector.length
import com.cout970.magneticraft.misc.vector.minus
import com.cout970.magneticraft.misc.world.isClient
/**
* Created by cout970 on 11/06/2016.
*/
open class ElectricConnection(
private val firstNode: IElectricNode,
private val secondNode: IElectricNode
) : IElectricConnection {
override fun getFirstNode() = firstNode
override fun getSecondNode() = secondNode
override fun getSeparationDistance() = (firstNode.pos - secondNode.pos).length
override fun iterate() {
if (firstNode.world.isClient) return
//total resistance of the connection
val R = (firstNode.resistance + secondNode.resistance) * separationDistance
//capacity in the connection
val C = 1.0 / (1.0 / firstNode.capacity + 1.0 / secondNode.capacity)
//voltage difference
val V = (firstNode.voltage * firstNode.capacity + secondNode.voltage * secondNode.capacity) / (firstNode.capacity + secondNode.capacity) - secondNode.voltage
//intensity or amperage
val I = ((1 - Math.exp(-1 / (R * C))) * V * secondNode.capacity / firstNode.capacity) * C * 2
//the charge is moved
firstNode.applyCurrent(-I)
secondNode.applyCurrent(I)
}
override fun equals(other: Any?): Boolean {
if (other is IElectricConnection) {
return firstNode.id == other.firstNode.id && secondNode.id == other.secondNode.id
}
return super.equals(other)
}
override fun hashCode(): Int {
return (super.hashCode() * 31 + firstNode.id.hashCode()) * 31 + secondNode.id.hashCode()
}
override fun toString(): String {
return "ElectricConnection(firstNode=$firstNode, secondNode=$secondNode)"
}
}
|
gpl-2.0
|
4932dcdcfd732dcd1b60dfda4f091011
| 35.792453 | 165 | 0.690611 | 4.085954 | false | false | false | false |
Ph1b/MaterialAudiobookPlayer
|
playback/src/main/kotlin/de/ph1b/audiobook/playback/notification/NotificationCreator.kt
|
1
|
5455
|
package de.ph1b.audiobook.playback.notification
import android.app.Notification
import android.app.PendingIntent
import android.content.Context
import android.graphics.Bitmap
import android.support.v4.media.session.MediaSessionCompat
import android.support.v4.media.session.PlaybackStateCompat.ACTION_FAST_FORWARD
import android.support.v4.media.session.PlaybackStateCompat.ACTION_PAUSE
import android.support.v4.media.session.PlaybackStateCompat.ACTION_PLAY
import android.support.v4.media.session.PlaybackStateCompat.ACTION_REWIND
import android.support.v4.media.session.PlaybackStateCompat.ACTION_STOP
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationCompat.Builder
import androidx.core.graphics.drawable.toBitmap
import androidx.media.app.NotificationCompat.MediaStyle
import androidx.media.session.MediaButtonReceiver.buildMediaButtonPendingIntent
import coil.imageLoader
import coil.request.ImageRequest
import de.ph1b.audiobook.data.Book2
import de.ph1b.audiobook.playback.R
import de.ph1b.audiobook.playback.di.PlaybackScope
import de.ph1b.audiobook.playback.playstate.PlayStateManager
import javax.inject.Inject
/**
* Provides Notifications based on playing information.
*/
@PlaybackScope
class NotificationCreator
@Inject constructor(
private val context: Context,
private val playStateManager: PlayStateManager,
private val mediaSession: MediaSessionCompat,
notificationChannelCreator: NotificationChannelCreator,
private val toBookIntentProvider: ToBookIntentProvider
) {
private val fastForwardAction = NotificationCompat.Action(
R.drawable.ic_fast_forward_white_36dp,
context.getString(R.string.fast_forward),
buildMediaButtonPendingIntent(context, ACTION_FAST_FORWARD)
)
private val rewindAction = NotificationCompat.Action(
R.drawable.ic_rewind_white_36dp,
context.getString(R.string.rewind),
buildMediaButtonPendingIntent(context, ACTION_REWIND)
)
private val playAction = NotificationCompat.Action(
R.drawable.ic_play_white_36dp,
context.getString(R.string.play),
buildMediaButtonPendingIntent(context, ACTION_PLAY)
)
private val pauseAction = NotificationCompat.Action(
R.drawable.ic_pause_white_36dp,
context.getString(R.string.pause),
buildMediaButtonPendingIntent(context, ACTION_PAUSE)
)
init {
notificationChannelCreator.createChannel()
}
private var cachedImage: CachedImage? = null
suspend fun createNotification(book: Book2): Notification {
val mediaStyle = MediaStyle()
.setShowActionsInCompactView(0, 1, 2)
.setCancelButtonIntent(stopIntent())
.setShowCancelButton(true)
.setMediaSession(mediaSession.sessionToken)
return Builder(context, MUSIC_CHANNEL_ID)
.addAction(rewindAction)
.addPlayPauseAction(playStateManager.playState)
.addAction(fastForwardAction)
.setCategory(NotificationCompat.CATEGORY_TRANSPORT)
.setChapterInfo(book)
.setContentIntent(contentIntent(book))
.setContentTitle(book)
.setDeleteIntent(stopIntent())
.setLargeIcon(book)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setShowWhen(false)
.setSmallIcon(R.drawable.ic_notification)
.setStyle(mediaStyle)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setWhen(0)
.build()
}
private suspend fun cover(book: Book2): Bitmap {
cachedImage?.let {
if (it.matches(book)) return it.cover
}
val coverFile = book.content.cover
val cover = context.imageLoader
.execute(ImageRequest.Builder(context)
.data(coverFile)
.size(
width = context.resources.getDimensionPixelSize(R.dimen.compat_notification_large_icon_max_width),
height = context.resources.getDimensionPixelSize(R.dimen.compat_notification_large_icon_max_height)
)
.fallback(R.drawable.default_album_art)
.error(R.drawable.default_album_art)
.allowHardware(false)
.build()
)
.drawable!!.toBitmap()
cachedImage = CachedImage(book.content.cover, cover)
return cover
}
private suspend fun Builder.setLargeIcon(book: Book2): Builder {
setLargeIcon(cover(book))
return this
}
private fun Builder.setContentTitle(book: Book2): Builder {
setContentTitle(book.content.name)
return this
}
private fun contentIntent(book: Book2): PendingIntent {
val contentIntent = toBookIntentProvider.goToBookIntent(book.content.id)
return PendingIntent.getActivity(
context,
0,
contentIntent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
}
private fun Builder.setChapterInfo(book: Book2): Builder {
val chapters = book.content.chapters
if (chapters.size > 1) {
// we need the current chapter title and number only if there is more than one chapter.
setContentInfo("${(book.content.currentChapterIndex + 1)}/${chapters.size}")
setContentText(book.currentChapter.name)
} else {
setContentInfo(null)
setContentText(null)
}
return this
}
private fun stopIntent(): PendingIntent {
return buildMediaButtonPendingIntent(context, ACTION_STOP)
}
private fun Builder.addPlayPauseAction(playState: PlayStateManager.PlayState): Builder {
return if (playState == PlayStateManager.PlayState.Playing) {
addAction(pauseAction)
} else {
addAction(playAction)
}
}
}
|
lgpl-3.0
|
10f7e78da58a238a8670fe9ef63c9a5a
| 32.67284 | 109 | 0.751237 | 4.325932 | false | false | false | false |
ReactiveCircus/FlowBinding
|
flowbinding-android/src/androidTest/java/reactivecircus/flowbinding/android/view/MenuItemActionViewEventFlowTest.kt
|
1
|
3605
|
package reactivecircus.flowbinding.android.view
import androidx.test.filters.LargeTest
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.flow.filterIsInstance
import org.junit.Test
import reactivecircus.flowbinding.android.fixtures.view.AndroidViewFragment
import reactivecircus.flowbinding.android.testutil.TestMenuItem
import reactivecircus.flowbinding.testing.FlowRecorder
import reactivecircus.flowbinding.testing.launchTest
import reactivecircus.flowbinding.testing.recordWith
@LargeTest
class MenuItemActionViewEventFlowTest {
@Test
fun menuItemActionViewEvents_expand() {
launchTest<AndroidViewFragment> {
val recorder = FlowRecorder<MenuItemActionViewEvent.Expand>(testScope)
val menuItem = TestMenuItem(rootView.context)
menuItem.actionViewEvents()
.filterIsInstance<MenuItemActionViewEvent.Expand>()
.recordWith(recorder)
recorder.assertNoMoreValues()
menuItem.expandActionView()
assertThat(recorder.takeValue().menuItem)
.isEqualTo(menuItem)
recorder.assertNoMoreValues()
cancelTestScope()
menuItem.collapseActionView()
menuItem.expandActionView()
recorder.assertNoMoreValues()
}
}
@Test
fun menuItemActionViewEvents_expand_notHandled() {
launchTest<AndroidViewFragment> {
val recorder = FlowRecorder<MenuItemActionViewEvent.Expand>(testScope)
val menuItem = TestMenuItem(rootView.context)
menuItem.actionViewEvents { false }
.filterIsInstance<MenuItemActionViewEvent.Expand>()
.recordWith(recorder)
recorder.assertNoMoreValues()
menuItem.expandActionView()
recorder.assertNoMoreValues()
cancelTestScope()
menuItem.collapseActionView()
menuItem.expandActionView()
recorder.assertNoMoreValues()
}
}
@Test
fun menuItemActionViewEvents_collapse() {
launchTest<AndroidViewFragment> {
val recorder = FlowRecorder<MenuItemActionViewEvent.Collapse>(testScope)
val menuItem = TestMenuItem(rootView.context)
menuItem.actionViewEvents()
.filterIsInstance<MenuItemActionViewEvent.Collapse>()
.recordWith(recorder)
recorder.assertNoMoreValues()
menuItem.expandActionView()
menuItem.collapseActionView()
assertThat(recorder.takeValue().menuItem)
.isEqualTo(menuItem)
recorder.assertNoMoreValues()
cancelTestScope()
menuItem.expandActionView()
menuItem.collapseActionView()
recorder.assertNoMoreValues()
}
}
@Test
fun menuItemActionViewEvents_collapse_notHandled() {
launchTest<AndroidViewFragment> {
val recorder = FlowRecorder<MenuItemActionViewEvent.Collapse>(testScope)
val menuItem = TestMenuItem(rootView.context)
menuItem.actionViewEvents { false }
.filterIsInstance<MenuItemActionViewEvent.Collapse>()
.recordWith(recorder)
recorder.assertNoMoreValues()
menuItem.expandActionView()
menuItem.collapseActionView()
recorder.assertNoMoreValues()
cancelTestScope()
menuItem.expandActionView()
menuItem.collapseActionView()
recorder.assertNoMoreValues()
}
}
}
|
apache-2.0
|
e95b0534a14fc05c58aa2ab4d5655f41
| 32.073394 | 84 | 0.657698 | 6.258681 | false | true | false | false |
toastkidjp/Jitte
|
lib/src/main/java/jp/toastkid/lib/view/text/EmptyAlertSetter.kt
|
1
|
1492
|
/*
* Copyright (c) 2021 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.lib.view.text
import android.text.Editable
import android.text.TextWatcher
import android.widget.EditText
import com.google.android.material.textfield.TextInputLayout
import jp.toastkid.lib.R
/**
* @author toastkidjp
*/
class EmptyAlertSetter {
/**
* Set empty alert.
*
* @param inputLayout [TextInputLayout]
*/
operator fun invoke(inputLayout: TextInputLayout): EditText {
val input: EditText? = inputLayout.editText
input?.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) = Unit
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) = Unit
override fun afterTextChanged(s: Editable) {
if (s.toString().isEmpty()) {
inputLayout.error = inputLayout.context
.getString(R.string.favorite_search_addition_dialog_empty_message)
return
}
inputLayout.isErrorEnabled = false
}
})
return input ?: EditText(inputLayout.context)
}
}
|
epl-1.0
|
e030cbdf69e04998b904be00b6ff1760
| 31.456522 | 102 | 0.656166 | 4.6625 | false | false | false | false |
google-developer-training/android-demos
|
DonutTracker/NestedGraphs_Include/coffee/src/main/java/com/android/samples/donuttracker/coffee/CoffeeListAdapter.kt
|
2
|
2969
|
/*
* 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.android.samples.donuttracker.coffee
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.android.samples.donuttracker.coffee.databinding.CoffeeItemBinding
import com.android.samples.donuttracker.core.model.Coffee
/**
* The adapter used by the RecyclerView to display the current list of Coffees
*/
class CoffeeListAdapter(
private var onEdit: (Coffee) -> Unit,
private var onDelete: (Coffee) -> Unit
) : ListAdapter<Coffee, CoffeeListAdapter.CoffeeListViewHolder>(CoffeeDiffCallback()) {
class CoffeeListViewHolder(
private val binding: CoffeeItemBinding,
private var onEdit: (Coffee) -> Unit,
private var onDelete: (Coffee) -> Unit
) : RecyclerView.ViewHolder(binding.root) {
private var coffeeId: Long = -1
private var nameView = binding.name
private var description = binding.description
private var thumbnail = binding.thumbnail
private var rating = binding.rating
private var coffee: Coffee? = null
fun bind(coffee: Coffee) {
coffeeId = coffee.id
nameView.text = coffee.name
description.text = coffee.description
rating.text = coffee.rating.toString()
thumbnail.setImageResource(R.drawable.coffee_cup)
this.coffee = coffee
binding.deleteButton.setOnClickListener {
onDelete(coffee)
}
binding.root.setOnClickListener {
onEdit(coffee)
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = CoffeeListViewHolder(
CoffeeItemBinding.inflate(LayoutInflater.from(parent.context), parent, false),
onEdit,
onDelete
)
override fun onBindViewHolder(holder: CoffeeListViewHolder, position: Int) {
holder.bind(getItem(position))
}
}
class CoffeeDiffCallback : DiffUtil.ItemCallback<Coffee>() {
override fun areItemsTheSame(oldItem: Coffee, newItem: Coffee): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: Coffee, newItem: Coffee): Boolean {
return oldItem == newItem
}
}
|
apache-2.0
|
12fb5175fc33579fff040f0505f44b01
| 35.207317 | 94 | 0.696531 | 4.78871 | false | false | false | false |
intrigus/chemie
|
android/src/main/kotlin/de/intrigus/chem/util/PseDatabaseHelper.kt
|
1
|
2188
|
/*Copyright 2015 Simon Gerst
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 de.intrigus.chem.util
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
class PseDatabaseHelper private constructor(val context: Context) : SQLiteOpenHelper(context, PseDatabaseHelper.DATABASE_NAME, null, PseDatabaseHelper.DATABASE_VERSION) {
override fun onCreate(db: SQLiteDatabase) {
run {
val stream = context.applicationContext.resources.assets.open("elements_table_create.sql")
stream.buffered().reader().use { reader ->
db.execSQL(reader.readText())
}
}
run {
val stream = context.applicationContext.resources.assets.open("elements_table_content.sql")
stream.buffered().reader().use { reader ->
db.execSQL(reader.readText())
}
}
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
}
companion object {
public val ELEMENT_SMYBOL_INDEX = 1
public val ELEMENT_NAME_INDEX = 2
private val ELEMENT_NAME = "elementName"
private val ELEMENT_SYMBOL = "name"
private val DATABASE_NAME = "chemDatabase"
private val DATABASE_VERSION = 1
private val TABLE_ELEMENTS = "elements"
private var sInstance: PseDatabaseHelper? = null
@Synchronized fun getInstance(context: Context): PseDatabaseHelper {
if (sInstance == null) {
sInstance = PseDatabaseHelper(context.applicationContext)
}
return sInstance as PseDatabaseHelper
}
}
}
|
apache-2.0
|
c92ca700e4a7afafda5cc4a280c63e4f
| 32.676923 | 170 | 0.682815 | 4.625793 | false | false | false | false |
inorichi/tachiyomi
|
app/src/main/java/eu/kanade/tachiyomi/network/OkHttpExtensions.kt
|
1
|
4112
|
package eu.kanade.tachiyomi.network
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import okhttp3.Call
import okhttp3.Callback
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.internal.closeQuietly
import rx.Observable
import rx.Producer
import rx.Subscription
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.fullType
import java.io.IOException
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.coroutines.resumeWithException
val jsonMime = "application/json; charset=utf-8".toMediaType()
fun Call.asObservable(): Observable<Response> {
return Observable.unsafeCreate { subscriber ->
// Since Call is a one-shot type, clone it for each new subscriber.
val call = clone()
// Wrap the call in a helper which handles both unsubscription and backpressure.
val requestArbiter = object : AtomicBoolean(), Producer, Subscription {
override fun request(n: Long) {
if (n == 0L || !compareAndSet(false, true)) return
try {
val response = call.execute()
if (!subscriber.isUnsubscribed) {
subscriber.onNext(response)
subscriber.onCompleted()
}
} catch (error: Exception) {
if (!subscriber.isUnsubscribed) {
subscriber.onError(error)
}
}
}
override fun unsubscribe() {
call.cancel()
}
override fun isUnsubscribed(): Boolean {
return call.isCanceled()
}
}
subscriber.add(requestArbiter)
subscriber.setProducer(requestArbiter)
}
}
// Based on https://github.com/gildor/kotlin-coroutines-okhttp
suspend fun Call.await(): Response {
return suspendCancellableCoroutine { continuation ->
enqueue(
object : Callback {
override fun onResponse(call: Call, response: Response) {
if (!response.isSuccessful) {
continuation.resumeWithException(Exception("HTTP error ${response.code}"))
return
}
continuation.resume(response) {
response.body?.closeQuietly()
}
}
override fun onFailure(call: Call, e: IOException) {
// Don't bother with resuming the continuation if it is already cancelled.
if (continuation.isCancelled) return
continuation.resumeWithException(e)
}
}
)
continuation.invokeOnCancellation {
try {
cancel()
} catch (ex: Throwable) {
// Ignore cancel exception
}
}
}
}
fun Call.asObservableSuccess(): Observable<Response> {
return asObservable().doOnNext { response ->
if (!response.isSuccessful) {
response.close()
throw Exception("HTTP error ${response.code}")
}
}
}
fun OkHttpClient.newCallWithProgress(request: Request, listener: ProgressListener): Call {
val progressClient = newBuilder()
.cache(null)
.addNetworkInterceptor { chain ->
val originalResponse = chain.proceed(chain.request())
originalResponse.newBuilder()
.body(ProgressResponseBody(originalResponse.body!!, listener))
.build()
}
.build()
return progressClient.newCall(request)
}
inline fun <reified T> Response.parseAs(): T {
// Avoiding Injekt.get<Json>() due to compiler issues
val json = Injekt.getInstance<Json>(fullType<Json>().type)
this.use {
val responseBody = it.body?.string().orEmpty()
return json.decodeFromString(responseBody)
}
}
|
apache-2.0
|
d96882617c88db7c60ada99dc3e95162
| 31.896 | 98 | 0.593872 | 5.298969 | false | false | false | false |
Deletescape-Media/Lawnchair
|
lawnchair/src/app/lawnchair/ui/preferences/DebugMenuPreferences.kt
|
1
|
3327
|
package app.lawnchair.ui.preferences
import android.content.Intent
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalContext
import androidx.datastore.preferences.core.Preferences
import androidx.navigation.NavGraphBuilder
import app.lawnchair.preferences.PreferenceManager
import app.lawnchair.preferences.getAdapter
import app.lawnchair.preferences.preferenceManager
import app.lawnchair.preferences2.PreferenceManager2
import app.lawnchair.preferences2.preferenceManager2
import app.lawnchair.ui.preferences.components.*
import com.android.launcher3.settings.DeveloperOptionsFragment
import com.android.launcher3.settings.SettingsActivity
import com.patrykmichalik.opto.domain.Preference
fun NavGraphBuilder.debugMenuGraph(route: String) {
preferenceGraph(route, { DebugMenuPreferences() })
}
/**
* A screen to house unfinished preferences and debug flags
*/
@Composable
fun DebugMenuPreferences() {
val prefs = preferenceManager()
val prefs2 = preferenceManager2()
val flags = remember { prefs.debugFlags }
val flags2 = remember { prefs2.debugFlags }
val textFlags = remember { prefs2.textFlags }
val fontFlags = remember { prefs.fontFlags }
val context = LocalContext.current
PreferenceLayout(label = "Debug Menu") {
PreferenceGroup {
ClickablePreference(
label = "Feature Flags",
onClick = {
Intent(context, SettingsActivity::class.java)
.putExtra(":settings:fragment", DeveloperOptionsFragment::class.java.name)
.also { context.startActivity(it) }
},
)
ClickablePreference(
label = "Crash Launcher",
onClick = { throw RuntimeException("User triggered crash") },
)
}
PreferenceGroup(heading = "Debug Flags") {
flags2.forEach {
SwitchPreference(
adapter = it.getAdapter(),
label = it.key.name
)
}
flags.forEach {
SwitchPreference(
adapter = it.getAdapter(),
label = it.key,
)
}
textFlags.forEach {
TextPreference(
adapter = it.getAdapter(),
label = it.key.name
)
}
fontFlags.forEach {
FontPreference(
fontPref = it,
label = it.key,
)
}
}
}
}
private val PreferenceManager2.debugFlags: List<Preference<Boolean, Boolean, Preferences.Key<Boolean>>>
get() = listOf(showComponentNames)
private val PreferenceManager2.textFlags: List<Preference<String, String, Preferences.Key<String>>>
get() = listOf(additionalFonts)
private val PreferenceManager.debugFlags
get() = listOf(
deviceSearch,
searchResultShortcuts,
searchResultPeople,
searchResultPixelTips,
searchResultSettings,
)
private val PreferenceManager.fontFlags
get() = listOf(
fontHeading,
fontHeadingMedium,
fontBody,
fontBodyMedium,
)
|
gpl-3.0
|
761028a5e52352ab667a161cfda834cb
| 32.27 | 103 | 0.622783 | 5.087156 | false | false | false | false |
yshrsmz/monotweety
|
app2/src/main/java/net/yslibrary/monotweety/ui/arch/mvi.kt
|
1
|
4342
|
package net.yslibrary.monotweety.ui.arch
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.scan
import kotlinx.coroutines.launch
import net.yslibrary.monotweety.base.CoroutineDispatchers
import kotlin.coroutines.CoroutineContext
interface Intent
interface Action
interface State
interface Effect
sealed class ULIEState {
object UNINITIALIZED : ULIEState()
object LOADING : ULIEState()
object IDLE : ULIEState()
data class ERROR(val error: Throwable? = null) : ULIEState()
}
sealed class GlobalAction : Action {
object NoOp : GlobalAction()
}
abstract class Processor<ACTION : Action>(
private val dispatchers: CoroutineDispatchers,
) : CoroutineScope {
private val job = SupervisorJob()
override val coroutineContext: CoroutineContext = dispatchers.background + job
private var postActionCallback: ((action: ACTION) -> Unit)? = null
abstract fun processAction(action: ACTION)
protected fun put(action: ACTION) = launch(dispatchers.main) {
postActionCallback?.invoke(action)
}
fun setPostActionCallback(callback: (action: ACTION) -> Unit) {
postActionCallback = callback
}
fun onCleared() {
coroutineContext.cancel()
}
}
@OptIn(ExperimentalCoroutinesApi::class)
abstract class MviViewModel<INTENT : Intent, ACTION : Action, STATE : State, EFFECT : Effect>(
initialState: STATE,
private val dispatchers: CoroutineDispatchers,
private val processor: Processor<ACTION> = NoOpProcessor(dispatchers),
) : ViewModel() {
private val _states = MutableStateFlow(initialState)
val states: Flow<STATE> get() = _states
val state: STATE get() = _states.value
private val _effects = MutableSharedFlow<EFFECT>()
val effects: Flow<EFFECT> get() = _effects
private val _actions = Channel<Any>(Channel.BUFFERED)
protected fun sendEffect(effect: EFFECT) {
viewModelScope.launch {
_effects.emit(effect)
}
}
fun dispatch(intent: INTENT) {
val action = intentToAction(intent, state)
processAction(action)
}
private fun processAction(action: Action) {
viewModelScope.launch {
_actions.send(action)
@Suppress("UNCHECKED_CAST") val a = action as? ACTION
if (a != null) processor.processAction(action)
}
}
private fun reduceGlobal(previousState: STATE, action: GlobalAction): STATE {
return when (action) {
GlobalAction.NoOp -> previousState
}
}
private fun initReducer(initialState: STATE) {
_actions.consumeAsFlow()
.scan(initialState) { previousState, action ->
when (action) {
is GlobalAction -> reduceGlobal(previousState, action)
else -> {
@Suppress("UNCHECKED_CAST")
val a = action as? ACTION
if (a == null) {
previousState
} else {
reduce(previousState, a)
}
}
}
}
.flowOn(dispatchers.background)
.onEach { newState -> _states.value = newState }
.launchIn(viewModelScope)
}
protected abstract fun intentToAction(intent: INTENT, state: STATE): Action
protected abstract fun reduce(previousState: STATE, action: ACTION): STATE
init {
processor.setPostActionCallback(::processAction)
initReducer(initialState)
}
class NoOpProcessor<ACTION : Action>(dispatchers: CoroutineDispatchers) :
Processor<ACTION>(dispatchers) {
override fun processAction(action: ACTION) {
// no-op
}
}
}
|
apache-2.0
|
7f81753e80ec70c70b551071b07620e2
| 30.23741 | 94 | 0.662137 | 4.950969 | false | false | false | false |
kory33/SignVote
|
src/main/kotlin/com/github/kory33/signvote/command/subcommand/DeleteCommandExecutor.kt
|
1
|
1806
|
package com.github.kory33.signvote.command.subcommand
import com.github.kory33.signvote.configurable.JSONConfiguration
import com.github.kory33.signvote.constants.MessageConfigNodes
import com.github.kory33.signvote.constants.PermissionNodes
import com.github.kory33.signvote.core.SignVote
import com.github.kory33.signvote.manager.VoteSessionManager
import org.bukkit.command.Command
import org.bukkit.command.CommandSender
import java.util.*
/**
* Executor class of "delete" sub-command
* @author Kory
*/
class DeleteCommandExecutor(plugin: SignVote) : SubCommandExecutor {
private val messageConfiguration: JSONConfiguration = plugin.messagesConfiguration!!
private val voteSessionManager: VoteSessionManager = plugin.voteSessionManager!!
override val helpString: String
get() = this.messageConfiguration.getString(MessageConfigNodes.DELETE_SESS_COMMAND_HELP)
override fun onCommand(sender: CommandSender, command: Command, args: ArrayList<String>): Boolean {
if (!sender.hasPermission(PermissionNodes.DELETE_SESSION)) {
sender.sendMessage(messageConfiguration.getString(MessageConfigNodes.MISSING_PERMS))
return true
}
if (args.size < 1) {
return false
}
val targetSessionName = args.removeAt(0)
val targetVoteSession = this.voteSessionManager.getVoteSession(targetSessionName)
if (targetVoteSession == null) {
sender.sendMessage(this.messageConfiguration.getString(MessageConfigNodes.SESSION_DOES_NOT_EXIST))
return true
}
this.voteSessionManager.deleteSession(targetVoteSession)
sender.sendMessage(this.messageConfiguration.getFormatted(MessageConfigNodes.F_SESSION_DELETED, targetSessionName))
return true
}
}
|
gpl-3.0
|
6be7ab94dcdd18eb3ab9b53710338519
| 37.425532 | 123 | 0.752492 | 4.618926 | false | true | false | false |
vase4kin/TeamCityApp
|
app/src/main/java/com/github/vase4kin/teamcityapp/changes/data/ChangesDataManagerImpl.kt
|
1
|
3768
|
/*
* Copyright 2019 Andrey Tolpeev
*
* 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.vase4kin.teamcityapp.changes.data
import com.github.vase4kin.teamcityapp.account.create.data.OnLoadingListener
import com.github.vase4kin.teamcityapp.api.Repository
import com.github.vase4kin.teamcityapp.base.list.data.BaseListRxDataManagerImpl
import com.github.vase4kin.teamcityapp.base.tabs.data.OnTextTabChangeEvent
import com.github.vase4kin.teamcityapp.build_details.presenter.BuildDetailsPresenter
import com.github.vase4kin.teamcityapp.changes.api.Changes
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.rxkotlin.addTo
import io.reactivex.rxkotlin.subscribeBy
import io.reactivex.schedulers.Schedulers
import org.greenrobot.eventbus.EventBus
/**
* Impl of [ChangesDataManager]
*/
class ChangesDataManagerImpl(
private val repository: Repository,
private val eventBus: EventBus
) : BaseListRxDataManagerImpl<Changes, Changes.Change>(), ChangesDataManager {
private var loadMoreUrl: String? = null
/**
* {@inheritDoc}
*/
override fun loadTabTitle(
url: String,
loadingListener: OnLoadingListener<Int>
) {
repository.listChanges(url + ",count:" + Integer.MAX_VALUE + "&fields=count", true)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeBy(
onSuccess = { loadingListener.onSuccess(it.count) },
onError = { loadingListener.onSuccess(0) }
)
.addTo(subscriptions)
}
/**
* {@inheritDoc}
*/
override fun loadLimited(
url: String,
loadingListener: OnLoadingListener<List<Changes.Change>>,
update: Boolean
) {
load("$url,count:10", loadingListener, update)
}
/**
* {@inheritDoc}
*/
override fun load(
url: String,
loadingListener: OnLoadingListener<List<Changes.Change>>,
update: Boolean
) {
repository.listChanges(url, update)
.subscribeOn(Schedulers.io())
.flatMapObservable {
if (it.count == 0) {
Observable.fromIterable(emptyList())
} else {
loadMoreUrl = it.nextHref
Observable.fromIterable(it.objects)
}
}
.flatMapSingle { repository.change(it.href) }
.toList()
.observeOn(AndroidSchedulers.mainThread())
.subscribeBy(
onSuccess = { loadingListener.onSuccess(it) },
onError = { loadingListener.onFail(it.message ?: "") }
).addTo(subscriptions)
}
/**
* {@inheritDoc}
*/
override fun loadMore(loadingListener: OnLoadingListener<List<Changes.Change>>) {
load(loadMoreUrl!!, loadingListener, false)
}
/**
* {@inheritDoc}
*/
override fun canLoadMore(): Boolean {
return loadMoreUrl != null
}
/**
* {@inheritDoc}
*/
override fun postChangeTabTitleEvent(size: Int?) {
eventBus.post(OnTextTabChangeEvent(size!!, BuildDetailsPresenter.CHANGES_TAB))
}
}
|
apache-2.0
|
b61344abc7f5500c69fe8553bd42bf59
| 31.205128 | 91 | 0.650212 | 4.534296 | false | false | false | false |
yyued/CodeX-UIKit-Android
|
library/src/main/java/com/yy/codex/uikit/UIGestureRecognizer.kt
|
1
|
4756
|
package com.yy.codex.uikit
import android.os.Handler
import com.yy.codex.foundation.NSInvocation
import java.lang.ref.WeakReference
import java.util.ArrayList
import java.util.Timer
import java.util.TimerTask
/**
* Created by it on 17/1/4.
*/
open class UIGestureRecognizer {
interface Delegate {
fun shouldBegin(gestureRecognizer: UIGestureRecognizer): Boolean
}
internal var _looper: UIGestureRecognizerLooper? = null
internal var _looperOrder = 0
var enabled = true
var stealer = false
var stealable = false
var delegate: Delegate? = null
private var actions: List<NSInvocation> = listOf()
private var triggerBlock: Runnable? = null
var state = UIGestureRecognizerState.Possible
constructor(target: Any, selector: String) {
actions = listOf(NSInvocation(target, selector))
}
constructor(triggerBlock: Runnable) {
this.triggerBlock = triggerBlock
}
fun addTarget(target: Any, selector: String) {
val actions = actions.toMutableList()
actions.add(NSInvocation(target, selector))
this.actions = actions.toList()
}
fun removeTarget(target: Any?, selector: String?) {
if (target == null && selector == null) {
actions = listOf()
return
}
actions = actions.filter {
!(target != null && it.target === target && selector != null && it.selector == selector) &&
!(target == null && selector != null && it.selector == selector) &&
!(target != null && it.target === target && selector == null)
}
}
/* Props */
internal fun didAddToView(view: UIView) {
this.view = view
}
var view: UIView? = null
/* Events */
open fun touchesBegan(touches: List<UITouch>, event: UIEvent) {
if (!enabled) {
state = UIGestureRecognizerState.Failed
}
lastPoints = touches.toList()
}
open fun touchesMoved(touches: List<UITouch>, event: UIEvent) {
if (!enabled) {
state = UIGestureRecognizerState.Failed
}
lastPoints = touches.toList()
}
open fun touchesEnded(touches: List<UITouch>, event: UIEvent) {
if (!enabled) {
state = UIGestureRecognizerState.Failed
}
lastPoints = touches.toList()
}
open fun touchesCancelled() {
state = UIGestureRecognizerState.Cancelled
sendActions()
}
protected open fun sendActions() {
for (action in actions) {
action.invoke(arrayOf<Any>(this))
}
triggerBlock?.let { it.run() }
}
/* Points */
protected var lastPoints: List<UITouch> = listOf()
fun location(): CGPoint {
val view = view
if (view != null) {
return location(view, 0)
}
return CGPoint(0.0, 0.0)
}
@JvmOverloads fun location(inView: UIView, touchIndex: Int = 0): CGPoint {
if (touchIndex < lastPoints.size) {
return lastPoints[touchIndex].locationInView(inView)
}
return CGPoint(0.0, 0.0)
}
fun numberOfTouches(): Int {
return lastPoints.size
}
/* Delegates */
internal open fun gesturePriority(): Int {
return 0
}
protected var gestureRecognizersRequiresFailed: List<UIGestureRecognizer> = listOf()
protected var gestureRecognizerRequiresFailedTimer: Timer? = null
fun requireGestureRecognizerToFail(otherGestureRecognizer: UIGestureRecognizer) {
val mutableList = gestureRecognizersRequiresFailed.toMutableList()
mutableList.add(otherGestureRecognizer)
gestureRecognizersRequiresFailed = mutableList.toList()
}
protected fun waitOtherGesture(runnable: Runnable) {
val handler = Handler()
if (gestureRecognizersRequiresFailed.size > 0) {
if (gestureRecognizerRequiresFailedTimer == null) {
gestureRecognizerRequiresFailedTimer = Timer()
gestureRecognizerRequiresFailedTimer?.schedule(object : TimerTask() {
override fun run() {
gestureRecognizerRequiresFailedTimer = null
if (state == UIGestureRecognizerState.Failed) {
return
}
if (gestureRecognizersRequiresFailed.none { it.state != UIGestureRecognizerState.Failed }) {
handler.post(runnable)
} else {
handler.post { waitOtherGesture(runnable) }
}
}
}, 350)
}
} else {
runnable.run()
}
}
}
|
gpl-3.0
|
cc1d5082ad59461e81de26355cb67770
| 28 | 116 | 0.591253 | 4.858018 | false | false | false | false |
herbeth1u/VNDB-Android
|
app/src/main/java/com/booboot/vndbandroid/model/vndb/StaffVns.kt
|
1
|
237
|
package com.booboot.vndbandroid.model.vndb
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class StaffVns(
var id: Int = 0,
var aid: Int = 0,
var role: String = "",
var note: String? = null
)
|
gpl-3.0
|
c8711448e772475401bc11b7a4e2904e
| 20.636364 | 42 | 0.683544 | 3.434783 | false | false | false | false |
dataloom/conductor-client
|
src/main/kotlin/com/openlattice/hazelcast/serializers/TransportEntitySetEntryProcessorStreamSerializer.kt
|
1
|
3338
|
package com.openlattice.hazelcast.serializers
import com.google.common.collect.Maps
import com.hazelcast.nio.ObjectDataInput
import com.hazelcast.nio.ObjectDataOutput
import com.kryptnostic.rhizome.hazelcast.serializers.UUIDStreamSerializerUtils
import com.openlattice.hazelcast.StreamSerializerTypeIds
import com.openlattice.transporter.processors.TransportEntitySetEntryProcessor
import com.openlattice.transporter.types.TransporterDatastore
import com.openlattice.transporter.types.TransporterDependent
import org.apache.olingo.commons.api.edm.FullQualifiedName
import org.springframework.stereotype.Component
import java.util.ArrayList
import java.util.UUID
/**
* @author Drew Bailey <[email protected]>
*/
@Component
class TransportEntitySetEntryProcessorStreamSerializer:
TestableSelfRegisteringStreamSerializer<TransportEntitySetEntryProcessor> ,
TransporterDependent<Void?>
{
@Transient
private lateinit var data: TransporterDatastore
override fun write(out: ObjectDataOutput, `object`: TransportEntitySetEntryProcessor) {
out.writeInt(`object`.ptIdToFqnColumns.size)
`object`.ptIdToFqnColumns.forEach { id, fqn ->
UUIDStreamSerializerUtils.serialize(out, id)
FullQualifiedNameStreamSerializer.serialize(out, fqn)
}
UUIDStreamSerializerUtils.serialize(out, `object`.organizationId)
out.writeInt(`object`.usersToColumnPermissions.size)
`object`.usersToColumnPermissions.forEach { (key, vals) ->
out.writeUTF(key)
out.writeInt(vals.size)
vals.forEach {
out.writeUTF( it )
}
}
}
override fun read(`in`: ObjectDataInput): TransportEntitySetEntryProcessor {
val colSize = `in`.readInt()
val columns = Maps.newLinkedHashMapWithExpectedSize<UUID, FullQualifiedName>( colSize )
for ( i in 0 until colSize ) {
columns.put(
UUIDStreamSerializerUtils.deserialize(`in`),
FullQualifiedNameStreamSerializer.deserialize(`in`)
)
}
val orgId = UUIDStreamSerializerUtils.deserialize(`in`)
val size = `in`.readInt()
val usersToColPerms = Maps.newLinkedHashMapWithExpectedSize<String, List<String>>(size)
var innerSize: Int
for ( i in 0 until size ) {
val key = `in`.readUTF()
innerSize = `in`.readInt()
val list = ArrayList<String>(innerSize)
for ( j in 0 until innerSize ) {
list.add(`in`.readUTF())
}
usersToColPerms[key] = list
}
return TransportEntitySetEntryProcessor(columns, orgId, usersToColPerms).init(data)
}
override fun generateTestValue(): TransportEntitySetEntryProcessor {
return TransportEntitySetEntryProcessor(
mapOf(),
UUID.randomUUID(),
mapOf()
)
}
override fun getTypeId(): Int {
return StreamSerializerTypeIds.TRANSPORT_ENTITY_SET_EP.ordinal
}
override fun getClazz(): Class<out TransportEntitySetEntryProcessor> {
return TransportEntitySetEntryProcessor::class.java
}
override fun init(data: TransporterDatastore): Void? {
this.data = data
return null
}
}
|
gpl-3.0
|
0f919bc3da0f3ec08684c434b8e36be7
| 36.516854 | 95 | 0.681546 | 5.049924 | false | false | false | false |
daemontus/glucose
|
bundle-list/src/main/java/com/glucose/app/presenter/bundleListUtils.kt
|
2
|
1960
|
package com.glucose.app.presenter
import android.os.Bundle
import android.os.Parcelable
import java.util.*
@JvmField val charSequenceArrayListBundler = object : ObjectBundler<ArrayList<CharSequence>?> {
override fun getter(bundle: Bundle, key: String): ArrayList<CharSequence>? = bundle.getCharSequenceArrayList(key)
override fun setter(bundle: Bundle, key: String, value: ArrayList<CharSequence>?) = bundle.putCharSequenceArrayList(key, value)
}
@JvmField val stringArrayListBundler = object : ObjectBundler<ArrayList<String>?> {
override fun getter(bundle: Bundle, key: String): ArrayList<String>? = bundle.getStringArrayList(key)
override fun setter(bundle: Bundle, key: String, value: ArrayList<String>?) = bundle.putStringArrayList(key, value)
}
@JvmField val intArrayListBundler = object : ObjectBundler<ArrayList<Int>?> {
override fun getter(bundle: Bundle, key: String): ArrayList<Int>? = bundle.getIntegerArrayList(key)
override fun setter(bundle: Bundle, key: String, value: ArrayList<Int>?) = bundle.putIntegerArrayList(key, value)
}
fun <P: Parcelable> parcelableArrayListBundler() = object : ObjectBundler<ArrayList<P>?> {
override fun getter(bundle: Bundle, key: String): ArrayList<P>? = bundle.getParcelableArrayList(key)
override fun setter(bundle: Bundle, key: String, value: ArrayList<P>?) = bundle.putParcelableArrayList(key, value)
}
infix fun String.withCharSequenceList(value: ArrayList<CharSequence>?): Bundled<ArrayList<CharSequence>?> = Bundled(this, value, charSequenceArrayListBundler)
infix fun String.withStringList(value: ArrayList<String>?): Bundled<ArrayList<String>?> = Bundled(this, value, stringArrayListBundler)
infix fun String.withIntList(value: ArrayList<Int>?): Bundled<ArrayList<Int>?> = Bundled(this, value, intArrayListBundler)
infix fun <P: Parcelable> String.withParcelableList(value: ArrayList<P>?): Bundled<ArrayList<P>?> = Bundled(this, value, parcelableArrayListBundler<P>())
|
mit
|
e686f64a93812fcc95a3b6021854ed82
| 71.592593 | 158 | 0.77398 | 4.251627 | false | false | false | false |
square/moshi
|
moshi/src/main/java/com/squareup/moshi/-MoshiKotlinTypesExtensions.kt
|
1
|
2621
|
/*
* Copyright (C) 2020 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.moshi
import com.squareup.moshi.internal.boxIfPrimitive
import java.lang.reflect.GenericArrayType
import java.lang.reflect.Type
import java.lang.reflect.WildcardType
import kotlin.reflect.KClass
import kotlin.reflect.KType
import kotlin.reflect.javaType
import kotlin.reflect.typeOf
/** Returns the raw [Class] type of this type. */
public val Type.rawType: Class<*> get() = Types.getRawType(this)
/**
* Checks if [this] contains [T]. Returns the subset of [this] without [T], or null if
* [this] does not contain [T].
*/
public inline fun <reified T : Annotation> Set<Annotation>.nextAnnotations(): Set<Annotation>? = Types.nextAnnotations(this, T::class.java)
/**
* Returns a type that represents an unknown type that extends [T]. For example, if
* [T] is [CharSequence], this returns `out CharSequence`. If
* [T] is [Any], this returns `*`, which is shorthand for `out Any?`.
*/
@ExperimentalStdlibApi
public inline fun <reified T> subtypeOf(): WildcardType {
var type = typeOf<T>().javaType
if (type is Class<*>) {
type = type.boxIfPrimitive()
}
return Types.subtypeOf(type)
}
/**
* Returns a type that represents an unknown supertype of [T] bound. For example, if [T] is
* [String], this returns `in String`.
*/
@ExperimentalStdlibApi
public inline fun <reified T> supertypeOf(): WildcardType {
var type = typeOf<T>().javaType
if (type is Class<*>) {
type = type.boxIfPrimitive()
}
return Types.supertypeOf(type)
}
/** Returns a [GenericArrayType] with [this] as its [GenericArrayType.getGenericComponentType]. */
@ExperimentalStdlibApi
public fun KType.asArrayType(): GenericArrayType = javaType.asArrayType()
/** Returns a [GenericArrayType] with [this] as its [GenericArrayType.getGenericComponentType]. */
public fun KClass<*>.asArrayType(): GenericArrayType = java.asArrayType()
/** Returns a [GenericArrayType] with [this] as its [GenericArrayType.getGenericComponentType]. */
public fun Type.asArrayType(): GenericArrayType = Types.arrayOf(this)
|
apache-2.0
|
fe89257ef9f3cc5215d8addc2564a1ef
| 35.915493 | 139 | 0.734834 | 3.941353 | false | false | false | false |
alter-ego/unisannio-reboot
|
app/src/main/java/solutions/alterego/android/unisannio/navigation/Navigator.kt
|
1
|
3654
|
package solutions.alterego.android.unisannio.navigation
import android.app.Activity
import android.content.Intent
import android.support.v4.app.TaskStackBuilder
import solutions.alterego.android.unisannio.ateneo.AteneoActivity
import solutions.alterego.android.unisannio.ateneo.AteneoStudentiActivity
import solutions.alterego.android.unisannio.giurisprudenza.GiurisprudenzaActivity
import solutions.alterego.android.unisannio.giurisprudenza.GiurisprudenzaComunicazioniActivity
import solutions.alterego.android.unisannio.ingegneria.IngegneriaAvvisiStudentiActivity
import solutions.alterego.android.unisannio.ingegneria.IngegneriaDipartimentoActivity
import solutions.alterego.android.unisannio.ingegneria.IngengeriaCercapersoneActivity
import solutions.alterego.android.unisannio.scienze.ScienzeActivity
import solutions.alterego.android.unisannio.sea.SeaActivity
class Navigator(val activityContext: Activity) {
fun toAteneo() {
val ateneo = Intent(activityContext, AteneoActivity::class.java)
activityContext.startActivity(ateneo);
activityContext.overridePendingTransition(0,0);
}
fun toAteneoStudenti() {
val ateneo_studenti = Intent(activityContext, AteneoStudentiActivity::class.java)
activityContext.startActivity(ateneo_studenti);
activityContext.overridePendingTransition(0,0);
}
fun toIngegneriaDipartimento() {
val ingegneriaDipartimento = Intent(activityContext, IngegneriaDipartimentoActivity::class.java);
activityContext.startActivity(ingegneriaDipartimento);
activityContext.overridePendingTransition(0,0);
}
fun toIngegneriaStudenti(){
val ingegneriaStudenti = Intent(activityContext, IngegneriaAvvisiStudentiActivity::class.java);
activityContext.startActivity(ingegneriaStudenti);
activityContext.overridePendingTransition(0,0);
}
fun toIngegneriaCercapersone(){
val cercapersone_ingegneria = Intent(activityContext, IngengeriaCercapersoneActivity::class.java);
activityContext.startActivity(cercapersone_ingegneria);
activityContext.overridePendingTransition(0,0);
}
fun toScienzeStudenti(){
val scienze_studenti = Intent(activityContext, ScienzeActivity::class.java);
activityContext.startActivity(scienze_studenti);
activityContext.overridePendingTransition(0,0);
}
fun toGiurisprudenzaStudenti(){
val giurisprudenza = Intent(activityContext, GiurisprudenzaActivity::class.java);
activityContext.startActivity(giurisprudenza);
activityContext.overridePendingTransition(0,0);
}
fun toGiurisprudenzaComunicazioni(){
val giurisprudenza_comunicazioni = Intent(activityContext,GiurisprudenzaComunicazioniActivity::class.java);
activityContext.startActivity(giurisprudenza_comunicazioni);
activityContext.overridePendingTransition(0,0);
}
fun toSeaStudenti(){
val sea = Intent(activityContext,SeaActivity::class.java);
activityContext.startActivity(sea);
activityContext.overridePendingTransition(0,0);
}
fun toAlterego(){
}
fun toGithub(){
}
fun upToParent() {
val intent = activityContext.getParentActivityIntent()
if (intent == null) {
activityContext.finish()
return
}
if (activityContext.shouldUpRecreateTask(intent)) {
TaskStackBuilder.create(activityContext)
.addParentStack(activityContext)
.startActivities()
} else {
activityContext.navigateUpTo(intent)
}
}
}
|
apache-2.0
|
c747c2883eba7e99af85d628a8bc1184
| 37.0625 | 115 | 0.746853 | 4.096413 | false | false | false | false |
pnemonic78/RemoveDuplicates
|
duplicates-android/app/src/main/java/com/github/duplicates/contact/PhoneData.kt
|
1
|
1379
|
/*
* Copyright 2016, Moshe Waisberg
*
* 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.duplicates.contact
import android.provider.ContactsContract.CommonDataKinds.Phone
import android.text.TextUtils
/**
* Contact telephone data.
*
* @author moshe.w
*/
class PhoneData : ContactData() {
val number: String?
get() = data1
val type: Int
get() = parseInt(data2)
val label: String?
get() = data3
init {
mimeType = Phone.CONTENT_ITEM_TYPE
}
override fun toString(): String {
val label = label
return number!! + if (TextUtils.isEmpty(label)) "" else " " + label!!
}
override fun containsAny(s: CharSequence, ignoreCase: Boolean): Boolean {
return (label?.contains(s, ignoreCase) ?: false)
|| (number?.contains(s, ignoreCase) ?: false)
}
}
|
apache-2.0
|
daca2b240753177b9911bcd6baeaf4a2
| 26.58 | 77 | 0.670051 | 4.153614 | false | false | false | false |
http4k/http4k
|
http4k-testing/servirtium/src/test/kotlin/org/http4k/junit/ServirtiumReplayTest.kt
|
1
|
1483
|
package org.http4k.junit
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import org.http4k.core.HttpHandler
import org.http4k.core.Method.POST
import org.http4k.core.Request
import org.http4k.core.Response
import org.http4k.core.Status.Companion.OK
import org.http4k.servirtium.InteractionOptions
import org.http4k.servirtium.InteractionStorage.Companion.InMemory
import org.junit.jupiter.api.Test
class ServirtiumReplayTest {
object AContract
private val storage = InMemory()
@Test
fun `replays traffic from the recording`() {
javaClass.getResourceAsStream("/org/http4k/junit/storedTraffic.txt").reader().use { r ->
storage("name.hashCode").accept(r.readText().toByteArray())
}
val stub = JUnitStub(AContract)
val originalRequest = Request(POST, "/foo")
.header("header1", "value1")
.body("body")
val expectedResponse = Response(OK)
.header("header3", "value3")
.body("body1")
val servirtiumReplay = ServirtiumReplay("name", storage,
object : InteractionOptions {
override fun modify(request: Request): Request = request.header("toBeAdded", "value")
})
@Suppress("UNCHECKED_CAST")
val actualResponse = (servirtiumReplay.resolveParameter(stub, stub) as HttpHandler)(originalRequest)
assertThat(actualResponse, equalTo(expectedResponse))
}
}
|
apache-2.0
|
b3ebc110df481f54ecfbd7237252630b
| 31.23913 | 108 | 0.687795 | 4.16573 | false | true | false | false |
msebire/intellij-community
|
platform/platform-impl/src/com/intellij/internal/statistic/eventLog/FeatureUsageData.kt
|
1
|
4993
|
// 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.internal.statistic.eventLog
import com.intellij.internal.statistic.service.fus.collectors.FUSUsageContext
import com.intellij.internal.statistic.utils.PluginInfo
import com.intellij.internal.statistic.utils.getPluginType
import com.intellij.internal.statistic.utils.getProjectId
import com.intellij.lang.Language
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.Version
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.wm.impl.content.ToolWindowContentUi
import com.intellij.util.containers.ContainerUtil
import java.awt.event.KeyEvent
import java.util.*
class FeatureUsageData {
private var data: MutableMap<String, Any> = ContainerUtil.newHashMap<String, Any>()
fun addFeatureContext(context: FUSUsageContext?): FeatureUsageData {
if (context != null) {
data.putAll(context.data)
}
return this
}
fun addProject(project: Project?): FeatureUsageData {
if (project != null) {
data["project"] = getProjectId(project)
}
return this
}
fun addVersionByString(version: String?): FeatureUsageData {
if (version == null) {
data["version"] = "unknown"
}
else {
addVersion(Version.parseVersion(version))
}
return this
}
fun addVersion(version: Version?): FeatureUsageData {
data["version"] = if (version != null) "${version.major}.${version.minor}" else "unknown.format"
return this
}
fun addOS(): FeatureUsageData {
data["os"] = getOS()
return this
}
private fun getOS(): String {
if (SystemInfo.isWindows) return "Windows"
if (SystemInfo.isMac) return "Mac"
return if (SystemInfo.isLinux) "Linux" else "Other"
}
fun addPluginInfo(info: PluginInfo): FeatureUsageData {
data["plugin_type"] = info.type.name
if (info.type.isSafeToReport() && info.id != null && StringUtil.isNotEmpty(info.id)) {
data["plugin"] = info.id
}
return this
}
fun addLanguage(language: Language): FeatureUsageData {
val type = getPluginType(language.javaClass)
if (type.isSafeToReport()) {
data["lang"] = language.id
}
return this
}
fun addInputEvent(event: AnActionEvent): FeatureUsageData {
val inputEvent = ShortcutDataProvider.getActionEventText(event)
if (inputEvent != null && StringUtil.isNotEmpty(inputEvent)) {
data["input_event"] = inputEvent
}
return this
}
fun addInputEvent(event: KeyEvent): FeatureUsageData {
val inputEvent = ShortcutDataProvider.getKeyEventText(event)
if (inputEvent != null && StringUtil.isNotEmpty(inputEvent)) {
data["input_event"] = inputEvent
}
return this
}
fun addPlace(place: String?): FeatureUsageData {
if (place == null) return this
var reported = ActionPlaces.UNKNOWN
if (isCommonPlace(place)) {
reported = place
}
else if (ActionPlaces.isPopupPlace(place)) {
reported = ActionPlaces.POPUP
}
data["place"] = reported
return this
}
private fun isCommonPlace(place: String): Boolean {
return ActionPlaces.isCommonPlace(place) || ToolWindowContentUi.POPUP_PLACE == place
}
fun addData(key: String, value: Boolean): FeatureUsageData {
return addDataInternal(key, value)
}
fun addData(key: String, value: Int): FeatureUsageData {
return addDataInternal(key, value)
}
fun addData(key: String, value: Long): FeatureUsageData {
return addDataInternal(key, value)
}
fun addData(key: String, value: String): FeatureUsageData {
return addDataInternal(key, value)
}
private fun addDataInternal(key: String, value: Any): FeatureUsageData {
data[key] = value
return this
}
fun build(): Map<String, Any> {
return data
}
fun merge(next: FeatureUsageData, prefix: String): FeatureUsageData {
for ((key, value) in next.build()) {
val newKey = if (key.startsWith("data_")) "$prefix$key" else key
addDataInternal(newKey, value)
}
return this
}
fun copy(): FeatureUsageData {
val result = FeatureUsageData()
for ((key, value) in data) {
result.addDataInternal(key, value)
}
return result
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as FeatureUsageData
if (data != other.data) return false
return true
}
override fun hashCode(): Int {
return data.hashCode()
}
}
fun newData(project: Project?, context: FUSUsageContext?): Map<String, Any> {
if (project == null && context == null) return Collections.emptyMap()
return FeatureUsageData().addProject(project).addFeatureContext(context).build()
}
|
apache-2.0
|
d449617eb84764c93059fb4bf95994ef
| 27.701149 | 140 | 0.69998 | 4.274829 | false | false | false | false |
ankidroid/Anki-Android
|
AnkiDroid/src/main/java/com/ichi2/libanki/sched/AbstractDeckTreeNode.kt
|
1
|
5242
|
/*
* Copyright (c) 2020 Arthur Milchior <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ichi2.libanki.sched
import com.ichi2.libanki.Collection
import com.ichi2.libanki.DeckId
import com.ichi2.libanki.Decks
import java.lang.UnsupportedOperationException
import java.util.*
/**
* Holds the data for a single node (row) in the deck due tree (the user-visible list
* of decks and their counts).
*
* The names field is an array of names that build a deck name from a hierarchy (i.e., a nested
* deck will have an entry for every level of nesting). While the python version interchanges
* between a string and a list of strings throughout processing, we always use an array for
* this field and use getNamePart(0) for those cases.
*
* [processChildren] should be called if the children of this node are modified.
*/
abstract class AbstractDeckTreeNode(
/**
* @return The full deck name, e.g. "A::B::C"
*/
val fullDeckName: String,
val did: DeckId,
// only set when new backend active
open var collapsed: Boolean = false,
open var filtered: Boolean = false
) : Comparable<AbstractDeckTreeNode> {
private val mNameComponents: Array<String>
/**
* Sort on the head of the node.
*/
override fun compareTo(other: AbstractDeckTreeNode): Int {
val minDepth = Math.min(depth, other.depth) + 1
// Consider each subdeck name in the ordering
for (i in 0 until minDepth) {
val cmp = mNameComponents[i].compareTo(other.mNameComponents[i])
if (cmp == 0) {
continue
}
return cmp
}
// If we made it this far then the arrays are of different length. The longer one should
// always come after since it contains all of the sections of the shorter one inside it
// (i.e., the short one is an ancestor of the longer one).
return Integer.compare(depth, other.depth)
}
/** Line representing this string without its children. Used in timbers only. */
protected open fun toStringLine(): String? {
return String.format(
Locale.US, "%s, %d",
fullDeckName, did
)
}
abstract fun processChildren(col: Collection, children: List<AbstractDeckTreeNode>, addRev: Boolean)
override fun toString(): String {
val buf = StringBuffer()
toString(buf)
return buf.toString()
}
protected fun toString(buf: StringBuffer) {
for (i in 0 until depth) {
buf.append(" ")
}
buf.append(toStringLine())
}
/**
* For deck "A::B::C", `getDeckNameComponent(0)` returns "A",
* `getDeckNameComponent(1)` returns "B", etc...
*/
fun getDeckNameComponent(part: Int): String {
return mNameComponents[part]
}
/**
* The part of the name displayed in deck picker, i.e. the
* part that does not belong to its parents. E.g. for deck
* "A::B::C", returns "C".
*/
val lastDeckNameComponent: String
get() = getDeckNameComponent(depth)
/**
* @return The depth of a deck. Top level decks have depth 0,
* their children have depth 1, etc... So "A::B::C" would have
* depth 2.
*/
val depth: Int
get() = mNameComponents.size - 1
override fun hashCode(): Int {
return fullDeckName.hashCode()
}
/**
* Whether both elements have the same structure and numbers.
* @param other
* @return
*/
override fun equals(other: Any?): Boolean {
if (other !is AbstractDeckTreeNode) {
return false
}
return Decks.equalName(fullDeckName, other.fullDeckName)
}
open fun shouldDisplayCounts(): Boolean {
return false
}
/* Number of new cards to see today known to be in this deck and its descendants. The number to show to user*/
open var newCount: Int = 0
get() {
throw UnsupportedOperationException()
}
/* Number of lrn cards (or repetition) to see today known to be in this deck and its descendants. The number to show to user*/
open var lrnCount: Int = 0
get() {
throw UnsupportedOperationException()
}
/* Number of rev cards to see today known to be in this deck and its descendants. The number to show to user*/
open var revCount: Int = 0
get() {
throw UnsupportedOperationException()
}
open fun knownToHaveRep(): Boolean {
return false
}
init {
mNameComponents = Decks.path(fullDeckName)
}
}
|
gpl-3.0
|
f054b2819a00bb7e2969d520d3969d08
| 32.177215 | 130 | 0.640404 | 4.251419 | false | false | false | false |
sksamuel/elasticsearch-river-neo4j
|
streamops-datastore/src/main/kotlin/com/octaldata/datastore/TopicViewDatastore.kt
|
1
|
1793
|
package com.octaldata.datastore
import com.octaldata.domain.DeploymentId
import com.octaldata.domain.topics.TopicView
import com.octaldata.domain.topics.TopicViewId
import com.octaldata.domain.topics.TopicViewName
import org.springframework.jdbc.core.RowMapper
import javax.sql.DataSource
class TopicViewDatastore(ds: DataSource) {
private val template = JdbcCoroutineTemplate(ds)
private val mapper = RowMapper { rs, _ ->
TopicView(
id = TopicViewId(rs.getString("id")),
deploymentId = DeploymentId(rs.getString("deployment_id")),
filter = rs.getString("filter"),
name = TopicViewName(rs.getString("name")),
)
}
suspend fun findAll(): Result<List<TopicView>> {
return template.queryForList("SELECT * FROM `topic_view`", mapper)
}
suspend fun insert(view: TopicView): Result<Int> {
return template.update(
"""INSERT INTO `topic_view`
(id, deployment_id, `name`, `filter`)
VALUES (?,?,?,?)""",
listOf(
view.id.value,
view.deploymentId.value,
view.name.value,
view.filter,
)
)
}
suspend fun delete(id: TopicViewId): Result<Int> {
return template.update(
"DELETE FROM `topic_view` WHERE id=?",
listOf(id.value)
)
}
suspend fun getById(id: TopicViewId): Result<TopicView?> {
return template.query(
"SELECT * FROM `topic_view` WHERE id=?",
mapper,
listOf(id.value)
)
}
suspend fun findByDeploymentId(deploymentId: DeploymentId): Result<List<TopicView>> {
return template.queryForList(
"SELECT * FROM `topic_view` WHERE deployment_id=?",
mapper,
listOf(deploymentId.value)
)
}
}
|
apache-2.0
|
571be07b53ab944ba2600b9093dbea28
| 27.47619 | 88 | 0.621863 | 4.20892 | false | false | false | false |
LanternPowered/LanternServer
|
src/main/kotlin/org/lanternpowered/server/inventory/crafting/LanternCraftingInventory.kt
|
1
|
1987
|
/*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.inventory.crafting
import org.lanternpowered.api.item.inventory.crafting.ExtendedCraftingGridInventory
import org.lanternpowered.api.item.inventory.crafting.ExtendedCraftingInventory
import org.lanternpowered.api.item.inventory.crafting.ExtendedCraftingOutput
import org.lanternpowered.api.item.inventory.query
import org.lanternpowered.server.inventory.AbstractChildrenInventory
import org.lanternpowered.server.inventory.AbstractInventory
import org.lanternpowered.server.inventory.InventoryView
import org.lanternpowered.server.inventory.asInventories
import org.lanternpowered.server.inventory.createViews
open class LanternCraftingInventory : AbstractChildrenInventory(), ExtendedCraftingInventory {
private lateinit var craftingGrid: ExtendedCraftingGridInventory
private lateinit var craftingOutput: ExtendedCraftingOutput
override fun init(children: List<AbstractInventory>) {
super.init(children)
this.craftingGrid = this.query<ExtendedCraftingGridInventory>().first()
this.craftingOutput = this.query<ExtendedCraftingOutput>().first()
}
override fun getCraftingGrid(): ExtendedCraftingGridInventory = this.craftingGrid
override fun getCraftingOutput(): ExtendedCraftingOutput = this.craftingOutput
override fun instantiateView(): InventoryView<LanternCraftingInventory> = View(this)
private class View(
override val backing: LanternCraftingInventory
) : LanternCraftingInventory(), InventoryView<LanternCraftingInventory> {
init {
this.init(this.backing.children().createViews(this).asInventories())
}
}
}
|
mit
|
f3964b5024c11dc629a1f2854514a489
| 40.395833 | 94 | 0.785606 | 4.675294 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.