repo_name
stringlengths 7
81
| path
stringlengths 4
242
| copies
stringclasses 95
values | size
stringlengths 1
6
| content
stringlengths 3
991k
| license
stringclasses 15
values |
---|---|---|---|---|---|
rhdunn/xquery-intellij-plugin | src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/ast/xpath/XPathForExpr.kt | 1 | 864 | /*
* Copyright (C) 2019-2020 Reece H. Dunn
*
* 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 uk.co.reecedunn.intellij.plugin.xpath.ast.xpath
import uk.co.reecedunn.intellij.plugin.xpm.optree.expression.flwor.XpmFlworExpression
/**
* An XPath 2.0 `ForExpr` node in the XPath AST.
*/
interface XPathForExpr : XPathExprSingle, XpmFlworExpression
| apache-2.0 |
jakubveverka/SportApp | app/src/main/java/com/example/jakubveverka/sportapp/Models/DataManager.kt | 1 | 6201 | package com.example.jakubveverka.sportapp.Models
import android.content.Context
import com.example.jakubveverka.sportapp.Adapters.EventsRecyclerViewAdapter
import com.example.jakubveverka.sportapp.Entities.Event
import java.util.*
import android.widget.Toast
import com.example.jakubveverka.sportapp.Utils.MyLog
import com.google.firebase.database.*
/**
* Created by jakubveverka on 14.06.17.
* Class for data managment (Firebase and local SQL db)
*/
object DataManager {
var context: Context? = null
var userUid: String? = null
val childEventListener: ChildEventListener by lazy {
object : ChildEventListener {
override fun onChildAdded(dataSnapshot: DataSnapshot, previousChildName: String?) {
MyLog.d("onChildAdded:" + dataSnapshot.key)
val newEvent = dataSnapshot.getValue(Event::class.java) ?: return
newEvent.firebaseKey = dataSnapshot.key
addNewEventToOrderedList(newEvent)
}
override fun onChildChanged(dataSnapshot: DataSnapshot, previousChildName: String?) {
MyLog.d("onChildChanged:" + dataSnapshot.key)
val changedEvent = dataSnapshot.getValue(Event::class.java) ?: return
changedEvent.firebaseKey = dataSnapshot.key
updateEventInList(changedEvent)
}
override fun onChildRemoved(dataSnapshot: DataSnapshot) {
MyLog.d("onChildRemoved:" + dataSnapshot.key)
val eventKey = dataSnapshot.key
removeEventInListWithKey(eventKey)
}
override fun onChildMoved(dataSnapshot: DataSnapshot, previousChildName: String?) {
MyLog.d("onChildMoved:" + dataSnapshot.key)
val movedEvent = dataSnapshot.getValue(Event::class.java) ?: return
movedEvent.firebaseKey = dataSnapshot.key
removeEventInListWithKey(movedEvent.firebaseKey!!)
addNewEventToOrderedList(movedEvent)
}
override fun onCancelled(databaseError: DatabaseError) {
MyLog.d("onCancelled " + databaseError.toException().toString())
Toast.makeText(context, "Failed to load events.", Toast.LENGTH_SHORT).show()
}
}
}
var eventsRef: Query? = null
fun init(context: Context, userUid: String): DataManager {
this.context = context
this.userUid = userUid
return this
}
private val mEventsAdapter: EventsRecyclerViewAdapter by lazy {
EventsRecyclerViewAdapter(context!!)
}
private val mEvents: LinkedList<Event> = LinkedList()
/**
* Method decides where to save event and saves it
*/
fun saveEvent(event: Event): Boolean {
when (event.storage) {
Event.EventStorage.LOCAL -> return saveEventToDb(event)
Event.EventStorage.FIREBASE -> return saveEventToFirebase(event)
else -> throw Exception("Not supported EventStorage type")
}
}
private fun saveEventToDb(event: Event): Boolean {
return EventsDbHelper.getInstance(context!!).saveEvent(event)
}
private fun saveEventToFirebase(event: Event): Boolean {
val database = FirebaseDatabase.getInstance().reference
val eventsRef = database.child("users").child(event.userUid).child("events").push()
eventsRef.setValue(event)
return true
}
fun getAllEventsAdapterOfUserWithUid(): EventsRecyclerViewAdapter {
mEvents.clear()
getAllEventsOfUserWithUid()
mEventsAdapter.mValues = mEvents
return mEventsAdapter
}
private fun getAllEventsOfUserWithUid() {
getLocalDbEventsOfUserWithUid()
getFirebaseDbEventsOfUserWithUid()
}
fun getLocalDbEventsOfUserWithUid() {
mEvents.addAll(EventsDbHelper.getInstance(context!!).getAllEventsOfUserWithUid(userUid!!))
}
/*private fun getFirebaseDbEventsOfUserWithUid(userUid: String) {
startListeningForEvents(userUid)
}*/
private fun addNewEventToOrderedList(newEvent: Event) {
var inserted = false
var insertedIndex = 0
MyLog.d("mEventsSize in addNewEventToOrderedList: ${mEvents.size}")
val iterator = mEvents.listIterator(mEvents.size)
while(iterator.hasPrevious()) {
val event = iterator.previous()
if(newEvent.startTime >= event.startTime) {
if(iterator.hasNext()) iterator.next()
iterator.add(newEvent)
inserted = true
insertedIndex = iterator.nextIndex() - 1
MyLog.d("inserting at index: $insertedIndex")
break
}
}
if(!inserted) iterator.add(newEvent)
mEventsAdapter.notifyItemInserted(insertedIndex)
}
private fun updateEventInList(changedEvent: Event) {
val iterator = mEvents.listIterator(mEvents.size)
while(iterator.hasPrevious()) {
val event = iterator.previous()
if(event.firebaseKey == changedEvent.firebaseKey) {
iterator.set(changedEvent)
mEventsAdapter.notifyItemChanged(iterator.nextIndex())
break
}
}
}
private fun removeEventInListWithKey(key: String) {
val iterator = mEvents.listIterator(mEvents.size)
while(iterator.hasPrevious()) {
val event = iterator.previous()
if(event.firebaseKey == key) {
val removedIndex = iterator.nextIndex()
iterator.remove()
mEventsAdapter.notifyItemRemoved(removedIndex)
break
}
}
}
fun getFirebaseDbEventsOfUserWithUid() {
eventsRef?.removeEventListener(childEventListener)
val database = FirebaseDatabase.getInstance().reference
eventsRef = database.child("users").child(userUid!!).child("events").orderByChild("startTime")
eventsRef?.addChildEventListener(childEventListener)
}
fun stopListeningOnFirebaseDb() {
eventsRef?.removeEventListener(childEventListener)
}
} | mit |
robfletcher/orca | orca-queue/src/main/kotlin/com/netflix/spinnaker/orca/q/handler/RunTaskHandler.kt | 2 | 17767 | /*
* 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.spectator.api.BasicTag
import com.netflix.spectator.api.Registry
import com.netflix.spinnaker.kork.dynamicconfig.DynamicConfigService
import com.netflix.spinnaker.kork.exceptions.UserException
import com.netflix.spinnaker.orca.TaskExecutionInterceptor
import com.netflix.spinnaker.orca.TaskResolver
import com.netflix.spinnaker.orca.api.pipeline.OverridableTimeoutRetryableTask
import com.netflix.spinnaker.orca.api.pipeline.RetryableTask
import com.netflix.spinnaker.orca.api.pipeline.Task
import com.netflix.spinnaker.orca.api.pipeline.TaskResult
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.CANCELED
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.FAILED_CONTINUE
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.PAUSED
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.REDIRECT
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.RUNNING
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.SKIPPED
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.STOPPED
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.SUCCEEDED
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.TERMINAL
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionType
import com.netflix.spinnaker.orca.api.pipeline.models.PipelineExecution
import com.netflix.spinnaker.orca.api.pipeline.models.StageExecution
import com.netflix.spinnaker.orca.api.pipeline.models.TaskExecution
import com.netflix.spinnaker.orca.clouddriver.utils.CloudProviderAware
import com.netflix.spinnaker.orca.exceptions.ExceptionHandler
import com.netflix.spinnaker.orca.exceptions.TimeoutException
import com.netflix.spinnaker.orca.ext.beforeStages
import com.netflix.spinnaker.orca.ext.failureStatus
import com.netflix.spinnaker.orca.ext.isManuallySkipped
import com.netflix.spinnaker.orca.pipeline.RestrictExecutionDuringTimeWindow
import com.netflix.spinnaker.orca.pipeline.StageDefinitionBuilderFactory
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.orca.pipeline.util.ContextParameterProcessor
import com.netflix.spinnaker.orca.pipeline.util.StageNavigator
import com.netflix.spinnaker.orca.q.CompleteTask
import com.netflix.spinnaker.orca.q.InvalidTaskType
import com.netflix.spinnaker.orca.q.PauseTask
import com.netflix.spinnaker.orca.q.RunTask
import com.netflix.spinnaker.orca.q.metrics.MetricsTagHelper
import com.netflix.spinnaker.orca.time.toDuration
import com.netflix.spinnaker.orca.time.toInstant
import com.netflix.spinnaker.q.Message
import com.netflix.spinnaker.q.Queue
import java.time.Clock
import java.time.Duration
import java.time.Duration.ZERO
import java.time.Instant
import java.time.temporal.TemporalAmount
import java.util.concurrent.TimeUnit
import kotlin.collections.set
import org.apache.commons.lang3.time.DurationFormatUtils
import org.slf4j.MDC
import org.springframework.stereotype.Component
@Component
class RunTaskHandler(
override val queue: Queue,
override val repository: ExecutionRepository,
override val stageNavigator: StageNavigator,
override val stageDefinitionBuilderFactory: StageDefinitionBuilderFactory,
override val contextParameterProcessor: ContextParameterProcessor,
private val taskResolver: TaskResolver,
private val clock: Clock,
private val exceptionHandlers: List<ExceptionHandler>,
private val taskExecutionInterceptors: List<TaskExecutionInterceptor>,
private val registry: Registry,
private val dynamicConfigService: DynamicConfigService
) : OrcaMessageHandler<RunTask>, ExpressionAware, AuthenticationAware {
/**
* If a task takes longer than this number of ms to run, we will print a warning.
* This is an indication that the task might eventually hit the dreaded message ack timeout and might end
* running multiple times cause unintended side-effects.
*/
private val warningInvocationTimeMs: Int = dynamicConfigService.getConfig(
Int::class.java,
"tasks.warningInvocationTimeMs",
30000
)
override fun handle(message: RunTask) {
message.withTask { origStage, taskModel, task ->
var stage = origStage
stage.withAuth {
stage.withLoggingContext(taskModel) {
val thisInvocationStartTimeMs = clock.millis()
val execution = stage.execution
var taskResult: TaskResult? = null
try {
taskExecutionInterceptors.forEach { t -> stage = t.beforeTaskExecution(task, stage) }
if (execution.isCanceled) {
task.onCancel(stage)
queue.push(CompleteTask(message, CANCELED))
} else if (execution.status.isComplete) {
queue.push(CompleteTask(message, CANCELED))
} else if (execution.status == PAUSED) {
queue.push(PauseTask(message))
} else if (stage.isManuallySkipped()) {
queue.push(CompleteTask(message, SKIPPED))
} else {
try {
task.checkForTimeout(stage, taskModel, message)
} catch (e: TimeoutException) {
registry
.timeoutCounter(stage.execution.type, stage.execution.application, stage.type, taskModel.name)
.increment()
taskResult = task.onTimeout(stage)
if (taskResult == null) {
// This means this task doesn't care to alter the timeout flow, just throw
throw e
}
if (!setOf(TERMINAL, FAILED_CONTINUE).contains(taskResult.status)) {
log.error("Task ${task.javaClass.name} returned invalid status (${taskResult.status}) for onTimeout")
throw e
}
}
if (taskResult == null) {
taskResult = task.execute(stage.withMergedContext())
taskExecutionInterceptors.forEach { t -> taskResult = t.afterTaskExecution(task, stage, taskResult) }
}
taskResult!!.let { result: TaskResult ->
// TODO: rather send this data with CompleteTask message
stage.processTaskOutput(result)
when (result.status) {
RUNNING -> {
queue.push(message, task.backoffPeriod(taskModel, stage))
trackResult(stage, thisInvocationStartTimeMs, taskModel, result.status)
}
SUCCEEDED, REDIRECT, SKIPPED, FAILED_CONTINUE, STOPPED -> {
queue.push(CompleteTask(message, result.status))
trackResult(stage, thisInvocationStartTimeMs, taskModel, result.status)
}
CANCELED -> {
task.onCancel(stage)
val status = stage.failureStatus(default = result.status)
queue.push(CompleteTask(message, status, result.status))
trackResult(stage, thisInvocationStartTimeMs, taskModel, status)
}
TERMINAL -> {
val status = stage.failureStatus(default = result.status)
queue.push(CompleteTask(message, status, result.status))
trackResult(stage, thisInvocationStartTimeMs, taskModel, status)
}
else ->
TODO("Unhandled task status ${result.status}")
}
}
}
} catch (e: Exception) {
val exceptionDetails = exceptionHandlers.shouldRetry(e, taskModel.name)
if (exceptionDetails?.shouldRetry == true) {
log.warn("Error running ${message.taskType.simpleName} for ${message.executionType}[${message.executionId}]")
queue.push(message, task.backoffPeriod(taskModel, stage))
trackResult(stage, thisInvocationStartTimeMs, taskModel, RUNNING)
} else if (e is TimeoutException && stage.context["markSuccessfulOnTimeout"] == true) {
trackResult(stage, thisInvocationStartTimeMs, taskModel, SUCCEEDED)
queue.push(CompleteTask(message, SUCCEEDED))
} else {
if (e !is TimeoutException) {
if (e is UserException) {
log.warn("${message.taskType.simpleName} for ${message.executionType}[${message.executionId}] failed, likely due to user error", e)
} else {
log.error("Error running ${message.taskType.simpleName} for ${message.executionType}[${message.executionId}]", e)
}
}
val status = stage.failureStatus(default = TERMINAL)
stage.context["exception"] = exceptionDetails
repository.storeStage(stage)
queue.push(CompleteTask(message, status, TERMINAL))
trackResult(stage, thisInvocationStartTimeMs, taskModel, status)
}
}
}
}
}
}
private fun trackResult(stage: StageExecution, thisInvocationStartTimeMs: Long, taskModel: TaskExecution, status: ExecutionStatus) {
try {
val commonTags = MetricsTagHelper.commonTags(stage, taskModel, status)
val detailedTags = MetricsTagHelper.detailedTaskTags(stage, taskModel, status)
val elapsedMillis = clock.millis() - thisInvocationStartTimeMs
hashMapOf(
"task.invocations.duration" to commonTags + BasicTag("application", stage.execution.application),
"task.invocations.duration.withType" to commonTags + detailedTags
).forEach { name, tags ->
registry.timer(name, tags).record(elapsedMillis, TimeUnit.MILLISECONDS)
}
if (elapsedMillis >= warningInvocationTimeMs) {
log.info(
"Task invocation took over ${warningInvocationTimeMs}ms " +
"(taskType: ${taskModel.implementingClass}, stageType: ${stage.type}, stageId: ${stage.id})"
)
}
} catch (e: java.lang.Exception) {
log.warn("Failed to track result for stage: ${stage.id}, task: ${taskModel.id}", e)
}
}
override val messageType = RunTask::class.java
private fun RunTask.withTask(block: (StageExecution, TaskExecution, Task) -> Unit) =
withTask { stage, taskModel ->
try {
taskResolver.getTask(taskModel.implementingClass)
} catch (e: TaskResolver.NoSuchTaskException) {
try {
taskResolver.getTask(taskType)
} catch (e: TaskResolver.NoSuchTaskException) {
queue.push(InvalidTaskType(this, taskType.name))
null
}
}?.let {
block.invoke(stage, taskModel, it)
}
}
private fun Task.backoffPeriod(taskModel: TaskExecution, stage: StageExecution): TemporalAmount =
when (this) {
is RetryableTask -> Duration.ofMillis(
retryableBackOffPeriod(taskModel, stage).coerceAtMost(taskExecutionInterceptors.maxBackoff())
)
else -> Duration.ofMillis(1000)
}
/**
* The max back off value always wins. For example, given the following dynamic configs:
* `tasks.global.backOffPeriod = 5000`
* `tasks.aws.backOffPeriod = 80000`
* `tasks.aws.someAccount.backoffPeriod = 60000`
* `tasks.aws.backoffPeriod` will be used (given the criteria matches and unless the default dynamicBackOffPeriod is greater).
*/
private fun RetryableTask.retryableBackOffPeriod(
taskModel: TaskExecution,
stage: StageExecution
): Long {
val dynamicBackOffPeriod = getDynamicBackoffPeriod(
stage, Duration.ofMillis(System.currentTimeMillis() - (taskModel.startTime ?: 0))
)
val backOffs: MutableList<Long> = mutableListOf(
dynamicBackOffPeriod,
dynamicConfigService.getConfig(
Long::class.java,
"tasks.global.backOffPeriod",
dynamicBackOffPeriod
)
)
if (this is CloudProviderAware && hasCloudProvider(stage)) {
backOffs.add(
dynamicConfigService.getConfig(
Long::class.java,
"tasks.${getCloudProvider(stage)}.backOffPeriod",
dynamicBackOffPeriod
)
)
if (hasCredentials(stage)) {
backOffs.add(
dynamicConfigService.getConfig(
Long::class.java,
"tasks.${getCloudProvider(stage)}.${getCredentials(stage)}.backOffPeriod",
dynamicBackOffPeriod
)
)
}
}
return backOffs.max() ?: dynamicBackOffPeriod
}
private fun List<TaskExecutionInterceptor>.maxBackoff(): Long =
this.fold(Long.MAX_VALUE) { backoff, interceptor ->
backoff.coerceAtMost(interceptor.maxTaskBackoff())
}
private fun formatTimeout(timeout: Long): String {
return DurationFormatUtils.formatDurationWords(timeout, true, true)
}
private fun Task.checkForTimeout(stage: StageExecution, taskModel: TaskExecution, message: Message) {
if (stage.type == RestrictExecutionDuringTimeWindow.TYPE) {
return
} else {
checkForStageTimeout(stage)
checkForTaskTimeout(taskModel, stage, message)
}
}
private fun Task.checkForTaskTimeout(taskModel: TaskExecution, stage: StageExecution, message: Message) {
if (this is RetryableTask) {
val startTime = taskModel.startTime.toInstant()
if (startTime != null) {
val pausedDuration = stage.execution.pausedDurationRelativeTo(startTime)
val elapsedTime = Duration.between(startTime, clock.instant())
val actualTimeout = (
if (this is OverridableTimeoutRetryableTask && stage.parentWithTimeout.isPresent)
stage.parentWithTimeout.get().timeout.get().toDuration()
else
getDynamicTimeout(stage).toDuration()
)
if (elapsedTime.minus(pausedDuration) > actualTimeout) {
val durationString = formatTimeout(elapsedTime.toMillis())
val msg = StringBuilder("${javaClass.simpleName} of stage ${stage.name} timed out after $durationString. ")
msg.append("pausedDuration: ${formatTimeout(pausedDuration.toMillis())}, ")
msg.append("elapsedTime: ${formatTimeout(elapsedTime.toMillis())}, ")
msg.append("timeoutValue: ${formatTimeout(actualTimeout.toMillis())}")
log.info(msg.toString())
throw TimeoutException(msg.toString())
}
}
}
}
private fun checkForStageTimeout(stage: StageExecution) {
stage.parentWithTimeout.ifPresent {
val startTime = it.startTime.toInstant()
if (startTime != null) {
val elapsedTime = Duration.between(startTime, clock.instant())
val pausedDuration = stage.execution.pausedDurationRelativeTo(startTime)
val executionWindowDuration = stage.executionWindow?.duration ?: ZERO
val timeout = Duration.ofMillis(it.timeout.get())
if (elapsedTime.minus(pausedDuration).minus(executionWindowDuration) > timeout) {
throw TimeoutException("Stage ${stage.name} timed out after ${formatTimeout(elapsedTime.toMillis())}")
}
}
}
}
private val StageExecution.executionWindow: StageExecution?
get() = beforeStages()
.firstOrNull { it.type == RestrictExecutionDuringTimeWindow.TYPE }
private val StageExecution.duration: Duration
get() = run {
if (startTime == null || endTime == null) {
throw IllegalStateException("Only valid on completed stages")
}
Duration.between(startTime.toInstant(), endTime.toInstant())
}
private fun Registry.timeoutCounter(
executionType: ExecutionType,
application: String,
stageType: String,
taskType: String
) =
counter(
createId("queue.task.timeouts")
.withTags(
mapOf(
"executionType" to executionType.toString(),
"application" to application,
"stageType" to stageType,
"taskType" to taskType
)
)
)
private fun PipelineExecution.pausedDurationRelativeTo(instant: Instant?): Duration {
val pausedDetails = paused
return if (pausedDetails != null) {
if (pausedDetails.pauseTime.toInstant()?.isAfter(instant) == true) {
Duration.ofMillis(pausedDetails.pausedMs)
} else ZERO
} else ZERO
}
private fun StageExecution.processTaskOutput(result: TaskResult) {
val filteredOutputs = result.outputs.filterKeys { it != "stageTimeoutMs" }
if (result.context.isNotEmpty() || filteredOutputs.isNotEmpty()) {
context.putAll(result.context)
outputs.putAll(filteredOutputs)
repository.storeStage(this)
}
}
private fun StageExecution.withLoggingContext(taskModel: TaskExecution, block: () -> Unit) {
try {
MDC.put("stageType", type)
MDC.put("taskType", taskModel.implementingClass)
if (taskModel.startTime != null) {
MDC.put("taskStartTime", taskModel.startTime.toString())
}
block.invoke()
} finally {
MDC.remove("stageType")
MDC.remove("taskType")
MDC.remove("taskStartTime")
}
}
}
| apache-2.0 |
jiaminglu/kotlin-native | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/ir/util/IrUnboundSymbolReplacer.kt | 1 | 14575 | package org.jetbrains.kotlin.ir.util
import org.jetbrains.kotlin.backend.common.pop
import org.jetbrains.kotlin.backend.common.push
import org.jetbrains.kotlin.backend.konan.Context
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.ir.IrElement
import org.jetbrains.kotlin.ir.IrStatement
import org.jetbrains.kotlin.ir.declarations.IrAnonymousInitializer
import org.jetbrains.kotlin.ir.declarations.IrFunction
import org.jetbrains.kotlin.ir.declarations.IrModuleFragment
import org.jetbrains.kotlin.ir.declarations.IrSymbolOwner
import org.jetbrains.kotlin.ir.expressions.*
import org.jetbrains.kotlin.ir.expressions.impl.*
import org.jetbrains.kotlin.ir.symbols.IrBindableSymbol
import org.jetbrains.kotlin.ir.symbols.IrClassifierSymbol
import org.jetbrains.kotlin.ir.symbols.IrFunctionSymbol
import org.jetbrains.kotlin.ir.symbols.IrSymbol
import org.jetbrains.kotlin.ir.visitors.*
@Deprecated("")
internal fun IrModuleFragment.replaceUnboundSymbols(context: Context) {
val collector = DeclarationSymbolCollector()
with(collector) {
with(irBuiltins) {
for (op in arrayOf(eqeqeqFun, eqeqFun, lt0Fun, lteq0Fun, gt0Fun, gteq0Fun, throwNpeFun, booleanNotFun,
noWhenBranchMatchedExceptionFun)) {
register(op.symbol)
}
}
}
this.acceptVoid(collector)
val symbolTable = context.ir.symbols.symbolTable
this.transformChildrenVoid(IrUnboundSymbolReplacer(symbolTable, collector.descriptorToSymbol))
// Generate missing external stubs:
// TODO: ModuleGenerator::generateUnboundSymbolsAsDependencies(IRModuleFragment) is private function :/
ExternalDependenciesGenerator(symbolTable = context.psi2IrGeneratorContext.symbolTable, irBuiltIns = context.irBuiltIns).generateUnboundSymbolsAsDependencies(this)
// Merge duplicated module and package declarations:
this.acceptVoid(object : IrElementVisitorVoid {
override fun visitElement(element: IrElement) {}
override fun visitModuleFragment(declaration: IrModuleFragment) {
declaration.dependencyModules.forEach { it.acceptVoid(this) }
val dependencyModules = declaration.dependencyModules.groupBy { it.descriptor }.map { (_, fragments) ->
fragments.reduce { firstModule, nextModule ->
firstModule.apply {
mergeFrom(nextModule)
}
}
}
declaration.dependencyModules.clear()
declaration.dependencyModules.addAll(dependencyModules)
}
})
}
private fun IrModuleFragment.mergeFrom(other: IrModuleFragment): Unit {
assert(this.files.isEmpty())
assert(other.files.isEmpty())
val thisPackages = this.externalPackageFragments.groupBy { it.packageFragmentDescriptor }
other.externalPackageFragments.forEach {
val thisPackage = thisPackages[it.packageFragmentDescriptor]?.single()
if (thisPackage == null) {
this.externalPackageFragments.add(it)
} else {
thisPackage.declarations.addAll(it.declarations)
}
}
}
private class DeclarationSymbolCollector : IrElementVisitorVoid {
val descriptorToSymbol = mutableMapOf<DeclarationDescriptor, IrSymbol>()
fun register(symbol: IrSymbol) {
descriptorToSymbol[symbol.descriptor] = symbol
}
override fun visitElement(element: IrElement) {
element.acceptChildrenVoid(this)
if (element is IrSymbolOwner && element !is IrAnonymousInitializer) {
register(element.symbol)
}
}
}
private class IrUnboundSymbolReplacer(
val symbolTable: SymbolTable,
val descriptorToSymbol: Map<DeclarationDescriptor, IrSymbol>
) : IrElementTransformerVoid() {
private inline fun <D : DeclarationDescriptor, reified S : IrBindableSymbol<D, *>> S.replace(
referenceSymbol: (SymbolTable, D) -> S): S? {
if (this.isBound) {
return null
}
descriptorToSymbol[this.descriptor]?.let {
return it as S
}
return referenceSymbol(symbolTable, this.descriptor)
}
private inline fun <D : DeclarationDescriptor, reified S : IrBindableSymbol<D, *>> S.replaceOrSame(
referenceSymbol: (SymbolTable, D) -> S): S = this.replace(referenceSymbol) ?: this
private fun IrFunctionSymbol.replace(
referenceSymbol: (SymbolTable, FunctionDescriptor) -> IrFunctionSymbol): IrFunctionSymbol? {
if (this.isBound) {
return null
}
descriptorToSymbol[this.descriptor]?.let {
return it as IrFunctionSymbol
}
return referenceSymbol(symbolTable, this.descriptor)
}
private inline fun <reified S : IrSymbol> S.replaceLocal(): S? {
return if (this.isBound) {
null
} else {
descriptorToSymbol[this.descriptor] as S
}
}
override fun visitGetValue(expression: IrGetValue): IrExpression {
val symbol = expression.symbol.replaceLocal() ?: return super.visitGetValue(expression)
expression.transformChildrenVoid(this)
return with(expression) {
IrGetValueImpl(startOffset, endOffset, symbol, origin)
}
}
override fun visitSetVariable(expression: IrSetVariable): IrExpression {
val symbol = expression.symbol.replaceLocal() ?: return super.visitSetVariable(expression)
expression.transformChildrenVoid(this)
return with(expression) {
IrSetVariableImpl(startOffset, endOffset, symbol, value, origin)
}
}
override fun visitGetObjectValue(expression: IrGetObjectValue): IrExpression {
val symbol = expression.symbol.replace(SymbolTable::referenceClass) ?:
return super.visitGetObjectValue(expression)
expression.transformChildrenVoid(this)
return with(expression) {
IrGetObjectValueImpl(startOffset, endOffset, type, symbol)
}
}
override fun visitGetEnumValue(expression: IrGetEnumValue): IrExpression {
val symbol = expression.symbol.replace(SymbolTable::referenceEnumEntry) ?:
return super.visitGetEnumValue(expression)
expression.transformChildrenVoid(this)
return with(expression) {
IrGetEnumValueImpl(startOffset, endOffset, type, symbol)
}
}
override fun visitClassReference(expression: IrClassReference): IrExpression {
val symbol = expression.symbol.let {
if (it.isBound) {
return super.visitClassReference(expression)
}
descriptorToSymbol[it.descriptor]?.let {
it as IrClassifierSymbol
}
symbolTable.referenceClassifier(it.descriptor)
}
expression.transformChildrenVoid(this)
return with(expression) {
IrClassReferenceImpl(startOffset, endOffset, type, symbol)
}
}
override fun visitGetField(expression: IrGetField): IrExpression {
val symbol = expression.symbol.replaceOrSame(SymbolTable::referenceField)
val superQualifierSymbol = expression.superQualifierSymbol?.replaceOrSame(SymbolTable::referenceClass)
if (symbol == expression.symbol && superQualifierSymbol == expression.superQualifierSymbol) {
return super.visitGetField(expression)
}
expression.transformChildrenVoid(this)
return with(expression) {
IrGetFieldImpl(startOffset, endOffset, symbol, receiver, origin, superQualifierSymbol)
}
}
override fun visitSetField(expression: IrSetField): IrExpression {
val symbol = expression.symbol.replaceOrSame(SymbolTable::referenceField)
val superQualifierSymbol = expression.superQualifierSymbol?.replaceOrSame(SymbolTable::referenceClass)
if (symbol == expression.symbol && superQualifierSymbol == expression.superQualifierSymbol) {
return super.visitSetField(expression)
}
expression.transformChildrenVoid(this)
return with(expression) {
IrSetFieldImpl(startOffset, endOffset, symbol, receiver, value, origin, superQualifierSymbol)
}
}
override fun visitCall(expression: IrCall): IrExpression {
val symbol = expression.symbol.replace(SymbolTable::referenceFunction) ?: expression.symbol
val superQualifierSymbol = expression.superQualifierSymbol?.replaceOrSame(SymbolTable::referenceClass)
if (symbol == expression.symbol && superQualifierSymbol == expression.superQualifierSymbol) {
return super.visitCall(expression)
}
expression.transformChildrenVoid()
return with(expression) {
IrCallImpl(startOffset, endOffset, symbol, descriptor,
getTypeArgumentsMap(),
origin, superQualifierSymbol).also {
it.copyArgumentsFrom(this)
}
}
}
private fun IrMemberAccessExpression.getTypeArgumentsMap() =
descriptor.original.typeParameters.associate { it to getTypeArgumentOrDefault(it) }
private fun IrMemberAccessExpressionBase.copyArgumentsFrom(original: IrMemberAccessExpression) {
dispatchReceiver = original.dispatchReceiver
extensionReceiver = original.extensionReceiver
original.descriptor.valueParameters.forEachIndexed { index, _ ->
putValueArgument(index, original.getValueArgument(index))
}
}
override fun visitEnumConstructorCall(expression: IrEnumConstructorCall): IrExpression {
val symbol = expression.symbol.replace(SymbolTable::referenceConstructor) ?:
return super.visitEnumConstructorCall(expression)
return with(expression) {
IrEnumConstructorCallImpl(startOffset, endOffset, symbol).also {
it.copyArgumentsFrom(this)
}
}
}
override fun visitDelegatingConstructorCall(expression: IrDelegatingConstructorCall): IrExpression {
val symbol = expression.symbol.replace(SymbolTable::referenceConstructor) ?:
return super.visitDelegatingConstructorCall(expression)
expression.transformChildrenVoid()
return with(expression) {
IrDelegatingConstructorCallImpl(startOffset, endOffset, symbol, descriptor, getTypeArgumentsMap()).also {
it.copyArgumentsFrom(this)
}
}
}
override fun visitFunctionReference(expression: IrFunctionReference): IrExpression {
val symbol = expression.symbol.replace(SymbolTable::referenceFunction) ?:
return super.visitFunctionReference(expression)
expression.transformChildrenVoid(this)
return with(expression) {
IrFunctionReferenceImpl(startOffset, endOffset, type, symbol, descriptor, getTypeArgumentsMap()).also {
it.copyArgumentsFrom(this)
}
}
}
override fun visitPropertyReference(expression: IrPropertyReference): IrExpression {
val field = expression.field?.replaceOrSame(SymbolTable::referenceField)
val getter = expression.getter?.replace(SymbolTable::referenceFunction) ?: expression.getter
val setter = expression.setter?.replace(SymbolTable::referenceFunction) ?: expression.setter
if (field == expression.field && getter == expression.getter && setter == expression.setter) {
return super.visitPropertyReference(expression)
}
expression.transformChildrenVoid(this)
return with(expression) {
IrPropertyReferenceImpl(startOffset, endOffset, type, descriptor,
field,
getter,
setter,
getTypeArgumentsMap(), origin).also {
it.copyArgumentsFrom(this)
}
}
}
override fun visitLocalDelegatedPropertyReference(expression: IrLocalDelegatedPropertyReference): IrExpression {
val delegate = expression.delegate.replaceOrSame(SymbolTable::referenceVariable)
val getter = expression.getter.replace(SymbolTable::referenceFunction) ?: expression.getter
val setter = expression.setter?.replace(SymbolTable::referenceFunction) ?: expression.setter
if (delegate == expression.delegate && getter == expression.getter && setter == expression.setter) {
return super.visitLocalDelegatedPropertyReference(expression)
}
expression.transformChildrenVoid(this)
return with(expression) {
IrLocalDelegatedPropertyReferenceImpl(startOffset, endOffset, type, descriptor,
delegate, getter, setter, origin).also {
it.copyArgumentsFrom(this)
}
}
}
private val returnTargetStack = mutableListOf<IrFunctionSymbol>()
override fun visitFunction(declaration: IrFunction): IrStatement {
returnTargetStack.push(declaration.symbol)
try {
return super.visitFunction(declaration)
} finally {
returnTargetStack.pop()
}
}
override fun visitBlock(expression: IrBlock): IrExpression {
if (expression is IrReturnableBlock) {
returnTargetStack.push(expression.symbol)
try {
return super.visitBlock(expression)
} finally {
returnTargetStack.pop()
}
} else {
return super.visitBlock(expression)
}
}
override fun visitReturn(expression: IrReturn): IrExpression {
if (expression.returnTargetSymbol.isBound) {
return super.visitReturn(expression)
}
val returnTargetSymbol = returnTargetStack.last { it.descriptor == expression.returnTarget }
expression.transformChildrenVoid(this)
return with(expression) {
IrReturnImpl(startOffset, endOffset, type, returnTargetSymbol, value)
}
}
override fun visitInstanceInitializerCall(expression: IrInstanceInitializerCall): IrExpression {
val classSymbol = expression.classSymbol.replace(SymbolTable::referenceClass) ?:
return super.visitInstanceInitializerCall(expression)
expression.transformChildrenVoid(this)
return with(expression) {
IrInstanceInitializerCallImpl(startOffset, endOffset, classSymbol)
}
}
}
| apache-2.0 |
dhleong/ideavim | test/org/jetbrains/plugins/ideavim/action/motion/gn/GnNextTextObjectTest.kt | 1 | 2541 | /*
* IdeaVim - Vim emulator for IDEs based on the IntelliJ platform
* Copyright (C) 2003-2019 The IdeaVim authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
@file:Suppress("RemoveCurlyBracesFromTemplate")
package org.jetbrains.plugins.ideavim.action.motion.gn
import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.command.CommandState
import com.maddyhome.idea.vim.helper.StringHelper.parseKeys
import com.maddyhome.idea.vim.helper.noneOfEnum
import org.jetbrains.plugins.ideavim.VimTestCase
import javax.swing.KeyStroke
class GnNextTextObjectTest : VimTestCase() {
fun `test delete word`() {
doTestWithSearch(parseKeys("dgn"), """
Hello, ${c}this is a test here
""".trimIndent(),
"""
Hello, this is a ${c} here
""".trimIndent())
}
fun `test delete second word`() {
doTestWithSearch(parseKeys("2dgn"), """
Hello, ${c}this is a test here
Hello, this is a test here
""".trimIndent(),
"""
Hello, this is a test here
Hello, this is a ${c} here
""".trimIndent())
}
fun `test with repeat`() {
doTestWithSearch(parseKeys("cgnNewValue<ESC>..."), """
Hello, ${c}this is a test here
Hello, this is a test here
Hello, this is a test here
Hello, this is a test here
Hello, this is a test here
""".trimIndent(),
"""
Hello, this is a NewValue here
Hello, this is a NewValue here
Hello, this is a NewValue here
Hello, this is a NewValu${c}e here
Hello, this is a test here
""".trimIndent())
}
private fun doTestWithSearch(keys: List<KeyStroke>, before: String,
after: String) {
configureByText(before)
VimPlugin.getSearch().search(myFixture.editor, "test", 1, noneOfEnum(), false)
typeText(keys)
myFixture.checkResult(after)
assertState(CommandState.Mode.COMMAND, CommandState.SubMode.NONE)
}
} | gpl-2.0 |
NerdNumber9/TachiyomiEH | app/src/main/java/eu/kanade/tachiyomi/ui/reader/ReaderPageSheet.kt | 1 | 2069 | package eu.kanade.tachiyomi.ui.reader
import android.os.Bundle
import android.support.design.widget.BottomSheetDialog
import android.view.ViewGroup
import com.afollestad.materialdialogs.MaterialDialog
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.ui.reader.model.ReaderPage
import kotlinx.android.synthetic.main.reader_page_sheet.*
/**
* Sheet to show when a page is long clicked.
*/
class ReaderPageSheet(
private val activity: ReaderActivity,
private val page: ReaderPage
) : BottomSheetDialog(activity) {
/**
* View used on this sheet.
*/
private val view = activity.layoutInflater.inflate(R.layout.reader_page_sheet, null)
init {
setContentView(view)
set_as_cover_layout.setOnClickListener { setAsCover() }
share_layout.setOnClickListener { share() }
save_layout.setOnClickListener { save() }
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val width = context.resources.getDimensionPixelSize(R.dimen.bottom_sheet_width)
if (width > 0) {
window?.setLayout(width, ViewGroup.LayoutParams.MATCH_PARENT)
}
}
/**
* Sets the image of this page as the cover of the manga.
*/
private fun setAsCover() {
if (page.status != Page.READY) return
MaterialDialog.Builder(activity)
.content(activity.getString(R.string.confirm_set_image_as_cover))
.positiveText(android.R.string.yes)
.negativeText(android.R.string.no)
.onPositive { _, _ ->
activity.setAsCover(page)
dismiss()
}
.show()
}
/**
* Shares the image of this page with external apps.
*/
private fun share() {
activity.shareImage(page)
dismiss()
}
/**
* Saves the image of this page on external storage.
*/
private fun save() {
activity.saveImage(page)
dismiss()
}
}
| apache-2.0 |
Lucas-Lu/KotlinWorld | KT10/src/main/kotlin/net/println/kt10/LazyThreadSafeDoubleCheck.kt | 1 | 655 | package net.println.kt10.kotlin
/**
* Created by luliju on 2017/7/8.
*/
class LazyThreadSafeDoubleCheck private constructor(){
companion object{
val instance by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED){
LazyThreadSafeDoubleCheck()
}
private @Volatile var instance2: LazyThreadSafeDoubleCheck? = null
fun get(): LazyThreadSafeDoubleCheck {
if(instance2 == null){
synchronized(this){
if(instance2 == null)
instance2 = LazyThreadSafeDoubleCheck()
}
}
return instance2!!
}
}
} | mit |
savvasdalkitsis/gameframe | storage/src/main/java/com/savvasdalkitsis/gameframe/feature/storage/injector/StorageInjector.kt | 1 | 972 | /**
* Copyright 2018 Savvas Dalkitsis
* 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.
*
* 'Game Frame' is a registered trademark of LEDSEQ
*/
package com.savvasdalkitsis.gameframe.feature.storage.injector
import com.savvasdalkitsis.gameframe.feature.storage.usecase.LocalStorageUseCase
import com.savvasdalkitsis.gameframe.infra.injector.ApplicationInjector.application
object StorageInjector {
fun localStorageUseCase() = LocalStorageUseCase(application())
} | apache-2.0 |
farmerbb/Notepad | app/src/main/java/com/farmerbb/notepad/ui/routes/AppSettings.kt | 1 | 5461 | /* Copyright 2021 Braden Farmer
*
* 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:OptIn(
ExperimentalComposeUiApi::class,
ExperimentalMaterialApi::class
)
package com.farmerbb.notepad.ui.routes
import androidx.annotation.ArrayRes
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.ReadOnlyComposable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.res.stringArrayResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import com.farmerbb.notepad.R
import com.farmerbb.notepad.model.Prefs
import com.farmerbb.notepad.viewmodel.NotepadViewModel
import de.schnettler.datastore.compose.material.PreferenceScreen
import de.schnettler.datastore.compose.material.model.Preference.PreferenceItem.ListPreference
import de.schnettler.datastore.compose.material.model.Preference.PreferenceItem.SwitchPreference
import org.koin.androidx.compose.getViewModel
@Composable
fun SettingsDialog(onDismiss: () -> Unit) {
Dialog(onDismissRequest = onDismiss) {
Surface(shape = MaterialTheme.shapes.medium) {
NotepadPreferenceScreen()
}
}
}
@Composable
fun NotepadPreferenceScreen(
vm: NotepadViewModel = getViewModel()
) {
val markdown by vm.prefs.markdown.collectAsState()
val directEdit by vm.prefs.directEdit.collectAsState()
PreferenceScreen(
items = listOf(
ListPreference(
request = Prefs.Theme,
title = stringResource(id = R.string.action_theme),
singleLineTitle = false,
entries = listPrefEntries(
keyRes = R.array.theme_list_values,
valueRes = R.array.theme_list
),
),
ListPreference(
request = Prefs.FontSize,
title = stringResource(id = R.string.action_font_size),
singleLineTitle = false,
entries = listPrefEntries(
keyRes = R.array.font_size_list_values,
valueRes = R.array.font_size_list
),
),
ListPreference(
request = Prefs.SortBy,
title = stringResource(id = R.string.action_sort_by),
singleLineTitle = false,
entries = listPrefEntries(
keyRes = R.array.sort_by_list_values,
valueRes = R.array.sort_by_list
),
),
ListPreference(
request = Prefs.ExportFilename,
title = stringResource(id = R.string.action_export_filename),
singleLineTitle = false,
entries = listPrefEntries(
keyRes = R.array.exported_filename_list_values,
valueRes = R.array.exported_filename_list
),
),
SwitchPreference(
request = Prefs.ShowDialogs,
title = stringResource(id = R.string.pref_title_show_dialogs),
singleLineTitle = false
),
SwitchPreference(
request = Prefs.ShowDate,
title = stringResource(id = R.string.pref_title_show_date),
singleLineTitle = false
),
SwitchPreference(
request = Prefs.DirectEdit,
title = stringResource(id = R.string.pref_title_direct_edit),
singleLineTitle = false,
enabled = !markdown
),
SwitchPreference(
request = Prefs.Markdown,
title = stringResource(id = R.string.pref_title_markdown),
singleLineTitle = false,
enabled = !directEdit
),
SwitchPreference(
request = Prefs.RtlSupport,
title = stringResource(id = R.string.rtl_layout),
singleLineTitle = false
)
),
contentPadding = PaddingValues(8.dp),
dataStoreManager = vm.dataStoreManager
)
}
@ReadOnlyComposable
@Composable
private fun listPrefEntries(
@ArrayRes keyRes: Int,
@ArrayRes valueRes: Int
): Map<String, String> {
val keys = stringArrayResource(id = keyRes)
val values = stringArrayResource(id = valueRes)
if(keys.size != values.size) {
throw RuntimeException("Keys and values are not the same size")
}
val map = mutableMapOf<String, String>()
for(i in keys.indices) {
map[keys[i]] = values[i]
}
return map.toMutableMap()
} | apache-2.0 |
apollostack/apollo-android | apollo-compiler/src/main/kotlin/com/apollographql/apollo3/compiler/introspection/UnkownTypeException.kt | 1 | 195 | package com.apollographql.apollo3.compiler.introspection
internal class UnkownTypeException(message: String) : RuntimeException(message) {
override fun fillInStackTrace(): Throwable = this
}
| mit |
sn3d/nomic | nomic-oozie/src/test/kotlin/nomic/oozie/OozieCoordinatorXmlTest.kt | 1 | 1024 | /*
* Copyright 2017 [email protected]
*
* 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 nomic.oozie
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
/**
* @author [email protected]
*/
class OozieCoordinatorXmlTest {
@Test
fun `parse simple daily coordinator`() {
this::class.java.getResourceAsStream("/daily.xml").use {
val coordinator = OozieCoordinatorXml(it)
val name = coordinator.appName
assertThat(name).isEqualToIgnoringCase("daily")
}
}
} | apache-2.0 |
exponentjs/exponent | packages/expo-image-picker/android/src/main/java/expo/modules/imagepicker/ImagePickerConstants.kt | 2 | 9500 | package expo.modules.imagepicker
import androidx.exifinterface.media.ExifInterface
object ImagePickerConstants {
const val TAG = "ExponentImagePicker"
const val REQUEST_LAUNCH_CAMERA = 1
const val REQUEST_LAUNCH_IMAGE_LIBRARY = 2
const val DEFAULT_QUALITY = 100
const val CACHE_DIR_NAME = "ImagePicker"
const val PENDING_RESULT_EVENT = "ExpoImagePicker.onPendingResult"
const val ERR_MISSING_ACTIVITY = "ERR_MISSING_ACTIVITY"
const val MISSING_ACTIVITY_MESSAGE = "Activity which was provided during module initialization is no longer available"
const val ERR_CAN_NOT_DEDUCE_TYPE = "ERR_CAN_NOT_DEDUCE_TYPE"
const val CAN_NOT_DEDUCE_TYPE_MESSAGE = "Can not deduce type of the returned file."
const val ERR_CAN_NOT_SAVE_RESULT = "ERR_CAN_NOT_SAVE_RESULT"
const val CAN_NOT_SAVE_RESULT_MESSAGE = "Can not save result to the file."
const val ERR_CAN_NOT_EXTRACT_METADATA = "ERR_CAN_NOT_EXTRACT_METADATA"
const val CAN_NOT_EXTRACT_METADATA_MESSAGE = "Can not extract metadata."
const val ERR_INVALID_OPTION = "ERR_INVALID_OPTION"
const val ERR_MISSING_URL = "ERR_MISSING_URL"
const val MISSING_URL_MESSAGE = "Intent doesn't contain `url`."
const val ERR_CAN_NOT_OPEN_CROP = "ERR_CAN_NOT_OPEN_CROP"
const val CAN_NOT_OPEN_CROP_MESSAGE = "Can not open the crop tool."
const val COROUTINE_CANCELED = "Coroutine canceled by module destruction."
const val PROMISES_CANCELED = "Module destroyed, all promises canceled."
const val UNKNOWN_EXCEPTION = "Unknown exception."
const val OPTION_QUALITY = "quality"
const val OPTION_ALLOWS_EDITING = "allowsEditing"
const val OPTION_MEDIA_TYPES = "mediaTypes"
const val OPTION_ASPECT = "aspect"
const val OPTION_BASE64 = "base64"
const val OPTION_EXIF = "exif"
const val OPTION_VIDEO_MAX_DURATION = "videoMaxDuration"
val exifTags = arrayOf(
arrayOf("string", ExifInterface.TAG_ARTIST),
arrayOf("int", ExifInterface.TAG_BITS_PER_SAMPLE),
arrayOf("int", ExifInterface.TAG_COMPRESSION),
arrayOf("string", ExifInterface.TAG_COPYRIGHT),
arrayOf("string", ExifInterface.TAG_DATETIME),
arrayOf("string", ExifInterface.TAG_IMAGE_DESCRIPTION),
arrayOf("int", ExifInterface.TAG_IMAGE_LENGTH),
arrayOf("int", ExifInterface.TAG_IMAGE_WIDTH),
arrayOf("int", ExifInterface.TAG_JPEG_INTERCHANGE_FORMAT),
arrayOf("int", ExifInterface.TAG_JPEG_INTERCHANGE_FORMAT_LENGTH),
arrayOf("string", ExifInterface.TAG_MAKE),
arrayOf("string", ExifInterface.TAG_MODEL),
arrayOf("int", ExifInterface.TAG_ORIENTATION),
arrayOf("int", ExifInterface.TAG_PHOTOMETRIC_INTERPRETATION),
arrayOf("int", ExifInterface.TAG_PLANAR_CONFIGURATION),
arrayOf("double", ExifInterface.TAG_PRIMARY_CHROMATICITIES),
arrayOf("double", ExifInterface.TAG_REFERENCE_BLACK_WHITE),
arrayOf("int", ExifInterface.TAG_RESOLUTION_UNIT),
arrayOf("int", ExifInterface.TAG_ROWS_PER_STRIP),
arrayOf("int", ExifInterface.TAG_SAMPLES_PER_PIXEL),
arrayOf("string", ExifInterface.TAG_SOFTWARE),
arrayOf("int", ExifInterface.TAG_STRIP_BYTE_COUNTS),
arrayOf("int", ExifInterface.TAG_STRIP_OFFSETS),
arrayOf("int", ExifInterface.TAG_TRANSFER_FUNCTION),
arrayOf("double", ExifInterface.TAG_WHITE_POINT),
arrayOf("double", ExifInterface.TAG_X_RESOLUTION),
arrayOf("double", ExifInterface.TAG_Y_CB_CR_COEFFICIENTS),
arrayOf("int", ExifInterface.TAG_Y_CB_CR_POSITIONING),
arrayOf("int", ExifInterface.TAG_Y_CB_CR_SUB_SAMPLING),
arrayOf("double", ExifInterface.TAG_Y_RESOLUTION),
arrayOf("double", ExifInterface.TAG_APERTURE_VALUE),
arrayOf("double", ExifInterface.TAG_BRIGHTNESS_VALUE),
arrayOf("string", ExifInterface.TAG_CFA_PATTERN),
arrayOf("int", ExifInterface.TAG_COLOR_SPACE),
arrayOf("string", ExifInterface.TAG_COMPONENTS_CONFIGURATION),
arrayOf("double", ExifInterface.TAG_COMPRESSED_BITS_PER_PIXEL),
arrayOf("int", ExifInterface.TAG_CONTRAST),
arrayOf("int", ExifInterface.TAG_CUSTOM_RENDERED),
arrayOf("string", ExifInterface.TAG_DATETIME_DIGITIZED),
arrayOf("string", ExifInterface.TAG_DATETIME_ORIGINAL),
arrayOf("string", ExifInterface.TAG_DEVICE_SETTING_DESCRIPTION),
arrayOf("double", ExifInterface.TAG_DIGITAL_ZOOM_RATIO),
arrayOf("string", ExifInterface.TAG_EXIF_VERSION),
arrayOf("double", ExifInterface.TAG_EXPOSURE_BIAS_VALUE),
arrayOf("double", ExifInterface.TAG_EXPOSURE_INDEX),
arrayOf("int", ExifInterface.TAG_EXPOSURE_MODE),
arrayOf("int", ExifInterface.TAG_EXPOSURE_PROGRAM),
arrayOf("double", ExifInterface.TAG_EXPOSURE_TIME),
arrayOf("double", ExifInterface.TAG_F_NUMBER),
arrayOf("string", ExifInterface.TAG_FILE_SOURCE),
arrayOf("int", ExifInterface.TAG_FLASH),
arrayOf("double", ExifInterface.TAG_FLASH_ENERGY),
arrayOf("string", ExifInterface.TAG_FLASHPIX_VERSION),
arrayOf("double", ExifInterface.TAG_FOCAL_LENGTH),
arrayOf("int", ExifInterface.TAG_FOCAL_LENGTH_IN_35MM_FILM),
arrayOf("int", ExifInterface.TAG_FOCAL_PLANE_RESOLUTION_UNIT),
arrayOf("double", ExifInterface.TAG_FOCAL_PLANE_X_RESOLUTION),
arrayOf("double", ExifInterface.TAG_FOCAL_PLANE_Y_RESOLUTION),
arrayOf("int", ExifInterface.TAG_GAIN_CONTROL),
arrayOf("int", ExifInterface.TAG_ISO_SPEED_RATINGS),
arrayOf("string", ExifInterface.TAG_IMAGE_UNIQUE_ID),
arrayOf("int", ExifInterface.TAG_LIGHT_SOURCE),
arrayOf("string", ExifInterface.TAG_MAKER_NOTE),
arrayOf("double", ExifInterface.TAG_MAX_APERTURE_VALUE),
arrayOf("int", ExifInterface.TAG_METERING_MODE),
arrayOf("int", ExifInterface.TAG_NEW_SUBFILE_TYPE),
arrayOf("string", ExifInterface.TAG_OECF),
arrayOf("int", ExifInterface.TAG_PIXEL_X_DIMENSION),
arrayOf("int", ExifInterface.TAG_PIXEL_Y_DIMENSION),
arrayOf("string", ExifInterface.TAG_RELATED_SOUND_FILE),
arrayOf("int", ExifInterface.TAG_SATURATION),
arrayOf("int", ExifInterface.TAG_SCENE_CAPTURE_TYPE),
arrayOf("string", ExifInterface.TAG_SCENE_TYPE),
arrayOf("int", ExifInterface.TAG_SENSING_METHOD),
arrayOf("int", ExifInterface.TAG_SHARPNESS),
arrayOf("double", ExifInterface.TAG_SHUTTER_SPEED_VALUE),
arrayOf("string", ExifInterface.TAG_SPATIAL_FREQUENCY_RESPONSE),
arrayOf("string", ExifInterface.TAG_SPECTRAL_SENSITIVITY),
arrayOf("int", ExifInterface.TAG_SUBFILE_TYPE),
arrayOf("string", ExifInterface.TAG_SUBSEC_TIME),
arrayOf("string", ExifInterface.TAG_SUBSEC_TIME_DIGITIZED),
arrayOf("string", ExifInterface.TAG_SUBSEC_TIME_ORIGINAL),
arrayOf("int", ExifInterface.TAG_SUBJECT_AREA),
arrayOf("double", ExifInterface.TAG_SUBJECT_DISTANCE),
arrayOf("int", ExifInterface.TAG_SUBJECT_DISTANCE_RANGE),
arrayOf("int", ExifInterface.TAG_SUBJECT_LOCATION),
arrayOf("string", ExifInterface.TAG_USER_COMMENT),
arrayOf("int", ExifInterface.TAG_WHITE_BALANCE),
arrayOf("double", ExifInterface.TAG_GPS_ALTITUDE),
arrayOf("int", ExifInterface.TAG_GPS_ALTITUDE_REF),
arrayOf("string", ExifInterface.TAG_GPS_AREA_INFORMATION),
arrayOf("double", ExifInterface.TAG_GPS_DOP),
arrayOf("string", ExifInterface.TAG_GPS_DATESTAMP),
arrayOf("double", ExifInterface.TAG_GPS_DEST_BEARING),
arrayOf("string", ExifInterface.TAG_GPS_DEST_BEARING_REF),
arrayOf("double", ExifInterface.TAG_GPS_DEST_DISTANCE),
arrayOf("string", ExifInterface.TAG_GPS_DEST_DISTANCE_REF),
arrayOf("double", ExifInterface.TAG_GPS_DEST_LATITUDE),
arrayOf("string", ExifInterface.TAG_GPS_DEST_LATITUDE_REF),
arrayOf("double", ExifInterface.TAG_GPS_DEST_LONGITUDE),
arrayOf("string", ExifInterface.TAG_GPS_DEST_LONGITUDE_REF),
arrayOf("int", ExifInterface.TAG_GPS_DIFFERENTIAL),
arrayOf("string", ExifInterface.TAG_GPS_H_POSITIONING_ERROR),
arrayOf("double", ExifInterface.TAG_GPS_IMG_DIRECTION),
arrayOf("string", ExifInterface.TAG_GPS_IMG_DIRECTION_REF),
arrayOf("double", ExifInterface.TAG_GPS_LATITUDE),
arrayOf("string", ExifInterface.TAG_GPS_LATITUDE_REF),
arrayOf("double", ExifInterface.TAG_GPS_LONGITUDE),
arrayOf("string", ExifInterface.TAG_GPS_LONGITUDE_REF),
arrayOf("string", ExifInterface.TAG_GPS_MAP_DATUM),
arrayOf("string", ExifInterface.TAG_GPS_MEASURE_MODE),
arrayOf("string", ExifInterface.TAG_GPS_PROCESSING_METHOD),
arrayOf("string", ExifInterface.TAG_GPS_SATELLITES),
arrayOf("double", ExifInterface.TAG_GPS_SPEED),
arrayOf("string", ExifInterface.TAG_GPS_SPEED_REF),
arrayOf("string", ExifInterface.TAG_GPS_STATUS),
arrayOf("string", ExifInterface.TAG_GPS_TIMESTAMP),
arrayOf("double", ExifInterface.TAG_GPS_TRACK),
arrayOf("string", ExifInterface.TAG_GPS_TRACK_REF),
arrayOf("string", ExifInterface.TAG_GPS_VERSION_ID),
arrayOf("string", ExifInterface.TAG_INTEROPERABILITY_INDEX),
arrayOf("int", ExifInterface.TAG_THUMBNAIL_IMAGE_LENGTH),
arrayOf("int", ExifInterface.TAG_THUMBNAIL_IMAGE_WIDTH),
arrayOf("int", ExifInterface.TAG_DNG_VERSION),
arrayOf("int", ExifInterface.TAG_DEFAULT_CROP_SIZE),
arrayOf("int", ExifInterface.TAG_ORF_PREVIEW_IMAGE_START),
arrayOf("int", ExifInterface.TAG_ORF_PREVIEW_IMAGE_LENGTH),
arrayOf("int", ExifInterface.TAG_ORF_ASPECT_FRAME),
arrayOf("int", ExifInterface.TAG_RW2_SENSOR_BOTTOM_BORDER),
arrayOf("int", ExifInterface.TAG_RW2_SENSOR_LEFT_BORDER),
arrayOf("int", ExifInterface.TAG_RW2_SENSOR_RIGHT_BORDER),
arrayOf("int", ExifInterface.TAG_RW2_SENSOR_TOP_BORDER),
arrayOf("int", ExifInterface.TAG_RW2_ISO)
)
}
| bsd-3-clause |
Heiner1/AndroidAPS | database/src/main/java/info/nightscout/androidaps/database/transactions/CutCarbsTransaction.kt | 1 | 1222 | package info.nightscout.androidaps.database.transactions
import info.nightscout.androidaps.database.entities.Carbs
import info.nightscout.androidaps.database.interfaces.end
import kotlin.math.roundToInt
class CutCarbsTransaction(val id: Long, val end: Long) : Transaction<CutCarbsTransaction.TransactionResult>() {
override fun run(): TransactionResult {
val result = TransactionResult()
val carbs = database.carbsDao.findById(id)
?: throw IllegalArgumentException("There is no such Carbs with the specified ID.")
if (carbs.timestamp == end) {
carbs.isValid = false
database.carbsDao.updateExistingEntry(carbs)
result.invalidated.add(carbs)
} else if (end in carbs.timestamp..carbs.end) {
val pctRun = (end - carbs.timestamp) / carbs.duration.toDouble()
carbs.amount = (carbs.amount * pctRun).roundToInt().toDouble()
carbs.end = end
database.carbsDao.updateExistingEntry(carbs)
result.updated.add(carbs)
}
return result
}
class TransactionResult {
val invalidated = mutableListOf<Carbs>()
val updated = mutableListOf<Carbs>()
}
} | agpl-3.0 |
Heiner1/AndroidAPS | database/src/main/java/info/nightscout/androidaps/database/entities/Carbs.kt | 1 | 1880 | package info.nightscout.androidaps.database.entities
import androidx.room.Embedded
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Index
import androidx.room.PrimaryKey
import info.nightscout.androidaps.database.TABLE_CARBS
import info.nightscout.androidaps.database.embedments.InterfaceIDs
import info.nightscout.androidaps.database.interfaces.DBEntryWithTimeAndDuration
import info.nightscout.androidaps.database.interfaces.TraceableDBEntry
import java.util.*
@Entity(tableName = TABLE_CARBS,
foreignKeys = [ForeignKey(
entity = Carbs::class,
parentColumns = ["id"],
childColumns = ["referenceId"])],
indices = [
Index("id"),
Index("isValid"),
Index("nightscoutId"),
Index("referenceId"),
Index("timestamp")
])
data class Carbs(
@PrimaryKey(autoGenerate = true)
override var id: Long = 0,
override var version: Int = 0,
override var dateCreated: Long = -1,
override var isValid: Boolean = true,
override var referenceId: Long? = null,
@Embedded
override var interfaceIDs_backing: InterfaceIDs? = null,
override var timestamp: Long,
override var utcOffset: Long = TimeZone.getDefault().getOffset(timestamp).toLong(),
override var duration: Long, // in milliseconds
var amount: Double
) : TraceableDBEntry, DBEntryWithTimeAndDuration {
private fun contentEqualsTo(other: Carbs): Boolean =
isValid == other.isValid &&
timestamp == other.timestamp &&
utcOffset == other.utcOffset &&
amount == other.amount &&
duration == other.duration
fun onlyNsIdAdded(previous: Carbs): Boolean =
previous.id != id &&
contentEqualsTo(previous) &&
previous.interfaceIDs.nightscoutId == null &&
interfaceIDs.nightscoutId != null
} | agpl-3.0 |
Heiner1/AndroidAPS | automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/TestBase.kt | 1 | 1583 | package info.nightscout.androidaps
import info.nightscout.shared.logging.AAPSLoggerTest
import info.nightscout.androidaps.utils.rx.AapsSchedulers
import info.nightscout.androidaps.utils.rx.TestAapsSchedulers
import org.junit.Before
import org.junit.Rule
import org.mockito.ArgumentMatcher
import org.mockito.Mockito
import org.mockito.junit.MockitoJUnit
import org.mockito.junit.MockitoRule
import java.util.*
@Suppress("SpellCheckingInspection")
open class TestBase {
val aapsLogger = AAPSLoggerTest()
val aapsSchedulers: AapsSchedulers = TestAapsSchedulers()
// Add a JUnit rule that will setup the @Mock annotated vars and log.
// Another possibility would be to add `MockitoAnnotations.initMocks(this) to the setup method.
@get:Rule
val mockitoRule: MockitoRule = MockitoJUnit.rule()
@Before
fun setupLocale() {
Locale.setDefault(Locale.ENGLISH)
System.setProperty("disableFirebase", "true")
}
// Workaround for Kotlin nullability.
// https://medium.com/@elye.project/befriending-kotlin-and-mockito-1c2e7b0ef791
// https://stackoverflow.com/questions/30305217/is-it-possible-to-use-mockito-in-kotlin
fun <T> anyObject(): T {
Mockito.any<T>()
return uninitialized()
}
fun <T> argThatKotlin(matcher: ArgumentMatcher<T>): T {
Mockito.argThat(matcher)
return uninitialized()
}
fun <T> eqObject(expected: T): T {
Mockito.eq<T>(expected)
return uninitialized()
}
@Suppress("Unchecked_Cast")
fun <T> uninitialized(): T = null as T
}
| agpl-3.0 |
ouattararomuald/kotlin-experiment | src/test/kotlin/com/ouattararomuald/datastructures/StackTest.kt | 1 | 2196 | /*
* Copyright 2017 Romuald OUATTARA
*
* 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.ouattararomuald.datastructures
import org.junit.Before
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertTrue
internal class StackTest {
val NUMBER_OF_ITEMS_TO_INSERT = 10
private lateinit var stack: Stack<Int>
@Before
fun setUp() {
stack = Stack()
}
@Test
fun isEmpty() {
assertTrue(stack.isEmpty)
for (i in 1..NUMBER_OF_ITEMS_TO_INSERT) {
stack.push(i)
}
assertFalse(stack.isEmpty)
for (i in 1..NUMBER_OF_ITEMS_TO_INSERT) {
stack.pop()
}
assertTrue(stack.isEmpty)
}
@Test
fun peek() {
for (i in 1..NUMBER_OF_ITEMS_TO_INSERT) {
stack.push(i)
}
(NUMBER_OF_ITEMS_TO_INSERT downTo 1).forEach {
assertEquals(it, stack.peek())
stack.pop()
}
}
@Test
fun peekWhenEmptyShouldFail() {
assertTrue(stack.isEmpty)
assertFailsWith(UnderflowException::class) {
stack.peek()
}
}
@Test
fun pop() {
for (i in 1..NUMBER_OF_ITEMS_TO_INSERT) {
stack.push(i)
}
(NUMBER_OF_ITEMS_TO_INSERT downTo 1).forEach { assertEquals(it, stack.pop()) }
}
@Test
fun popWhenEmptyShouldFail() {
assertTrue(stack.isEmpty)
assertFailsWith(UnderflowException::class) {
stack.pop()
}
}
@Test
fun push() {
assertTrue(stack.isEmpty)
for (i in 1..NUMBER_OF_ITEMS_TO_INSERT) {
stack.push(i)
assertEquals(i, stack.size)
}
assertFalse(stack.isEmpty)
assertEquals(NUMBER_OF_ITEMS_TO_INSERT, stack.size)
}
} | apache-2.0 |
DanilaFe/abacus | core/src/main/kotlin/org/nwapw/abacus/function/Applicable.kt | 1 | 1774 | package org.nwapw.abacus.function
import org.nwapw.abacus.context.MutableEvaluationContext
import org.nwapw.abacus.context.PluginEvaluationContext
import org.nwapw.abacus.exception.DomainException
/**
* A class that can be applied to arguments.
*
* Applicable is a class that represents something that can be applied to one or more
* arguments of the same type, and returns a single value from that application.
* @param <T> the type of the parameters passed to this applicable.
* @param <O> the return type of the applicable.
*/
interface Applicable<in T : Any, out O : Any> {
/**
* Checks if the given applicable can be used with the given parameters.
* @param params the parameter array to verify for compatibility.
* @return whether the array can be used with applyInternal.
*/
fun matchesParams(context: PluginEvaluationContext, params: Array<out T>): Boolean
/**
* Applies the applicable object to the given parameters,
* without checking for compatibility.
* @param params the parameters to apply to.
* @return the result of the application.
*/
fun applyInternal(context: PluginEvaluationContext, params: Array<out T>): O
/**
* If the parameters can be used with this applicable, returns
* the result of the application of the applicable to the parameters.
* Otherwise, returns null.
* @param params the parameters to apply to.
* @return the result of the operation, or null if parameters do not match.
*/
fun apply(context: PluginEvaluationContext, vararg params: T): O {
if (!matchesParams(context, params))
throw DomainException("parameters do not match function requirements.")
return applyInternal(context, params)
}
} | mit |
PolymerLabs/arcs | particles/Tutorial/Kotlin/7_Functional/DisplayGreeting.kt | 2 | 734 | /*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.tutorials
/**
* Sample WASM Particle.
*/
class DisplayGreeting : AbstractDisplayGreeting() {
private var name = "Human"
init {
handles.person.onUpdate { p ->
name = p?.name ?: name
this.renderOutput()
}
}
override fun getTemplate(slotName: String) = "Hello, <span>{{name}}</span>!"
override fun populateModel(slotName: String, model: Map<String, Any>) = mapOf("name" to name)
}
| bsd-3-clause |
JetBrains/ideavim | vim-engine/src/main/kotlin/com/maddyhome/idea/vim/vimscript/model/commands/EchoCommand.kt | 1 | 1246 | /*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.vimscript.model.commands
import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.command.OperatorArguments
import com.maddyhome.idea.vim.ex.ranges.Ranges
import com.maddyhome.idea.vim.vimscript.model.ExecutionResult
import com.maddyhome.idea.vim.vimscript.model.expressions.Expression
/**
* see "h :echo"
*/
data class EchoCommand(val ranges: Ranges, val args: List<Expression>) : Command.SingleExecution(ranges) {
override val argFlags = flags(RangeFlag.RANGE_FORBIDDEN, ArgumentFlag.ARGUMENT_OPTIONAL, Access.READ_ONLY)
override fun processCommand(editor: VimEditor, context: ExecutionContext, operatorArguments: OperatorArguments): ExecutionResult.Success {
val text = args.joinToString(separator = " ", postfix = "\n") {
it.evaluate(editor, context, this).toString()
}
injector.exOutputPanel.getPanel(editor).output(text)
return ExecutionResult.Success
}
}
| mit |
AcornUI/Acorn | acornui-core/src/main/kotlin/com/acornui/command/Command.kt | 1 | 1327 | /*
* Copyright 2020 Poly Forest, 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.acornui.command
import com.acornui.ExperimentalAcorn
@ExperimentalAcorn
interface Command {
/**
* Executes this command.
* This should only be invoked from the command manager.
*/
fun execute()
/**
* Undoes this command.
* This should only be invoked from the command manager.
*/
fun undo()
}
@ExperimentalAcorn
class CommandGroup
@ExperimentalAcorn
object NoopCommand : Command {
override fun execute() {}
override fun undo() {}
}
/**
* Creates an anonymous command out of the given invocation and undo blocks.
*/
@ExperimentalAcorn
fun createCommand(invoke: () -> Unit, undo: () -> Unit): Command = object : Command {
override fun execute() = invoke()
override fun undo() = undo()
} | apache-2.0 |
JStege1206/AdventOfCode | aoc-2015/src/main/kotlin/nl/jstege/adventofcode/aoc2015/days/Day15.kt | 1 | 4418 | package nl.jstege.adventofcode.aoc2015.days
import nl.jstege.adventofcode.aoccommon.days.Day
import nl.jstege.adventofcode.aoccommon.utils.extensions.component6
import nl.jstege.adventofcode.aoccommon.utils.extensions.component7
import nl.jstege.adventofcode.aoccommon.utils.extensions.extractValues
import kotlin.math.max
import kotlin.reflect.KProperty1
/**
*
* @author Jelle Stege
*/
class Day15 : Day(title = "Science for Hungry People") {
private companion object Configuration {
private const val TEA_SPOONS_AMOUNT = 100
private const val NEEDED_CALORIES = 500
private const val SPRINKLES = "Sprinkles"
private const val BUTTERSCOTCH = "Butterscotch"
private const val CHOCOLATE = "Chocolate"
private const val CANDY = "Candy"
}
override fun first(input: Sequence<String>) = input
.map(Ingredient.Parser::parse)
.associate { it.name to it }
.calculateMaxScore()
override fun second(input: Sequence<String>) = input
.map(Ingredient.Parser::parse)
.associate { it.name to it }
.calculateMaxScore(true)
private fun Map<String, Ingredient>.calculateMaxScore(useCalories: Boolean = false): Int {
var score = 0
(0 until TEA_SPOONS_AMOUNT).forEach { sprinkle ->
(0 until TEA_SPOONS_AMOUNT - sprinkle).forEach { butterscotch ->
(0 until TEA_SPOONS_AMOUNT - butterscotch - sprinkle).forEach { chocolate ->
val candy = TEA_SPOONS_AMOUNT - chocolate - butterscotch - sprinkle
score = max(
score,
calculateScore(
sprinkle to this[SPRINKLES]!!,
butterscotch to this[BUTTERSCOTCH]!!,
chocolate to this[CHOCOLATE]!!,
candy to this[CANDY]!!,
useCalories = useCalories
)
)
}
}
}
return score
}
private fun calculateScore(vararg recipe: Pair<Int, Ingredient>, useCalories: Boolean): Int {
fun calculateScore(
recipe: Array<out Pair<Int, Ingredient>>,
property: KProperty1<Ingredient, Int>
) = recipe.sumBy { (amount, ingredient) -> amount * ingredient.run(property) }
return if (useCalories && calculateScore(recipe, Ingredient::calories) != NEEDED_CALORIES) 0
else setOf(
Ingredient::capacity,
Ingredient::durability,
Ingredient::flavor,
Ingredient::texture
).let {
it.fold(1) { acc, property -> acc * Math.max(calculateScore(recipe, property), 0) }
}
}
private data class Ingredient(
val name: String,
val capacity: Int,
val durability: Int,
val flavor: Int,
val texture: Int,
val calories: Int
) {
companion object Parser {
private val INPUT_REGEX = ("(\\w+): " +
"capacity (-?\\d+), " +
"durability (-?\\d+), flavor (-?\\d+), " +
"texture (-?\\d+), " +
"calories (-?\\d+)").toRegex()
private const val NAME_INDEX = 1
private const val CAPACITY_INDEX = 2
private const val DURABILITY_INDEX = 3
private const val FLAVOR_INDEX = 4
private const val TEXTURE_INDEX = 5
private const val CALORIES_INDEX = 6
private val PARAM_INDICES = intArrayOf(
NAME_INDEX,
CAPACITY_INDEX,
DURABILITY_INDEX,
FLAVOR_INDEX,
TEXTURE_INDEX,
CALORIES_INDEX
)
@JvmStatic
fun parse(input: String): Ingredient {
return input.extractValues(INPUT_REGEX, *PARAM_INDICES)
.let { (name, capacity, durability, flavor, texture, calories) ->
Ingredient(
name,
capacity.toInt(),
durability.toInt(),
flavor.toInt(),
texture.toInt(),
calories.toInt()
)
}
}
}
}
}
| mit |
K0zka/finder4j | finder4j-backtrack/src/test/kotlin/com/github/k0zka/finder4j/backtrack/termination/TimeoutTerminationStrategyTest.kt | 1 | 488 | package com.github.k0zka.finder4j.backtrack.termination
import com.nhaarman.mockito_kotlin.mock
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class TimeoutTerminationStrategyTest {
private val state: Any = mock()
@Test
fun stop() {
assertTrue(TimeoutTerminationStrategy<Any>(
System.currentTimeMillis() - 1000).stop(state))
assertFalse(TimeoutTerminationStrategy<Any>(
System.currentTimeMillis() + 1000).stop(state))
}
}
| apache-2.0 |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/activitylog/list/ActivityLogDiffCallback.kt | 1 | 2047 | package org.wordpress.android.ui.activitylog.list
import android.os.Bundle
import androidx.recyclerview.widget.DiffUtil
import org.wordpress.android.ui.activitylog.list.ActivityLogListItem.Event
import org.wordpress.android.ui.activitylog.list.ActivityLogListItem.IActionableItem
import org.wordpress.android.ui.activitylog.list.ActivityLogListItem.Notice
import org.wordpress.android.ui.activitylog.list.ActivityLogListItem.Progress
class ActivityLogDiffCallback(
private val oldList: List<ActivityLogListItem>,
private val newList: List<ActivityLogListItem>
) : DiffUtil.Callback() {
companion object {
const val LIST_ITEM_BUTTON_VISIBILITY_KEY = "list_item_button_visibility_key"
}
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
val oldItem = oldList[oldItemPosition]
val newItem = newList[newItemPosition]
return when {
oldItem is Event && newItem is Event -> oldItem.activityId == newItem.activityId
oldItem is Progress && newItem is Progress -> oldItem == newItem
oldItem is Notice && newItem is Notice -> oldItem == newItem
else -> false
}
}
override fun getOldListSize(): Int {
return oldList.size
}
override fun getNewListSize(): Int {
return newList.size
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldList[oldItemPosition] == newList[newItemPosition]
}
override fun getChangePayload(oldItemPosition: Int, newItemPosition: Int): Any? {
val oldItem = oldList[oldItemPosition]
val newItem = newList[newItemPosition]
val bundle = Bundle()
if (oldItem is IActionableItem && newItem is IActionableItem &&
oldItem.isButtonVisible != newItem.isButtonVisible) {
bundle.putBoolean(LIST_ITEM_BUTTON_VISIBILITY_KEY, newItem.isButtonVisible)
}
if (bundle.size() == 0) return null
return bundle
}
}
| gpl-2.0 |
ingokegel/intellij-community | plugins/gradle/src/org/jetbrains/plugins/gradle/GradleContentRootContributor.kt | 9 | 2318 | // 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.plugins.gradle
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.ProjectKeys
import com.intellij.openapi.externalSystem.model.project.ContentRootData
import com.intellij.openapi.externalSystem.model.project.ExternalSystemSourceType
import com.intellij.openapi.externalSystem.model.project.ModuleData
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.externalSystem.util.ExternalSystemContentRootContributor
import com.intellij.openapi.module.Module
import org.jetbrains.plugins.gradle.model.data.GradleSourceSetData
import org.jetbrains.plugins.gradle.util.GradleConstants
import org.jetbrains.plugins.gradle.util.GradleUtil.findGradleModuleData
import kotlin.io.path.Path
class GradleContentRootContributor : ExternalSystemContentRootContributor {
override fun isApplicable(systemId: String): Boolean = systemId == GradleConstants.SYSTEM_ID.id
override fun findContentRoots(
module: Module,
sourceTypes: Collection<ExternalSystemSourceType>,
): Collection<ExternalSystemContentRootContributor.ExternalContentRoot> = mutableListOf<ExternalSystemContentRootContributor.ExternalContentRoot>().apply {
processContentRoots(module) { rootData ->
for (sourceType in sourceTypes) {
rootData.getPaths(sourceType).mapTo(this) {
ExternalSystemContentRootContributor.ExternalContentRoot(Path(it.path), sourceType)
}
}
}
}.toList()
companion object {
internal fun processContentRoots(
module: Module,
processor: (ContentRootData) -> Unit,
) {
val moduleData = findGradleModuleData(module) ?: return
moduleData.processModule(processor)
for (eachSourceSetNode in ExternalSystemApiUtil.getChildren(moduleData, GradleSourceSetData.KEY)) {
eachSourceSetNode.processModule(processor)
}
}
}
}
private fun DataNode<out ModuleData>.processModule(processor: (ContentRootData) -> Unit) {
for (eachContentRootNode in ExternalSystemApiUtil.findAll(this, ProjectKeys.CONTENT_ROOT)) {
processor(eachContentRootNode.data)
}
} | apache-2.0 |
mdaniel/intellij-community | platform/core-impl/src/com/intellij/ide/plugins/PluginDescriptorLoader.kt | 1 | 37561 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplaceNegatedIsEmptyWithIsNotEmpty", "ReplacePutWithAssignment")
@file:JvmName("PluginDescriptorLoader")
@file:Internal
package com.intellij.ide.plugins
import com.intellij.diagnostic.StartUpMeasurer
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.util.BuildNumber
import com.intellij.openapi.util.io.NioFiles
import com.intellij.util.PlatformUtils
import com.intellij.util.io.Decompressor
import com.intellij.util.io.URLUtil
import com.intellij.util.lang.UrlClassLoader
import com.intellij.util.lang.ZipFilePool
import com.intellij.util.xml.dom.createNonCoalescingXmlStreamReader
import kotlinx.coroutines.*
import org.codehaus.stax2.XMLStreamReader2
import org.jetbrains.annotations.ApiStatus.Internal
import org.jetbrains.annotations.TestOnly
import org.jetbrains.annotations.VisibleForTesting
import java.io.Closeable
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.net.URL
import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.nio.file.NoSuchFileException
import java.nio.file.Path
import java.nio.file.Paths
import java.util.*
import java.util.concurrent.CancellationException
import java.util.concurrent.ExecutionException
import java.util.zip.ZipFile
import javax.xml.stream.XMLStreamException
import kotlin.io.path.name
private val LOG: Logger
get() = PluginManagerCore.getLogger()
@TestOnly
fun loadDescriptor(file: Path, parentContext: DescriptorListLoadingContext): IdeaPluginDescriptorImpl? {
return loadDescriptorFromFileOrDir(file = file,
context = parentContext,
pathResolver = PluginXmlPathResolver.DEFAULT_PATH_RESOLVER,
isBundled = false,
isEssential = false,
isDirectory = Files.isDirectory(file),
useCoreClassLoader = false,
pool = null)
}
internal fun loadForCoreEnv(pluginRoot: Path, fileName: String): IdeaPluginDescriptorImpl? {
val pathResolver = PluginXmlPathResolver.DEFAULT_PATH_RESOLVER
val parentContext = DescriptorListLoadingContext(disabledPlugins = DisabledPluginsState.getDisabledIds())
if (Files.isDirectory(pluginRoot)) {
return loadDescriptorFromDir(file = pluginRoot,
descriptorRelativePath = "${PluginManagerCore.META_INF}$fileName",
pluginPath = null,
context = parentContext,
isBundled = true,
isEssential = true,
pathResolver = pathResolver,
useCoreClassLoader = false)
}
else {
return runBlocking {
loadDescriptorFromJar(file = pluginRoot,
fileName = fileName,
pathResolver = pathResolver,
parentContext = parentContext,
isBundled = true,
isEssential = true,
pluginPath = null,
useCoreClassLoader = false,
pool = null)
}
}
}
private fun loadDescriptorFromDir(file: Path,
descriptorRelativePath: String,
pluginPath: Path?,
context: DescriptorListLoadingContext,
isBundled: Boolean,
isEssential: Boolean,
useCoreClassLoader: Boolean,
pathResolver: PathResolver): IdeaPluginDescriptorImpl? {
try {
val input = Files.readAllBytes(file.resolve(descriptorRelativePath))
val dataLoader = LocalFsDataLoader(file)
val raw = readModuleDescriptor(input = input,
readContext = context,
pathResolver = pathResolver,
dataLoader = dataLoader,
includeBase = null,
readInto = null,
locationSource = file.toString())
val descriptor = IdeaPluginDescriptorImpl(raw = raw, path = pluginPath ?: file, isBundled = isBundled, id = null, moduleName = null,
useCoreClassLoader = useCoreClassLoader)
descriptor.readExternal(raw = raw, pathResolver = pathResolver, context = context, isSub = false, dataLoader = dataLoader)
descriptor.jarFiles = Collections.singletonList(file)
return descriptor
}
catch (e: NoSuchFileException) {
return null
}
catch (e: Throwable) {
if (isEssential) {
throw e
}
LOG.warn("Cannot load ${file.resolve(descriptorRelativePath)}", e)
return null
}
}
private fun loadDescriptorFromJar(file: Path,
fileName: String,
pathResolver: PathResolver,
parentContext: DescriptorListLoadingContext,
isBundled: Boolean,
isEssential: Boolean,
useCoreClassLoader: Boolean,
pluginPath: Path?,
pool: ZipFilePool?): IdeaPluginDescriptorImpl? {
var closeable: Closeable? = null
try {
val dataLoader = if (pool == null) {
val zipFile = ZipFile(file.toFile(), StandardCharsets.UTF_8)
closeable = zipFile
JavaZipFileDataLoader(zipFile)
}
else {
ImmutableZipFileDataLoader(pool.load(file), file, pool)
}
val raw = readModuleDescriptor(input = dataLoader.load("META-INF/$fileName") ?: return null,
readContext = parentContext,
pathResolver = pathResolver,
dataLoader = dataLoader,
includeBase = null,
readInto = null,
locationSource = file.toString())
val descriptor = IdeaPluginDescriptorImpl(raw = raw, path = pluginPath ?: file, isBundled = isBundled, id = null, moduleName = null,
useCoreClassLoader = useCoreClassLoader)
descriptor.readExternal(raw = raw, pathResolver = pathResolver, context = parentContext, isSub = false, dataLoader = dataLoader)
descriptor.jarFiles = Collections.singletonList(descriptor.pluginPath)
return descriptor
}
catch (e: Throwable) {
if (isEssential) {
throw if (e is XMLStreamException) RuntimeException("Cannot read $file", e) else e
}
parentContext.reportCannotLoad(file, e)
}
finally {
closeable?.close()
}
return null
}
private class JavaZipFileDataLoader(private val file: ZipFile) : DataLoader {
override val pool: ZipFilePool?
get() = null
override fun load(path: String): InputStream? {
val entry = file.getEntry(if (path[0] == '/') path.substring(1) else path) ?: return null
return file.getInputStream(entry)
}
override fun toString() = file.toString()
}
@VisibleForTesting
fun loadDescriptorFromFileOrDir(
file: Path,
context: DescriptorListLoadingContext,
pathResolver: PathResolver,
isBundled: Boolean,
isEssential: Boolean,
isDirectory: Boolean,
useCoreClassLoader: Boolean,
isUnitTestMode: Boolean = false,
pool: ZipFilePool?,
): IdeaPluginDescriptorImpl? {
return when {
isDirectory -> {
loadFromPluginDir(
file = file,
parentContext = context,
isBundled = isBundled,
isEssential = isEssential,
useCoreClassLoader = useCoreClassLoader,
pathResolver = pathResolver,
isUnitTestMode = isUnitTestMode,
pool = pool,
)
}
file.fileName.toString().endsWith(".jar", ignoreCase = true) -> {
loadDescriptorFromJar(file = file,
fileName = PluginManagerCore.PLUGIN_XML,
pathResolver = pathResolver,
parentContext = context,
isBundled = isBundled,
isEssential = isEssential,
pluginPath = null,
useCoreClassLoader = useCoreClassLoader,
pool = pool)
}
else -> null
}
}
// [META-INF] [classes] lib/*.jar
private fun loadFromPluginDir(
file: Path,
parentContext: DescriptorListLoadingContext,
isBundled: Boolean,
isEssential: Boolean,
useCoreClassLoader: Boolean,
pathResolver: PathResolver,
isUnitTestMode: Boolean = false,
pool: ZipFilePool?,
): IdeaPluginDescriptorImpl? {
val pluginJarFiles = resolveArchives(file)
if (!pluginJarFiles.isNullOrEmpty()) {
putMoreLikelyPluginJarsFirst(file, pluginJarFiles)
val pluginPathResolver = PluginXmlPathResolver(pluginJarFiles)
for (jarFile in pluginJarFiles) {
loadDescriptorFromJar(file = jarFile,
fileName = PluginManagerCore.PLUGIN_XML,
pathResolver = pluginPathResolver,
parentContext = parentContext,
isBundled = isBundled,
isEssential = isEssential,
pluginPath = file,
useCoreClassLoader = useCoreClassLoader,
pool = pool)?.let {
it.jarFiles = pluginJarFiles
return it
}
}
}
// not found, ok, let's check classes (but only for unbundled plugins)
if (!isBundled || isUnitTestMode) {
val classesDir = file.resolve("classes")
sequenceOf(classesDir, file)
.firstNotNullOfOrNull {
loadDescriptorFromDir(
file = it,
descriptorRelativePath = PluginManagerCore.PLUGIN_XML_PATH,
pluginPath = file,
context = parentContext,
isBundled = isBundled,
isEssential = isEssential,
pathResolver = pathResolver,
useCoreClassLoader = useCoreClassLoader,
)
}?.let {
if (pluginJarFiles.isNullOrEmpty()) {
it.jarFiles = Collections.singletonList(classesDir)
}
else {
val classPath = ArrayList<Path>(pluginJarFiles.size + 1)
classPath.add(classesDir)
classPath.addAll(pluginJarFiles)
it.jarFiles = classPath
}
return it
}
}
return null
}
private fun resolveArchives(path: Path): MutableList<Path>? {
try {
return Files.newDirectoryStream(path.resolve("lib")).use { stream ->
stream.filterTo(ArrayList()) {
val childPath = it.toString()
childPath.endsWith(".jar", ignoreCase = true) || childPath.endsWith(".zip", ignoreCase = true)
}
}
}
catch (e: NoSuchFileException) {
return null
}
}
/*
* Sort the files heuristically to load the plugin jar containing plugin descriptors without extra ZipFile accesses.
* File name preference:
* a) last order for files with resources in name, like resources_en.jar
* b) last order for files that have `-digit` suffix is the name e.g., completion-ranking.jar is before `gson-2.8.0.jar` or `junit-m5.jar`
* c) jar with name close to plugin's directory name, e.g., kotlin-XXX.jar is before all-open-XXX.jar
* d) shorter name, e.g., android.jar is before android-base-common.jar
*/
private fun putMoreLikelyPluginJarsFirst(pluginDir: Path, filesInLibUnderPluginDir: MutableList<Path>) {
val pluginDirName = pluginDir.fileName.toString()
// don't use kotlin sortWith to avoid loading of CollectionsKt
Collections.sort(filesInLibUnderPluginDir, Comparator { o1: Path, o2: Path ->
val o2Name = o2.fileName.toString()
val o1Name = o1.fileName.toString()
val o2StartsWithResources = o2Name.startsWith("resources")
val o1StartsWithResources = o1Name.startsWith("resources")
if (o2StartsWithResources != o1StartsWithResources) {
return@Comparator if (o2StartsWithResources) -1 else 1
}
val o2IsVersioned = fileNameIsLikeVersionedLibraryName(o2Name)
val o1IsVersioned = fileNameIsLikeVersionedLibraryName(o1Name)
if (o2IsVersioned != o1IsVersioned) {
return@Comparator if (o2IsVersioned) -1 else 1
}
val o2StartsWithNeededName = o2Name.startsWith(pluginDirName, ignoreCase = true)
val o1StartsWithNeededName = o1Name.startsWith(pluginDirName, ignoreCase = true)
if (o2StartsWithNeededName != o1StartsWithNeededName) {
return@Comparator if (o2StartsWithNeededName) 1 else -1
}
val o2EndsWithIdea = o2Name.endsWith("-idea.jar")
val o1EndsWithIdea = o1Name.endsWith("-idea.jar")
if (o2EndsWithIdea != o1EndsWithIdea) {
return@Comparator if (o2EndsWithIdea) 1 else -1
}
o1Name.length - o2Name.length
})
}
private fun fileNameIsLikeVersionedLibraryName(name: String): Boolean {
val i = name.lastIndexOf('-')
if (i == -1) {
return false
}
if (i + 1 < name.length) {
val c = name[i + 1]
return Character.isDigit(c) || ((c == 'm' || c == 'M') && i + 2 < name.length && Character.isDigit(name[i + 2]))
}
return false
}
private fun CoroutineScope.loadDescriptorsFromProperty(context: DescriptorListLoadingContext,
pool: ZipFilePool?): List<Deferred<IdeaPluginDescriptorImpl?>> {
val pathProperty = System.getProperty("plugin.path") ?: return emptyList()
// gradle-intellij-plugin heavily depends on this property in order to have core class loader plugins during tests
val useCoreClassLoaderForPluginsFromProperty = java.lang.Boolean.getBoolean("idea.use.core.classloader.for.plugin.path")
val t = StringTokenizer(pathProperty, File.pathSeparatorChar + ",")
val list = mutableListOf<Deferred<IdeaPluginDescriptorImpl?>>()
while (t.hasMoreTokens()) {
val file = Paths.get(t.nextToken())
list.add(async {
loadDescriptorFromFileOrDir(
file = file,
context = context,
pathResolver = PluginXmlPathResolver.DEFAULT_PATH_RESOLVER,
isBundled = false,
isEssential = false,
isDirectory = Files.isDirectory(file),
useCoreClassLoader = useCoreClassLoaderForPluginsFromProperty,
pool = pool,
)
})
}
return list
}
@Suppress("DeferredIsResult")
internal fun CoroutineScope.scheduleLoading(zipFilePoolDeferred: Deferred<ZipFilePool>?): Deferred<PluginSet> {
val resultDeferred = async {
val activity = StartUpMeasurer.startActivity("plugin descriptor loading")
val isUnitTestMode = PluginManagerCore.isUnitTestMode
val isRunningFromSources = PluginManagerCore.isRunningFromSources()
val result = DescriptorListLoadingContext(
isMissingSubDescriptorIgnored = true,
isMissingIncludeIgnored = isUnitTestMode,
checkOptionalConfigFileUniqueness = isUnitTestMode || isRunningFromSources,
disabledPlugins = DisabledPluginsState.getDisabledIds(),
).use { context ->
context to loadDescriptors(
context = context,
isUnitTestMode = isUnitTestMode,
isRunningFromSources = isRunningFromSources,
zipFilePoolDeferred = zipFilePoolDeferred,
)
}
activity.end()
result
}
val pluginSetDeferred = async {
val pair = resultDeferred.await()
PluginManagerCore.initializeAndSetPlugins(pair.first, pair.second, PluginManagerCore::class.java.classLoader)
}
// logging is no not as a part of plugin set job for performance reasons
launch {
val pair = resultDeferred.await()
logPlugins(plugins = pluginSetDeferred.await().allPlugins, context = pair.first, loadingResult = pair.second)
}
return pluginSetDeferred
}
private fun logPlugins(plugins: Collection<IdeaPluginDescriptorImpl>,
context: DescriptorListLoadingContext,
loadingResult: PluginLoadingResult) {
if (IdeaPluginDescriptorImpl.disableNonBundledPlugins) {
LOG.info("Running with disableThirdPartyPlugins argument, third-party plugins will be disabled")
}
val bundled = StringBuilder()
val disabled = StringBuilder()
val custom = StringBuilder()
val disabledPlugins = HashSet<PluginId>()
for (descriptor in plugins) {
var target: StringBuilder
val pluginId = descriptor.pluginId
target = if (!descriptor.isEnabled) {
if (!context.isPluginDisabled(pluginId)) {
// plugin will be logged as part of "Problems found loading plugins"
continue
}
disabledPlugins.add(pluginId)
disabled
}
else if (descriptor.isBundled || PluginManagerCore.SPECIAL_IDEA_PLUGIN_ID == pluginId) {
bundled
}
else {
custom
}
appendPlugin(descriptor, target)
}
for ((pluginId, descriptor) in loadingResult.getIncompleteIdMap()) {
// log only explicitly disabled plugins
if (context.isPluginDisabled(pluginId) && !disabledPlugins.contains(pluginId)) {
appendPlugin(descriptor, disabled)
}
}
val log = LOG
log.info("Loaded bundled plugins: $bundled")
if (custom.isNotEmpty()) {
log.info("Loaded custom plugins: $custom")
}
if (disabled.isNotEmpty()) {
log.info("Disabled plugins: $disabled")
}
}
private fun appendPlugin(descriptor: IdeaPluginDescriptor, target: StringBuilder) {
if (target.isNotEmpty()) {
target.append(", ")
}
target.append(descriptor.name)
val version = descriptor.version
if (version != null) {
target.append(" (").append(version).append(')')
}
}
// used and must be used only by Rider
@Suppress("unused")
@Internal
suspend fun getLoadedPluginsForRider(): List<IdeaPluginDescriptorImpl?> {
PluginManagerCore.getNullablePluginSet()?.enabledPlugins?.let {
return it
}
val isUnitTestMode = PluginManagerCore.isUnitTestMode
val isRunningFromSources = PluginManagerCore.isRunningFromSources()
return DescriptorListLoadingContext(
isMissingSubDescriptorIgnored = true,
isMissingIncludeIgnored = isUnitTestMode,
checkOptionalConfigFileUniqueness = isUnitTestMode || isRunningFromSources,
disabledPlugins = DisabledPluginsState.getDisabledIds(),
).use { context ->
val result = loadDescriptors(context = context, isUnitTestMode = isUnitTestMode, isRunningFromSources = isRunningFromSources)
PluginManagerCore.initializeAndSetPlugins(context, result, PluginManagerCore::class.java.classLoader).enabledPlugins
}
}
@Internal
@Deprecated("do not use")
fun loadDescriptorsForDeprecatedWizard(): PluginLoadingResult {
return runBlocking {
val isUnitTestMode = PluginManagerCore.isUnitTestMode
val isRunningFromSources = PluginManagerCore.isRunningFromSources()
DescriptorListLoadingContext(
isMissingSubDescriptorIgnored = true,
isMissingIncludeIgnored = isUnitTestMode,
checkOptionalConfigFileUniqueness = isUnitTestMode || isRunningFromSources,
disabledPlugins = DisabledPluginsState.getDisabledIds(),
).use { context ->
loadDescriptors(context = context, isUnitTestMode = isUnitTestMode, isRunningFromSources = isRunningFromSources)
}
}
}
/**
* Think twice before use and get approve from core team.
*
* Returns enabled plugins only.
*/
@Internal
suspend fun loadDescriptors(
context: DescriptorListLoadingContext,
isUnitTestMode: Boolean = PluginManagerCore.isUnitTestMode,
isRunningFromSources: Boolean,
zipFilePoolDeferred: Deferred<ZipFilePool>? = null,
): PluginLoadingResult {
val list: List<IdeaPluginDescriptorImpl?>
val extraList: List<IdeaPluginDescriptorImpl?>
coroutineScope {
withContext(Dispatchers.IO) {
val zipFilePool = if (context.transient) null else zipFilePoolDeferred?.await()
val listDeferred = loadDescriptorsFromDirs(
context = context,
customPluginDir = Paths.get(PathManager.getPluginsPath()),
isUnitTestMode = isUnitTestMode,
isRunningFromSources = isRunningFromSources,
zipFilePool = zipFilePool,
)
val extraListDeferred = loadDescriptorsFromProperty(context, zipFilePool)
list = listDeferred.awaitAll()
extraList = extraListDeferred.awaitAll()
}
}
val buildNumber = context.productBuildNumber()
val loadingResult = PluginLoadingResult()
loadingResult.addAll(descriptors = list, overrideUseIfCompatible = false, productBuildNumber = buildNumber)
if (!extraList.isEmpty()) {
// plugins added via property shouldn't be overridden to avoid plugin root detection issues when running external plugin tests
loadingResult.addAll(descriptors = extraList, overrideUseIfCompatible = true, productBuildNumber = buildNumber)
}
if (isUnitTestMode && loadingResult.enabledPluginsById.size <= 1) {
// we're running in unit test mode, but the classpath doesn't contain any plugins; try to load bundled plugins anyway
loadingResult.addAll(
descriptors = coroutineScope {
loadDescriptorsFromDir(
dir = Paths.get(PathManager.getPreInstalledPluginsPath()),
context = context,
isBundled = true,
pool = if (context.transient) null else zipFilePoolDeferred?.await()
).awaitAll()
},
overrideUseIfCompatible = false,
productBuildNumber = buildNumber
)
}
return loadingResult
}
private suspend fun loadDescriptorsFromDirs(
context: DescriptorListLoadingContext,
customPluginDir: Path,
bundledPluginDir: Path? = null,
isUnitTestMode: Boolean = PluginManagerCore.isUnitTestMode,
isRunningFromSources: Boolean = PluginManagerCore.isRunningFromSources(),
zipFilePool: ZipFilePool?,
): List<Deferred<IdeaPluginDescriptorImpl?>> {
val isInDevServerMode = java.lang.Boolean.getBoolean("idea.use.dev.build.server")
val platformPrefixProperty = PlatformUtils.getPlatformPrefix()
val platformPrefix = if (platformPrefixProperty == PlatformUtils.QODANA_PREFIX) {
System.getProperty("idea.parent.prefix", PlatformUtils.IDEA_PREFIX)
}
else {
platformPrefixProperty
}
return coroutineScope {
val root = loadCoreModules(context = context,
platformPrefix = platformPrefix,
isUnitTestMode = isUnitTestMode,
isInDevServerMode = isInDevServerMode,
isRunningFromSources = isRunningFromSources,
pool = zipFilePool)
val custom = loadDescriptorsFromDir(dir = customPluginDir, context = context, isBundled = false, pool = zipFilePool)
val effectiveBundledPluginDir = bundledPluginDir ?: if (isUnitTestMode) {
null
}
else if (isInDevServerMode) {
Paths.get(PathManager.getHomePath(), "out/dev-run", platformPrefix, "plugins")
}
else {
Paths.get(PathManager.getPreInstalledPluginsPath())
}
val bundled = if (effectiveBundledPluginDir == null) {
emptyList()
}
else {
loadDescriptorsFromDir(dir = effectiveBundledPluginDir, context = context, isBundled = true, pool = zipFilePool)
}
(root + custom + bundled)
}
}
private fun CoroutineScope.loadCoreModules(context: DescriptorListLoadingContext,
platformPrefix: String,
isUnitTestMode: Boolean,
isInDevServerMode: Boolean,
isRunningFromSources: Boolean,
pool: ZipFilePool?): List<Deferred<IdeaPluginDescriptorImpl?>> {
val classLoader = DescriptorListLoadingContext::class.java.classLoader
val pathResolver = ClassPathXmlPathResolver(classLoader = classLoader, isRunningFromSources = isRunningFromSources && !isInDevServerMode)
val useCoreClassLoader = pathResolver.isRunningFromSources ||
platformPrefix.startsWith("CodeServer") ||
java.lang.Boolean.getBoolean("idea.force.use.core.classloader")
// should be the only plugin in lib (only for Ultimate and WebStorm for now)
val rootModuleDescriptors = if ((platformPrefix == PlatformUtils.IDEA_PREFIX || platformPrefix == PlatformUtils.WEB_PREFIX) &&
(isInDevServerMode || (!isUnitTestMode && !isRunningFromSources))) {
Collections.singletonList(async {
loadCoreProductPlugin(getResourceReader(PluginManagerCore.PLUGIN_XML_PATH, classLoader)!!,
context = context,
pathResolver = pathResolver,
useCoreClassLoader = useCoreClassLoader)
})
}
else {
val fileName = "${platformPrefix}Plugin.xml"
var result = listOf(async {
getResourceReader("${PluginManagerCore.META_INF}$fileName", classLoader)?.let {
loadCoreProductPlugin(it, context, pathResolver, useCoreClassLoader)
}
})
val urlToFilename = collectPluginFilesInClassPath(classLoader)
if (!urlToFilename.isEmpty()) {
@Suppress("SuspiciousCollectionReassignment")
result += loadDescriptorsFromClassPath(urlToFilename = urlToFilename,
context = context,
pathResolver = pathResolver,
useCoreClassLoader = useCoreClassLoader,
pool = pool)
}
result
}
return rootModuleDescriptors
}
private fun getResourceReader(path: String, classLoader: ClassLoader): XMLStreamReader2? {
if (classLoader is UrlClassLoader) {
return createNonCoalescingXmlStreamReader(classLoader.getResourceAsBytes(path, false) ?: return null, path)
}
else {
return createNonCoalescingXmlStreamReader(classLoader.getResourceAsStream(path) ?: return null, path)
}
}
private fun loadCoreProductPlugin(reader: XMLStreamReader2,
context: DescriptorListLoadingContext,
pathResolver: ClassPathXmlPathResolver,
useCoreClassLoader: Boolean): IdeaPluginDescriptorImpl {
val dataLoader = object : DataLoader {
override val pool: ZipFilePool
get() = throw IllegalStateException("must be not called")
override val emptyDescriptorIfCannotResolve: Boolean
get() = true
override fun load(path: String) = throw IllegalStateException("must be not called")
override fun toString() = "product classpath"
}
val raw = readModuleDescriptor(reader,
readContext = context,
pathResolver = pathResolver,
dataLoader = dataLoader,
includeBase = null,
readInto = null)
val descriptor = IdeaPluginDescriptorImpl(raw = raw,
path = Paths.get(PathManager.getLibPath()),
isBundled = true,
id = null,
moduleName = null,
useCoreClassLoader = useCoreClassLoader)
descriptor.readExternal(raw = raw, pathResolver = pathResolver, context = context, isSub = false, dataLoader = dataLoader)
return descriptor
}
private fun collectPluginFilesInClassPath(loader: ClassLoader): Map<URL, String> {
val urlToFilename = LinkedHashMap<URL, String>()
try {
val enumeration = loader.getResources(PluginManagerCore.PLUGIN_XML_PATH)
while (enumeration.hasMoreElements()) {
urlToFilename.put(enumeration.nextElement(), PluginManagerCore.PLUGIN_XML)
}
}
catch (e: IOException) {
LOG.warn(e)
}
return urlToFilename
}
@Throws(IOException::class)
fun loadDescriptorFromArtifact(file: Path, buildNumber: BuildNumber?): IdeaPluginDescriptorImpl? {
val context = DescriptorListLoadingContext(isMissingSubDescriptorIgnored = true,
disabledPlugins = DisabledPluginsState.getDisabledIds(),
productBuildNumber = { buildNumber ?: PluginManagerCore.getBuildNumber() },
transient = true)
val descriptor = runBlocking {
loadDescriptorFromFileOrDir(file = file,
context = context,
pathResolver = PluginXmlPathResolver.DEFAULT_PATH_RESOLVER,
isBundled = false,
isEssential = false,
isDirectory = false,
useCoreClassLoader = false,
pool = null)
}
if (descriptor != null || !file.toString().endsWith(".zip")) {
return descriptor
}
val outputDir = Files.createTempDirectory("plugin")!!
try {
Decompressor.Zip(file).extract(outputDir)
try {
//org.jetbrains.intellij.build.io.ZipArchiveOutputStream may add __index__ entry to the plugin zip, we need to ignore it here
val rootDir = NioFiles.list(outputDir).firstOrNull { it.name != "__index__" }
if (rootDir != null) {
return runBlocking {
loadDescriptorFromFileOrDir(file = rootDir,
context = context,
pathResolver = PluginXmlPathResolver.DEFAULT_PATH_RESOLVER,
isBundled = false,
isEssential = false,
isDirectory = true,
useCoreClassLoader = false,
pool = null)
}
}
}
catch (ignore: NoSuchFileException) {
}
}
finally {
NioFiles.deleteRecursively(outputDir)
}
return null
}
fun loadDescriptor(file: Path,
disabledPlugins: Set<PluginId>,
isBundled: Boolean,
pathResolver: PathResolver): IdeaPluginDescriptorImpl? {
DescriptorListLoadingContext(disabledPlugins = disabledPlugins).use { context ->
return runBlocking {
loadDescriptorFromFileOrDir(file = file,
context = context,
pathResolver = pathResolver,
isBundled = isBundled,
isEssential = false,
isDirectory = Files.isDirectory(file),
useCoreClassLoader = false,
pool = null)
}
}
}
@Throws(ExecutionException::class, InterruptedException::class)
fun loadDescriptors(
customPluginDir: Path,
bundledPluginDir: Path?,
brokenPluginVersions: Map<PluginId, Set<String?>>?,
productBuildNumber: BuildNumber?,
): PluginLoadingResult {
return DescriptorListLoadingContext(
disabledPlugins = emptySet(),
brokenPluginVersions = brokenPluginVersions ?: PluginManagerCore.getBrokenPluginVersions(),
productBuildNumber = { productBuildNumber ?: PluginManagerCore.getBuildNumber() },
isMissingIncludeIgnored = true,
isMissingSubDescriptorIgnored = true,
).use { context ->
runBlocking {
val result = PluginLoadingResult()
result.addAll(
descriptors = loadDescriptorsFromDirs(context = context,
customPluginDir = customPluginDir,
bundledPluginDir = bundledPluginDir,
zipFilePool = null).awaitAll(),
overrideUseIfCompatible = false,
productBuildNumber = context.productBuildNumber()
)
result
}
}
}
@TestOnly
fun testLoadDescriptorsFromClassPath(loader: ClassLoader): List<IdeaPluginDescriptor> {
val urlToFilename = collectPluginFilesInClassPath(loader)
val buildNumber = BuildNumber.fromString("2042.42")!!
val context = DescriptorListLoadingContext(disabledPlugins = Collections.emptySet(),
brokenPluginVersions = emptyMap(),
productBuildNumber = { buildNumber })
return runBlocking {
val result = PluginLoadingResult(checkModuleDependencies = false)
result.addAll(loadDescriptorsFromClassPath(
urlToFilename = urlToFilename,
context = context,
pathResolver = ClassPathXmlPathResolver(loader, isRunningFromSources = false),
useCoreClassLoader = true,
pool = if (context.transient) null else ZipFilePool.POOL,
).awaitAll(), overrideUseIfCompatible = false, productBuildNumber = buildNumber)
result.enabledPlugins
}
}
private fun CoroutineScope.loadDescriptorsFromDir(dir: Path,
context: DescriptorListLoadingContext,
isBundled: Boolean,
pool: ZipFilePool?): List<Deferred<IdeaPluginDescriptorImpl?>> {
if (!Files.isDirectory(dir)) {
return emptyList()
}
return Files.newDirectoryStream(dir).use { dirStream ->
dirStream.map { file ->
async {
loadDescriptorFromFileOrDir(
file = file,
context = context,
pathResolver = PluginXmlPathResolver.DEFAULT_PATH_RESOLVER,
isBundled = isBundled,
isDirectory = Files.isDirectory(file),
isEssential = false,
useCoreClassLoader = false,
pool = pool,
)
}
}
}
}
// urls here expected to be a file urls to plugin.xml
private fun CoroutineScope.loadDescriptorsFromClassPath(
urlToFilename: Map<URL, String>,
context: DescriptorListLoadingContext,
pathResolver: ClassPathXmlPathResolver,
useCoreClassLoader: Boolean,
pool: ZipFilePool?,
): List<Deferred<IdeaPluginDescriptorImpl?>> {
return urlToFilename.map { (url, filename) ->
async {
loadDescriptorFromResource(resource = url,
filename = filename,
context = context,
pathResolver = pathResolver,
useCoreClassLoader = useCoreClassLoader,
pool = pool)
}
}
}
// filename - plugin.xml or ${platformPrefix}Plugin.xml
private fun loadDescriptorFromResource(
resource: URL,
filename: String,
context: DescriptorListLoadingContext,
pathResolver: ClassPathXmlPathResolver,
useCoreClassLoader: Boolean,
pool: ZipFilePool?,
): IdeaPluginDescriptorImpl? {
val file = Paths.get(UrlClassLoader.urlToFilePath(resource.path))
var closeable: Closeable? = null
val dataLoader: DataLoader
val basePath: Path
try {
val input: InputStream
when {
URLUtil.FILE_PROTOCOL == resource.protocol -> {
basePath = file.parent.parent
dataLoader = LocalFsDataLoader(basePath)
input = Files.newInputStream(file)
}
URLUtil.JAR_PROTOCOL == resource.protocol -> {
// support for unpacked plugins in classpath, e.g. .../community/build/dependencies/build/kotlin/Kotlin/lib/kotlin-plugin.jar
basePath = file.parent?.takeIf { !it.endsWith("lib") }?.parent ?: file
if (pool == null) {
val zipFile = ZipFile(file.toFile(), StandardCharsets.UTF_8)
closeable = zipFile
dataLoader = JavaZipFileDataLoader(zipFile)
}
else {
dataLoader = ImmutableZipFileDataLoader(pool.load(file), file, pool)
}
input = dataLoader.load("META-INF/$filename") ?: return null
}
else -> return null
}
val raw = readModuleDescriptor(input = input,
readContext = context,
pathResolver = pathResolver,
dataLoader = dataLoader,
includeBase = null,
readInto = null,
locationSource = file.toString())
// it is very important to not set useCoreClassLoader = true blindly
// - product modules must uses own class loader if not running from sources
val descriptor = IdeaPluginDescriptorImpl(raw = raw,
path = basePath,
isBundled = true,
id = null,
moduleName = null,
useCoreClassLoader = useCoreClassLoader)
descriptor.readExternal(raw = raw, pathResolver = pathResolver, context = context, isSub = false, dataLoader = dataLoader)
// do not set jarFiles by intention - doesn't make sense
return descriptor
}
catch (e: CancellationException) {
throw e
}
catch (e: Throwable) {
LOG.info("Cannot load $resource", e)
return null
}
finally {
closeable?.close()
}
} | apache-2.0 |
ingokegel/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/redundantAsSequence/sequenceWithTypeArgument.kt | 9 | 135 | // PROBLEM: none
// WITH_STDLIB
fun foo(a: Sequence<String>): Sequence<CharSequence> {
return a.<caret>asSequence<CharSequence>()
} | apache-2.0 |
ingokegel/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/move/kotlin/changePackage/changeToNonDefaultPackage/before/usages/usagesWithImports.kt | 26 | 87 | package usages
import source.Foo
import source.foo
fun test() {
Foo()
foo()
} | apache-2.0 |
android/nowinandroid | core/network/src/main/java/com/google/samples/apps/nowinandroid/core/network/model/NetworkAuthor.kt | 1 | 1022 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.nowinandroid.core.network.model
import com.google.samples.apps.nowinandroid.core.model.data.Author
import kotlinx.serialization.Serializable
/**
* Network representation of [Author]
*/
@Serializable
data class NetworkAuthor(
val id: String,
val name: String,
val imageUrl: String,
val twitter: String,
val mediumPage: String,
val bio: String,
)
| apache-2.0 |
cwoodwar6/okbuck | libraries/kotlinandroidlibrary/src/test/java/com/uber/okbuck/java/KPojoTest.kt | 1 | 148 | package com.uber.okbuck.java
import org.junit.Test
class KPojoTest {
@Test
fun shouldCreateKPojo() {
val kPojo = KPojo()
}
}
| mit |
spinnaker/orca | orca-api-tck/src/test/kotlin/com/netflix/spinnaker/orca/api/test/OrcaFixtureTest.kt | 4 | 2294 | /*
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.api.test
import com.netflix.spinnaker.orca.notifications.AlwaysUnlockedNotificationClusterLock
import com.netflix.spinnaker.orca.notifications.NotificationClusterLock
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.orca.pipeline.persistence.InMemoryExecutionRepository
import com.netflix.spinnaker.orca.q.pending.InMemoryPendingExecutionService
import com.netflix.spinnaker.orca.q.pending.PendingExecutionService
import com.netflix.spinnaker.q.Queue
import com.netflix.spinnaker.q.memory.InMemoryQueue
import dev.minutest.junit.JUnit5Minutests
import dev.minutest.rootContext
import org.springframework.beans.factory.annotation.Autowired
import strikt.api.expect
import strikt.assertions.isA
class OrcaFixtureTest : JUnit5Minutests {
fun tests() = rootContext<Fixture> {
context("an orca integration test environment") {
orcaFixture {
Fixture()
}
test("the application starts with expected in-memory beans") {
expect {
that(executionRepository).isA<InMemoryExecutionRepository>()
that(queue).isA<InMemoryQueue>()
that(notificationClusterLock).isA<AlwaysUnlockedNotificationClusterLock>()
that(pendingExecutionService).isA<InMemoryPendingExecutionService>()
}
}
}
}
private inner class Fixture : OrcaFixture() {
@Autowired
lateinit var executionRepository: ExecutionRepository
@Autowired
lateinit var queue: Queue
@Autowired
lateinit var notificationClusterLock: NotificationClusterLock
@Autowired
lateinit var pendingExecutionService: PendingExecutionService
}
}
| apache-2.0 |
GunoH/intellij-community | platform/platform-api/src/com/intellij/openapi/observable/dispatcher/PromiseUtil.kt | 2 | 805 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.observable.dispatcher
import com.intellij.openapi.Disposable
import com.intellij.openapi.observable.util.getPromise1
import com.intellij.openapi.observable.util.getPromise2
fun SingleEventDispatcher.Observable.getPromise(parentDisposable: Disposable?) =
com.intellij.openapi.observable.util.getPromise(parentDisposable, ::onceWhenEventHappened)
fun <A1> SingleEventDispatcher.Observable1<A1>.getPromise(parentDisposable: Disposable?) =
getPromise1(parentDisposable, ::onceWhenEventHappened)
fun <A1, A2> SingleEventDispatcher.Observable2<A1, A2>.getPromise(parentDisposable: Disposable?) =
getPromise2(parentDisposable, ::onceWhenEventHappened) | apache-2.0 |
GunoH/intellij-community | plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/GradleOperationHelperExtension.kt | 2 | 1402 | // 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.service.project
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId
import org.gradle.tooling.LongRunningOperation
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.plugins.gradle.settings.GradleExecutionSettings
/**
* Extension point to fine-tune Gradle Tooling API calls.
*
* E.g. a client may add GradleEventListeners to collect specific information or statistics.
*/
@ApiStatus.Experimental
interface GradleOperationHelperExtension {
companion object {
@JvmField
val EP_NAME: ExtensionPointName<GradleOperationHelperExtension> = ExtensionPointName.create("org.jetbrains.plugins.gradle.operationHelperExtension")
}
/**
* Prepare an operation call during Gradle sync.
* May be called more than once with different operations for a single Gradle project refresh.
*/
fun prepareForSync(operation: LongRunningOperation, resolverCtx: ProjectResolverContext)
/**
* Prepare an operation call before Gradle task execution
*/
fun prepareForExecution(id: ExternalSystemTaskId,
operation: LongRunningOperation,
gradleExecutionSettings: GradleExecutionSettings)
} | apache-2.0 |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/segmentedActionBar/SegmentedActionToolbarComponent.kt | 2 | 7130 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.actionSystem.impl.segmentedActionBar
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.ex.ActionButtonLook
import com.intellij.openapi.actionSystem.ex.ComboBoxAction
import com.intellij.openapi.actionSystem.ex.ComboBoxAction.ComboBoxButton
import com.intellij.openapi.actionSystem.ex.CustomComponentAction
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.util.ui.JBInsets
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import java.awt.*
import javax.swing.JComponent
import javax.swing.border.Border
open class SegmentedActionToolbarComponent(place: String,
group: ActionGroup,
private val paintBorderForSingleItem: Boolean = true) : ActionToolbarImpl(place, group, true) {
companion object {
internal const val CONTROL_BAR_PROPERTY = "CONTROL_BAR_PROPERTY"
internal const val CONTROL_BAR_FIRST = "CONTROL_BAR_PROPERTY_FIRST"
internal const val CONTROL_BAR_LAST = "CONTROL_BAR_PROPERTY_LAST"
internal const val CONTROL_BAR_MIDDLE = "CONTROL_BAR_PROPERTY_MIDDLE"
internal const val CONTROL_BAR_SINGLE = "CONTROL_BAR_PROPERTY_SINGLE"
const val RUN_TOOLBAR_COMPONENT_ACTION = "RUN_TOOLBAR_COMPONENT_ACTION"
private val LOG = Logger.getInstance(SegmentedActionToolbarComponent::class.java)
val segmentedButtonLook = object : ActionButtonLook() {
override fun paintBorder(g: Graphics, c: JComponent, state: Int) {
}
override fun paintBackground(g: Graphics, component: JComponent, state: Int) {
SegmentedBarPainter.paintActionButtonBackground(g, component, state)
}
}
fun isCustomBar(component: Component): Boolean {
if (component !is JComponent) return false
return component.getClientProperty(CONTROL_BAR_PROPERTY)?.let {
it != CONTROL_BAR_SINGLE
} ?: false
}
fun paintButtonDecorations(g: Graphics2D, c: JComponent, paint: Paint): Boolean {
return SegmentedBarPainter.paintButtonDecorations(g, c, paint)
}
}
init {
layoutPolicy = NOWRAP_LAYOUT_POLICY
setActionButtonBorder(JBUI.Borders.empty(0, 3))
setCustomButtonLook(segmentedButtonLook)
}
private var isActive = false
private var visibleActions: List<AnAction>? = null
override fun getInsets(): Insets {
return JBInsets.emptyInsets()
}
override fun setBorder(border: Border?) {
}
override fun createCustomComponent(action: CustomComponentAction, presentation: Presentation): JComponent {
var component = super.createCustomComponent(action, presentation)
if (!isActive) {
return component
}
if (action is ComboBoxAction) {
UIUtil.uiTraverser(component).filter(ComboBoxButton::class.java).firstOrNull()?.let {
component.remove(it)
component = it
}
}
if (component !is ActionButton) {
component.border = JBUI.Borders.empty()
}
return component
}
override fun fillToolBar(actions: List<AnAction>, layoutSecondaries: Boolean) {
if (!isActive) {
super.fillToolBar(actions, layoutSecondaries)
return
}
val rightAligned: MutableList<AnAction> = ArrayList()
for (i in actions.indices) {
val action = actions[i]
if (action is RightAlignedToolbarAction) {
rightAligned.add(action)
continue
}
if (action is CustomComponentAction) {
val component = getCustomComponent(action)
addMetadata(component, i, actions.size)
add(CUSTOM_COMPONENT_CONSTRAINT, component)
component.putClientProperty(RUN_TOOLBAR_COMPONENT_ACTION, action)
}
else {
val component = createToolbarButton(action)
addMetadata(component, i, actions.size)
add(ACTION_BUTTON_CONSTRAINT, component)
component.putClientProperty(RUN_TOOLBAR_COMPONENT_ACTION, action)
}
}
}
protected open fun isSuitableAction(action: AnAction): Boolean {
return true
}
override fun paintComponent(g: Graphics) {
super.paintComponent(g)
paintActiveBorder(g)
}
private fun paintActiveBorder(g: Graphics) {
if ((isActive || paintBorderForSingleItem) && visibleActions != null) {
SegmentedBarPainter.paintActionBarBorder(this, g)
}
}
override fun paintBorder(g: Graphics) {
super.paintBorder(g)
paintActiveBorder(g)
}
override fun paint(g: Graphics) {
super.paint(g)
paintActiveBorder(g)
}
private fun addMetadata(component: JComponent, index: Int, count: Int) {
if (count == 1) {
component.putClientProperty(CONTROL_BAR_PROPERTY, CONTROL_BAR_SINGLE)
return
}
val property = when (index) {
0 -> CONTROL_BAR_FIRST
count - 1 -> CONTROL_BAR_LAST
else -> CONTROL_BAR_MIDDLE
}
component.putClientProperty(CONTROL_BAR_PROPERTY, property)
}
protected open fun logNeeded() = false
protected fun forceUpdate() {
if (logNeeded()) LOG.info("RunToolbar MAIN SLOT forceUpdate")
visibleActions?.let {
update(true, it)
revalidate()
repaint()
}
}
override fun actionsUpdated(forced: Boolean, newVisibleActions: List<AnAction>) {
visibleActions = newVisibleActions
update(forced, newVisibleActions)
}
private var lastIds: List<String> = emptyList()
private var lastActions: List<AnAction> = emptyList()
private fun update(forced: Boolean, newVisibleActions: List<AnAction>) {
val filtered = newVisibleActions.filter { isSuitableAction(it) }
val ides = newVisibleActions.map { ActionManager.getInstance().getId(it) }.toList()
val filteredIds = filtered.map { ActionManager.getInstance().getId(it) }.toList()
traceState(lastIds, filteredIds, ides)
isActive = newVisibleActions.size > 1
super.actionsUpdated(forced, if (filtered.size > 1) filtered else if(lastActions.isEmpty()) newVisibleActions else lastActions)
lastIds = filteredIds
lastActions = filtered
ApplicationManager.getApplication().messageBus.syncPublisher(ToolbarActionsUpdatedListener.TOPIC).actionsUpdated()
}
protected open fun traceState(lastIds: List<String>, filteredIds: List<String>, ides: List<String>) {
// if(logNeeded() && filteredIds != lastIds) LOG.info("MAIN SLOT new filtered: ${filteredIds}} visible: $ides RunToolbar")
}
override fun calculateBounds(size2Fit: Dimension, bounds: MutableList<Rectangle>) {
bounds.clear()
for (i in 0 until componentCount) {
bounds.add(Rectangle())
}
var offset = 0
for (i in 0 until componentCount) {
val d = getChildPreferredSize(i)
val r = bounds[i]
r.setBounds(insets.left + offset, insets.top, d.width, DEFAULT_MINIMUM_BUTTON_SIZE.height)
offset += d.width
}
}
} | apache-2.0 |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/quickfix/autoImports/dslMarkersOnReceiver.after.kt | 6 | 226 | import BExtSpace.aaa
// "Import extension function 'BBB.aaa'" "true"
// WITH_STDLIB
// ERROR: Unresolved reference: aaa
fun test() {
AAA().apply {
sub {
aaa<caret>()
}
}
}
/* IGNORE_FIR */ | apache-2.0 |
GunoH/intellij-community | platform/projectModel-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/module/roots/ModifiableContentEntryBridge.kt | 2 | 13555 | // 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.workspaceModel.ide.impl.legacyBridge.module.roots
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.roots.*
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.util.CachedValueProvider
import com.intellij.util.CachedValueImpl
import com.intellij.workspaceModel.ide.getInstance
import com.intellij.workspaceModel.ide.impl.toVirtualFileUrl
import com.intellij.workspaceModel.ide.isEqualOrParentOf
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.bridgeEntities.addSourceRootEntity
import com.intellij.workspaceModel.storage.bridgeEntities.ContentRootEntity
import com.intellij.workspaceModel.storage.bridgeEntities.ExcludeUrlEntity
import com.intellij.workspaceModel.storage.bridgeEntities.modifyEntity
import com.intellij.workspaceModel.storage.bridgeEntities.asJavaResourceRoot
import com.intellij.workspaceModel.storage.bridgeEntities.asJavaSourceRoot
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import org.jetbrains.jps.model.JpsElement
import org.jetbrains.jps.model.java.JavaResourceRootProperties
import org.jetbrains.jps.model.java.JavaSourceRootProperties
import org.jetbrains.jps.model.java.JavaSourceRootType
import org.jetbrains.jps.model.module.JpsModuleSourceRootType
import org.jetbrains.jps.model.serialization.module.JpsModuleSourceRootPropertiesSerializer
internal class ModifiableContentEntryBridge(
private val diff: MutableEntityStorage,
private val modifiableRootModel: ModifiableRootModelBridgeImpl,
val contentEntryUrl: VirtualFileUrl
) : ContentEntry {
companion object {
private val LOG = logger<ModifiableContentEntryBridge>()
}
private val virtualFileManager = VirtualFileUrlManager.getInstance(modifiableRootModel.project)
private val currentContentEntry = CachedValueImpl {
val contentEntry = modifiableRootModel.currentModel.contentEntries.firstOrNull { it.url == contentEntryUrl.url } as? ContentEntryBridge
?: error("Unable to find content entry in parent modifiable root model by url: $contentEntryUrl")
CachedValueProvider.Result.createSingleDependency(contentEntry, modifiableRootModel)
}
private fun <P : JpsElement> addSourceFolder(sourceFolderUrl: VirtualFileUrl,
type: JpsModuleSourceRootType<P>,
properties: P,
folderEntitySource: EntitySource): SourceFolder {
if (!contentEntryUrl.isEqualOrParentOf(sourceFolderUrl)) {
error("Source folder $sourceFolderUrl must be under content entry $contentEntryUrl")
}
val duplicate = findDuplicate(sourceFolderUrl, type, properties)
if (duplicate != null) {
LOG.debug("Source folder for '$sourceFolderUrl' and type '$type' already exist")
return duplicate
}
val serializer: JpsModuleSourceRootPropertiesSerializer<P> = SourceRootPropertiesHelper.findSerializer(type)
?: error("Module source root type $type is not registered as JpsModelSerializerExtension")
val contentRootEntity = currentContentEntry.value.entity
val sourceRootEntity = diff.addSourceRootEntity(
contentRoot = contentRootEntity,
url = sourceFolderUrl,
rootType = serializer.typeId,
source = folderEntitySource
)
SourceRootPropertiesHelper.addPropertiesEntity(diff, sourceRootEntity, properties, serializer)
return currentContentEntry.value.sourceFolders.firstOrNull {
it.url == sourceFolderUrl.url && it.rootType == type
} ?: error("Source folder for '$sourceFolderUrl' and type '$type' was not found after adding")
}
private fun <P : JpsElement?> findDuplicate(sourceFolderUrl: VirtualFileUrl, type: JpsModuleSourceRootType<P>,
properties: P): SourceFolder? {
val propertiesFilter: (SourceFolder) -> Boolean = when (properties) {
is JavaSourceRootProperties -> label@{ sourceFolder: SourceFolder ->
val javaSourceRoot = (sourceFolder as SourceFolderBridge).sourceRootEntity.asJavaSourceRoot()
return@label javaSourceRoot != null && javaSourceRoot.generated == properties.isForGeneratedSources
&& javaSourceRoot.packagePrefix == properties.packagePrefix
}
is JavaResourceRootProperties -> label@{ sourceFolder: SourceFolder ->
val javaResourceRoot = (sourceFolder as SourceFolderBridge).sourceRootEntity.asJavaResourceRoot()
return@label javaResourceRoot != null && javaResourceRoot.generated == properties.isForGeneratedSources
&& javaResourceRoot.relativeOutputPath == properties.relativeOutputPath
}
else -> { _ -> true }
}
return sourceFolders.filter { it.url == sourceFolderUrl.url && it.rootType == type }.find { propertiesFilter.invoke(it) }
}
override fun removeSourceFolder(sourceFolder: SourceFolder) {
val legacyBridgeSourceFolder = sourceFolder as SourceFolderBridge
val sourceRootEntity = currentContentEntry.value.sourceRootEntities.firstOrNull { it == legacyBridgeSourceFolder.sourceRootEntity }
if (sourceRootEntity == null) {
LOG.error("SourceFolder ${sourceFolder.url} is not present under content entry $contentEntryUrl")
return
}
modifiableRootModel.removeCachedJpsRootProperties(sourceRootEntity.url)
diff.removeEntity(sourceRootEntity)
}
override fun clearSourceFolders() {
currentContentEntry.value.sourceRootEntities.forEach { sourceRoot -> diff.removeEntity(sourceRoot) }
}
private fun addExcludeFolder(excludeUrl: VirtualFileUrl, projectSource: ProjectModelExternalSource?): ExcludeFolder {
if (!contentEntryUrl.isEqualOrParentOf(excludeUrl)) {
error("Exclude folder $excludeUrl must be under content entry $contentEntryUrl")
}
if (excludeUrl !in currentContentEntry.value.entity.excludedUrls.map { it.url }) {
updateContentEntry {
val source = if (projectSource == null) getInternalFileSource(entitySource) ?: entitySource else entitySource
excludedUrls = excludedUrls + ExcludeUrlEntity(excludeUrl, source)
}
}
return currentContentEntry.value.excludeFolders.firstOrNull {
it.url == excludeUrl.url
} ?: error("Exclude folder $excludeUrl must be present after adding it to content entry $contentEntryUrl")
}
override fun addExcludeFolder(file: VirtualFile): ExcludeFolder = addExcludeFolder(file.toVirtualFileUrl(virtualFileManager), null)
override fun addExcludeFolder(url: String): ExcludeFolder = addExcludeFolder(virtualFileManager.fromUrl(url), null)
override fun addExcludeFolder(url: String, source: ProjectModelExternalSource): ExcludeFolder {
return addExcludeFolder(virtualFileManager.fromUrl(url), source)
}
override fun removeExcludeFolder(excludeFolder: ExcludeFolder) {
val virtualFileUrl = (excludeFolder as ExcludeFolderBridge).excludeFolderUrl
val excludeUrlEntities = currentContentEntry.value.entity.excludedUrls.filter { it.url == virtualFileUrl }
if (excludeUrlEntities.isEmpty()) {
error("Exclude folder ${excludeFolder.url} is not under content entry $contentEntryUrl")
}
excludeUrlEntities.forEach {
diff.removeEntity(it)
}
}
private fun updateContentEntry(updater: ContentRootEntity.Builder.() -> Unit) {
diff.modifyEntity(currentContentEntry.value.entity, updater)
}
override fun removeExcludeFolder(url: String): Boolean {
val virtualFileUrl = virtualFileManager.fromUrl(url)
val excludedUrls = currentContentEntry.value.entity.excludedUrls.map { it.url }
if (!excludedUrls.contains(virtualFileUrl)) return false
val contentRootEntity = currentContentEntry.value.entity
val (new, toRemove) = contentRootEntity.excludedUrls.partition {excludedUrl -> excludedUrl.url != virtualFileUrl }
updateContentEntry {
this.excludedUrls = new
}
toRemove.forEach { diff.removeEntity(it) }
return true
}
override fun clearExcludeFolders() {
updateContentEntry {
excludedUrls = mutableListOf()
}
}
override fun addExcludePattern(pattern: String) {
updateContentEntry {
if (!excludedPatterns.contains(pattern)) excludedPatterns.add(pattern)
}
}
override fun removeExcludePattern(pattern: String) {
updateContentEntry {
excludedPatterns.remove(pattern)
}
}
override fun setExcludePatterns(patterns: MutableList<String>) {
updateContentEntry {
excludedPatterns = patterns.toMutableList()
}
}
override fun equals(other: Any?): Boolean {
return (other as? ContentEntry)?.url == url
}
override fun hashCode(): Int {
return url.hashCode()
}
override fun addSourceFolder(file: VirtualFile, isTestSource: Boolean) = addSourceFolder(file, isTestSource, "")
override fun addSourceFolder(file: VirtualFile, isTestSource: Boolean, packagePrefix: String): SourceFolder =
addSourceFolder(file, if (isTestSource) JavaSourceRootType.TEST_SOURCE else JavaSourceRootType.SOURCE,
JavaSourceRootProperties(packagePrefix, false))
override fun <P : JpsElement> addSourceFolder(file: VirtualFile, type: JpsModuleSourceRootType<P>): SourceFolder =
addSourceFolder(file, type, type.createDefaultProperties())
override fun addSourceFolder(url: String, isTestSource: Boolean): SourceFolder =
addSourceFolder(url, if (isTestSource) JavaSourceRootType.TEST_SOURCE else JavaSourceRootType.SOURCE)
override fun <P : JpsElement> addSourceFolder(url: String, type: JpsModuleSourceRootType<P>): SourceFolder {
return addSourceFolder(url, type, type.createDefaultProperties())
}
override fun <P : JpsElement> addSourceFolder(url: String,
type: JpsModuleSourceRootType<P>,
externalSource: ProjectModelExternalSource): SourceFolder {
return addSourceFolder(url, type, type.createDefaultProperties(), externalSource)
}
override fun <P : JpsElement> addSourceFolder(url: String,
type: JpsModuleSourceRootType<P>,
useSourceOfContentRoot: Boolean): SourceFolder {
val contentRootSource = currentContentEntry.value.entity.entitySource
val source = if (useSourceOfContentRoot) contentRootSource else getInternalFileSource(contentRootSource) ?: contentRootSource
return addSourceFolder(virtualFileManager.fromUrl(url), type, type.createDefaultProperties(), source)
}
override fun <P : JpsElement> addSourceFolder(file: VirtualFile, type: JpsModuleSourceRootType<P>, properties: P): SourceFolder {
val contentRootSource = currentContentEntry.value.entity.entitySource
val source: EntitySource = getInternalFileSource(contentRootSource) ?: contentRootSource
return addSourceFolder(file.toVirtualFileUrl(virtualFileManager), type, properties, source)
}
override fun <P : JpsElement> addSourceFolder(url: String, type: JpsModuleSourceRootType<P>, properties: P): SourceFolder {
val contentRootSource = currentContentEntry.value.entity.entitySource
val source: EntitySource = getInternalFileSource(contentRootSource) ?: contentRootSource
return addSourceFolder(virtualFileManager.fromUrl(url), type, properties, source)
}
override fun <P : JpsElement> addSourceFolder(url: String,
type: JpsModuleSourceRootType<P>,
properties: P,
externalSource: ProjectModelExternalSource?): SourceFolder {
val contentRootSource = currentContentEntry.value.entity.entitySource
val source = if (externalSource != null) contentRootSource else getInternalFileSource(contentRootSource) ?: contentRootSource
return addSourceFolder(virtualFileManager.fromUrl(url), type, properties, source)
}
override fun getFile(): VirtualFile? = currentContentEntry.value.file
override fun getUrl(): String = contentEntryUrl.url
override fun getSourceFolders(): Array<SourceFolder> = currentContentEntry.value.sourceFolders
override fun getSourceFolders(rootType: JpsModuleSourceRootType<*>): List<SourceFolder> =
currentContentEntry.value.getSourceFolders(rootType)
override fun getSourceFolders(rootTypes: MutableSet<out JpsModuleSourceRootType<*>>): List<SourceFolder> =
currentContentEntry.value.getSourceFolders(rootTypes)
override fun getSourceFolderFiles(): Array<VirtualFile> = currentContentEntry.value.sourceFolderFiles
override fun getExcludeFolders(): Array<ExcludeFolder> = currentContentEntry.value.excludeFolders
override fun getExcludeFolderUrls(): MutableList<String> = currentContentEntry.value.excludeFolderUrls
override fun getExcludeFolderFiles(): Array<VirtualFile> = currentContentEntry.value.excludeFolderFiles
override fun getExcludePatterns(): List<String> = currentContentEntry.value.excludePatterns
override fun getRootModel(): ModuleRootModel = modifiableRootModel
override fun isSynthetic(): Boolean = currentContentEntry.value.isSynthetic
}
| apache-2.0 |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/branched/ifThenToSafeAccess/missingNecessaryElseClause.kt | 13 | 119 | // PROBLEM: none
fun main(args: Array<String>) {
val foo = null
if (foo == null<caret>) {
null
}
}
| apache-2.0 |
GunoH/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/models/versions/PackageVersionNormalizer.kt | 2 | 8609 | /*******************************************************************************
* Copyright 2000-2022 JetBrains s.r.o. and contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.versions
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageVersion
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.versions.NormalizedPackageVersion.Garbage
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.versions.NormalizedPackageVersion.Semantic
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.versions.NormalizedPackageVersion.TimestampLike
import com.jetbrains.packagesearch.intellij.plugin.util.CoroutineLRUCache
import com.jetbrains.packagesearch.intellij.plugin.util.nullIfBlank
import kotlinx.coroutines.runBlocking
internal class PackageVersionNormalizer(
private val versionsCache: CoroutineLRUCache<PackageVersion.Named, NormalizedPackageVersion<PackageVersion.Named>> = CoroutineLRUCache(2_000)
) {
private val HEX_STRING_LETTER_CHARS = 'a'..'f'
/**
* Matches a whole string starting with a semantic version. A valid semantic version
* has [1, 5] numeric components, each up to 5 digits long. Between each component
* there is a period character.
*
* Examples of valid semver: 1, 1.0-whatever, 1.2.3, 2.3.3.0-beta02, 21.4.0.0.1
* Examples of invalid semver: 1.0.0.0.0.1 (too many components), 123456 (component too long)
*
* Group 0 matches the whole string, group 1 is the semver minus any suffixes.
*/
private val SEMVER_REGEX = "^((?:\\d{1,5}\\.){0,4}\\d{1,5}(?!\\.?\\d)).*\$".toRegex(option = RegexOption.IGNORE_CASE)
/**
* Extracts stability markers. Must be used on the string that follows a valid semver (see [SEMVER_REGEX]).
*
* Stability markers are made up by a separator character (one of: . _ - +), then one of the stability tokens (see the list below), followed by an
* optional separator (one of: . _ -), AND [0, 5] numeric digits. After the digits, there must be a word boundary (most punctuation, except for
* underscores, qualifies as such).
*
* We only support up to two stability markers (arguably, having two already qualifies for the [Garbage] tier, but we have well-known libraries
* out there that do the two-markers game, now and then, and we need to support those shenanigans).
*
* ### Stability tokens
* We support the following stability tokens:
* * `snapshots`*, `snapshot`, `snap`, `s`*
* * `preview`, `eap`, `pre`, `p`*
* * `develop`*, `dev`*
* * `milestone`*, `m`, `build`*
* * `alpha`, `a`
* * `betta` (yes, there are Bettas out there), `beta`, `b`
* * `candidate`*, `rc`
* * `sp`
* * `release`, `final`, `stable`*, `rel`, `r`
*
* Tokens denoted by a `*` are considered as meaningless words by [com.intellij.util.text.VersionComparatorUtil] when comparing without a custom
* token priority provider, so sorting may be funky when they appear.
*/
private val STABILITY_MARKER_REGEX =
("^((?:[._\\-+]" +
"(?:snapshots?|preview|milestone|candidate|release|develop|stable|build|alpha|betta|final|snap|beta|dev|pre|eap|rel|sp|rc|m|r|b|a|p)" +
"(?:[._\\-]?\\d{1,5})?){1,2})(?:\\b|_)")
.toRegex(option = RegexOption.IGNORE_CASE)
suspend fun <T : PackageVersion> parse(version: T): NormalizedPackageVersion<*> =
when (version) {
is PackageVersion.Missing -> NormalizedPackageVersion.Missing
is PackageVersion.Named -> parse(version)
else -> error("Unknown version type: ${version.javaClass.simpleName}")
}
suspend fun parse(version: PackageVersion.Named): NormalizedPackageVersion<PackageVersion.Named> {
val cachedValue = versionsCache.get(version)
if (cachedValue != null) return cachedValue
// Before parsing, we rule out git commit hashes — those are garbage as far as we're concerned.
// The initial step attempts to parse the version as a date(time) string starting at 0; if that fails,
// and the version is not one uninterrupted alphanumeric blob (trying to catch more garbage), it
// tries parsing it as a semver; if that fails too, the version name is considered "garbage"
// (that is, it realistically can't be sorted if not by timestamp, and by hoping for the best).
val garbage = Garbage(version)
if (version.looksLikeGitCommitOrOtherHash()) {
versionsCache.put(version, garbage)
return garbage
}
val timestampPrefix = VeryLenientDateTimeExtractor.extractTimestampLookingPrefixOrNull(version.versionName)
if (timestampPrefix != null) {
val normalized = parseTimestampVersion(version, timestampPrefix)
versionsCache.put(version, normalized)
return normalized
}
if (version.isOneBigHexadecimalBlob()) {
versionsCache.put(version, garbage)
return garbage
}
val semanticVersionPrefix = version.semanticVersionPrefixOrNull()
if (semanticVersionPrefix != null) {
val normalized = parseSemanticVersion(version, semanticVersionPrefix)
versionsCache.put(version, normalized)
return normalized
}
versionsCache.put(version, garbage)
return garbage
}
fun parseBlocking(version: PackageVersion.Named) = runBlocking { parse(version) }
private fun PackageVersion.Named.looksLikeGitCommitOrOtherHash(): Boolean {
val hexLookingPrefix = versionName.takeWhile { it.isDigit() || HEX_STRING_LETTER_CHARS.contains(it) }
return when (hexLookingPrefix.length) {
7, 40 -> true
else -> false
}
}
private fun parseTimestampVersion(version: PackageVersion.Named, timestampPrefix: String): NormalizedPackageVersion<PackageVersion.Named> =
TimestampLike(
original = version,
timestampPrefix = timestampPrefix,
stabilityMarker = version.stabilitySuffixComponentOrNull(timestampPrefix),
nonSemanticSuffix = version.nonSemanticSuffix(timestampPrefix)
)
private fun PackageVersion.Named.isOneBigHexadecimalBlob(): Boolean {
var hasHexChars = false
for (char in versionName.lowercase()) {
when {
char in HEX_STRING_LETTER_CHARS -> hasHexChars = true
!char.isDigit() -> return false
}
}
return hasHexChars
}
private fun parseSemanticVersion(version: PackageVersion.Named, semanticVersionPrefix: String): NormalizedPackageVersion<PackageVersion.Named> =
Semantic(
original = version,
semanticPart = semanticVersionPrefix,
stabilityMarker = version.stabilitySuffixComponentOrNull(semanticVersionPrefix),
nonSemanticSuffix = version.nonSemanticSuffix(semanticVersionPrefix)
)
private fun PackageVersion.Named.semanticVersionPrefixOrNull(): String? {
val groupValues = SEMVER_REGEX.find(versionName)?.groupValues ?: return null
if (groupValues.size <= 1) return null
return groupValues[1]
}
private fun PackageVersion.Named.stabilitySuffixComponentOrNull(ignoredPrefix: String): String? {
val groupValues = STABILITY_MARKER_REGEX.find(versionName.substringAfter(ignoredPrefix))
?.groupValues ?: return null
if (groupValues.size <= 1) return null
return groupValues[1].takeIf { it.isNotBlank() }
}
private fun PackageVersion.Named.nonSemanticSuffix(ignoredPrefix: String?): String? {
val semanticPart = stabilitySuffixComponentOrNull(ignoredPrefix ?: return null)
?: ignoredPrefix
return versionName.substringAfter(semanticPart).nullIfBlank()
}
}
| apache-2.0 |
GunoH/intellij-community | plugins/kotlin/code-insight/inspections-k2/tests/testData/inspectionsLocal/mainFunctionReturnUnit/insideClass/simple.kt | 2 | 80 | // PROBLEM: none
class Foo {
fun main(args: Array<String>): <caret>Int {}
} | apache-2.0 |
google/accompanist | insets/src/main/java/com/google/accompanist/insets/WindowInsets.kt | 1 | 20258 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.
*/
@file:Suppress("DEPRECATION")
package com.google.accompanist.insets
import android.view.View
import android.view.WindowInsetsAnimation
import androidx.annotation.FloatRange
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.ProvidableCompositionLocal
import androidx.compose.runtime.Stable
import androidx.compose.runtime.remember
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.platform.LocalView
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsAnimationCompat
import androidx.core.view.WindowInsetsCompat
/**
* The main insets holder, containing instances of [WindowInsets.Type] which each refer to different
* types of system display insets.
*/
@Stable
@Deprecated(
"""
accompanist/insets is deprecated.
For more migration information, please visit https://google.github.io/accompanist/insets/#migration
""",
replaceWith = ReplaceWith(
"WindowInsets",
"androidx.compose.foundation.layout.WindowInsets"
)
)
interface WindowInsets {
/**
* Inset values which match [WindowInsetsCompat.Type.navigationBars]
*/
val navigationBars: Type
/**
* Inset values which match [WindowInsetsCompat.Type.statusBars]
*/
val statusBars: Type
/**
* Inset values which match [WindowInsetsCompat.Type.ime]
*/
val ime: Type
/**
* Inset values which match [WindowInsetsCompat.Type.systemGestures]
*/
val systemGestures: Type
/**
* Inset values which match [WindowInsetsCompat.Type.systemBars]
*/
val systemBars: Type
/**
* Inset values which match [WindowInsetsCompat.Type.displayCutout]
*/
val displayCutout: Type
/**
* Returns a copy of this instance with the given values.
*/
fun copy(
navigationBars: Type = this.navigationBars,
statusBars: Type = this.statusBars,
systemGestures: Type = this.systemGestures,
ime: Type = this.ime,
displayCutout: Type = this.displayCutout,
): WindowInsets = ImmutableWindowInsets(
systemGestures = systemGestures,
navigationBars = navigationBars,
statusBars = statusBars,
ime = ime,
displayCutout = displayCutout
)
companion object {
/**
* Empty and immutable instance of [WindowInsets].
*/
val Empty: WindowInsets = ImmutableWindowInsets()
}
/**
* Represents the values for a type of insets, and stores information about the layout insets,
* animating insets, and visibility of the insets.
*
* [WindowInsets.Type] instances are commonly stored in a [WindowInsets] instance.
*/
@Stable
@Deprecated(
"accompanist/insets is deprecated",
replaceWith = ReplaceWith(
"WindowInsets",
"androidx.compose.foundation.layout.WindowInsets"
)
)
interface Type : Insets {
/**
* The layout insets for this [WindowInsets.Type]. These are the insets which are defined from the
* current window layout.
*
* You should not normally need to use this directly, and instead use [left], [top],
* [right], and [bottom] to return the correct value for the current state.
*/
val layoutInsets: Insets
/**
* The animated insets for this [WindowInsets.Type]. These are the insets which are updated from
* any on-going animations. If there are no animations in progress, the returned [Insets] will
* be empty.
*
* You should not normally need to use this directly, and instead use [left], [top],
* [right], and [bottom] to return the correct value for the current state.
*/
val animatedInsets: Insets
/**
* Whether the insets are currently visible.
*/
val isVisible: Boolean
/**
* Whether this insets type is being animated at this moment.
*/
val animationInProgress: Boolean
/**
* The left dimension of the insets in pixels.
*/
override val left: Int
get() = (if (animationInProgress) animatedInsets else layoutInsets).left
/**
* The top dimension of the insets in pixels.
*/
override val top: Int
get() = (if (animationInProgress) animatedInsets else layoutInsets).top
/**
* The right dimension of the insets in pixels.
*/
override val right: Int
get() = (if (animationInProgress) animatedInsets else layoutInsets).right
/**
* The bottom dimension of the insets in pixels.
*/
override val bottom: Int
get() = (if (animationInProgress) animatedInsets else layoutInsets).bottom
/**
* The progress of any ongoing animations, in the range of 0 to 1.
* If there is no animation in progress, this will return 0.
*/
@get:FloatRange(from = 0.0, to = 1.0)
val animationFraction: Float
companion object {
/**
* Empty and immutable instance of [WindowInsets.Type].
*/
val Empty: Type = ImmutableWindowInsetsType()
}
}
}
/**
* This class sets up the necessary listeners on the given [view] to be able to observe
* [WindowInsetsCompat] instances dispatched by the system.
*
* This class is useful for when you prefer to handle the ownership of the [WindowInsets]
* yourself. One example of this is if you find yourself using [ProvideWindowInsets] in fragments.
*
* It is convenient to use [ProvideWindowInsets] in fragments, but that can result in a
* delay in the initial inset update, which results in a visual flicker.
* See [this issue](https://github.com/google/accompanist/issues/155) for more information.
*
* The alternative is for fragments to manage the [WindowInsets] themselves, like so:
*
* ```
* override fun onCreateView(
* inflater: LayoutInflater,
* container: ViewGroup?,
* savedInstanceState: Bundle?
* ): View = ComposeView(requireContext()).apply {
* layoutParams = LayoutParams(MATCH_PARENT, MATCH_PARENT)
*
* // Create an ViewWindowInsetObserver using this view
* val observer = ViewWindowInsetObserver(this)
*
* // Call start() to start listening now.
* // The WindowInsets instance is returned to us.
* val windowInsets = observer.start()
*
* setContent {
* // Instead of calling ProvideWindowInsets, we use CompositionLocalProvider to provide
* // the WindowInsets instance from above to LocalWindowInsets
* CompositionLocalProvider(LocalWindowInsets provides windowInsets) {
* /* Content */
* }
* }
* }
* ```
*
* @param view The view to observe [WindowInsetsCompat]s from.
*/
@Deprecated(
"""
accompanist/insets is deprecated.
ViewWindowInsetObserver is not necessary in androidx.compose and can be removed.
For more migration information, please visit https://google.github.io/accompanist/insets/#migration
"""
)
class ViewWindowInsetObserver(private val view: View) {
private val attachListener = object : View.OnAttachStateChangeListener {
override fun onViewAttachedToWindow(v: View) = v.requestApplyInsets()
override fun onViewDetachedFromWindow(v: View) = Unit
}
/**
* Whether this [ViewWindowInsetObserver] is currently observing.
*/
@Suppress("MemberVisibilityCanBePrivate")
var isObserving: Boolean = false
private set
/**
* Start observing window insets from [view]. Make sure to call [stop] if required.
*
* @param windowInsetsAnimationsEnabled Whether to listen for [WindowInsetsAnimation]s, such as
* IME animations.
* @param consumeWindowInsets Whether to consume any [WindowInsetsCompat]s which are
* dispatched to the host view. Defaults to `true`.
*/
fun start(
consumeWindowInsets: Boolean = true,
windowInsetsAnimationsEnabled: Boolean = true,
): WindowInsets = RootWindowInsets().also {
observeInto(
windowInsets = it,
consumeWindowInsets = consumeWindowInsets,
windowInsetsAnimationsEnabled = windowInsetsAnimationsEnabled
)
}
internal fun observeInto(
windowInsets: RootWindowInsets,
consumeWindowInsets: Boolean,
windowInsetsAnimationsEnabled: Boolean,
) {
require(!isObserving) {
"start() called, but this ViewWindowInsetObserver is already observing"
}
ViewCompat.setOnApplyWindowInsetsListener(view) { _, wic ->
// Go through each inset type and update its layoutInsets from the
// WindowInsetsCompat values
windowInsets.statusBars.run {
layoutInsets.updateFrom(wic.getInsets(WindowInsetsCompat.Type.statusBars()))
isVisible = wic.isVisible(WindowInsetsCompat.Type.statusBars())
}
windowInsets.navigationBars.run {
layoutInsets.updateFrom(wic.getInsets(WindowInsetsCompat.Type.navigationBars()))
isVisible = wic.isVisible(WindowInsetsCompat.Type.navigationBars())
}
windowInsets.systemGestures.run {
layoutInsets.updateFrom(wic.getInsets(WindowInsetsCompat.Type.systemGestures()))
isVisible = wic.isVisible(WindowInsetsCompat.Type.systemGestures())
}
windowInsets.ime.run {
layoutInsets.updateFrom(wic.getInsets(WindowInsetsCompat.Type.ime()))
isVisible = wic.isVisible(WindowInsetsCompat.Type.ime())
}
windowInsets.displayCutout.run {
layoutInsets.updateFrom(wic.getInsets(WindowInsetsCompat.Type.displayCutout()))
isVisible = wic.isVisible(WindowInsetsCompat.Type.displayCutout())
}
if (consumeWindowInsets) WindowInsetsCompat.CONSUMED else wic
}
// Add an OnAttachStateChangeListener to request an inset pass each time we're attached
// to the window
view.addOnAttachStateChangeListener(attachListener)
if (windowInsetsAnimationsEnabled) {
ViewCompat.setWindowInsetsAnimationCallback(
view,
InnerWindowInsetsAnimationCallback(windowInsets)
)
} else {
ViewCompat.setWindowInsetsAnimationCallback(view, null)
}
if (view.isAttachedToWindow) {
// If the view is already attached, we can request an inset pass now
view.requestApplyInsets()
}
isObserving = true
}
/**
* Removes any listeners from the [view] so that we no longer observe inset changes.
*
* This is only required to be called from hosts which have a shorter lifetime than the [view].
* For example, if you're using [ViewWindowInsetObserver] from a `@Composable` function,
* you should call [stop] from an `onDispose` block, like so:
*
* ```
* DisposableEffect(view) {
* val observer = ViewWindowInsetObserver(view)
* // ...
* onDispose {
* observer.stop()
* }
* }
* ```
*
* Whereas if you're using this class from a fragment (or similar), it is not required to
* call this function since it will live as least as longer as the view.
*/
fun stop() {
require(isObserving) {
"stop() called, but this ViewWindowInsetObserver is not currently observing"
}
view.removeOnAttachStateChangeListener(attachListener)
ViewCompat.setOnApplyWindowInsetsListener(view, null)
isObserving = false
}
}
/**
* Applies any [WindowInsetsCompat] values to [LocalWindowInsets], which are then available
* within [content].
*
* If you're using this in fragments, you may wish to take a look at
* [ViewWindowInsetObserver] for a more optimal solution.
*
* @param windowInsetsAnimationsEnabled Whether to listen for [WindowInsetsAnimation]s, such as
* IME animations.
* @param consumeWindowInsets Whether to consume any [WindowInsetsCompat]s which are dispatched to
* the host view. Defaults to `true`.
*/
@Deprecated(
"""
accompanist/insets is deprecated.
For more migration information, please visit https://google.github.io/accompanist/insets/#migration
""",
replaceWith = ReplaceWith("content")
)
@Composable
fun ProvideWindowInsets(
consumeWindowInsets: Boolean = true,
windowInsetsAnimationsEnabled: Boolean = true,
content: @Composable () -> Unit
) {
val view = LocalView.current
val windowInsets = remember { RootWindowInsets() }
DisposableEffect(view) {
val observer = ViewWindowInsetObserver(view)
observer.observeInto(
windowInsets = windowInsets,
consumeWindowInsets = consumeWindowInsets,
windowInsetsAnimationsEnabled = windowInsetsAnimationsEnabled
)
onDispose { observer.stop() }
}
CompositionLocalProvider(LocalWindowInsets provides windowInsets) {
content()
}
}
private class InnerWindowInsetsAnimationCallback(
private val windowInsets: RootWindowInsets,
) : WindowInsetsAnimationCompat.Callback(DISPATCH_MODE_STOP) {
override fun onPrepare(animation: WindowInsetsAnimationCompat) {
// Go through each type and flag that an animation has started
if (animation.typeMask and WindowInsetsCompat.Type.ime() != 0) {
windowInsets.ime.onAnimationStart()
}
if (animation.typeMask and WindowInsetsCompat.Type.statusBars() != 0) {
windowInsets.statusBars.onAnimationStart()
}
if (animation.typeMask and WindowInsetsCompat.Type.navigationBars() != 0) {
windowInsets.navigationBars.onAnimationStart()
}
if (animation.typeMask and WindowInsetsCompat.Type.systemGestures() != 0) {
windowInsets.systemGestures.onAnimationStart()
}
if (animation.typeMask and WindowInsetsCompat.Type.displayCutout() != 0) {
windowInsets.displayCutout.onAnimationStart()
}
}
override fun onProgress(
platformInsets: WindowInsetsCompat,
runningAnimations: List<WindowInsetsAnimationCompat>
): WindowInsetsCompat {
// Update each inset type with the given parameters
windowInsets.ime.updateAnimation(
platformInsets = platformInsets,
runningAnimations = runningAnimations,
type = WindowInsetsCompat.Type.ime()
)
windowInsets.statusBars.updateAnimation(
platformInsets = platformInsets,
runningAnimations = runningAnimations,
type = WindowInsetsCompat.Type.statusBars()
)
windowInsets.navigationBars.updateAnimation(
platformInsets = platformInsets,
runningAnimations = runningAnimations,
type = WindowInsetsCompat.Type.navigationBars()
)
windowInsets.systemGestures.updateAnimation(
platformInsets = platformInsets,
runningAnimations = runningAnimations,
type = WindowInsetsCompat.Type.systemGestures()
)
windowInsets.displayCutout.updateAnimation(
platformInsets = platformInsets,
runningAnimations = runningAnimations,
type = WindowInsetsCompat.Type.displayCutout()
)
return platformInsets
}
private fun MutableWindowInsetsType.updateAnimation(
platformInsets: WindowInsetsCompat,
runningAnimations: List<WindowInsetsAnimationCompat>,
type: Int,
) {
// If there are animations of the given type...
if (runningAnimations.any { it.typeMask or type != 0 }) {
// Update our animated inset values
animatedInsets.updateFrom(platformInsets.getInsets(type))
// And update the animation fraction. We use the maximum animation progress of any
// ongoing animations for this type.
animationFraction = runningAnimations.maxOf { it.fraction }
}
}
override fun onEnd(animation: WindowInsetsAnimationCompat) {
// Go through each type and flag that an animation has ended
if (animation.typeMask and WindowInsetsCompat.Type.ime() != 0) {
windowInsets.ime.onAnimationEnd()
}
if (animation.typeMask and WindowInsetsCompat.Type.statusBars() != 0) {
windowInsets.statusBars.onAnimationEnd()
}
if (animation.typeMask and WindowInsetsCompat.Type.navigationBars() != 0) {
windowInsets.navigationBars.onAnimationEnd()
}
if (animation.typeMask and WindowInsetsCompat.Type.systemGestures() != 0) {
windowInsets.systemGestures.onAnimationEnd()
}
if (animation.typeMask and WindowInsetsCompat.Type.displayCutout() != 0) {
windowInsets.displayCutout.onAnimationEnd()
}
}
}
/**
* Holder of our root inset values.
*/
internal class RootWindowInsets : WindowInsets {
/**
* Inset values which match [WindowInsetsCompat.Type.systemGestures]
*/
override val systemGestures: MutableWindowInsetsType = MutableWindowInsetsType()
/**
* Inset values which match [WindowInsetsCompat.Type.navigationBars]
*/
override val navigationBars: MutableWindowInsetsType = MutableWindowInsetsType()
/**
* Inset values which match [WindowInsetsCompat.Type.statusBars]
*/
override val statusBars: MutableWindowInsetsType = MutableWindowInsetsType()
/**
* Inset values which match [WindowInsetsCompat.Type.ime]
*/
override val ime: MutableWindowInsetsType = MutableWindowInsetsType()
/**
* Inset values which match [WindowInsetsCompat.Type.displayCutout]
*/
override val displayCutout: MutableWindowInsetsType = MutableWindowInsetsType()
/**
* Inset values which match [WindowInsetsCompat.Type.systemBars]
*/
override val systemBars: WindowInsets.Type = derivedWindowInsetsTypeOf(statusBars, navigationBars)
}
/**
* Shallow-immutable implementation of [WindowInsets].
*/
internal class ImmutableWindowInsets(
override val systemGestures: WindowInsets.Type = WindowInsets.Type.Empty,
override val navigationBars: WindowInsets.Type = WindowInsets.Type.Empty,
override val statusBars: WindowInsets.Type = WindowInsets.Type.Empty,
override val ime: WindowInsets.Type = WindowInsets.Type.Empty,
override val displayCutout: WindowInsets.Type = WindowInsets.Type.Empty,
) : WindowInsets {
override val systemBars: WindowInsets.Type = derivedWindowInsetsTypeOf(statusBars, navigationBars)
}
@RequiresOptIn(message = "Animated Insets support is experimental. The API may be changed in the future.")
@Retention(AnnotationRetention.BINARY)
@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION)
annotation class ExperimentalAnimatedInsets
/**
* Composition local containing the current [WindowInsets].
*/
@Deprecated(
"""
accompanist/insets is deprecated.
The androidx.compose equivalent of LocalWindowInsets is the extensions on WindowInsets.
For more migration information, please visit https://google.github.io/accompanist/insets/#migration
"""
)
val LocalWindowInsets: ProvidableCompositionLocal<WindowInsets> =
staticCompositionLocalOf { WindowInsets.Empty }
| apache-2.0 |
AntonovAlexander/activecore | designs/rtl/ariele_test/hw/xbar_gen/src/gen_xbar.kt | 1 | 612 | import hwast.*
import ariele.*
fun main() {
println("xbar: generating")
val SLAVE_ADDR_WIDTH = 30
val SLAVE_SPACE_SIZE = 1L.shl(SLAVE_ADDR_WIDTH)
var map = addr_map()
for (i in 0..3) {
map.add(slave_entry((i * SLAVE_SPACE_SIZE).toString(), SLAVE_ADDR_WIDTH))
}
var xbar = ariele.xbar(("ariele_xbar"),
4,
32,
4,
hw_type(DATA_TYPE.BV_UNSIGNED, hw_dim_static(31, 0)),
hw_type(DATA_TYPE.BV_UNSIGNED, hw_dim_static(31, 0)),
map,
4,
4,
DEBUG_LEVEL.FULL)
xbar.export_to_sv("coregen", DEBUG_LEVEL.FULL)
} | apache-2.0 |
chaojimiaomiao/colorful_wechat | src/main/kotlin/com/rarnu/tophighlight/api/LocalApi.kt | 1 | 754 | package com.rarnu.tophighlight.api
import android.content.Context
import android.preference.PreferenceManager
/**
* Created by rarnu on 2/25/17.
*/
object LocalApi {
var ctx: Context? = null
private val KEY_USER_PROFILE_ID = "user_profile_id"
var userId: Int
get() {
var r = 0
if (ctx != null) {
val pref = PreferenceManager.getDefaultSharedPreferences(ctx)
r = pref.getInt(KEY_USER_PROFILE_ID, 0)
}
return r
}
set(value) {
if (ctx != null) {
val pref = PreferenceManager.getDefaultSharedPreferences(ctx)
pref.edit().putInt(KEY_USER_PROFILE_ID, value).apply()
}
}
} | gpl-3.0 |
MichaelRocks/grip | library/src/main/java/io/michaelrocks/grip/FileRegistry.kt | 1 | 3662 | /*
* Copyright 2021 Michael Rozumyanskiy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.michaelrocks.grip
import io.michaelrocks.grip.commons.closeQuietly
import io.michaelrocks.grip.commons.immutable
import io.michaelrocks.grip.io.FileSource
import io.michaelrocks.grip.mirrors.Type
import io.michaelrocks.grip.mirrors.getObjectTypeByInternalName
import java.io.Closeable
import java.io.File
import java.util.ArrayList
import java.util.HashMap
import java.util.LinkedHashMap
interface FileRegistry {
operator fun contains(file: File): Boolean
operator fun contains(type: Type.Object): Boolean
fun classpath(): Collection<File>
fun readClass(type: Type.Object): ByteArray
fun findTypesForFile(file: File): Collection<Type.Object>
fun findFileForType(type: Type.Object): File?
}
internal class FileRegistryImpl(
classpath: Iterable<File>,
private val fileSourceFactory: FileSource.Factory
) : FileRegistry, Closeable {
private val sources = LinkedHashMap<File, FileSource>()
private val filesByTypes = HashMap<Type.Object, File>()
private val typesByFiles = HashMap<File, MutableCollection<Type.Object>>()
init {
classpath.forEach {
it.canonicalFile.let { file ->
if (file !in sources) {
val fileSource = fileSourceFactory.createFileSource(file)
sources.put(file, fileSource)
fileSource.listFiles { path, fileType ->
if (fileType == FileSource.EntryType.CLASS) {
val name = path.replace('\\', '/').substringBeforeLast(".class")
val type = getObjectTypeByInternalName(name)
filesByTypes.put(type, file)
typesByFiles.getOrPut(file) { ArrayList() } += type
}
}
}
}
}
check(!sources.isEmpty()) { "Classpath is empty" }
}
override fun contains(file: File): Boolean {
checkNotClosed()
return file.canonicalFile in sources
}
override fun contains(type: Type.Object): Boolean {
checkNotClosed()
return type in filesByTypes
}
override fun classpath(): Collection<File> {
checkNotClosed()
return sources.keys.immutable()
}
override fun readClass(type: Type.Object): ByteArray {
checkNotClosed()
val file = filesByTypes.getOrElse(type) {
throw IllegalArgumentException("Unable to find a file for ${type.internalName}")
}
val fileSource = sources.getOrElse(file) {
throw IllegalArgumentException("Unable to find a source for ${type.internalName}")
}
return fileSource.readFile("${type.internalName}.class")
}
override fun findTypesForFile(file: File): Collection<Type.Object> {
require(contains(file)) { "File $file is not added to the registry" }
return typesByFiles[file.canonicalFile]?.immutable() ?: emptyList()
}
override fun findFileForType(type: Type.Object): File? {
return filesByTypes[type]
}
override fun close() {
sources.values.forEach { it.closeQuietly() }
sources.clear()
filesByTypes.clear()
typesByFiles.clear()
}
private fun checkNotClosed() {
check(!sources.isEmpty()) { "FileRegistry was closed" }
}
}
| apache-2.0 |
FountainMC/FountainAPI | src/main/kotlin/org/fountainmc/api/world/block/WoolBlock.kt | 1 | 166 | package org.fountainmc.api.world.block
import org.fountainmc.api.Color
interface WoolBlock : ColoredBlock {
override fun withColor(color: Color): WoolBlock
}
| mit |
code-disaster/lwjgl3 | modules/lwjgl/nanovg/src/templates/kotlin/nanovg/templates/nanovg_gles2.kt | 4 | 3291 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package nanovg.templates
import org.lwjgl.generator.*
import nanovg.*
val nanovg_gles2 = "NanoVGGLES2".dependsOn(Module.OPENGLES)?.nativeClass(Module.NANOVG, prefix = "NVG") {
includeNanoVGAPI("""#define NANOVG_GLES2_IMPLEMENTATION
#include "nanovg.h"
#include "nanovg_gl.h"
#include "nanovg_gl_utils.h"""")
documentation = "Implementation of the NanoVG API using OpenGL ES 2.0."
val CreateFlags = EnumConstant(
"Create flags.",
"ANTIALIAS".enum("Flag indicating if geometry based anti-aliasing is used (may not be needed when using MSAA).", "1<<0"),
"STENCIL_STROKES".enum(
"""
Flag indicating if strokes should be drawn using stencil buffer. The rendering will be a little slower, but path overlaps (i.e. self-intersecting
or sharp turns) will be drawn just once.
""",
"1<<1"
),
"DEBUG".enum("Flag indicating that additional debug checks are done.", "1<<2")
).javaDocLinks
EnumConstant(
"These are additional flags on top of NVGimageFlags.",
"IMAGE_NODELETE".enum("Do not delete GL texture handle.", "1<<16")
)
val ctx = NVGcontext.p("ctx", "the NanoVG context")
NativeName("nvglCreateImageFromHandleGLES2")..int(
"lCreateImageFromHandle",
"Creates a NanoVG image from an OpenGL texture.",
ctx,
GLuint("textureId", "the OpenGL texture id"),
int("w", "the image width"),
int("h", "the image height"),
int("flags", "the image flags"),
returnDoc = "a handle to the image"
)
NativeName("nvglImageHandleGLES2")..GLuint(
"lImageHandle",
"Returns the OpenGL texture id associated with a NanoVG image.",
ctx,
int("image", "the image handle")
)
NativeName("nvgCreateGLES2")..NVGcontext.p(
"Create",
"""
Creates a NanoVG context with an OpenGL ES 2.0 rendering back-end.
An OpenGL ES 2.0+ context must be current in the current thread when this function is called and the returned NanoVG context may only be used in
the thread in which that OpenGL context is current.
""",
JNI_ENV,
int("flags", "the context flags", CreateFlags)
)
NativeName("nvgDeleteGLES2")..void(
"Delete",
"Deletes a NanoVG context created with #Create().",
ctx
)
NativeName("nvgluCreateFramebufferGLES2")..NVGLUframebuffer.p(
"luCreateFramebuffer",
"Creates a framebuffer object to render to.",
ctx,
int("w", "the framebuffer width"),
int("h", "the framebuffer height"),
int("imageFlags", "the image flags")
)
NativeName("nvgluBindFramebufferGLES2")..void(
"luBindFramebuffer",
"Binds the framebuffer object associated with the specified ##NVGLUFramebuffer.",
ctx,
Input..nullable..NVGLUframebuffer.p("fb", "the framebuffer to bind")
)
NativeName("nvgluDeleteFramebufferGLES2")..void(
"luDeleteFramebuffer",
"Deletes an ##NVGLUFramebuffer.",
ctx,
Input..NVGLUframebuffer.p("fb", "the framebuffer to delete")
)
} | bsd-3-clause |
McMoonLakeDev/MoonLake | API/src/main/kotlin/com/mcmoonlake/api/packet/PacketStatus.kt | 1 | 796 | /*
* Copyright (C) 2016-Present The MoonLake ([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.mcmoonlake.api.packet
interface PacketStatus : Packet {
}
| gpl-3.0 |
mdanielwork/intellij-community | plugins/git4idea/src/git4idea/ignore/GitIgnoredFileContentProvider.kt | 1 | 1737 | // 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 git4idea.ignore
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.VcsKey
import com.intellij.openapi.vcs.changes.IgnoredFileContentProvider
import com.intellij.openapi.vcs.changes.IgnoredFileProvider
import com.intellij.openapi.vfs.VirtualFile
import git4idea.GitVcs
import git4idea.repo.GitRepositoryFiles.GITIGNORE
import java.lang.System.lineSeparator
open class GitIgnoredFileContentProvider(private val project: Project) : IgnoredFileContentProvider {
override fun getSupportedVcs(): VcsKey = GitVcs.getKey()
override fun getFileName() = GITIGNORE
override fun buildIgnoreFileContent(ignoreFileRoot: VirtualFile, ignoredFileProviders: Array<IgnoredFileProvider>): String {
val content = StringBuilder()
val lineSeparator = lineSeparator()
for (i in ignoredFileProviders.indices) {
val provider = ignoredFileProviders[i]
val ignoredFileMasks = provider.getIgnoredFilesMasks(project, ignoreFileRoot)
if (ignoredFileMasks.isEmpty()) continue
if (!content.isEmpty()) {
content.append(lineSeparator).append(lineSeparator)
}
val description = provider.masksGroupDescription
if (description.isNotBlank()) {
content.append(prependCommentHashCharacterIfNeeded(description))
content.append(lineSeparator)
}
content.append(ignoredFileMasks.joinToString(lineSeparator))
}
return content.toString()
}
private fun prependCommentHashCharacterIfNeeded(description: String): String =
if (description.startsWith("#")) description else "# $description"
}
| apache-2.0 |
Apolline-Lille/apolline-android | app/src/main/java/science/apolline/root/RootFragment.kt | 1 | 536 | package science.apolline.root
import android.os.Bundle
import android.support.v4.app.Fragment
import com.github.salomonbrys.kodein.KodeinInjected
import com.github.salomonbrys.kodein.KodeinInjector
import com.github.salomonbrys.kodein.android.appKodein
/**
* Created by sparow on 2/25/2018.
*/
open class RootFragment : Fragment(), KodeinInjected {
override val injector = KodeinInjector()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
inject(appKodein())
}
} | gpl-3.0 |
dhis2/dhis2-android-sdk | core/src/main/java/org/hisp/dhis/android/core/arch/fields/internal/FieldsHelper.kt | 1 | 3866 | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.arch.fields.internal
import org.hisp.dhis.android.core.arch.api.fields.internal.Field
import org.hisp.dhis.android.core.arch.api.fields.internal.NestedField
import org.hisp.dhis.android.core.arch.api.fields.internal.Property
import org.hisp.dhis.android.core.common.BaseIdentifiableObject
import org.hisp.dhis.android.core.common.BaseNameableObject
import org.hisp.dhis.android.core.common.ObjectWithUid
@Suppress("TooManyFunctions")
internal class FieldsHelper<O> {
fun <T> field(fieldName: String): Property<O, T> {
return Field.create(fieldName)
}
fun <T> nestedField(fieldName: String): NestedField<O, T> {
return NestedField.create(fieldName)
}
fun uid(): Field<O, String> {
return Field.create(BaseIdentifiableObject.UID)
}
fun code(): Field<O, String> {
return Field.create(BaseIdentifiableObject.CODE)
}
fun name(): Field<O, String> {
return Field.create(BaseIdentifiableObject.NAME)
}
fun displayName(): Field<O, String> {
return Field.create(BaseIdentifiableObject.DISPLAY_NAME)
}
fun created(): Field<O, String> {
return Field.create(BaseIdentifiableObject.CREATED)
}
fun lastUpdated(): Field<O, String> {
return Field.create(BaseIdentifiableObject.LAST_UPDATED)
}
fun deleted(): Field<O, String> {
return Field.create(BaseIdentifiableObject.DELETED)
}
fun nestedFieldWithUid(fieldName: String): NestedField<O, *> {
val nested = nestedField<ObjectWithUid>(fieldName)
return nested.with(ObjectWithUid.uid)
}
fun getIdentifiableFields(): List<Property<O, *>> {
return listOf<Property<O, *>>(
uid(),
code(),
name(),
displayName(),
created(),
lastUpdated(),
deleted()
)
}
fun getNameableFields(): List<Property<O, *>> {
return getIdentifiableFields() + listOf<Property<O, *>>(
this.field<O>(BaseNameableObject.SHORT_NAME),
this.field<O>(BaseNameableObject.DISPLAY_SHORT_NAME),
this.field<O>(BaseNameableObject.DESCRIPTION),
this.field<O>(BaseNameableObject.DISPLAY_DESCRIPTION)
)
}
}
| bsd-3-clause |
dahlstrom-g/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/editor/lists/ListItemIndentUnindentHandlerBase.kt | 7 | 3912 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.plugins.markdown.editor.lists
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.editor.Caret
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.actionSystem.EditorActionHandler
import com.intellij.openapi.editor.actionSystem.EditorWriteActionHandler
import com.intellij.openapi.util.registry.Registry
import com.intellij.psi.PsiDocumentManager
import com.intellij.refactoring.suggested.endOffset
import org.intellij.plugins.markdown.editor.lists.ListUtils.getListItemAtLine
import org.intellij.plugins.markdown.lang.psi.impl.MarkdownFile
import org.intellij.plugins.markdown.lang.psi.impl.MarkdownListItem
import org.intellij.plugins.markdown.settings.MarkdownSettings
/**
* This is a base class for classes, handling indenting/unindenting of list items.
* It collects selected items (or the ones the carets are inside) and calls [doIndentUnindent] and [updateNumbering] on them one by one.
*/
internal abstract class ListItemIndentUnindentHandlerBase(private val baseHandler: EditorActionHandler?) : EditorWriteActionHandler.ForEachCaret() {
override fun isEnabledForCaret(editor: Editor, caret: Caret, dataContext: DataContext?): Boolean =
baseHandler?.isEnabled(editor, caret, dataContext) == true
override fun executeWriteAction(editor: Editor, caret: Caret?, dataContext: DataContext?) {
val enabled = editor.project?.let { MarkdownSettings.getInstance(it) }?.isEnhancedEditingEnabled == true
if (caret == null || !enabled || !doExecuteAction(editor, caret)) {
baseHandler?.execute(editor, caret, dataContext)
}
}
private fun doExecuteAction(editor: Editor, caret: Caret): Boolean {
val project = editor.project ?: return false
val psiDocumentManager = PsiDocumentManager.getInstance(project)
val document = editor.document
val file = psiDocumentManager.getPsiFile(document) as? MarkdownFile ?: return false
val firstLinesOfSelectedItems = getFirstLinesOfSelectedItems(caret, document, file)
// use lines instead of items, because items may become invalid before used
var indentPerformed = false
for (line in firstLinesOfSelectedItems) {
psiDocumentManager.commitDocument(document)
val item = file.getListItemAtLine(line, document)!!
if (!doIndentUnindent(item, file, document)) {
continue
}
indentPerformed = true
if (Registry.`is`("markdown.lists.renumber.on.type.enable")) {
psiDocumentManager.commitDocument(document)
@Suppress("name_shadowing") // item is not valid anymore, but line didn't change
val item = file.getListItemAtLine(line, document)!!
updateNumbering(item, file, document)
}
}
return firstLinesOfSelectedItems.isNotEmpty() && indentPerformed
}
private fun getFirstLinesOfSelectedItems(caret: Caret, document: Document, file: MarkdownFile): List<Int> {
var line = document.getLineNumber(caret.selectionStart)
val lastLine = if (caret.hasSelection()) document.getLineNumber(caret.selectionEnd - 1) else line
val lines = mutableListOf<Int>()
while (line <= lastLine) {
val item = file.getListItemAtLine(line, document)
if (item == null) {
line++
continue
}
lines.add(line)
line = document.getLineNumber(item.endOffset) + 1
}
return lines
}
/** If this method returns `true`, then the document is committed and [updateNumbering] is called */
protected abstract fun doIndentUnindent(item: MarkdownListItem, file: MarkdownFile, document: Document): Boolean
protected abstract fun updateNumbering(item: MarkdownListItem, file: MarkdownFile, document: Document)
}
| apache-2.0 |
dahlstrom-g/intellij-community | plugins/kotlin/idea/tests/testData/formatter/trailingComma/collectionLiteralExpression/CollectionLiteralInAnnotation.call.after.inv.kt | 24 | 1366 | // SET_TRUE: ALLOW_TRAILING_COMMA
@Anno([1])
fun a() = Unit
@Anno([1])
fun a() = Unit
@Anno(
[1
]
)
fun a() = Unit
@Anno(
[
1,
]
)
fun a() = Unit
@Anno(
[
1]
)
fun a() = Unit
@Anno([1, 2])
fun a() = Unit
@Anno([1, 2])
fun a() = Unit
@Anno(
[1, 2
]
)
fun a() = Unit
@Anno(
[
1, 2,
]
)
fun a() = Unit
@Anno(
[
1, 2]
)
fun a() = Unit
@Anno([1, 2, 2])
fun a() = Unit
@Anno([1, 2, 2])
fun a() = Unit
@Anno(
["1"
]
)
fun a() = Unit
@Anno(
[
1,
]
)
fun a() = Unit
@Anno(
[
1, 2, 2]
)
fun a() = Unit
@Anno(
[1/*
*/]
)
fun a() = Unit
@Anno(
[
1, //dw
]
)
fun a() = Unit
@Anno(
[1 // ds
]
)
fun a() = Unit
@Anno(
[
/*
*/ // d
1,
/*
*/
/*
*/
]
)
fun a() = Unit
@Anno(
[
/*
*/ 1]
)
fun a() = Unit
@Anno(
[1/*
*/, 2]
)
fun a() = Unit
@Anno(
[
1, 2,
/*
*/
/*
*/
]
)
fun a() = Unit
@Anno(
[/*
*/1, 2
]
)
fun a() = Unit
@Anno(
["1"
]
)
fun a() = Unit
@Anno(
[
1,
]
)
fun a() = Unit
@Anno(
[
1, 2 /*
*/]
)
fun a() = Unit
@Component(
modules = [
AppModule::class, DataModule::class,
DomainModule::class
],
)
fun b() = Unit
| apache-2.0 |
dahlstrom-g/intellij-community | platform/platform-impl/src/com/intellij/openapi/options/newEditor/CopySettingsPathAction.kt | 4 | 6112 | // 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.options.newEditor
import com.google.common.net.UrlEscapers
import com.intellij.CommonBundle
import com.intellij.ide.IdeBundle
import com.intellij.idea.ActionsBundle
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.PlatformCoreDataKeys.CONTEXT_COMPONENT
import com.intellij.openapi.ide.CopyPasteManager
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.util.NlsActions
import com.intellij.openapi.util.SystemInfo.isMac
import com.intellij.ui.ComponentUtil
import com.intellij.ui.tabs.JBTabs
import com.intellij.util.PlatformUtils
import com.intellij.util.ui.TextTransferable
import org.jetbrains.ide.BuiltInServerManager
import java.awt.datatransfer.Transferable
import java.awt.event.ActionEvent
import java.util.*
import java.util.function.Supplier
import javax.swing.*
import javax.swing.border.TitledBorder
private val pathActionName: String
get() = ActionsBundle.message(if (isMac) "action.CopySettingsPath.mac.text" else "action.CopySettingsPath.text")
internal class CopySettingsPathAction : AnAction(pathActionName, ActionsBundle.message("action.CopySettingsPath.description"), null), DumbAware {
init {
isEnabledInModalContext = true
}
companion object {
@JvmStatic
fun createSwingActions(supplier: Supplier<Collection<String>>): List<Action> {
return listOf(
createSwingAction("CopySettingsPath", pathActionName) { copy(supplier.get()) },
// disable until REST API is not able to delegate to proper IDE
//createSwingAction(null, "Copy ${CommonBundle.settingsTitle()} Link") {
// copyLink(supplier, isHttp = true)
//},
createSwingAction(null, IdeBundle.message("action.copy.link.text", CommonBundle.settingsTitle())) {
copyLink(supplier, isHttp = false)
}
)
}
@JvmStatic
fun createTransferable(names: Collection<String>): Transferable? {
if (names.isEmpty()) {
return null
}
val prefix = if (isMac) CommonBundle.message("action.settings.path.mac") else CommonBundle.message("action.settings.path")
val sb = StringBuilder(prefix)
for (name in names) {
sb.append(" | ").append(name)
}
return TextTransferable(sb)
}
}
override fun update(event: AnActionEvent) {
val component = event.getData(CONTEXT_COMPONENT)
val editor = ComponentUtil.getParentOfType(SettingsEditor::class.java, component)
event.presentation.isEnabledAndVisible = editor != null
}
override fun actionPerformed(event: AnActionEvent) {
var component = event.getData(CONTEXT_COMPONENT)
if (component is JTree) {
ComponentUtil.getParentOfType(SettingsTreeView::class.java, component)?.let { settingsTreeView ->
settingsTreeView.createTransferable(event.inputEvent)?.let {
CopyPasteManager.getInstance().setContents(it)
}
return
}
}
val names = ComponentUtil.getParentOfType(SettingsEditor::class.java, component)?.pathNames ?: return
if (names.isEmpty()) {
return
}
val inner = ComponentUtil.getParentOfType(ConfigurableEditor::class.java, component)
if (inner != null) {
val label = getTextLabel(component)
val path = ArrayDeque<String>()
while (component != null && component !== inner) {
if (component is JBTabs) {
component.selectedInfo?.let {
path.addFirst(it.text)
}
}
if (component is JTabbedPane) {
path.addFirst(component.getTitleAt(component.selectedIndex))
}
if (component is JComponent) {
val border = component.border
if (border is TitledBorder) {
val title = border.title
if (!title.isNullOrEmpty()) {
path.addFirst(title)
}
}
}
component = component.parent
}
names.addAll(path)
if (label != null) {
names.add(label)
}
}
copy(names)
}
}
private fun copy(names: Collection<String>): Boolean {
val transferable = CopySettingsPathAction.createTransferable(names)
if (transferable == null) {
return false
}
CopyPasteManager.getInstance().setContents(transferable)
return true
}
private fun getTextLabel(component: Any?): String? {
if (component is JToggleButton) {
val text = component.text
if (!text.isNullOrEmpty()) {
return text
}
}
// find corresponding label
if (component is JLabel) {
val text = component.text
if (!text.isNullOrEmpty()) {
return text
}
}
else if (component is JComponent) {
return getTextLabel(component.getClientProperty("labeledBy"))
}
return null
}
private inline fun createSwingAction(id: String?, @NlsActions.ActionText name: String, crossinline performer: () -> Unit): Action {
val action = object : AbstractAction(name) {
override fun actionPerformed(event: ActionEvent) {
performer()
}
}
if (id != null) {
ActionManager.getInstance().getKeyboardShortcut(id)?.let {
action.putValue(Action.ACCELERATOR_KEY, it.firstKeyStroke)
}
}
return action
}
private fun copyLink(supplier: Supplier<Collection<String>>, isHttp: Boolean) {
val builder = StringBuilder()
if (isHttp) {
builder
.append("http://localhost:")
.append(BuiltInServerManager.getInstance().port)
.append("/api")
}
else {
builder.append("jetbrains://").append(PlatformUtils.getPlatformPrefix())
}
builder.append("/settings?name=")
// -- is used as separator to avoid ugly URL due to percent encoding (| encoded as %7C, but - encoded as is)
supplier.get().joinTo(builder, "--", transform = UrlEscapers.urlFormParameterEscaper()::escape)
CopyPasteManager.getInstance().setContents(TextTransferable(builder))
} | apache-2.0 |
dahlstrom-g/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/rename/quotedToNonQuotedCaretAtTheEnd/before/test.kt | 13 | 74 | fun `fun`/*rename*/(n: Int) {
}
fun test() {
`fun`(1)
`fun`(2)
} | apache-2.0 |
dahlstrom-g/intellij-community | plugins/kotlin/base/fe10/obsolete-compat/src/org/jetbrains/kotlin/idea/core/ModuleUtils.kt | 2 | 1384 | // 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.core
import com.intellij.facet.FacetManager
import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider
import com.intellij.openapi.module.Module
import org.jetbrains.kotlin.analyzer.ModuleInfo
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.ModuleSourceInfo
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.PlatformModuleInfo
@Deprecated("Use 'org.jetbrains.kotlin.idea.base.util.isAndroidModule' instead")
fun Module.isAndroidModule(modelsProvider: IdeModifiableModelsProvider? = null): Boolean {
val facetModel = modelsProvider?.getModifiableFacetModel(this) ?: FacetManager.getInstance(this)
val facets = facetModel.allFacets
return facets.any { it.javaClass.simpleName == "AndroidFacet" }
}
@Deprecated("Use 'org.jetbrains.kotlin.idea.base.projectStructure.unwrapModuleSourceInfo()' instead")
@Suppress("unused", "DEPRECATION", "DeprecatedCallableAddReplaceWith")
fun ModuleInfo.unwrapModuleSourceInfo(): org.jetbrains.kotlin.idea.caches.project.ModuleSourceInfo? {
return when (this) {
is ModuleSourceInfo -> this
is PlatformModuleInfo -> this.platformModule
else -> null
}
} | apache-2.0 |
dahlstrom-g/intellij-community | platform/lang-impl/testSources/com/intellij/openapi/roots/ui/configuration/SdkComboBoxTest.kt | 12 | 6834 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.roots.ui.configuration
import com.intellij.openapi.projectRoots.ProjectJdkTable
import com.intellij.openapi.projectRoots.Sdk
class SdkComboBoxTest : SdkComboBoxTestCase() {
fun `test simple usage`() {
val sdk1 = createAndRegisterSdk()
val sdk2 = createAndRegisterSdk(isProjectSdk = true)
val sdk3 = createAndRegisterSdk()
val sdk4 = TestSdkGenerator.createNextSdk()
val sdk5 = createAndRegisterDependentSdk()
val comboBox = createJdkComboBox()
assertComboBoxContent(comboBox)
.item<SdkListItem.ProjectSdkItem> { assertEquals(sdk2, comboBox.getProjectSdk()) }
.item<SdkListItem.SdkItem> { assertSdkItem(sdk1, it) }
.item<SdkListItem.SdkItem> { assertSdkItem(sdk2, it) }
.item<SdkListItem.SdkItem> { assertSdkItem(sdk3, it) }
.item<SdkListItem.SdkItem> { assertSdkItem(sdk5.parent, it) }
.nothing()
assertComboBoxSelection<SdkListItem.NoneSdkItem>(comboBox, null)
comboBox.setSelectedSdk(sdk1)
assertComboBoxSelection<SdkListItem.SdkItem>(comboBox, sdk1)
comboBox.setSelectedSdk(sdk2)
assertComboBoxSelection<SdkListItem.SdkItem>(comboBox, sdk2)
comboBox.setSelectedSdk(sdk3)
assertComboBoxSelection<SdkListItem.SdkItem>(comboBox, sdk3)
comboBox.setSelectedSdk(sdk4)
assertComboBoxSelection<SdkListItem.InvalidSdkItem>(comboBox, null)
comboBox.setSelectedSdk(sdk1.name)
assertComboBoxSelection<SdkListItem.SdkItem>(comboBox, sdk1)
comboBox.setSelectedSdk(sdk2.name)
assertComboBoxSelection<SdkListItem.SdkItem>(comboBox, sdk2)
comboBox.setSelectedSdk(sdk3.name)
assertComboBoxSelection<SdkListItem.SdkItem>(comboBox, sdk3)
comboBox.setSelectedSdk(sdk4.name)
assertComboBoxSelection<SdkListItem.InvalidSdkItem>(comboBox, null)
comboBox.selectedItem = SdkListItem.NoneSdkItem()
assertComboBoxSelection<SdkListItem.NoneSdkItem>(comboBox, null)
assertComboBoxContent(comboBox)
.item<SdkListItem.NoneSdkItem>(isSelected = true)
.item<SdkListItem.ProjectSdkItem> { assertEquals(sdk2, comboBox.getProjectSdk()) }
.item<SdkListItem.InvalidSdkItem> { assertEquals(sdk4.name, it.sdkName) }
.item<SdkListItem.SdkItem> { assertSdkItem(sdk1, it) }
.item<SdkListItem.SdkItem> { assertSdkItem(sdk2, it) }
.item<SdkListItem.SdkItem> { assertSdkItem(sdk3, it) }
.item<SdkListItem.SdkItem> { assertSdkItem(sdk5.parent, it) }
.nothing()
comboBox.setSelectedSdk(sdk5)
assertComboBoxSelection<SdkListItem.InvalidSdkItem>(comboBox, null)
assertComboBoxContent(comboBox)
.item<SdkListItem.NoneSdkItem>()
.item<SdkListItem.ProjectSdkItem> { assertEquals(sdk2, comboBox.getProjectSdk()) }
.item<SdkListItem.InvalidSdkItem>(isSelected = true) { assertEquals(sdk5.name, it.sdkName) }
.item<SdkListItem.SdkItem> { assertSdkItem(sdk1, it) }
.item<SdkListItem.SdkItem> { assertSdkItem(sdk2, it) }
.item<SdkListItem.SdkItem> { assertSdkItem(sdk3, it) }
.item<SdkListItem.SdkItem> { assertSdkItem(sdk5.parent, it) }
.nothing()
comboBox.setSelectedItem(SdkListItem.ProjectSdkItem())
assertComboBoxSelection<SdkListItem.ProjectSdkItem>(comboBox, sdk2)
comboBox.setSelectedItem(SdkListItem.NoneSdkItem())
assertComboBoxSelection<SdkListItem.NoneSdkItem>(comboBox, null)
comboBox.setSelectedItem(SdkListItem.InvalidSdkItem("invalid sdk"))
assertComboBoxSelection<SdkListItem.InvalidSdkItem>(comboBox, null)
assertComboBoxContent(comboBox)
.item<SdkListItem.NoneSdkItem>()
.item<SdkListItem.ProjectSdkItem> { assertEquals(sdk2, comboBox.getProjectSdk()) }
.item<SdkListItem.InvalidSdkItem>(isSelected = true) { assertEquals("invalid sdk", it.sdkName) }
.item<SdkListItem.SdkItem> { assertSdkItem(sdk1, it) }
.item<SdkListItem.SdkItem> { assertSdkItem(sdk2, it) }
.item<SdkListItem.SdkItem> { assertSdkItem(sdk3, it) }
.item<SdkListItem.SdkItem> { assertSdkItem(sdk5.parent, it) }
.nothing()
}
fun `test combobox actions`() {
val comboBox = createJdkComboBox()
.withOpenDropdownPopup()
assertComboBoxContent(comboBox)
.item<SdkListItem.ActionItem> { assertActionItem(SdkListItem.ActionRole.DOWNLOAD, TestSdkType, it) }
.item<SdkListItem.ActionItem> { assertActionItem(SdkListItem.ActionRole.ADD, TestSdkType, it) }
.nothing()
val download1 = comboBox.touchDownloadAction()
val download2 = comboBox.touchDownloadAction()
val download3 = comboBox.touchDownloadAction()
val download4 = comboBox.touchDownloadAction()
assertComboBoxContent(comboBox)
.item<SdkListItem.SdkItem> { assertSdkItem(download1, it) }
.item<SdkListItem.SdkItem> { assertSdkItem(download2, it) }
.item<SdkListItem.SdkItem> { assertSdkItem(download3, it) }
.item<SdkListItem.SdkItem>(isSelected = true) { assertSdkItem(download4, it) }
.item<SdkListItem.ActionItem> { assertActionItem(SdkListItem.ActionRole.DOWNLOAD, TestSdkType, it) }
.item<SdkListItem.ActionItem> { assertActionItem(SdkListItem.ActionRole.ADD, TestSdkType, it) }
.nothing()
val add1 = comboBox.touchAddAction()
val add2 = comboBox.touchAddAction()
val add3 = comboBox.touchAddAction()
val add4 = comboBox.touchAddAction()
assertComboBoxContent(comboBox)
.item<SdkListItem.SdkItem> { assertSdkItem(download1, it) }
.item<SdkListItem.SdkItem> { assertSdkItem(download2, it) }
.item<SdkListItem.SdkItem> { assertSdkItem(download3, it) }
.item<SdkListItem.SdkItem> { assertSdkItem(download4, it) }
.item<SdkListItem.SdkItem> { assertSdkItem(add1, it) }
.item<SdkListItem.SdkItem> { assertSdkItem(add2, it) }
.item<SdkListItem.SdkItem> { assertSdkItem(add3, it) }
.item<SdkListItem.SdkItem>(isSelected = true) { assertSdkItem(add4, it) }
.item<SdkListItem.ActionItem> { assertActionItem(SdkListItem.ActionRole.DOWNLOAD, TestSdkType, it) }
.item<SdkListItem.ActionItem> { assertActionItem(SdkListItem.ActionRole.ADD, TestSdkType, it) }
.nothing()
assertCollectionContent(comboBox.model.sdksModel.projectSdks.values.sortedBy { it.name })
.element<Sdk> { assertSdk(download1, it) }
.element<Sdk> { assertSdk(download2, it) }
.element<Sdk> { assertSdk(download3, it) }
.element<Sdk> { assertSdk(download4, it) }
.element<Sdk> { assertSdk(add1, it) }
.element<Sdk> { assertSdk(add2, it) }
.element<Sdk> { assertSdk(add3, it) }
.element<Sdk> { assertSdk(add4, it) }
.nothing()
assertCollectionContent(ProjectJdkTable.getInstance().getSdksOfType(TestSdkType))
.nothing()
}
} | apache-2.0 |
dahlstrom-g/intellij-community | plugins/settings-sync/src/com/intellij/settingsSync/SettingsSyncEvents.kt | 5 | 1425 | package com.intellij.settingsSync
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.util.EventDispatcher
internal class SettingsSyncEvents : Disposable {
private val settingsChangeDispatcher = EventDispatcher.create(SettingsChangeListener::class.java)
private val enabledStateChangeDispatcher = EventDispatcher.create(SettingsSyncEnabledStateListener::class.java)
fun addSettingsChangedListener(settingsChangeListener: SettingsChangeListener) {
settingsChangeDispatcher.addListener(settingsChangeListener)
}
fun fireSettingsChanged(event: SyncSettingsEvent) {
settingsChangeDispatcher.multicaster.settingChanged(event)
}
fun addEnabledStateChangeListener(listener: SettingsSyncEnabledStateListener, parentDisposable: Disposable? = null) {
if (parentDisposable != null) enabledStateChangeDispatcher.addListener(listener, parentDisposable)
else enabledStateChangeDispatcher.addListener(listener, this)
}
fun fireEnabledStateChanged(syncEnabled: Boolean) {
enabledStateChangeDispatcher.multicaster.enabledStateChanged(syncEnabled)
}
companion object {
fun getInstance(): SettingsSyncEvents = ApplicationManager.getApplication().getService(SettingsSyncEvents::class.java)
}
override fun dispose() {
settingsChangeDispatcher.listeners.clear()
enabledStateChangeDispatcher.listeners.clear()
}
} | apache-2.0 |
dahlstrom-g/intellij-community | plugins/groovy/src/org/jetbrains/plugins/groovy/util/GroovySelectModuleStep.kt | 12 | 969 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.util
import com.intellij.openapi.module.Module
import com.intellij.openapi.ui.popup.PopupStep
import com.intellij.openapi.ui.popup.util.BaseListPopupStep
import com.intellij.util.PlatformIcons
import org.jetbrains.plugins.groovy.GroovyBundle.message
class GroovySelectModuleStep(
modules: List<Module>,
private val consumer: (Module) -> Unit
) : BaseListPopupStep<Module>(message("select.module.popup.title"), modules, PlatformIcons.CONTENT_ROOT_ICON_CLOSED) {
override fun getTextFor(value: Module): String = value.name
override fun getIndexedString(value: Module): String = value.name
override fun isSpeedSearchEnabled(): Boolean = true
override fun onChosen(selectedValue: Module, finalChoice: Boolean): PopupStep<*>? {
consumer(selectedValue)
return null
}
}
| apache-2.0 |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/actions/internal/FindImplicitNothingAction.kt | 2 | 7105 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.actions.internal
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileVisitor
import com.intellij.psi.PsiManager
import com.intellij.usageView.UsageInfo
import com.intellij.usages.UsageInfo2UsageAdapter
import com.intellij.usages.UsageTarget
import com.intellij.usages.UsageViewManager
import com.intellij.usages.UsageViewPresentation
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.builtins.getReturnTypeFromFunctionType
import org.jetbrains.kotlin.builtins.isFunctionType
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.util.application.isApplicationInternalMode
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.resolve.calls.util.getCalleeExpressionIfAny
import org.jetbrains.kotlin.types.KotlinType
import javax.swing.SwingUtilities
class FindImplicitNothingAction : AnAction() {
companion object {
private val LOG = Logger.getInstance("#org.jetbrains.kotlin.idea.actions.internal.FindImplicitNothingAction")
}
override fun actionPerformed(e: AnActionEvent) {
val selectedFiles = selectedKotlinFiles(e).toList()
val project = CommonDataKeys.PROJECT.getData(e.dataContext)!!
ProgressManager.getInstance().runProcessWithProgressSynchronously(
{ find(selectedFiles, project) },
KotlinBundle.message("progress.finding.implicit.nothing.s"),
true,
project
)
}
private fun find(files: Collection<KtFile>, project: Project) {
val progressIndicator = ProgressManager.getInstance().progressIndicator
val found = ArrayList<KtCallExpression>()
for ((i, file) in files.withIndex()) {
progressIndicator?.text = KotlinBundle.message("scanning.files.0.fo.1.file.2.occurrences.found", i, files.size, found.size)
progressIndicator?.text2 = file.virtualFile.path
val resolutionFacade = file.getResolutionFacade()
file.acceptChildren(object : KtVisitorVoid() {
override fun visitKtElement(element: KtElement) {
ProgressManager.checkCanceled()
element.acceptChildren(this)
}
override fun visitCallExpression(expression: KtCallExpression) {
expression.acceptChildren(this)
try {
val bindingContext = resolutionFacade.analyze(expression)
val type = bindingContext.getType(expression) ?: return
if (KotlinBuiltIns.isNothing(type) && !expression.hasExplicitNothing(bindingContext)) { //TODO: what about nullable Nothing?
found.add(expression)
}
} catch (e: ProcessCanceledException) {
throw e
} catch (t: Throwable) { // do not stop on internal error
LOG.error(t)
}
}
})
progressIndicator?.fraction = (i + 1) / files.size.toDouble()
}
SwingUtilities.invokeLater {
if (found.isNotEmpty()) {
val usages = found.map { UsageInfo2UsageAdapter(UsageInfo(it)) }.toTypedArray()
val presentation = UsageViewPresentation()
presentation.tabName = KotlinBundle.message("implicit.nothing.s")
UsageViewManager.getInstance(project).showUsages(arrayOf<UsageTarget>(), usages, presentation)
} else {
Messages.showInfoMessage(
project,
KotlinBundle.message("not.found.in.0.files", files.size),
KotlinBundle.message("titile.not.found")
)
}
}
}
private fun KtExpression.hasExplicitNothing(bindingContext: BindingContext): Boolean {
val callee = getCalleeExpressionIfAny() ?: return false
when (callee) {
is KtSimpleNameExpression -> {
val target = bindingContext[BindingContext.REFERENCE_TARGET, callee] ?: return false
val callableDescriptor = (target as? CallableDescriptor ?: return false).original
val declaration = DescriptorToSourceUtils.descriptorToDeclaration(callableDescriptor) as? KtCallableDeclaration
if (declaration != null && declaration.typeReference == null) return false // implicit type
val type = callableDescriptor.returnType ?: return false
return type.isNothingOrNothingFunctionType()
}
else -> {
return callee.hasExplicitNothing(bindingContext)
}
}
}
private fun KotlinType.isNothingOrNothingFunctionType(): Boolean {
return KotlinBuiltIns.isNothing(this) ||
(isFunctionType && this.getReturnTypeFromFunctionType().isNothingOrNothingFunctionType())
}
override fun update(e: AnActionEvent) {
val internalMode = isApplicationInternalMode()
e.presentation.isVisible = internalMode
e.presentation.isEnabled = internalMode
}
private fun selectedKotlinFiles(e: AnActionEvent): Sequence<KtFile> {
val virtualFiles = e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY) ?: return sequenceOf()
val project = CommonDataKeys.PROJECT.getData(e.dataContext) ?: return sequenceOf()
return allKotlinFiles(virtualFiles, project)
}
private fun allKotlinFiles(filesOrDirs: Array<VirtualFile>, project: Project): Sequence<KtFile> {
val manager = PsiManager.getInstance(project)
return allFiles(filesOrDirs)
.asSequence()
.mapNotNull { manager.findFile(it) as? KtFile }
}
private fun allFiles(filesOrDirs: Array<VirtualFile>): Collection<VirtualFile> {
val result = ArrayList<VirtualFile>()
for (file in filesOrDirs) {
VfsUtilCore.visitChildrenRecursively(file, object : VirtualFileVisitor<Unit>() {
override fun visitFile(file: VirtualFile): Boolean {
result.add(file)
return true
}
})
}
return result
}
}
| apache-2.0 |
dkandalov/katas | kotlin/src/katas/kotlin/skiena/graphs/BFS.kt | 1 | 4504 | package katas.kotlin.skiena.graphs
import katas.kotlin.skiena.graphs.UnweightedGraphs.diamondGraph
import katas.kotlin.skiena.graphs.UnweightedGraphs.disconnectedGraph
import katas.kotlin.skiena.graphs.UnweightedGraphs.linearGraph
import katas.kotlin.skiena.graphs.UnweightedGraphs.meshGraph
import datsok.shouldEqual
import org.junit.Test
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap
import kotlin.collections.HashSet
import kotlin.collections.LinkedHashSet
data class SearchResult<T>(
val prevVertex: Map<T, T>,
val vertices: LinkedHashSet<T>
)
// This implementation which roughly copies the one from the book
// is bloated with unnecessary complexity so I'll try to avoid it.
fun <T> Graph<T>.bfs_skiena(
fromVertex: T,
processVertexEarly: (T) -> Unit = {},
processVertexLate: (T) -> Unit = {},
processEdge: (Edge<T>) -> Unit = {}
): SearchResult<T> {
if (!vertices.contains(fromVertex)) error("Graph doesn't contain vertex '$fromVertex'")
val prevVertex = HashMap<T, T>()
val processed = LinkedHashSet<T>()
val discovered = LinkedHashSet<T>()
val queue = LinkedList<T>()
queue.add(fromVertex)
discovered.add(fromVertex)
while (queue.isNotEmpty()) {
val vertex = queue.removeFirst()
processVertexEarly(vertex)
processed.add(vertex)
(edgesByVertex[vertex] ?: emptyList<Edge<T>>())
.forEach { edge ->
if (!processed.contains(edge.to)) processEdge(edge)
if (!discovered.contains(edge.to)) {
queue.add(edge.to)
discovered.add(edge.to)
prevVertex[edge.to] = vertex
}
}
processVertexLate(vertex)
}
return SearchResult(prevVertex, processed)
}
fun <T> Graph<T>.bfs(fromVertex: T = vertices.first()): List<T> {
val result = ArrayList<T>()
val wasQueued = HashSet<T>().apply { add(fromVertex) }
val queue = LinkedList<T>().apply { add(fromVertex) }
while (queue.isNotEmpty()) {
val vertex = queue.removeFirst()
result.add(vertex)
edgesByVertex[vertex]?.map { it.to }
?.forEach {
val justAdded = wasQueued.add(it)
if (justAdded) queue.add(it)
}
}
return result
}
fun <T> Graph<T>.bfsEdges(fromVertex: T = vertices.first()): List<Edge<T>> {
val result = ArrayList<Edge<T>>()
val visited = HashSet<T>()
val queue = LinkedList<T>().apply { add(fromVertex) }
while (queue.isNotEmpty()) {
val vertex = queue.removeFirst()
visited.add(vertex)
edgesByVertex[vertex]?.forEach { edge ->
if (edge.to !in visited) {
result.add(edge)
if (edge.to !in queue) queue.add(edge.to)
}
}
}
return result
}
class BFSTests {
@Test fun `breadth-first search Skiena`() {
val earlyVertices = ArrayList<Int>()
val lateVertices = ArrayList<Int>()
val edges = ArrayList<Edge<Int>>()
val searchResult = diamondGraph.bfs_skiena(
fromVertex = 1,
processVertexEarly = { earlyVertices.add(it) },
processVertexLate = { lateVertices.add(it) },
processEdge = { edges.add(it) }
)
searchResult.vertices.toList() shouldEqual listOf(1, 2, 4, 3)
earlyVertices shouldEqual listOf(1, 2, 4, 3)
lateVertices shouldEqual listOf(1, 2, 4, 3)
edges shouldEqual listOf(Edge(1, 2), Edge(1, 4), Edge(2, 3), Edge(4, 3))
}
@Test fun `breadth-first vertex traversal`() {
linearGraph.bfs(fromVertex = 1) shouldEqual listOf(1, 2, 3)
disconnectedGraph.bfs(fromVertex = 1) shouldEqual listOf(1, 2)
diamondGraph.bfs(fromVertex = 1) shouldEqual listOf(1, 2, 4, 3)
meshGraph.bfs(fromVertex = 1) shouldEqual listOf(1, 2, 3, 4)
}
@Test fun `breadth-first edge traversal`() {
linearGraph.bfsEdges(fromVertex = 1) shouldEqual listOf(
Edge(1, 2), Edge(2, 3)
)
disconnectedGraph.bfsEdges(fromVertex = 1) shouldEqual listOf(
Edge(1, 2)
)
diamondGraph.bfsEdges(fromVertex = 1) shouldEqual listOf(
Edge(1, 2), Edge(1, 4), Edge(2, 3), Edge(4, 3)
)
meshGraph.bfsEdges(fromVertex = 1) shouldEqual listOf(
Edge(1, 2), Edge(1, 3), Edge(1, 4), Edge(2, 3), Edge(2, 4), Edge(3, 4)
)
}
} | unlicense |
TheMrMilchmann/lwjgl3 | modules/lwjgl/vulkan/src/templates/kotlin/vulkan/templates/KHR_external_semaphore_fd.kt | 1 | 7632 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package vulkan.templates
import org.lwjgl.generator.*
import vulkan.*
val KHR_external_semaphore_fd = "KHRExternalSemaphoreFd".nativeClassVK("KHR_external_semaphore_fd", type = "device", postfix = "KHR") {
documentation =
"""
An application using external memory may wish to synchronize access to that memory using semaphores. This extension enables an application to export semaphore payload to and import semaphore payload from POSIX file descriptors.
<h5>VK_KHR_external_semaphore_fd</h5>
<dl>
<dt><b>Name String</b></dt>
<dd>{@code VK_KHR_external_semaphore_fd}</dd>
<dt><b>Extension Type</b></dt>
<dd>Device extension</dd>
<dt><b>Registered Extension Number</b></dt>
<dd>80</dd>
<dt><b>Revision</b></dt>
<dd>1</dd>
<dt><b>Extension and Version Dependencies</b></dt>
<dd><ul>
<li>Requires support for Vulkan 1.0</li>
<li>Requires {@link KHRExternalSemaphore VK_KHR_external_semaphore} to be enabled for any device-level functionality</li>
</ul></dd>
<dt><b>Contact</b></dt>
<dd><ul>
<li>James Jones <a target="_blank" href="https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_KHR_external_semaphore_fd]%20@cubanismo%250A%3C%3CHere%20describe%20the%20issue%20or%20question%20you%20have%20about%20the%20VK_KHR_external_semaphore_fd%20extension%3E%3E">cubanismo</a></li>
</ul></dd>
</dl>
<h5>Other Extension Metadata</h5>
<dl>
<dt><b>Last Modified Date</b></dt>
<dd>2016-10-21</dd>
<dt><b>IP Status</b></dt>
<dd>No known IP claims.</dd>
<dt><b>Contributors</b></dt>
<dd><ul>
<li>Jesse Hall, Google</li>
<li>James Jones, NVIDIA</li>
<li>Jeff Juliano, NVIDIA</li>
<li>Carsten Rohde, NVIDIA</li>
</ul></dd>
</dl>
"""
IntConstant(
"The extension specification version.",
"KHR_EXTERNAL_SEMAPHORE_FD_SPEC_VERSION".."1"
)
StringConstant(
"The extension name.",
"KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME".."VK_KHR_external_semaphore_fd"
)
EnumConstant(
"Extends {@code VkStructureType}.",
"STRUCTURE_TYPE_IMPORT_SEMAPHORE_FD_INFO_KHR".."1000079000",
"STRUCTURE_TYPE_SEMAPHORE_GET_FD_INFO_KHR".."1000079001"
)
VkResult(
"ImportSemaphoreFdKHR",
"""
Import a semaphore from a POSIX file descriptor.
<h5>C Specification</h5>
To import a semaphore payload from a POSIX file descriptor, call:
<pre><code>
VkResult vkImportSemaphoreFdKHR(
VkDevice device,
const VkImportSemaphoreFdInfoKHR* pImportSemaphoreFdInfo);</code></pre>
<h5>Description</h5>
Importing a semaphore payload from a file descriptor transfers ownership of the file descriptor from the application to the Vulkan implementation. The application <b>must</b> not perform any operations on the file descriptor after a successful import.
Applications <b>can</b> import the same semaphore payload into multiple instances of Vulkan, into the same instance from which it was exported, and multiple times into a given Vulkan instance.
<h5>Valid Usage</h5>
<ul>
<li>{@code semaphore} <b>must</b> not be associated with any queue command that has not yet completed execution on that queue</li>
</ul>
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code device} <b>must</b> be a valid {@code VkDevice} handle</li>
<li>{@code pImportSemaphoreFdInfo} <b>must</b> be a valid pointer to a valid ##VkImportSemaphoreFdInfoKHR structure</li>
</ul>
<h5>Return Codes</h5>
<dl>
<dt>On success, this command returns</dt>
<dd><ul>
<li>#SUCCESS</li>
</ul></dd>
<dt>On failure, this command returns</dt>
<dd><ul>
<li>#ERROR_OUT_OF_HOST_MEMORY</li>
<li>#ERROR_INVALID_EXTERNAL_HANDLE</li>
</ul></dd>
</dl>
<h5>See Also</h5>
##VkImportSemaphoreFdInfoKHR
""",
VkDevice("device", "the logical device that created the semaphore."),
VkImportSemaphoreFdInfoKHR.const.p("pImportSemaphoreFdInfo", "a pointer to a ##VkImportSemaphoreFdInfoKHR structure specifying the semaphore and import parameters.")
)
VkResult(
"GetSemaphoreFdKHR",
"""
Get a POSIX file descriptor handle for a semaphore.
<h5>C Specification</h5>
To export a POSIX file descriptor representing the payload of a semaphore, call:
<pre><code>
VkResult vkGetSemaphoreFdKHR(
VkDevice device,
const VkSemaphoreGetFdInfoKHR* pGetFdInfo,
int* pFd);</code></pre>
<h5>Description</h5>
Each call to {@code vkGetSemaphoreFdKHR} <b>must</b> create a new file descriptor and transfer ownership of it to the application. To avoid leaking resources, the application <b>must</b> release ownership of the file descriptor when it is no longer needed.
<div style="margin-left: 26px; border-left: 1px solid gray; padding-left: 14px;"><h5>Note</h5>
Ownership can be released in many ways. For example, the application can call {@code close}() on the file descriptor, or transfer ownership back to Vulkan by using the file descriptor to import a semaphore payload.
</div>
Where supported by the operating system, the implementation <b>must</b> set the file descriptor to be closed automatically when an {@code execve} system call is made.
Exporting a file descriptor from a semaphore <b>may</b> have side effects depending on the transference of the specified handle type, as described in <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#synchronization-semaphores-importing">Importing Semaphore State</a>.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code device} <b>must</b> be a valid {@code VkDevice} handle</li>
<li>{@code pGetFdInfo} <b>must</b> be a valid pointer to a valid ##VkSemaphoreGetFdInfoKHR structure</li>
<li>{@code pFd} <b>must</b> be a valid pointer to an {@code int} value</li>
</ul>
<h5>Return Codes</h5>
<dl>
<dt>On success, this command returns</dt>
<dd><ul>
<li>#SUCCESS</li>
</ul></dd>
<dt>On failure, this command returns</dt>
<dd><ul>
<li>#ERROR_TOO_MANY_OBJECTS</li>
<li>#ERROR_OUT_OF_HOST_MEMORY</li>
</ul></dd>
</dl>
<h5>See Also</h5>
##VkSemaphoreGetFdInfoKHR
""",
VkDevice("device", "the logical device that created the semaphore being exported."),
VkSemaphoreGetFdInfoKHR.const.p("pGetFdInfo", "a pointer to a ##VkSemaphoreGetFdInfoKHR structure containing parameters of the export operation."),
Check(1)..int.p("pFd", "will return the file descriptor representing the semaphore payload.")
)
} | bsd-3-clause |
tateisu/SubwayTooter | app/src/main/java/jp/juggler/subwaytooter/action/Action_User.kt | 1 | 34218 | package jp.juggler.subwaytooter.action
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.view.Gravity
import android.view.View
import android.widget.*
import androidx.appcompat.widget.AppCompatButton
import jp.juggler.subwaytooter.*
import jp.juggler.subwaytooter.actmain.addColumn
import jp.juggler.subwaytooter.api.*
import jp.juggler.subwaytooter.api.entity.*
import jp.juggler.subwaytooter.column.*
import jp.juggler.subwaytooter.dialog.ReportForm
import jp.juggler.subwaytooter.dialog.pickAccount
import jp.juggler.subwaytooter.table.AcctColor
import jp.juggler.subwaytooter.table.FavMute
import jp.juggler.subwaytooter.table.SavedAccount
import jp.juggler.subwaytooter.table.UserRelation
import jp.juggler.subwaytooter.util.matchHost
import jp.juggler.subwaytooter.util.openCustomTab
import jp.juggler.util.*
import kotlinx.coroutines.*
import okhttp3.Request
import java.util.*
// private val log = LogCategory("Action_User")
fun ActMain.clickMute(
accessInfo: SavedAccount,
who: TootAccount,
relation: UserRelation,
) = when {
relation.muting -> userUnmute(accessInfo, who, accessInfo)
else -> userMuteConfirm(accessInfo, who, accessInfo)
}
fun ActMain.clickBlock(
accessInfo: SavedAccount,
who: TootAccount,
relation: UserRelation,
) = when {
relation.blocking -> userBlock(accessInfo, who, accessInfo, false)
else -> userBlockConfirm(accessInfo, who, accessInfo)
}
fun ActMain.clickNicknameCustomize(
accessInfo: SavedAccount,
who: TootAccount,
) = arNickname.launch(ActNickname.createIntent(this, accessInfo.getFullAcct(who), true))
fun ActMain.openAvatarImage(who: TootAccount) {
openCustomTab(
when {
who.avatar.isNullOrEmpty() -> who.avatar_static
else -> who.avatar
}
)
}
fun ActMain.clickHideFavourite(
accessInfo: SavedAccount,
who: TootAccount,
) {
val acct = accessInfo.getFullAcct(who)
FavMute.save(acct)
showToast(false, R.string.changed)
for (column in appState.columnList) {
column.onHideFavouriteNotification(acct)
}
}
fun ActMain.clickShowFavourite(
accessInfo: SavedAccount,
who: TootAccount,
) {
FavMute.delete(accessInfo.getFullAcct(who))
showToast(false, R.string.changed)
}
fun ActMain.clickStatusNotification(
accessInfo: SavedAccount,
who: TootAccount,
relation: UserRelation,
) {
if (!accessInfo.isPseudo &&
accessInfo.isMastodon &&
relation.following
) {
userSetStatusNotification(accessInfo, who.id, enabled = !relation.notifying)
}
}
// ユーザをミュート/ミュート解除する
private fun ActMain.userMute(
accessInfo: SavedAccount,
whoArg: TootAccount,
whoAccessInfo: SavedAccount,
bMute: Boolean,
bMuteNotification: Boolean,
duration: Int?,
) {
val whoAcct = whoAccessInfo.getFullAcct(whoArg)
if (accessInfo.isMe(whoAcct)) {
showToast(false, R.string.it_is_you)
return
}
launchMain {
var resultRelation: UserRelation? = null
var resultWhoId: EntityId? = null
runApiTask(accessInfo) { client ->
val parser = TootParser(this, accessInfo)
if (accessInfo.isPseudo) {
if (!whoAcct.isValidFull) {
TootApiResult("can't mute pseudo acct ${whoAcct.pretty}")
} else {
val relation = UserRelation.loadPseudo(whoAcct)
relation.muting = bMute
relation.savePseudo(whoAcct.ascii)
resultRelation = relation
resultWhoId = whoArg.id
TootApiResult()
}
} else {
val whoId = if (accessInfo.matchHost(whoAccessInfo)) {
whoArg.id
} else {
val (result, accountRef) = client.syncAccountByAcct(accessInfo, whoAcct)
accountRef?.get()?.id ?: return@runApiTask result
}
resultWhoId = whoId
if (accessInfo.isMisskey) {
client.request(
when (bMute) {
true -> "/api/mute/create"
else -> "/api/mute/delete"
},
accessInfo.putMisskeyApiToken().apply {
put("userId", whoId.toString())
}.toPostRequestBuilder()
)?.apply {
if (jsonObject != null) {
// 204 no content
// update user relation
val ur = UserRelation.load(accessInfo.db_id, whoId)
ur.muting = bMute
accessInfo.saveUserRelationMisskey(
whoId,
parser
)
resultRelation = ur
}
}
} else {
client.request(
"/api/v1/accounts/$whoId/${if (bMute) "mute" else "unmute"}",
when {
!bMute -> "".toFormRequestBody()
else ->
jsonObject {
put("notifications", bMuteNotification)
if (duration != null) put("duration", duration)
}
.toRequestBody()
}.toPost()
)?.apply {
val jsonObject = jsonObject
if (jsonObject != null) {
resultRelation = accessInfo.saveUserRelation(
parseItem(::TootRelationShip, parser, jsonObject)
)
}
}
}
}
}?.let { result ->
val relation = resultRelation
val whoId = resultWhoId
if (relation == null || whoId == null) {
showToast(false, result.error)
} else {
// 未確認だが、自分をミュートしようとするとリクエストは成功するがレスポンス中のmutingはfalseになるはず
if (bMute && !relation.muting) {
showToast(false, R.string.not_muted)
return@launchMain
}
for (column in appState.columnList) {
if (column.accessInfo.isPseudo) {
if (relation.muting && column.type != ColumnType.PROFILE) {
// ミュートしたユーザの情報はTLから消える
column.removeAccountInTimelinePseudo(whoAcct)
}
// フォローアイコンの表示更新が走る
column.updateFollowIcons(accessInfo)
} else if (column.accessInfo == accessInfo) {
when {
!relation.muting -> {
if (column.type == ColumnType.MUTES) {
// ミュート解除したら「ミュートしたユーザ」カラムから消える
column.removeUser(accessInfo, ColumnType.MUTES, whoId)
} else {
// 他のカラムではフォローアイコンの表示更新が走る
column.updateFollowIcons(accessInfo)
}
}
column.type == ColumnType.PROFILE && column.profileId == whoId -> {
// 該当ユーザのプロフページのトゥートはミュートしてても見れる
// しかしフォローアイコンの表示更新は必要
column.updateFollowIcons(accessInfo)
}
else -> {
// ミュートしたユーザの情報はTLから消える
column.removeAccountInTimeline(accessInfo, whoId)
}
}
}
}
showToast(
false,
if (relation.muting) R.string.mute_succeeded else R.string.unmute_succeeded
)
}
}
}
}
fun ActMain.userUnmute(
accessInfo: SavedAccount,
whoArg: TootAccount,
whoAccessInfo: SavedAccount,
) = userMute(
accessInfo,
whoArg,
whoAccessInfo,
bMute = false,
bMuteNotification = false,
duration = null,
)
fun ActMain.userMuteConfirm(
accessInfo: SavedAccount,
who: TootAccount,
whoAccessInfo: SavedAccount,
) {
val activity = this@userMuteConfirm
// Mastodon 3.3から時限ミュート設定ができる
val choiceList = arrayOf(
Pair(0, getString(R.string.duration_indefinite)),
Pair(300, getString(R.string.duration_minutes_5)),
Pair(1800, getString(R.string.duration_minutes_30)),
Pair(3600, getString(R.string.duration_hours_1)),
Pair(21600, getString(R.string.duration_hours_6)),
Pair(86400, getString(R.string.duration_days_1)),
Pair(259200, getString(R.string.duration_days_3)),
Pair(604800, getString(R.string.duration_days_7)),
)
@SuppressLint("InflateParams")
val view = layoutInflater.inflate(R.layout.dlg_confirm, null, false)
val tvMessage = view.findViewById<TextView>(R.id.tvMessage)
tvMessage.text = getString(R.string.confirm_mute_user, who.username)
tvMessage.text = getString(R.string.confirm_mute_user, who.username)
// 「次回以降スキップ」のチェックボックスは「このユーザからの通知もミュート」に再利用する
// このオプションはMisskeyや疑似アカウントにはない
val cbMuteNotification = view.findViewById<CheckBox>(R.id.cbSkipNext)
val hasMuteNotification = !accessInfo.isMisskey && !accessInfo.isPseudo
cbMuteNotification.isChecked = hasMuteNotification
cbMuteNotification.vg(hasMuteNotification)
?.setText(R.string.confirm_mute_notification_for_user)
launchMain {
val spMuteDuration: Spinner = view.findViewById(R.id.spMuteDuration)
val hasMuteDuration = try {
when {
accessInfo.isMisskey || accessInfo.isPseudo -> false
else -> {
var resultBoolean = false
runApiTask(accessInfo) { client ->
val (ti, ri) = TootInstance.get(client)
resultBoolean = ti?.versionGE(TootInstance.VERSION_3_3_0_rc1) == true
ri
}
resultBoolean
}
}
} catch (ignored: CancellationException) {
// not show error
return@launchMain
} catch (ex: RuntimeException) {
showToast(true, ex.message)
return@launchMain
}
if (hasMuteDuration) {
view.findViewById<View>(R.id.llMuteDuration).vg(true)
spMuteDuration.apply {
adapter = ArrayAdapter(
activity,
android.R.layout.simple_spinner_item,
choiceList.map { it.second }.toTypedArray(),
).apply {
setDropDownViewResource(R.layout.lv_spinner_dropdown)
}
}
}
AlertDialog.Builder(activity)
.setView(view)
.setNegativeButton(R.string.cancel, null)
.setPositiveButton(R.string.ok) { _, _ ->
userMute(
accessInfo,
who,
whoAccessInfo,
bMute = true,
bMuteNotification = cbMuteNotification.isChecked,
duration = spMuteDuration.selectedItemPosition
.takeIf { hasMuteDuration && it in choiceList.indices }
?.let { choiceList[it].first }
)
}
.show()
}
}
fun ActMain.userMuteFromAnotherAccount(
who: TootAccount?,
whoAccessInfo: SavedAccount,
) {
who ?: return
launchMain {
pickAccount(
bAllowPseudo = false,
bAuto = false,
message = getString(R.string.account_picker_mute, who.acct.pretty),
accountListArg = accountListNonPseudo(who.apDomain)
)?.let {
userMuteConfirm(it, who, whoAccessInfo)
}
}
}
// ユーザをブロック/ブロック解除する
fun ActMain.userBlock(
accessInfo: SavedAccount,
whoArg: TootAccount,
whoAccessInfo: SavedAccount,
bBlock: Boolean,
) {
val whoAcct = whoArg.acct
if (accessInfo.isMe(whoAcct)) {
showToast(false, R.string.it_is_you)
return
}
launchMain {
var relationResult: UserRelation? = null
var whoIdResult: EntityId? = null
runApiTask(accessInfo) { client ->
if (accessInfo.isPseudo) {
if (whoAcct.ascii.contains('?')) {
TootApiResult("can't block pseudo account ${whoAcct.pretty}")
} else {
val relation = UserRelation.loadPseudo(whoAcct)
relation.blocking = bBlock
relation.savePseudo(whoAcct.ascii)
relationResult = relation
TootApiResult()
}
} else {
val whoId = if (accessInfo.matchHost(whoAccessInfo)) {
whoArg.id
} else {
val (result, accountRef) = client.syncAccountByAcct(accessInfo, whoAcct)
accountRef?.get()?.id ?: return@runApiTask result
}
whoIdResult = whoId
if (accessInfo.isMisskey) {
fun saveBlock(v: Boolean) {
val ur = UserRelation.load(accessInfo.db_id, whoId)
ur.blocking = v
UserRelation.save1Misskey(
System.currentTimeMillis(),
accessInfo.db_id,
whoId.toString(),
ur
)
relationResult = ur
}
client.request(
"/api/blocking/${if (bBlock) "create" else "delete"}",
accessInfo.putMisskeyApiToken().apply {
put("userId", whoId.toString())
}.toPostRequestBuilder()
)?.apply {
val error = this.error
when {
// success
error == null -> saveBlock(bBlock)
// already
error.contains("already blocking") -> saveBlock(bBlock)
error.contains("already not blocking") -> saveBlock(bBlock)
// else something error
}
}
} else {
client.request(
"/api/v1/accounts/$whoId/${if (bBlock) "block" else "unblock"}",
"".toFormRequestBody().toPost()
)?.also { result ->
val parser = TootParser(this, accessInfo)
relationResult = accessInfo.saveUserRelation(
parseItem(::TootRelationShip, parser, result.jsonObject)
)
}
}
}
}?.let { result ->
val relation = relationResult
val whoId = whoIdResult
when {
relation == null || whoId == null ->
showToast(false, result.error)
else -> {
// 自分をブロックしようとすると、blocking==falseで帰ってくる
if (bBlock && !relation.blocking) {
showToast(false, R.string.not_blocked)
return@launchMain
}
for (column in appState.columnList) {
if (column.accessInfo.isPseudo) {
if (relation.blocking) {
// ミュートしたユーザの情報はTLから消える
column.removeAccountInTimelinePseudo(whoAcct)
}
// フォローアイコンの表示更新が走る
column.updateFollowIcons(accessInfo)
} else if (column.accessInfo == accessInfo) {
when {
!relation.blocking -> {
if (column.type == ColumnType.BLOCKS) {
// ブロック解除したら「ブロックしたユーザ」カラムのリストから消える
column.removeUser(accessInfo, ColumnType.BLOCKS, whoId)
} else {
// 他のカラムではフォローアイコンの更新を行う
column.updateFollowIcons(accessInfo)
}
}
accessInfo.isMisskey -> {
// Misskeyのブロックはフォロー解除とフォロー拒否だけなので
// カラム中の投稿を消すなどの効果はない
// しかしカラム中のフォローアイコン表示の更新は必要
column.updateFollowIcons(accessInfo)
}
// 該当ユーザのプロフカラムではブロックしててもトゥートを見れる
// しかしカラム中のフォローアイコン表示の更新は必要
column.type == ColumnType.PROFILE && whoId == column.profileId -> {
column.updateFollowIcons(accessInfo)
}
// MastodonではブロックしたらTLからそのアカウントの投稿が消える
else -> column.removeAccountInTimeline(accessInfo, whoId)
}
}
}
showToast(
false,
when {
relation.blocking -> R.string.block_succeeded
else -> R.string.unblock_succeeded
}
)
}
}
}
}
}
fun ActMain.userBlockConfirm(
accessInfo: SavedAccount,
who: TootAccount,
whoAccessInfo: SavedAccount,
) {
AlertDialog.Builder(this)
.setMessage(getString(R.string.confirm_block_user, who.username))
.setNegativeButton(R.string.cancel, null)
.setPositiveButton(R.string.ok) { _, _ ->
userBlock(
accessInfo,
who,
whoAccessInfo,
bBlock = true
)
}
.show()
}
fun ActMain.userBlockFromAnotherAccount(
who: TootAccount?,
whoAccessInfo: SavedAccount,
) {
who ?: return
launchMain {
pickAccount(
bAllowPseudo = false,
bAuto = false,
message = getString(R.string.account_picker_block, who.acct.pretty),
accountListArg = accountListNonPseudo(who.apDomain)
)?.let { ai ->
userBlockConfirm(ai, who, whoAccessInfo)
}
}
}
//////////////////////////////////////////////////////////////////////////////////////
// ユーザURLを同期してプロフカラムを開く
private fun ActMain.userProfileFromUrlOrAcct(
pos: Int,
accessInfo: SavedAccount,
acct: Acct,
whoUrl: String,
) {
launchMain {
var resultWho: TootAccount? = null
runApiTask(accessInfo) { client ->
val (result, ar) = client.syncAccountByUrl(accessInfo, whoUrl)
if (result == null) {
null
} else {
resultWho = ar?.get()
if (resultWho != null) {
result
} else {
val (r2, ar2) = client.syncAccountByAcct(accessInfo, acct)
resultWho = ar2?.get()
r2
}
}
}?.let { result ->
when (val who = resultWho) {
null -> {
showToast(true, result.error)
// 仕方ないのでchrome tab で開く
openCustomTab(whoUrl)
}
else -> addColumn(pos, accessInfo, ColumnType.PROFILE, who.id)
}
}
}
}
// アカウントを選んでユーザプロフを開く
fun ActMain.userProfileFromAnotherAccount(
pos: Int,
accessInfo: SavedAccount,
who: TootAccount?,
) {
who?.url ?: return
launchMain {
pickAccount(
bAllowPseudo = false,
bAuto = false,
message = getString(
R.string.account_picker_open_user_who,
AcctColor.getNickname(accessInfo, who)
),
accountListArg = accountListNonPseudo(who.apDomain)
)?.let { ai ->
if (ai.matchHost(accessInfo)) {
addColumn(pos, ai, ColumnType.PROFILE, who.id)
} else {
userProfileFromUrlOrAcct(pos, ai, accessInfo.getFullAcct(who), who.url)
}
}
}
}
// 今のアカウントでユーザプロフを開く
fun ActMain.userProfileLocal(
pos: Int,
accessInfo: SavedAccount,
who: TootAccount,
) {
when {
accessInfo.isNA -> userProfileFromAnotherAccount(pos, accessInfo, who)
else -> addColumn(pos, accessInfo, ColumnType.PROFILE, who.id)
}
}
// user@host で指定されたユーザのプロフを開く
// Intent-Filter や openChromeTabから 呼ばれる
fun ActMain.userProfile(
pos: Int,
accessInfo: SavedAccount?,
acct: Acct,
userUrl: String,
originalUrl: String = userUrl,
) {
if (accessInfo?.isPseudo == false) {
// 文脈のアカウントがあり、疑似アカウントではない
if (!accessInfo.matchHost(acct.host)) {
// 文脈のアカウントと異なるインスタンスなら、別アカウントで開く
userProfileFromUrlOrAcct(pos, accessInfo, acct, userUrl)
} else {
// 文脈のアカウントと同じインスタンスなら、アカウントIDを探して開いてしまう
launchMain {
var resultWho: TootAccount? = null
runApiTask(accessInfo) { client ->
val (result, ar) = client.syncAccountByAcct(accessInfo, acct)
resultWho = ar?.get()
result
}?.let {
when (val who = resultWho) {
// ダメならchromeで開く
null -> openCustomTab(userUrl)
// 変換できたアカウント情報で開く
else -> userProfileLocal(pos, accessInfo, who)
}
}
}
}
return
}
// 文脈がない、もしくは疑似アカウントだった
// 疑似アカウントでは検索APIを使えないため、IDが分からない
if (!SavedAccount.hasRealAccount()) {
// 疑似アカウントしか登録されていない
// chrome tab で開く
openCustomTab(originalUrl)
return
}
launchMain {
val activity = this@userProfile
pickAccount(
bAllowPseudo = false,
bAuto = false,
message = getString(
R.string.account_picker_open_user_who,
AcctColor.getNickname(acct)
),
accountListArg = accountListNonPseudo(acct.host),
extraCallback = { ll, pad_se, pad_tb ->
// chrome tab で開くアクションを追加
val lp = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
)
val b = AppCompatButton(activity)
b.setPaddingRelative(pad_se, pad_tb, pad_se, pad_tb)
b.gravity = Gravity.START or Gravity.CENTER_VERTICAL
b.isAllCaps = false
b.layoutParams = lp
b.minHeight = (0.5f + 32f * activity.density).toInt()
b.text = getString(R.string.open_in_browser)
b.setBackgroundResource(R.drawable.btn_bg_transparent_round6dp)
b.setOnClickListener {
openCustomTab(originalUrl)
}
ll.addView(b, 0)
}
)?.let {
userProfileFromUrlOrAcct(pos, it, acct, userUrl)
}
}
}
//////////////////////////////////////////////////////////////////////////////////////
// 通報フォームを開く
fun ActMain.userReportForm(
accessInfo: SavedAccount,
who: TootAccount,
status: TootStatus? = null,
) {
ReportForm.showReportForm(this, accessInfo, who, status) { dialog, comment, forward ->
userReport(accessInfo, who, status, comment, forward) {
dialog.dismissSafe()
}
}
}
// 通報する
private fun ActMain.userReport(
accessInfo: SavedAccount,
who: TootAccount,
status: TootStatus?,
comment: String,
forward: Boolean,
onReportComplete: (result: TootApiResult) -> Unit,
) {
if (accessInfo.isMe(who)) {
showToast(false, R.string.it_is_you)
return
}
launchMain {
runApiTask(accessInfo) { client ->
if (accessInfo.isMisskey) {
client.request(
"/api/users/report-abuse",
accessInfo.putMisskeyApiToken().apply {
put("userId", who.id.toString())
put(
"comment",
StringBuilder().apply {
status?.let {
append(it.url)
append("\n")
}
append(comment)
}.toString()
)
}.toPostRequestBuilder()
)
} else {
client.request(
"/api/v1/reports",
JsonObject().apply {
put("account_id", who.id.toString())
put("comment", comment)
put("forward", forward)
if (status != null) {
put("status_ids", jsonArray {
add(status.id.toString())
})
}
}.toPostRequestBuilder()
)
}
}?.let { result ->
when (result.jsonObject) {
null -> showToast(true, result.error)
else -> {
onReportComplete(result)
showToast(false, R.string.report_completed)
}
}
}
}
}
// show/hide boosts from (following) user
fun ActMain.userSetShowBoosts(
accessInfo: SavedAccount,
who: TootAccount,
bShow: Boolean,
) {
if (accessInfo.isMe(who)) {
showToast(false, R.string.it_is_you)
return
}
launchMain {
var resultRelation: UserRelation? = null
runApiTask(accessInfo) { client ->
client.request(
"/api/v1/accounts/${who.id}/follow",
jsonObjectOf("reblogs" to bShow).toPostRequestBuilder()
)?.also { result ->
val parser = TootParser(this, accessInfo)
resultRelation = accessInfo.saveUserRelation(
parseItem(
::TootRelationShip,
parser,
result.jsonObject
)
)
}
}?.let { result ->
when (resultRelation) {
null -> showToast(true, result.error)
else -> showToast(true, R.string.operation_succeeded)
}
}
}
}
fun ActMain.userSuggestionDelete(
accessInfo: SavedAccount,
who: TootAccount,
bConfirmed: Boolean = false,
) {
if (!bConfirmed) {
val name = who.decodeDisplayName(applicationContext)
AlertDialog.Builder(this)
.setMessage(
name.intoStringResource(
applicationContext,
R.string.delete_succeeded_confirm
)
)
.setNegativeButton(R.string.cancel, null)
.setPositiveButton(R.string.ok) { _, _ ->
userSuggestionDelete(accessInfo, who, bConfirmed = true)
}
.show()
return
}
launchMain {
runApiTask(accessInfo) { client ->
client.request("/api/v1/suggestions/${who.id}", Request.Builder().delete())
}?.let { result ->
when (result.error) {
null -> {
showToast(false, R.string.delete_succeeded)
// update suggestion column
for (column in appState.columnList) {
column.removeUser(accessInfo, ColumnType.FOLLOW_SUGGESTION, who.id)
}
}
else -> showToast(true, result.error)
}
}
}
}
fun ActMain.userSetStatusNotification(
accessInfo: SavedAccount,
whoId: EntityId,
enabled: Boolean,
) {
launchMain {
runApiTask(accessInfo) { client ->
client.request(
"/api/v1/accounts/$whoId/follow",
jsonObject {
put("notify", enabled)
}.toPostRequestBuilder()
)?.also { result ->
val relation = parseItem(
::TootRelationShip,
TootParser(this, accessInfo),
result.jsonObject
)
if (relation != null) {
UserRelation.save1Mastodon(
System.currentTimeMillis(),
accessInfo.db_id,
relation
)
}
}
}?.let { result ->
when (val error = result.error) {
null -> showToast(false, R.string.operation_succeeded)
else -> showToast(true, error)
}
}
}
}
fun ActMain.userEndorsement(
accessInfo: SavedAccount,
who: TootAccount,
bSet: Boolean,
) {
if (accessInfo.isMisskey) {
showToast(false, "This feature is not provided on Misskey account.")
return
}
launchMain {
@Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
var resultRelation: UserRelation? = null
runApiTask(accessInfo) { client ->
client.request(
"/api/v1/accounts/${who.id}/" + when (bSet) {
true -> "pin"
false -> "unpin"
},
"".toFormRequestBody().toPost()
)
?.also { result ->
val parser = TootParser(this, accessInfo)
resultRelation = accessInfo.saveUserRelation(
parseItem(::TootRelationShip, parser, result.jsonObject)
)
}
}?.let { result ->
when (val error = result.error) {
null -> showToast(
false, when (bSet) {
true -> R.string.endorse_succeeded
else -> R.string.remove_endorse_succeeded
}
)
else -> showToast(true, error)
}
}
}
}
| apache-2.0 |
DreierF/MyTargets | app/src/main/java/de/dreier/mytargets/base/db/dao/TrainingDAO.kt | 1 | 1936 | /*
* 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.base.db.dao
import androidx.lifecycle.LiveData
import androidx.room.*
import de.dreier.mytargets.shared.models.db.Round
import de.dreier.mytargets.shared.models.db.Training
@Dao
abstract class TrainingDAO {
@Query("SELECT * FROM `Training`")
abstract fun loadTrainings(): List<Training>
@Query("SELECT * FROM `Training`")
abstract fun loadTrainingsLive(): LiveData<List<Training>>
@Query("SELECT * FROM `Training` WHERE `id` = :id")
abstract fun loadTraining(id: Long): Training
@Query("SELECT * FROM `Training` WHERE `id` = :id")
abstract fun loadTrainingLive(id: Long): LiveData<Training>
@Insert(onConflict = OnConflictStrategy.REPLACE)
abstract fun insertTraining(training: Training): Long
@Update
abstract fun updateTraining(training: Training)
@Query("UPDATE `Training` SET `comment`=:comment WHERE `id` = :trainingId")
abstract fun updateComment(trainingId: Long, comment: String)
@Transaction
open fun insertTraining(training: Training, rounds: List<Round>) {
training.id = insertTraining(training)
for (round in rounds) {
round.trainingId = training.id
round.id = insertRound(round)
}
}
@Insert(onConflict = OnConflictStrategy.REPLACE)
abstract fun insertRound(round: Round): Long
@Delete
abstract fun deleteTraining(training: Training)
}
| gpl-2.0 |
JuliaSoboleva/SmartReceiptsLibrary | app/src/test/java/co/smartreceipts/android/model/impl/MultiplePriceImplTest.kt | 1 | 10245 | package co.smartreceipts.android.model.impl
import android.os.Parcel
import co.smartreceipts.android.model.Distance
import co.smartreceipts.android.model.factory.ExchangeRateBuilderFactory
import co.smartreceipts.android.utils.TestLocaleToggler
import co.smartreceipts.android.utils.TestUtils
import org.joda.money.CurrencyUnit
import org.junit.After
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito.mock
import org.robolectric.RobolectricTestRunner
import java.math.BigDecimal
import java.util.*
@RunWith(RobolectricTestRunner::class)
class MultiplePriceImplTest {
companion object {
private val USD_CURRENCY = CurrencyUnit.USD
private val EUR_CURRENCY = CurrencyUnit.EUR
private val JPY_CURRENCY = CurrencyUnit.JPY // currency with 0 decimal places
private val USD_EXCHANGE_RATE =
ExchangeRateBuilderFactory().setBaseCurrency(USD_CURRENCY).setRate(EUR_CURRENCY, BigDecimal(0.5)).build()
private val EUR_EXCHANGE_RATE =
ExchangeRateBuilderFactory().setBaseCurrency(EUR_CURRENCY).setRate(USD_CURRENCY, BigDecimal(2.0)).build()
private val JPY_EXCHANGE_RATE = ExchangeRateBuilderFactory().setBaseCurrency(JPY_CURRENCY).build()
}
private lateinit var sameCurrencyPrice: MultiplePriceImpl
private lateinit var sameCurrencyWithNegativePrice: MultiplePriceImpl
private lateinit var differentCurrenciesNoExchangeRatePrice: MultiplePriceImpl
private lateinit var differentCurrenciesWithExchangeRatePrice: MultiplePriceImpl
@Before
@Throws(Exception::class)
fun setUp() {
TestLocaleToggler.setDefaultLocale(Locale.US)
val priceUsd1 = SinglePriceImpl(BigDecimal.ONE, USD_CURRENCY, USD_EXCHANGE_RATE)
val priceUsd2 = SinglePriceImpl(BigDecimal(2.0), USD_CURRENCY, USD_EXCHANGE_RATE)
val priceUsd2Negative = SinglePriceImpl(BigDecimal(-2.0), USD_CURRENCY, USD_EXCHANGE_RATE)
val priceEur1 = SinglePriceImpl(BigDecimal.ONE, EUR_CURRENCY, EUR_EXCHANGE_RATE)
val priceJpu1 = SinglePriceImpl(BigDecimal.ONE, JPY_CURRENCY, JPY_EXCHANGE_RATE)
sameCurrencyPrice = MultiplePriceImpl(USD_CURRENCY, listOf(priceUsd1, priceUsd2))
sameCurrencyWithNegativePrice = MultiplePriceImpl(USD_CURRENCY, listOf(priceUsd1, priceUsd2Negative))
differentCurrenciesWithExchangeRatePrice = MultiplePriceImpl(USD_CURRENCY, listOf(priceUsd1, priceUsd2, priceEur1))
differentCurrenciesNoExchangeRatePrice = MultiplePriceImpl(USD_CURRENCY, listOf(priceUsd1, priceEur1, priceJpu1))
}
@After
fun tearDown() {
TestLocaleToggler.resetDefaultLocale()
}
@Test
fun getPriceAsFloat() {
assertEquals(3f, sameCurrencyPrice.priceAsFloat, TestUtils.EPSILON)
assertEquals(-1f, sameCurrencyWithNegativePrice.priceAsFloat, TestUtils.EPSILON)
assertEquals(5f, differentCurrenciesWithExchangeRatePrice.priceAsFloat, TestUtils.EPSILON)
assertEquals(4f, differentCurrenciesNoExchangeRatePrice.priceAsFloat, TestUtils.EPSILON)
}
@Test
fun getPrice() {
assertEquals(3.0, sameCurrencyPrice.price.toDouble(), TestUtils.EPSILON.toDouble())
assertEquals(-1.0, sameCurrencyWithNegativePrice.price.toDouble(), TestUtils.EPSILON.toDouble())
assertEquals(5.0, differentCurrenciesWithExchangeRatePrice.price.toDouble(), TestUtils.EPSILON.toDouble())
assertEquals(4.0, differentCurrenciesNoExchangeRatePrice.price.toDouble(), TestUtils.EPSILON.toDouble())
}
@Test
fun getDecimalFormattedPrice() {
assertEquals("3.00", sameCurrencyPrice.decimalFormattedPrice)
assertEquals("-1.00", sameCurrencyWithNegativePrice.decimalFormattedPrice)
assertEquals("5.00", differentCurrenciesWithExchangeRatePrice.decimalFormattedPrice)
assertEquals("JPY 1; USD 3.00", differentCurrenciesNoExchangeRatePrice.decimalFormattedPrice)
}
@Test
fun getCurrencyFormattedPrice() {
assertEquals("$3.00", sameCurrencyPrice.currencyFormattedPrice)
assertEquals("$-1.00", sameCurrencyWithNegativePrice.currencyFormattedPrice)
assertEquals("$5.00", differentCurrenciesWithExchangeRatePrice.currencyFormattedPrice)
assertEquals("JPY1; $3.00", differentCurrenciesNoExchangeRatePrice.currencyFormattedPrice)
}
@Test
fun getCurrencyCodeFormattedPrice() {
assertEquals("USD 3.00", sameCurrencyPrice.currencyCodeFormattedPrice)
assertEquals("USD -1.00", sameCurrencyWithNegativePrice.currencyCodeFormattedPrice)
assertEquals("EUR 1.00; USD 3.00", differentCurrenciesWithExchangeRatePrice.currencyCodeFormattedPrice)
assertEquals("JPY 1; EUR 1.00; USD 1.00", differentCurrenciesNoExchangeRatePrice.currencyCodeFormattedPrice)
}
@Test
fun getCurrency() {
assertEquals(USD_CURRENCY, sameCurrencyPrice.currency)
assertEquals(USD_CURRENCY, sameCurrencyWithNegativePrice.currency)
assertEquals(USD_CURRENCY, differentCurrenciesNoExchangeRatePrice.currency)
assertEquals(USD_CURRENCY, differentCurrenciesWithExchangeRatePrice.currency)
}
@Test
fun getCurrencyCode() {
assertEquals(USD_CURRENCY.code, sameCurrencyPrice.currencyCode)
assertEquals(USD_CURRENCY.code, sameCurrencyWithNegativePrice.currencyCode)
assertEquals(String.format("%s; %s", EUR_CURRENCY.code, USD_CURRENCY.code), differentCurrenciesWithExchangeRatePrice.currencyCode)
assertEquals(
String.format("%s; %s; %s", JPY_CURRENCY.code, EUR_CURRENCY.code, USD_CURRENCY.code),
differentCurrenciesNoExchangeRatePrice.currencyCode
)
}
@Test
fun isSingleCurrency() {
assertEquals(true, sameCurrencyPrice.isSingleCurrency)
assertEquals(true, sameCurrencyWithNegativePrice.isSingleCurrency)
assertEquals(false, differentCurrenciesNoExchangeRatePrice.isSingleCurrency)
assertEquals(false, differentCurrenciesWithExchangeRatePrice.isSingleCurrency)
}
@Test
fun testToString() {
assertEquals("$3.00", sameCurrencyPrice.currencyFormattedPrice)
assertEquals("$-1.00", sameCurrencyWithNegativePrice.currencyFormattedPrice)
assertEquals("$5.00", differentCurrenciesWithExchangeRatePrice.currencyFormattedPrice)
assertEquals("JPY1; $3.00", differentCurrenciesNoExchangeRatePrice.currencyFormattedPrice)
}
@Test
fun parcel() {
// Test one
val parcel1 = Parcel.obtain()
sameCurrencyPrice.writeToParcel(parcel1, 0)
parcel1.setDataPosition(0)
val parcelPrice1 = MultiplePriceImpl.CREATOR.createFromParcel(parcel1)
assertNotNull(parcelPrice1)
assertEquals(sameCurrencyPrice, parcelPrice1)
// Test two
val parcel2 = Parcel.obtain()
differentCurrenciesNoExchangeRatePrice.writeToParcel(parcel2, 0)
parcel2.setDataPosition(0)
val parcelPrice2 = MultiplePriceImpl.CREATOR.createFromParcel(parcel2)
assertNotNull(parcelPrice2)
assertEquals(differentCurrenciesNoExchangeRatePrice, parcelPrice2)
// Test three
val parcel3 = Parcel.obtain()
differentCurrenciesWithExchangeRatePrice.writeToParcel(parcel3, 0)
parcel3.setDataPosition(0)
val parcelPrice3 = MultiplePriceImpl.CREATOR.createFromParcel(parcel3)
assertNotNull(parcelPrice3)
assertEquals(differentCurrenciesWithExchangeRatePrice, parcelPrice3)
// Test negative
val parcelNegative = Parcel.obtain()
sameCurrencyWithNegativePrice.writeToParcel(parcelNegative, 0)
parcelNegative.setDataPosition(0)
val parcelPriceNegative = MultiplePriceImpl.CREATOR.createFromParcel(parcelNegative)
assertNotNull(parcelPriceNegative)
assertEquals(sameCurrencyWithNegativePrice, parcelPriceNegative)
}
@Test
fun equals() {
val usd1 = SinglePriceImpl(BigDecimal.ONE, USD_CURRENCY, USD_EXCHANGE_RATE)
val usd2 = SinglePriceImpl(BigDecimal(2), USD_CURRENCY, USD_EXCHANGE_RATE)
val usd0 = SinglePriceImpl(BigDecimal.ZERO, USD_CURRENCY, USD_EXCHANGE_RATE)
val eur3 = SinglePriceImpl(BigDecimal(3), CurrencyUnit.EUR, EUR_EXCHANGE_RATE)
val eur1 = SinglePriceImpl(BigDecimal.ONE, CurrencyUnit.EUR, EUR_EXCHANGE_RATE)
val equalPrice = MultiplePriceImpl(USD_CURRENCY, listOf(usd1, usd2))
val equalPriceWithEur = MultiplePriceImpl(USD_CURRENCY, listOf(usd1, eur1))
assertEquals(sameCurrencyPrice, sameCurrencyPrice)
assertEquals(sameCurrencyPrice, equalPriceWithEur)
assertEquals(sameCurrencyPrice, equalPrice)
assertEquals(
sameCurrencyPrice,
SinglePriceImpl(BigDecimal(3), USD_CURRENCY, USD_EXCHANGE_RATE)
)
assertNotEquals(differentCurrenciesNoExchangeRatePrice, sameCurrencyPrice)
assertNotEquals(sameCurrencyWithNegativePrice, sameCurrencyPrice)
assertNotEquals(Any(), sameCurrencyPrice)
assertNotEquals(usd0, sameCurrencyPrice)
assertNotEquals(eur3, sameCurrencyPrice)
assertNotEquals(mock(Distance::class.java), sameCurrencyPrice)
}
@Test
fun localeBasedFormattingTest() {
val usd1 = SinglePriceImpl(BigDecimal(1000), USD_CURRENCY, USD_EXCHANGE_RATE)
val usd2 = SinglePriceImpl(BigDecimal(2.5023), USD_CURRENCY, USD_EXCHANGE_RATE)
TestLocaleToggler.setDefaultLocale(Locale.US)
val multiplePriceUs = MultiplePriceImpl(USD_CURRENCY, listOf(usd1, usd2))
assertEquals("1,002.50", multiplePriceUs.decimalFormattedPrice)
assertEquals("USD 1,002.50", multiplePriceUs.currencyCodeFormattedPrice)
assertEquals("$1,002.50", multiplePriceUs.currencyFormattedPrice)
TestLocaleToggler.setDefaultLocale(Locale.FRANCE)
val multiplePriceFrance = MultiplePriceImpl(USD_CURRENCY, listOf(usd1, usd2))
assertEquals("1 002,50", multiplePriceFrance.decimalFormattedPrice)
assertEquals("USD 1 002,50", multiplePriceFrance.currencyCodeFormattedPrice)
assertEquals("USD1 002,50", multiplePriceFrance.currencyFormattedPrice)
}
} | agpl-3.0 |
cxpqwvtj/himawari | web/src/main/kotlin/app/himawari/interceptor/AccessContextInterceptor.kt | 1 | 2030 | package app.himawari.interceptor
import app.himawari.model.AppDate
import org.aspectj.lang.ProceedingJoinPoint
import org.aspectj.lang.annotation.Around
import org.aspectj.lang.annotation.Aspect
import org.dbflute.hook.AccessContext
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.stereotype.Component
/**
* DBFluteのアクセスコンテキストを設定するためのインターセプタクラスです。
* Created by cxpqwvtj on 2017/02/11.
*/
@Component
@Aspect
class AccessContextInterceptor(
private val appDate: AppDate
) {
@Around("execution(* app.himawari.controller..*.*(..))")
fun around(point: ProceedingJoinPoint): Any? {
if (AccessContext.isExistAccessContextOnThread()) {
// 既に設定されていたら何もしないで次へ
// (二度呼び出しされたときのために念のため)
return point.proceed()
}
// [アクセスユーザ]
// 例えば、セッション上のログインユーザを利用。
// ログインしていない場合のことも考慮すること。
val authentication = SecurityContextHolder.getContext().authentication
val accessUser = if (authentication == null) {
"anonymous"
} else {
val principal = authentication.principal
if (principal is UserDetails) {
principal.username
} else {
principal.toString()
}
}
val context = AccessContext()
context.accessLocalDateTime = appDate.systemDate().toLocalDateTime()
context.accessUser = accessUser
AccessContext.setAccessContextOnThread(context)
try {
return point.proceed()
} finally {
// 最後はしっかりクリアすること (必須)
AccessContext.clearAccessContextOnThread()
}
}
} | mit |
paplorinc/intellij-community | platform/projectModel-impl/src/com/intellij/openapi/module/impl/ModulePointerImpl.kt | 7 | 2183 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.module.impl
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModulePointer
import java.util.concurrent.locks.ReentrantReadWriteLock
import kotlin.concurrent.read
private val LOG = Logger.getInstance(ModulePointerImpl::class.java)
class ModulePointerImpl : ModulePointer {
private var module: Module? = null
private var moduleName: String? = null
private val lock: ReentrantReadWriteLock
internal constructor(module: Module, lock: ReentrantReadWriteLock) {
this.module = module
this.lock = lock
}
internal constructor(moduleName: String, lock: ReentrantReadWriteLock) {
this.moduleName = moduleName
this.lock = lock
}
override fun getModule(): Module? = lock.read { module }
override fun getModuleName(): String = lock.read { module?.name ?: moduleName!! }
// must be called under lock, so, explicit lock using is not required
internal fun moduleAdded(module: Module) {
LOG.assertTrue(moduleName == module.name)
moduleName = null
this.module = module
}
// must be called under lock, so, explicit lock using is not required
internal fun moduleRemoved(module: Module) {
val resolvedModule = this.module
LOG.assertTrue(resolvedModule === module)
moduleName = resolvedModule!!.name
this.module = null
}
internal fun renameUnresolved(newName: String) {
LOG.assertTrue(module == null)
moduleName = newName
}
override fun toString(): String = "moduleName: $moduleName, module: $module"
}
| apache-2.0 |
peruukki/SimpleCurrencyConverter | app/src/main/java/com/peruukki/simplecurrencyconverter/network/FetchConversionRatesTask.kt | 1 | 4529 | package com.peruukki.simplecurrencyconverter.network
import android.content.Context
import android.net.Uri
import android.os.AsyncTask
import android.util.Log
import com.peruukki.simplecurrencyconverter.R
import com.peruukki.simplecurrencyconverter.models.ConversionRate
import com.squareup.okhttp.OkHttpClient
import com.squareup.okhttp.Request
import org.json.JSONException
import org.json.JSONObject
import java.io.IOException
import java.net.URL
import java.util.*
/**
* The background task to use for fetching updated conversion rates. Updates the rates in the
* database after fetching.
*/
class FetchConversionRatesTask
/**
* Creates a new background task for fetching updated conversion rates.
*
* @param context application context
* @param updateListener listener to notify after successful fetching
*/
(private val mContext: Context, private val mUpdateListener: OnConversionRatesFetchedListener) : AsyncTask<Void, Void, String>() {
private var mConversionRates: List<ConversionRate> = ArrayList()
private val currencyPairsForApiQuery = ConversionRate.allRates
.map { conversionRateToApiKeyName(it) }
.joinToString(",")
override fun doInBackground(vararg params: Void): String? {
val client = OkHttpClient()
val uri = Uri.parse("https://free.currencyconverterapi.com/api/v5/convert").buildUpon()
.appendQueryParameter("q", currencyPairsForApiQuery)
.build()
try {
val url = URL(uri.toString())
Log.i(LOG_TAG, "Fetching conversion rates from $url")
val request = Request.Builder()
.url(url)
.build()
val responseBody = client.newCall(request)
.execute()
.body()
val response = responseBody.string()
Log.i(LOG_TAG, "Conversion rates response: '$response'")
val conversionRates = parseConversionRates(response)
for (conversionRate in conversionRates) {
Log.d(LOG_TAG, "Parsed conversion rate: " + conversionRate.fixedCurrencyRateString +
" <-> " + conversionRate.variableCurrencyRateString)
}
storeConversionRates(conversionRates)
mConversionRates = conversionRates
responseBody.close()
return null
} catch (e: IOException) {
Log.e(LOG_TAG, "Error fetching conversion rates", e)
return mContext.getString(R.string.failed_to_fetch_conversion_rates)
} catch (e: JSONException) {
Log.e(LOG_TAG, "Error parsing conversion rates to JSON", e)
return mContext.getString(R.string.unexpected_conversion_rate_data)
} catch (e: NumberFormatException) {
Log.e(LOG_TAG, "Error converting JSON string to number", e)
return mContext.getString(R.string.invalid_conversion_rates)
}
}
private fun conversionRateToApiKeyName(conversionRate: ConversionRate): String {
return conversionRate.fixedCurrency + "_" + conversionRate.variableCurrency
}
@Throws(JSONException::class)
private fun parseConversionRates(responseBody: String): List<ConversionRate> {
val responseJson = JSONObject(responseBody)
val results = responseJson.getJSONObject("results")
return ConversionRate.allRates.map { conversionRate ->
val rate = results.getJSONObject(conversionRateToApiKeyName(conversionRate))
val rateValue = java.lang.Float.valueOf(rate.getString("val"))
ConversionRate(conversionRate.fixedCurrency, conversionRate.variableCurrency, rateValue)
}
}
private fun storeConversionRates(conversionRates: List<ConversionRate>) {
for (conversionRate in conversionRates) {
conversionRate.writeToDb(mContext.contentResolver)
}
}
override fun onPostExecute(errorMessage: String?) {
super.onPostExecute(errorMessage)
if (errorMessage == null) {
mUpdateListener.onConversionRatesUpdated(mConversionRates)
} else {
mUpdateListener.onUpdateFailed(errorMessage)
}
}
interface OnConversionRatesFetchedListener {
fun onConversionRatesUpdated(conversionRates: List<ConversionRate>)
fun onUpdateFailed(errorMessage: String)
}
companion object {
private val LOG_TAG = FetchConversionRatesTask::class.java.simpleName
}
}
| mit |
paplorinc/intellij-community | platform/diff-impl/src/com/intellij/openapi/vcs/ex/LineStatusTrackerBase.kt | 2 | 12215 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.vcs.ex
import com.intellij.diff.util.DiffUtil
import com.intellij.diff.util.Side
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.Application
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.command.undo.UndoConstants
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.impl.DocumentImpl
import com.intellij.openapi.localVcs.UpToDateLineNumberProvider.ABSENT_LINE_NUMBER
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vcs.VcsBundle
import com.intellij.openapi.vcs.ex.DocumentTracker.Block
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.containers.nullize
import org.jetbrains.annotations.CalledInAwt
import org.jetbrains.annotations.TestOnly
import java.util.*
abstract class LineStatusTrackerBase<R : Range> : LineStatusTrackerI<R> {
protected val application: Application = ApplicationManager.getApplication()
open val project: Project?
final override val document: Document
final override val vcsDocument: Document
protected val disposable: Disposable = Disposer.newDisposable()
protected val documentTracker: DocumentTracker
protected abstract val renderer: LineStatusMarkerRenderer
final override var isReleased: Boolean = false
private set
protected var isInitialized: Boolean = false
private set
protected val blocks: List<Block> get() = documentTracker.blocks
internal val LOCK: DocumentTracker.Lock get() = documentTracker.LOCK
constructor(project: Project?, document: Document) {
this.project = project
this.document = document
vcsDocument = DocumentImpl(this.document.immutableCharSequence, true)
vcsDocument.putUserData(UndoConstants.DONT_RECORD_UNDO, true)
vcsDocument.setReadOnly(true)
documentTracker = DocumentTracker(vcsDocument, this.document, createDocumentTrackerHandler())
Disposer.register(disposable, documentTracker)
}
@CalledInAwt
protected open fun isDetectWhitespaceChangedLines(): Boolean = false
@CalledInAwt
protected open fun fireFileUnchanged() {}
protected open fun fireLinesUnchanged(startLine: Int, endLine: Int) {}
override val virtualFile: VirtualFile? get() = null
protected abstract fun Block.toRange(): R
protected open fun createDocumentTrackerHandler(): DocumentTracker.Handler = MyDocumentTrackerHandler()
override fun getRanges(): List<R>? {
application.assertReadAccessAllowed()
LOCK.read {
if (!isValid()) return null
return blocks.filter { !it.range.isEmpty }.map { it.toRange() }
}
}
@CalledInAwt
open fun setBaseRevision(vcsContent: CharSequence) {
setBaseRevision(vcsContent, null)
}
@CalledInAwt
protected fun setBaseRevision(vcsContent: CharSequence, beforeUnfreeze: (() -> Unit)?) {
application.assertIsDispatchThread()
if (isReleased) return
documentTracker.doFrozen(Side.LEFT) {
updateDocument(Side.LEFT) {
vcsDocument.setText(vcsContent)
}
beforeUnfreeze?.invoke()
}
if (!isInitialized) {
isInitialized = true
updateHighlighters()
}
}
@CalledInAwt
fun dropBaseRevision() {
application.assertIsDispatchThread()
if (isReleased) return
isInitialized = false
updateHighlighters()
}
@CalledInAwt
protected fun updateDocument(side: Side, task: (Document) -> Unit): Boolean {
return updateDocument(side, null, task)
}
@CalledInAwt
protected fun updateDocument(side: Side, commandName: String?, task: (Document) -> Unit): Boolean {
if (side.isLeft) {
vcsDocument.setReadOnly(false)
try {
CommandProcessor.getInstance().runUndoTransparentAction {
task(vcsDocument)
}
return true
}
finally {
vcsDocument.setReadOnly(true)
}
}
else {
return DiffUtil.executeWriteCommand(document, project, commandName, { task(document) })
}
}
@CalledInAwt
override fun doFrozen(task: Runnable) {
documentTracker.doFrozen({ task.run() })
}
fun release() {
val runnable = Runnable {
if (isReleased) return@Runnable
isReleased = true
Disposer.dispose(disposable)
}
if (!application.isDispatchThread || LOCK.isHeldByCurrentThread) {
application.invokeLater(runnable)
}
else {
runnable.run()
}
}
protected open inner class MyDocumentTrackerHandler : DocumentTracker.Handler {
override fun onRangeShifted(before: Block, after: Block) {
after.ourData.innerRanges = before.ourData.innerRanges
}
override fun afterRangeChange() {
updateHighlighters()
}
override fun afterBulkRangeChange() {
checkIfFileUnchanged()
calcInnerRanges()
updateHighlighters()
}
override fun onUnfreeze(side: Side) {
calcInnerRanges()
updateHighlighters()
}
private fun checkIfFileUnchanged() {
if (blocks.isEmpty()) {
fireFileUnchanged()
}
}
private fun calcInnerRanges() {
if (isDetectWhitespaceChangedLines() &&
!documentTracker.isFrozen()) {
for (block in blocks) {
if (block.ourData.innerRanges == null) {
block.ourData.innerRanges = calcInnerRanges(block)
}
}
}
}
}
private fun calcInnerRanges(block: Block): List<Range.InnerRange> {
if (block.start == block.end || block.vcsStart == block.vcsEnd) return emptyList()
return createInnerRanges(block.range,
vcsDocument.immutableCharSequence, document.immutableCharSequence,
vcsDocument.lineOffsets, document.lineOffsets)
}
protected fun updateHighlighters() {
renderer.scheduleUpdate()
}
@CalledInAwt
protected fun updateInnerRanges() {
LOCK.write {
if (isDetectWhitespaceChangedLines()) {
for (block in blocks) {
block.ourData.innerRanges = calcInnerRanges(block)
}
}
else {
for (block in blocks) {
block.ourData.innerRanges = null
}
}
updateHighlighters()
}
}
override fun isOperational(): Boolean = LOCK.read {
return isInitialized && !isReleased
}
override fun isValid(): Boolean = LOCK.read {
return isOperational() && !documentTracker.isFrozen()
}
override fun findRange(range: Range): R? = findBlock(range)?.toRange()
protected fun findBlock(range: Range): Block? {
LOCK.read {
if (!isValid()) return null
for (block in blocks) {
if (block.start == range.line1 &&
block.end == range.line2 &&
block.vcsStart == range.vcsLine1 &&
block.vcsEnd == range.vcsLine2) {
return block
}
}
return null
}
}
override fun getNextRange(line: Int): R? {
LOCK.read {
if (!isValid()) return null
for (block in blocks) {
if (line < block.end && !block.isSelectedByLine(line)) {
return block.toRange()
}
}
return null
}
}
override fun getPrevRange(line: Int): R? {
LOCK.read {
if (!isValid()) return null
for (block in blocks.reversed()) {
if (line > block.start && !block.isSelectedByLine(line)) {
return block.toRange()
}
}
return null
}
}
override fun getRangesForLines(lines: BitSet): List<R>? {
LOCK.read {
if (!isValid()) return null
val result = ArrayList<R>()
for (block in blocks) {
if (block.isSelectedByLine(lines)) {
result.add(block.toRange())
}
}
return result
}
}
override fun getRangeForLine(line: Int): R? {
LOCK.read {
if (!isValid()) return null
for (block in blocks) {
if (block.isSelectedByLine(line)) {
return block.toRange()
}
}
return null
}
}
@CalledInAwt
override fun rollbackChanges(range: Range) {
val newRange = findBlock(range)
if (newRange != null) {
runBulkRollback { it == newRange }
}
}
@CalledInAwt
override fun rollbackChanges(lines: BitSet) {
runBulkRollback { it.isSelectedByLine(lines) }
}
@CalledInAwt
protected fun runBulkRollback(condition: (Block) -> Boolean) {
if (!isValid()) return
updateDocument(Side.RIGHT, VcsBundle.message("command.name.rollback.change")) {
documentTracker.partiallyApplyBlocks(Side.RIGHT, condition) { block, shift ->
fireLinesUnchanged(block.start + shift, block.start + shift + (block.vcsEnd - block.vcsStart))
}
}
}
override fun isLineModified(line: Int): Boolean {
return isRangeModified(line, line + 1)
}
override fun isRangeModified(startLine: Int, endLine: Int): Boolean {
if (startLine == endLine) return false
assert(startLine < endLine)
LOCK.read {
if (!isValid()) return false
for (block in blocks) {
if (block.start >= endLine) return false
if (block.end > startLine) return true
}
return false
}
}
override fun transferLineFromVcs(line: Int, approximate: Boolean): Int {
return transferLine(line, approximate, true)
}
override fun transferLineToVcs(line: Int, approximate: Boolean): Int {
return transferLine(line, approximate, false)
}
private fun transferLine(line: Int, approximate: Boolean, fromVcs: Boolean): Int {
LOCK.read {
if (!isValid()) return if (approximate) line else ABSENT_LINE_NUMBER
var result = line
for (block in blocks) {
val startLine1 = if (fromVcs) block.vcsStart else block.start
val endLine1 = if (fromVcs) block.vcsEnd else block.end
val startLine2 = if (fromVcs) block.start else block.vcsStart
val endLine2 = if (fromVcs) block.end else block.vcsEnd
if (line in startLine1 until endLine1) {
return if (approximate) startLine2 else ABSENT_LINE_NUMBER
}
if (endLine1 > line) return result
val length1 = endLine1 - startLine1
val length2 = endLine2 - startLine2
result += length2 - length1
}
return result
}
}
protected open class BlockData(internal var innerRanges: List<Range.InnerRange>? = null)
protected open fun createBlockData(): BlockData = BlockData()
protected open val Block.ourData: BlockData get() = getBlockData(this)
protected fun getBlockData(block: Block): BlockData {
if (block.data == null) block.data = createBlockData()
return block.data as BlockData
}
protected val Block.innerRanges: List<Range.InnerRange>? get() = this.ourData.innerRanges.nullize()
companion object {
@JvmStatic protected val LOG: Logger = Logger.getInstance("#com.intellij.openapi.vcs.ex.LineStatusTracker")
@JvmStatic protected val Block.start: Int get() = range.start2
@JvmStatic protected val Block.end: Int get() = range.end2
@JvmStatic protected val Block.vcsStart: Int get() = range.start1
@JvmStatic protected val Block.vcsEnd: Int get() = range.end1
@JvmStatic protected fun Block.isSelectedByLine(line: Int): Boolean = DiffUtil.isSelectedByLine(line, this.range.start2, this.range.end2)
@JvmStatic protected fun Block.isSelectedByLine(lines: BitSet): Boolean = DiffUtil.isSelectedByLine(lines, this.range.start2, this.range.end2)
}
@TestOnly
fun getDocumentTrackerInTestMode(): DocumentTracker = documentTracker
}
| apache-2.0 |
paplorinc/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/actions/SelectChangesGroupingActionGroup.kt | 6 | 1837 | // 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.openapi.vcs.changes.actions
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.vcs.changes.ui.ChangesGroupingSupport
import com.intellij.ui.JBColor
import com.intellij.ui.SeparatorWithText
import com.intellij.ui.popup.PopupFactoryImpl
import com.intellij.ui.popup.list.PopupListElementRenderer
import java.awt.Graphics
class SelectChangesGroupingActionGroup : DefaultActionGroup(), DumbAware {
override fun canBePerformed(context: DataContext): Boolean = true
override fun update(e: AnActionEvent) {
e.presentation.isEnabled = e.getData(ChangesGroupingSupport.KEY) != null
}
override fun actionPerformed(e: AnActionEvent) {
val group = DefaultActionGroup().apply {
addSeparator(e.presentation.text)
addAll(this@SelectChangesGroupingActionGroup)
}
val popup = SelectChangesGroupingActionPopup(group, e.dataContext)
val component = e.inputEvent?.component
when (component) {
is ActionButtonComponent -> popup.showUnderneathOf(component)
else -> popup.showInBestPositionFor(e.dataContext)
}
}
}
private class SelectChangesGroupingActionPopup(group: ActionGroup, dataContext: DataContext) : PopupFactoryImpl.ActionGroupPopup(
null, group, dataContext, false, false, false, true, null, -1, null, null) {
override fun getListElementRenderer() = object : PopupListElementRenderer<Any>(this) {
override fun createSeparator() = object : SeparatorWithText() {
init {
textForeground = JBColor.BLACK
setCaptionCentered(false)
}
override fun paintLine(g: Graphics, x: Int, y: Int, width: Int) = Unit
}
}
} | apache-2.0 |
georocket/georocket | src/main/kotlin/io/georocket/output/xml/AllSameStrategy.kt | 1 | 473 | package io.georocket.output.xml
import io.georocket.storage.XmlChunkMeta
/**
* Merge chunks whose root XML elements are all equal
* @author Michel Kraemer
*/
class AllSameStrategy : AbstractMergeStrategy() {
override fun canMerge(metadata: XmlChunkMeta): Boolean {
return (parents == null || parents == metadata.parents)
}
override fun mergeParents(chunkMetadata: XmlChunkMeta) {
if (parents == null) {
parents = chunkMetadata.parents
}
}
}
| apache-2.0 |
google/intellij-community | platform/lang-impl/src/com/intellij/openapi/projectRoots/impl/jdkDownloader/RuntimeChooserDialog.kt | 4 | 8827 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.projectRoots.impl.jdkDownloader
import com.intellij.icons.AllIcons
import com.intellij.lang.LangBundle
import com.intellij.openapi.actionSystem.DataProvider
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import com.intellij.openapi.ide.CopyPasteManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.ComboBox
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.ui.ExperimentalUI
import com.intellij.ui.JBColor
import com.intellij.ui.SimpleColoredComponent
import com.intellij.ui.dsl.builder.*
import com.intellij.ui.dsl.gridLayout.Gaps
import com.intellij.ui.dsl.gridLayout.HorizontalAlign
import com.intellij.ui.dsl.gridLayout.VerticalAlign
import com.intellij.ui.dsl.gridLayout.toJBEmptyBorder
import com.intellij.util.castSafelyTo
import com.intellij.util.io.isDirectory
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.components.BorderLayoutPanel
import java.awt.datatransfer.DataFlavor
import java.awt.event.WindowAdapter
import java.awt.event.WindowEvent
import java.nio.file.Path
import java.nio.file.Paths
import javax.swing.JComponent
import javax.swing.JPanel
sealed class RuntimeChooserDialogResult {
object Cancel : RuntimeChooserDialogResult()
object UseDefault: RuntimeChooserDialogResult()
data class DownloadAndUse(val item: JdkItem, val path: Path) : RuntimeChooserDialogResult()
data class UseCustomJdk(val name: String, val path: Path) : RuntimeChooserDialogResult()
}
class RuntimeChooserDialog(
private val project: Project?,
private val model: RuntimeChooserModel,
) : DialogWrapper(project), DataProvider {
private val USE_DEFAULT_RUNTIME_CODE = NEXT_USER_EXIT_CODE + 42
private lateinit var jdkInstallDirSelector: TextFieldWithBrowseButton
private lateinit var jdkCombobox: ComboBox<RuntimeChooserItem>
init {
title = LangBundle.message("dialog.title.choose.ide.runtime")
isResizable = false
init()
initClipboardListener()
}
private fun initClipboardListener() {
val knownPaths = mutableSetOf<String>()
val clipboardUpdateAction = {
val newPath = runCatching {
CopyPasteManager.getInstance().contents?.getTransferData(DataFlavor.stringFlavor) as? String
}.getOrNull()
if (!newPath.isNullOrBlank() && knownPaths.add(newPath)) {
RuntimeChooserCustom.importDetectedItem(newPath.trim(), model)
}
}
val windowListener = object: WindowAdapter() {
override fun windowActivated(e: WindowEvent?) {
invokeLater(ModalityState.any()) {
clipboardUpdateAction()
}
}
}
window?.let { window ->
window.addWindowListener(windowListener)
Disposer.register(disposable) { window.removeWindowListener(windowListener) }
}
clipboardUpdateAction()
}
override fun getData(dataId: String): Any? {
return RuntimeChooserCustom.jdkDownloaderExtensionProvider.getData(dataId)
}
override fun createSouthAdditionalPanel(): JPanel {
return BorderLayoutPanel().apply {
addToCenter(
createJButtonForAction(
DialogWrapperExitAction(
LangBundle.message("dialog.button.choose.ide.runtime.useDefault"),
USE_DEFAULT_RUNTIME_CODE)
)
)
}
}
fun showDialogAndGetResult() : RuntimeChooserDialogResult {
show()
if (exitCode == USE_DEFAULT_RUNTIME_CODE) {
return RuntimeChooserDialogResult.UseDefault
}
if (isOK) run {
val jdkItem = jdkCombobox.selectedItem.castSafelyTo<RuntimeChooserDownloadableItem>()?.item ?: return@run
val path = model.getInstallPathFromText(jdkItem, jdkInstallDirSelector.text)
return RuntimeChooserDialogResult.DownloadAndUse(jdkItem, path)
}
if (isOK) run {
val jdkItem = jdkCombobox.selectedItem.castSafelyTo<RuntimeChooserCustomItem>() ?: return@run
val home = Paths.get(jdkItem.homeDir)
if (home.isDirectory()) {
return RuntimeChooserDialogResult.UseCustomJdk(listOfNotNull(jdkItem.displayName, jdkItem.version).joinToString(" "), home)
}
}
return RuntimeChooserDialogResult.Cancel
}
override fun createTitlePane(): JComponent {
return panel {
row {
icon(AllIcons.General.Warning)
.verticalAlign(VerticalAlign.TOP)
.gap(RightGap.SMALL)
text(LangBundle.message("dialog.label.choose.ide.runtime.warn", ApplicationInfo.getInstance().shortCompanyName),
maxLineLength = DEFAULT_COMMENT_WIDTH)
}
}.apply {
val customLine = when {
SystemInfo.isWindows -> JBUI.Borders.customLine(JBColor.border(), 1, 0, 1, 0)
else -> JBUI.Borders.customLineBottom(JBColor.border())
}
border = JBUI.Borders.merge(JBUI.Borders.empty(10), customLine, true)
background = if (ExperimentalUI.isNewUI()) JBUI.CurrentTheme.Banner.WARNING_BACKGROUND else JBUI.CurrentTheme.Notification.BACKGROUND
foreground = JBUI.CurrentTheme.Notification.FOREGROUND
putClientProperty(DslComponentProperty.VISUAL_PADDINGS, Gaps.EMPTY)
}
}
override fun createCenterPanel(): JComponent {
jdkCombobox = object : ComboBox<RuntimeChooserItem>(model.mainComboBoxModel) {
init {
isSwingPopup = false
setRenderer(RuntimeChooserPresenter())
}
override fun setSelectedItem(anObject: Any?) {
if (anObject !is RuntimeChooserItem) return
if (anObject is RuntimeChooserAddCustomItem) {
RuntimeChooserCustom
.createSdkChooserPopup(jdkCombobox, [email protected])
?.showUnderneathOf(jdkCombobox)
return
}
if (anObject is RuntimeChooserDownloadableItem || anObject is RuntimeChooserCustomItem || anObject is RuntimeChooserCurrentItem) {
super.setSelectedItem(anObject)
}
}
}
return panel {
row(LangBundle.message("dialog.label.choose.ide.runtime.current")) {
val control = SimpleColoredComponent()
cell(control).horizontalAlign(HorizontalAlign.FILL)
model.currentRuntime.getAndSubscribe(disposable) {
control.clear()
if (it != null) {
RuntimeChooserPresenter.run {
control.presetCurrentRuntime(it)
}
}
}
}
row(LangBundle.message("dialog.label.choose.ide.runtime.combo")) {
cell(jdkCombobox).horizontalAlign(HorizontalAlign.FILL)
}
//download row
row(LangBundle.message("dialog.label.choose.ide.runtime.location")) {
jdkInstallDirSelector = textFieldWithBrowseButton(
project = project,
browseDialogTitle = LangBundle.message("dialog.title.choose.ide.runtime.select.path.to.install.jdk"),
fileChooserDescriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor()
).horizontalAlign(HorizontalAlign.FILL)
.comment(LangBundle.message("dialog.message.choose.ide.runtime.select.path.to.install.jdk"))
.component
val updateLocation = {
when(val item = jdkCombobox.selectedItem){
is RuntimeChooserDownloadableItem -> {
jdkInstallDirSelector.text = model.getDefaultInstallPathFor(item.item)
jdkInstallDirSelector.setButtonEnabled(true)
jdkInstallDirSelector.isEditable = true
jdkInstallDirSelector.setButtonVisible(true)
}
is RuntimeChooserItemWithFixedLocation -> {
jdkInstallDirSelector.text = FileUtil.getLocationRelativeToUserHome(item.homeDir, false)
jdkInstallDirSelector.setButtonEnabled(false)
jdkInstallDirSelector.isEditable = false
jdkInstallDirSelector.setButtonVisible(false)
}
else -> {
jdkInstallDirSelector.text = ""
jdkInstallDirSelector.setButtonEnabled(false)
jdkInstallDirSelector.isEditable = false
jdkInstallDirSelector.setButtonVisible(false)
}
}
}
updateLocation()
jdkCombobox.addItemListener { updateLocation() }
}
}.apply {
border = IntelliJSpacingConfiguration().dialogGap.toJBEmptyBorder()
putClientProperty(IS_VISUAL_PADDING_COMPENSATED_ON_COMPONENT_LEVEL_KEY, false)
}
}
}
| apache-2.0 |
google/intellij-community | plugins/gitlab/src/org/jetbrains/plugins/gitlab/GitLabSettingsConfigurable.kt | 5 | 2040 | // 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.gitlab
import com.intellij.collaboration.auth.ui.AccountsPanelFactory
import com.intellij.openapi.components.service
import com.intellij.openapi.options.BoundConfigurable
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.util.Disposer
import com.intellij.ui.dsl.builder.panel
import com.intellij.ui.dsl.gridLayout.HorizontalAlign
import com.intellij.ui.dsl.gridLayout.VerticalAlign
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import org.jetbrains.plugins.gitlab.authentication.accounts.GitLabAccountManager
import org.jetbrains.plugins.gitlab.authentication.accounts.GitLabProjectDefaultAccountHolder
import org.jetbrains.plugins.gitlab.authentication.ui.GitLabAccountsDetailsLoader
import org.jetbrains.plugins.gitlab.authentication.ui.GitLabAccountsListModel
import org.jetbrains.plugins.gitlab.util.GitLabUtil
internal class GitLabSettingsConfigurable(private val project: Project)
: BoundConfigurable(GitLabUtil.SERVICE_DISPLAY_NAME, "settings.gitlab") {
override fun createPanel(): DialogPanel {
val accountManager = service<GitLabAccountManager>()
val defaultAccountHolder = project.service<GitLabProjectDefaultAccountHolder>()
val accountsModel = GitLabAccountsListModel(project)
val scope = CoroutineScope(SupervisorJob()).also { Disposer.register(disposable!!) { it.cancel() } }
val detailsLoader = GitLabAccountsDetailsLoader(scope, accountManager, accountsModel)
val accountsPanelFactory = AccountsPanelFactory(accountManager, defaultAccountHolder, accountsModel, detailsLoader, disposable!!)
return panel {
row {
accountsPanelFactory.accountsPanelCell(this, true)
.horizontalAlign(HorizontalAlign.FILL)
.verticalAlign(VerticalAlign.FILL)
}.resizableRow()
}
}
} | apache-2.0 |
google/iosched | mobile/src/main/java/com/google/samples/apps/iosched/util/UiUtils.kt | 1 | 3485 | /*
* Copyright 2019 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.util
import android.content.Context
import android.graphics.drawable.Drawable
import android.view.View
import androidx.appcompat.content.res.AppCompatResources
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.graphics.drawable.DrawableCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.google.samples.apps.iosched.R
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
fun navigationItemBackground(context: Context): Drawable? {
// Need to inflate the drawable and CSL via AppCompatResources to work on Lollipop
var background =
AppCompatResources.getDrawable(context, R.drawable.navigation_item_background)
if (background != null) {
val tint = AppCompatResources.getColorStateList(
context, R.color.navigation_item_background_tint
)
background = DrawableCompat.wrap(background.mutate())
background.setTintList(tint)
}
return background
}
/**
* Map a slideOffset (in the range `[-1, 1]`) to an alpha value based on the desired range.
* For example, `slideOffsetToAlpha(0.5, 0.25, 1) = 0.33` because 0.5 is 1/3 of the way between
* 0.25 and 1. The result value is additionally clamped to the range `[0, 1]`.
*/
fun slideOffsetToAlpha(value: Float, rangeMin: Float, rangeMax: Float): Float {
return ((value - rangeMin) / (rangeMax - rangeMin)).coerceIn(0f, 1f)
}
/**
* Launches a new coroutine and repeats `block` every time the Fragment's viewLifecycleOwner
* is in and out of `minActiveState` lifecycle state.
*/
inline fun Fragment.launchAndRepeatWithViewLifecycle(
minActiveState: Lifecycle.State = Lifecycle.State.STARTED,
crossinline block: suspend CoroutineScope.() -> Unit
) {
viewLifecycleOwner.lifecycleScope.launch {
viewLifecycleOwner.lifecycle.repeatOnLifecycle(minActiveState) {
block()
}
}
}
/**
* Set the maximum width the view should take as a percent of its parent. The view must a direct
* child of a ConstraintLayout.
*/
fun setContentMaxWidth(view: View) {
val parent = view.parent as? ConstraintLayout ?: return
val layoutParams = view.layoutParams as ConstraintLayout.LayoutParams
val screenDensity = view.resources.displayMetrics.density
val widthDp = parent.width / screenDensity
val widthPercent = getContextMaxWidthPercent(widthDp.toInt())
layoutParams.matchConstraintPercentWidth = widthPercent
view.requestLayout()
}
private fun getContextMaxWidthPercent(maxWidthDp: Int): Float {
// These match @dimen/content_max_width_percent.
return when {
maxWidthDp >= 1024 -> 0.6f
maxWidthDp >= 840 -> 0.7f
maxWidthDp >= 600 -> 0.8f
else -> 1f
}
}
| apache-2.0 |
Leifzhang/AndroidRouter | CoroutineSupport/src/androidTest/java/com/kronos/router/coroutine/ExampleInstrumentedTest.kt | 2 | 686 | package com.kronos.router.coroutine
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.kronos.router.coroutine.test", appContext.packageName)
}
} | mit |
prt2121/kotlin-ios | message/ios/src/main/kotlin/com/prat/message/Message.kt | 1 | 688 | package com.prat.message
import org.robovm.apple.foundation.NSAutoreleasePool
import org.robovm.apple.uikit.UIApplication
import org.robovm.apple.uikit.UIApplicationDelegateAdapter
import org.robovm.apple.uikit.UIApplicationLaunchOptions
class Message : UIApplicationDelegateAdapter() {
override fun didFinishLaunching(application: UIApplication?, launchOptions: UIApplicationLaunchOptions?): Boolean {
return true
}
companion object {
@JvmStatic fun main(args: Array<String>) {
val pool = NSAutoreleasePool()
UIApplication.main<UIApplication, Message>(args, null, Message::class.java)
pool.release()
}
}
}
| apache-2.0 |
allotria/intellij-community | platform/testFramework/src/com/intellij/util/io/impl/DirectoryContentSpecImpl.kt | 1 | 7410 | // 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.util.io.impl
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.CharsetToolkit
import com.intellij.util.io.*
import org.junit.Assert.*
import java.io.File
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Path
import java.util.*
import kotlin.collections.LinkedHashMap
sealed class DirectoryContentSpecImpl : DirectoryContentSpec {
abstract override fun mergeWith(other: DirectoryContentSpec): DirectoryContentSpecImpl
}
abstract class DirectorySpecBase : DirectoryContentSpecImpl() {
protected val children: LinkedHashMap<String, DirectoryContentSpecImpl> = LinkedHashMap()
fun addChild(name: String, spec: DirectoryContentSpecImpl) {
if (name in children) {
val existing = children[name]
if (spec is DirectorySpecBase && existing is DirectorySpecBase) {
existing.children += spec.children
return
}
throw IllegalArgumentException("'$name' already exists")
}
children[name] = spec
}
protected fun generateInDirectory(target: File) {
for ((name, child) in children) {
child.generate(File(target, name))
}
}
override fun generateInTempDir(): Path {
val target = FileUtil.createTempDirectory("directory-by-spec", null, true)
generate(target)
return target.toPath()
}
fun getChildren() : Map<String, DirectoryContentSpecImpl> = Collections.unmodifiableMap(children)
override fun mergeWith(other: DirectoryContentSpec): DirectoryContentSpecImpl {
require(other.javaClass == javaClass)
other as DirectorySpecBase
val result = when (other) {
is DirectorySpec -> DirectorySpec()
is ZipSpec -> ZipSpec()
else -> error(other)
}
result.children.putAll(children)
for ((name, child) in other.children) {
val oldChild = children[name]
result.children[name] = oldChild?.mergeWith(child) ?: child
}
return result
}
}
class DirectorySpec : DirectorySpecBase() {
override fun generate(target: File) {
if (!FileUtil.createDirectory(target)) {
throw IOException("Cannot create directory $target")
}
generateInDirectory(target)
}
}
class ZipSpec : DirectorySpecBase() {
override fun generate(target: File) {
val contentDir = FileUtil.createTempDirectory("zip-content", null, false)
try {
generateInDirectory(contentDir)
Compressor.Zip(target).use { it.addDirectory(contentDir) }
}
finally {
FileUtil.delete(contentDir)
}
}
override fun generateInTempDir(): Path {
val target = FileUtil.createTempFile("zip-by-spec", ".zip", true)
generate(target)
return target.toPath()
}
}
class FileSpec(val content: ByteArray?) : DirectoryContentSpecImpl() {
override fun generate(target: File) {
FileUtil.writeToFile(target, content ?: ByteArray(0))
}
override fun generateInTempDir(): Path {
val target = FileUtil.createTempFile("file-by-spec", null, true)
generate(target)
return target.toPath()
}
override fun mergeWith(other: DirectoryContentSpec): DirectoryContentSpecImpl {
return other as DirectoryContentSpecImpl
}
}
class DirectoryContentBuilderImpl(val result: DirectorySpecBase) : DirectoryContentBuilder() {
override fun addChild(name: String, spec: DirectoryContentSpecImpl) {
result.addChild(name, spec)
}
override fun file(name: String) {
addChild(name, FileSpec(null))
}
override fun file(name: String, text: String) {
file(name, text.toByteArray())
}
override fun file(name: String, content: ByteArray) {
addChild(name, FileSpec(content))
}
}
fun assertDirectoryContentMatches(file: File,
spec: DirectoryContentSpecImpl,
relativePath: String,
fileTextMatcher: FileTextMatcher,
filePathFilter: (String) -> Boolean) {
assertTrue("$file doesn't exist", file.exists())
when (spec) {
is DirectorySpec -> {
assertDirectoryMatches(file, spec, relativePath, fileTextMatcher, filePathFilter)
}
is ZipSpec -> {
assertTrue("$file is not a file", file.isFile)
val dirForExtracted = FileUtil.createTempDirectory("extracted-${file.name}", null, false)
ZipUtil.extract(file, dirForExtracted, null)
assertDirectoryMatches(dirForExtracted, spec, relativePath, fileTextMatcher, filePathFilter)
FileUtil.delete(dirForExtracted)
}
is FileSpec -> {
assertTrue("$file is not a file", file.isFile)
if (spec.content != null) {
val actualBytes = FileUtil.loadFileBytes(file)
if (!Arrays.equals(actualBytes, spec.content)) {
val actualString = actualBytes.convertToText()
val expectedString = spec.content.convertToText()
val place = if (relativePath != ".") " at $relativePath" else ""
if (actualString != null && expectedString != null) {
if (!fileTextMatcher.matches(actualString, expectedString)) {
assertEquals("File content mismatch$place:", expectedString, actualString)
}
}
else {
fail("Binary file content mismatch$place")
}
}
}
}
}
}
private fun ByteArray.convertToText(): String? {
val encoding = CharsetToolkit(this, Charsets.UTF_8, false).guessFromContent(size)
val charset = when (encoding) {
CharsetToolkit.GuessedEncoding.SEVEN_BIT -> Charsets.US_ASCII
CharsetToolkit.GuessedEncoding.VALID_UTF8 -> Charsets.UTF_8
else -> return null
}
return String(this, charset)
}
private fun assertDirectoryMatches(file: File,
spec: DirectorySpecBase,
relativePath: String,
fileTextMatcher: FileTextMatcher,
filePathFilter: (String) -> Boolean) {
assertTrue("$file is not a directory", file.isDirectory)
fun childNameFilter(name: String) = filePathFilter("$relativePath/$name")
val actualChildrenNames = file.listFiles()!!.filter { it.isDirectory || childNameFilter(it.name) }
.map { it.name }.sortedWith(String.CASE_INSENSITIVE_ORDER)
val children = spec.getChildren()
val expectedChildrenNames = children.entries.filter { it.value !is FileSpec || childNameFilter(it.key) }
.map { it.key }.sortedWith(String.CASE_INSENSITIVE_ORDER)
assertEquals("Directory content mismatch${if (relativePath != "") " at $relativePath" else ""}:",
expectedChildrenNames.joinToString("\n"), actualChildrenNames.joinToString("\n"))
for (child in actualChildrenNames) {
assertDirectoryContentMatches(File(file, child), children.get(child)!!, "$relativePath/$child", fileTextMatcher, filePathFilter)
}
}
internal fun createSpecByDirectory(dir: Path): DirectorySpec {
val spec = DirectorySpec()
dir.directoryStreamIfExists { children ->
children.forEach {
spec.addChild(it.fileName.toString(), createSpecByPath(it))
}
}
return spec
}
private fun createSpecByPath(path: Path): DirectoryContentSpecImpl {
if (path.isFile()) {
return FileSpec(Files.readAllBytes(path))
}
//todo support zip files
return createSpecByDirectory(path)
}
| apache-2.0 |
ursjoss/sipamato | public/public-entity/src/test/kotlin/ch/difty/scipamato/publ/entity/NewStudyTest.kt | 2 | 862 | @file:Suppress("SpellCheckingInspection")
package ch.difty.scipamato.publ.entity
import nl.jqno.equalsverifier.EqualsVerifier
import org.amshove.kluent.shouldBeEqualTo
internal class NewStudyTest : PublicDbEntityTest<NewStudy>() {
override fun newEntity() =
NewStudy(
sort = 1,
number = 10,
year = 2018,
authors = "authors",
headline = "hl",
description = "descr",
)
override fun assertSpecificGetters() {
entity.sort shouldBeEqualTo 1
entity.number shouldBeEqualTo 10
entity.reference shouldBeEqualTo "(authors; 2018)"
entity.headline shouldBeEqualTo "hl"
entity.description shouldBeEqualTo "descr"
}
override fun verifyEquals() {
EqualsVerifier.simple().forClass(NewStudy::class.java).verify()
}
}
| gpl-3.0 |
allotria/intellij-community | plugins/github/src/org/jetbrains/plugins/github/api/data/pullrequest/GHTeam.kt | 3 | 571 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.api.data.pullrequest
import org.jetbrains.plugins.github.api.data.GHNode
class GHTeam(id: String,
val slug: String,
override val url: String,
override val avatarUrl: String,
override val name: String?,
val combinedSlug: String)
: GHNode(id), GHPullRequestRequestedReviewer {
override val shortName: String = combinedSlug
} | apache-2.0 |
LivingDoc/livingdoc | livingdoc-engine/src/main/kotlin/org/livingdoc/engine/execution/examples/scenarios/ScenarioNoFixture.kt | 2 | 1155 | package org.livingdoc.engine.execution.examples.scenarios
import org.livingdoc.engine.LivingDoc
import org.livingdoc.engine.fixtures.Fixture
import org.livingdoc.repositories.model.scenario.Scenario
import org.livingdoc.results.Status
import org.livingdoc.results.examples.scenarios.ScenarioResult
class ScenarioNoFixture : Fixture<Scenario> {
/**
* Executes the given test data as a manual test
*
* Does not throw any kind of exception.
* Exceptional state of the execution is packaged inside the [ScenarioResult] in
* the form of different status objects.
*
* @param testData Test data of the corresponding type
*/
override fun execute(testData: Scenario): ScenarioResult {
val resultBuilder = ScenarioResult.Builder()
.withScenario(testData).withFixtureSource(this.javaClass)
if (LivingDoc.failFastActivated) {
return resultBuilder.withStatus(
Status.Skipped
).build()
}
if (testData.description.isManual) {
resultBuilder.withStatus(Status.Manual)
}
return resultBuilder.build()
}
}
| apache-2.0 |
JetBrains/teamcity-dnx-plugin | plugin-dotnet-agent/src/main/kotlin/jetbrains/buildServer/dotnet/SystemParametersProvider.kt | 1 | 774 | package jetbrains.buildServer.dotnet
import jetbrains.buildServer.agent.VirtualContext
import jetbrains.buildServer.agent.runner.ParameterType
import jetbrains.buildServer.agent.runner.ParametersService
class SystemParametersProvider(
private val _parametersService: ParametersService,
private val _virtualContext: VirtualContext)
: MSBuildParametersProvider {
override fun getParameters(context: DotnetBuildContext): Sequence<MSBuildParameter> = sequence {
for (paramName in _parametersService.getParameterNames(ParameterType.System)) {
_parametersService.tryGetParameter(ParameterType.System, paramName)?.let {
yield(MSBuildParameter(paramName, _virtualContext.resolvePath(it)))
}
}
}
} | apache-2.0 |
F43nd1r/acra-backend | acrarium/src/main/kotlin/com/faendir/acra/ui/view/SettingsView.kt | 1 | 3138 | /*
* (C) Copyright 2019 Lukas Morawietz (https://github.com/F43nd1r)
*
* 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.faendir.acra.ui.view
import com.faendir.acra.i18n.Messages
import com.faendir.acra.navigation.View
import com.faendir.acra.settings.LocalSettings
import com.faendir.acra.ui.component.HasAcrariumTitle
import com.faendir.acra.i18n.TranslatableText
import com.faendir.acra.ui.ext.Align
import com.faendir.acra.ui.ext.content
import com.faendir.acra.ui.ext.formLayout
import com.faendir.acra.ui.ext.setAlignSelf
import com.faendir.acra.ui.ext.translatableCheckbox
import com.faendir.acra.ui.ext.translatableSelect
import com.faendir.acra.ui.view.main.MainView
import com.vaadin.flow.component.Composite
import com.vaadin.flow.component.formlayout.FormLayout.ResponsiveStep
import com.vaadin.flow.component.orderedlayout.FlexComponent
import com.vaadin.flow.component.orderedlayout.FlexComponent.JustifyContentMode
import com.vaadin.flow.component.orderedlayout.FlexLayout
import com.vaadin.flow.router.Route
import com.vaadin.flow.server.VaadinService
import com.vaadin.flow.server.VaadinSession
import com.vaadin.flow.theme.lumo.Lumo
/**
* @author lukas
* @since 10.09.19
*/
@View
@Route(value = "settings", layout = MainView::class)
class SettingsView(localSettings: LocalSettings) : Composite<FlexLayout>(), HasAcrariumTitle {
init {
content {
setSizeFull()
justifyContentMode = JustifyContentMode.CENTER
alignItems = FlexComponent.Alignment.CENTER
formLayout {
setResponsiveSteps(ResponsiveStep("0px", 1))
setAlignSelf(Align.AUTO)
translatableCheckbox(Messages.DARK_THEME) {
value = localSettings.darkTheme
addValueChangeListener {
localSettings.darkTheme = it.value
VaadinSession.getCurrent().uIs.forEach { ui -> ui.element.setAttribute("theme", if (it.value) Lumo.DARK else Lumo.LIGHT) }
}
}
translatableSelect(VaadinService.getCurrent().instantiator.i18NProvider.providedLocales, Messages.LOCALE) {
setItemLabelGenerator { it.getDisplayName(localSettings.locale) }
value = localSettings.locale
addValueChangeListener {
localSettings.locale = it.value
VaadinSession.getCurrent().locale = it.value
}
}
}
}
}
override val title = TranslatableText(Messages.SETTINGS)
} | apache-2.0 |
genonbeta/TrebleShot | app/src/main/java/org/monora/uprotocol/client/android/viewmodel/FilesViewModel.kt | 1 | 7682 | /*
* Copyright (C) 2021 Veli Tasalı
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.monora.uprotocol.client.android.viewmodel
import android.annotation.TargetApi
import android.content.Context
import android.content.Intent
import android.database.sqlite.SQLiteConstraintException
import android.net.Uri
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.ViewModel
import androidx.lifecycle.liveData
import androidx.lifecycle.viewModelScope
import com.genonbeta.android.framework.io.DocumentFile
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.monora.uprotocol.client.android.R
import org.monora.uprotocol.client.android.data.FileRepository
import org.monora.uprotocol.client.android.data.SelectionRepository
import org.monora.uprotocol.client.android.database.model.SafFolder
import org.monora.uprotocol.client.android.lifecycle.SingleLiveEvent
import org.monora.uprotocol.client.android.model.FileModel
import org.monora.uprotocol.client.android.model.ListItem
import org.monora.uprotocol.client.android.model.TitleSectionContentModel
import java.lang.ref.WeakReference
import java.text.Collator
import javax.inject.Inject
@HiltViewModel
class FilesViewModel @Inject internal constructor(
@ApplicationContext context: Context,
private val fileRepository: FileRepository,
private val selectionRepository: SelectionRepository,
) : ViewModel() {
private val context = WeakReference(context)
private val textFolder = context.getString(R.string.folder)
private val textFile = context.getString(R.string.file)
private val _files = MutableLiveData<List<ListItem>>()
val files = Transformations.map(
liveData {
requestPath(fileRepository.appDirectory)
emitSource(_files)
}
) {
selectionRepository.whenContains(it) { item, selected ->
if (item is FileModel) item.isSelected = selected
}
it
}
val isCustomStorageFolder: Boolean
get() = Uri.fromFile(fileRepository.defaultAppDirectory) != fileRepository.appDirectory.getUri()
private val _path = MutableLiveData<FileModel>()
val path = liveData {
emitSource(_path)
}
private val _pathTree = MutableLiveData<List<FileModel>>()
val pathTree = liveData {
emitSource(_pathTree)
}
val safAdded = SingleLiveEvent<SafFolder>()
val safFolders = fileRepository.getSafFolders()
var appDirectory
get() = fileRepository.appDirectory
set(value) {
fileRepository.appDirectory = value
}
fun clearStorageList() {
viewModelScope.launch(Dispatchers.IO) {
fileRepository.clearStorageList()
}
}
fun createFolder(displayName: String): Boolean {
val currentFolder = path.value ?: return false
val context = context.get() ?: return false
if (currentFolder.file.createDirectory(context, displayName) != null) {
requestPath(currentFolder.file)
return true
}
return false
}
private fun createOrderedFileList(file: DocumentFile): List<ListItem> {
val pathTree = mutableListOf<FileModel>()
var pathChild = file
do {
pathTree.add(FileModel(pathChild))
} while (pathChild.parent?.also { pathChild = it } != null)
pathTree.reverse()
_pathTree.postValue(pathTree)
val list = fileRepository.getFileList(file)
if (list.isEmpty()) return list
val collator = Collator.getInstance()
collator.strength = Collator.TERTIARY
val sortedList = list.sortedWith(compareBy(collator) {
it.file.getName()
})
val contents = ArrayList<ListItem>(0)
val files = ArrayList<FileModel>(0)
sortedList.forEach {
if (it.file.isDirectory()) contents.add(it)
else if (it.file.isFile()) files.add(it)
}
if (contents.isNotEmpty()) {
contents.add(0, TitleSectionContentModel(textFolder))
}
if (files.isNotEmpty()) {
contents.add(TitleSectionContentModel(textFile))
contents.addAll(files)
}
return contents
}
fun goUp(): Boolean {
val paths = pathTree.value ?: return false
if (paths.size < 2) {
return false
}
val iterator = paths.asReversed().listIterator()
if (iterator.hasNext()) {
iterator.next() // skip the first one that is already visible
do {
val next = iterator.next()
if (next.file.canRead()) {
requestPath(next.file)
return true
}
} while (iterator.hasNext())
}
return false
}
@TargetApi(19)
fun insertSafFolder(uri: Uri) {
viewModelScope.launch(Dispatchers.IO) {
try {
val context = context.get() ?: return@launch
context.contentResolver.takePersistableUriPermission(
uri, Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
)
val document = DocumentFile.fromUri(context, uri, true)
val safFolder = SafFolder(uri, document.getName())
try {
fileRepository.insertFolder(safFolder)
} catch (ignored: SQLiteConstraintException) {
// The selected path may already exist!
}
safAdded.postValue(safFolder)
} catch (e: Exception) {
e.printStackTrace()
}
}
}
fun requestDefaultStorageFolder() {
viewModelScope.launch(Dispatchers.IO) {
context.get()?.let {
requestPathInternal(DocumentFile.fromFile(fileRepository.defaultAppDirectory))
}
}
}
fun requestStorageFolder() {
viewModelScope.launch(Dispatchers.IO) {
context.get()?.let {
requestPathInternal(fileRepository.appDirectory)
}
}
}
fun requestPath(file: DocumentFile) {
viewModelScope.launch(Dispatchers.IO) {
requestPathInternal(file)
}
}
fun requestPath(folder: SafFolder) {
viewModelScope.launch(Dispatchers.IO) {
try {
context.get()?.let {
requestPathInternal(DocumentFile.fromUri(it, folder.uri, true))
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
private fun requestPathInternal(file: DocumentFile) {
_path.postValue(FileModel(file))
_files.postValue(createOrderedFileList(file))
}
}
| gpl-2.0 |
Kotlin/kotlinx.coroutines | kotlinx-coroutines-test/jvm/src/migration/TestCoroutineScope.kt | 1 | 15824 | /*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
@file:Suppress("DEPRECATION")
package kotlinx.coroutines.test
import kotlinx.coroutines.*
import kotlinx.coroutines.internal.*
import kotlin.coroutines.*
/**
* A scope which provides detailed control over the execution of coroutines for tests.
*
* This scope is deprecated in favor of [TestScope].
* Please see the
* [migration guide](https://github.com/Kotlin/kotlinx.coroutines/blob/master/kotlinx-coroutines-test/MIGRATION.md)
* for an instruction on how to update the code for the new API.
*/
@ExperimentalCoroutinesApi
@Deprecated("Use `TestScope` in combination with `runTest` instead." +
"Please see the migration guide for details: " +
"https://github.com/Kotlin/kotlinx.coroutines/blob/master/kotlinx-coroutines-test/MIGRATION.md",
level = DeprecationLevel.WARNING)
// Since 1.6.0, ERROR in 1.7.0 and removed as experimental in 1.8.0
public interface TestCoroutineScope : CoroutineScope {
/**
* Called after the test completes.
*
* * It checks that there were no uncaught exceptions caught by its [CoroutineExceptionHandler].
* If there were any, then the first one is thrown, whereas the rest are suppressed by it.
* * It runs the tasks pending in the scheduler at the current time. If there are any uncompleted tasks afterwards,
* it fails with [UncompletedCoroutinesError].
* * It checks whether some new child [Job]s were created but not completed since this [TestCoroutineScope] was
* created. If so, it fails with [UncompletedCoroutinesError].
*
* For backward compatibility, if the [CoroutineExceptionHandler] is an [UncaughtExceptionCaptor], its
* [TestCoroutineExceptionHandler.cleanupTestCoroutines] behavior is performed.
* Likewise, if the [ContinuationInterceptor] is a [DelayController], its [DelayController.cleanupTestCoroutines]
* is called.
*
* @throws Throwable the first uncaught exception, if there are any uncaught exceptions.
* @throws AssertionError if any pending tasks are active.
* @throws IllegalStateException if called more than once.
*/
@ExperimentalCoroutinesApi
@Deprecated("Please call `runTest`, which automatically performs the cleanup, instead of using this function.")
// Since 1.6.0, ERROR in 1.7.0 and removed as experimental in 1.8.0
public fun cleanupTestCoroutines()
/**
* The delay-skipping scheduler used by the test dispatchers running the code in this scope.
*/
@ExperimentalCoroutinesApi
public val testScheduler: TestCoroutineScheduler
}
private class TestCoroutineScopeImpl(
override val coroutineContext: CoroutineContext
) : TestCoroutineScope {
private val lock = SynchronizedObject()
private var exceptions = mutableListOf<Throwable>()
private var cleanedUp = false
/**
* Reports an exception so that it is thrown on [cleanupTestCoroutines].
*
* If several exceptions are reported, only the first one will be thrown, and the other ones will be suppressed by
* it.
*
* Returns `false` if [cleanupTestCoroutines] was already called.
*/
fun reportException(throwable: Throwable): Boolean =
synchronized(lock) {
if (cleanedUp) {
false
} else {
exceptions.add(throwable)
true
}
}
override val testScheduler: TestCoroutineScheduler
get() = coroutineContext[TestCoroutineScheduler]!!
/** These jobs existed before the coroutine scope was used, so it's alright if they don't get cancelled. */
private val initialJobs = coroutineContext.activeJobs()
override fun cleanupTestCoroutines() {
val delayController = coroutineContext.delayController
val hasUnfinishedJobs = if (delayController != null) {
try {
delayController.cleanupTestCoroutines()
false
} catch (e: UncompletedCoroutinesError) {
true
}
} else {
testScheduler.runCurrent()
!testScheduler.isIdle(strict = false)
}
(coroutineContext[CoroutineExceptionHandler] as? UncaughtExceptionCaptor)?.cleanupTestCoroutines()
synchronized(lock) {
if (cleanedUp)
throw IllegalStateException("Attempting to clean up a test coroutine scope more than once.")
cleanedUp = true
}
exceptions.firstOrNull()?.let { toThrow ->
exceptions.drop(1).forEach { toThrow.addSuppressed(it) }
throw toThrow
}
if (hasUnfinishedJobs)
throw UncompletedCoroutinesError(
"Unfinished coroutines during teardown. Ensure all coroutines are" +
" completed or cancelled by your test."
)
val jobs = coroutineContext.activeJobs()
if ((jobs - initialJobs).isNotEmpty())
throw UncompletedCoroutinesError("Test finished with active jobs: $jobs")
}
}
internal fun CoroutineContext.activeJobs(): Set<Job> {
return checkNotNull(this[Job]).children.filter { it.isActive }.toSet()
}
/**
* A coroutine scope for launching test coroutines using [TestCoroutineDispatcher].
*
* [createTestCoroutineScope] is a similar function that defaults to [StandardTestDispatcher].
*/
@Deprecated(
"This constructs a `TestCoroutineScope` with a deprecated `CoroutineDispatcher` by default. " +
"Please use `createTestCoroutineScope` instead.",
ReplaceWith(
"createTestCoroutineScope(TestCoroutineDispatcher() + TestCoroutineExceptionHandler() + context)",
"kotlin.coroutines.EmptyCoroutineContext"
),
level = DeprecationLevel.WARNING
)
// Since 1.6.0, ERROR in 1.7.0 and removed as experimental in 1.8.0
public fun TestCoroutineScope(context: CoroutineContext = EmptyCoroutineContext): TestCoroutineScope {
val scheduler = context[TestCoroutineScheduler] ?: TestCoroutineScheduler()
return createTestCoroutineScope(TestCoroutineDispatcher(scheduler) + TestCoroutineExceptionHandler() + context)
}
/**
* A coroutine scope for launching test coroutines.
*
* This is a function for aiding in migration from [TestCoroutineScope] to [TestScope].
* Please see the
* [migration guide](https://github.com/Kotlin/kotlinx.coroutines/blob/master/kotlinx-coroutines-test/MIGRATION.md)
* for an instruction on how to update the code for the new API.
*
* It ensures that all the test module machinery is properly initialized.
* * If [context] doesn't define a [TestCoroutineScheduler] for orchestrating the virtual time used for delay-skipping,
* a new one is created, unless either
* - a [TestDispatcher] is provided, in which case [TestDispatcher.scheduler] is used;
* - at the moment of the creation of the scope, [Dispatchers.Main] is delegated to a [TestDispatcher], in which case
* its [TestCoroutineScheduler] is used.
* * If [context] doesn't have a [ContinuationInterceptor], a [StandardTestDispatcher] is created.
* * A [CoroutineExceptionHandler] is created that makes [TestCoroutineScope.cleanupTestCoroutines] throw if there were
* any uncaught exceptions, or forwards the exceptions further in a platform-specific manner if the cleanup was
* already performed when an exception happened. Passing a [CoroutineExceptionHandler] is illegal, unless it's an
* [UncaughtExceptionCaptor], in which case the behavior is preserved for the time being for backward compatibility.
* If you need to have a specific [CoroutineExceptionHandler], please pass it to [launch] on an already-created
* [TestCoroutineScope] and share your use case at
* [our issue tracker](https://github.com/Kotlin/kotlinx.coroutines/issues).
* * If [context] provides a [Job], that job is used for the new scope; otherwise, a [CompletableJob] is created.
*
* @throws IllegalArgumentException if [context] has both [TestCoroutineScheduler] and a [TestDispatcher] linked to a
* different scheduler.
* @throws IllegalArgumentException if [context] has a [ContinuationInterceptor] that is not a [TestDispatcher].
* @throws IllegalArgumentException if [context] has an [CoroutineExceptionHandler] that is not an
* [UncaughtExceptionCaptor].
*/
@ExperimentalCoroutinesApi
@Deprecated(
"This function was introduced in order to help migrate from TestCoroutineScope to TestScope. " +
"Please use TestScope() construction instead, or just runTest(), without creating a scope.",
level = DeprecationLevel.WARNING
)
// Since 1.6.0, ERROR in 1.7.0 and removed as experimental in 1.8.0
public fun createTestCoroutineScope(context: CoroutineContext = EmptyCoroutineContext): TestCoroutineScope {
val ctxWithDispatcher = context.withDelaySkipping()
var scope: TestCoroutineScopeImpl? = null
val ownExceptionHandler =
object : AbstractCoroutineContextElement(CoroutineExceptionHandler), TestCoroutineScopeExceptionHandler {
override fun handleException(context: CoroutineContext, exception: Throwable) {
if (!scope!!.reportException(exception))
throw exception // let this exception crash everything
}
}
val exceptionHandler = when (val exceptionHandler = ctxWithDispatcher[CoroutineExceptionHandler]) {
is UncaughtExceptionCaptor -> exceptionHandler
null -> ownExceptionHandler
is TestCoroutineScopeExceptionHandler -> ownExceptionHandler
else -> throw IllegalArgumentException(
"A CoroutineExceptionHandler was passed to TestCoroutineScope. " +
"Please pass it as an argument to a `launch` or `async` block on an already-created scope " +
"if uncaught exceptions require special treatment."
)
}
val job: Job = ctxWithDispatcher[Job] ?: Job()
return TestCoroutineScopeImpl(ctxWithDispatcher + exceptionHandler + job).also {
scope = it
}
}
/** A marker that shows that this [CoroutineExceptionHandler] was created for [TestCoroutineScope]. With this,
* constructing a new [TestCoroutineScope] with the [CoroutineScope.coroutineContext] of an existing one will override
* the exception handler, instead of failing. */
private interface TestCoroutineScopeExceptionHandler : CoroutineExceptionHandler
private inline val CoroutineContext.delayController: DelayController?
get() {
val handler = this[ContinuationInterceptor]
return handler as? DelayController
}
/**
* The current virtual time on [testScheduler][TestCoroutineScope.testScheduler].
* @see TestCoroutineScheduler.currentTime
*/
@ExperimentalCoroutinesApi
public val TestCoroutineScope.currentTime: Long
get() = coroutineContext.delayController?.currentTime ?: testScheduler.currentTime
/**
* Advances the [testScheduler][TestCoroutineScope.testScheduler] by [delayTimeMillis] and runs the tasks up to that
* moment (inclusive).
*
* @see TestCoroutineScheduler.advanceTimeBy
*/
@ExperimentalCoroutinesApi
@Deprecated(
"The name of this function is misleading: it not only advances the time, but also runs the tasks " +
"scheduled *at* the ending moment.",
ReplaceWith("this.testScheduler.apply { advanceTimeBy(delayTimeMillis); runCurrent() }"),
DeprecationLevel.WARNING
)
// Since 1.6.0, ERROR in 1.7.0 and removed as experimental in 1.8.0
public fun TestCoroutineScope.advanceTimeBy(delayTimeMillis: Long): Unit =
when (val controller = coroutineContext.delayController) {
null -> {
testScheduler.advanceTimeBy(delayTimeMillis)
testScheduler.runCurrent()
}
else -> {
controller.advanceTimeBy(delayTimeMillis)
Unit
}
}
/**
* Advances the [testScheduler][TestCoroutineScope.testScheduler] to the point where there are no tasks remaining.
* @see TestCoroutineScheduler.advanceUntilIdle
*/
@ExperimentalCoroutinesApi
public fun TestCoroutineScope.advanceUntilIdle() {
coroutineContext.delayController?.advanceUntilIdle() ?: testScheduler.advanceUntilIdle()
}
/**
* Run any tasks that are pending at the current virtual time, according to
* the [testScheduler][TestCoroutineScope.testScheduler].
*
* @see TestCoroutineScheduler.runCurrent
*/
@ExperimentalCoroutinesApi
public fun TestCoroutineScope.runCurrent() {
coroutineContext.delayController?.runCurrent() ?: testScheduler.runCurrent()
}
@ExperimentalCoroutinesApi
@Deprecated(
"The test coroutine scope isn't able to pause its dispatchers in the general case. " +
"Only `TestCoroutineDispatcher` supports pausing; pause it directly, or use a dispatcher that is always " +
"\"paused\", like `StandardTestDispatcher`.",
ReplaceWith(
"(this.coroutineContext[ContinuationInterceptor]!! as DelayController).pauseDispatcher(block)",
"kotlin.coroutines.ContinuationInterceptor"
),
DeprecationLevel.WARNING
)
// Since 1.6.0, ERROR in 1.7.0 and removed as experimental in 1.8.0
public suspend fun TestCoroutineScope.pauseDispatcher(block: suspend () -> Unit) {
delayControllerForPausing.pauseDispatcher(block)
}
@ExperimentalCoroutinesApi
@Deprecated(
"The test coroutine scope isn't able to pause its dispatchers in the general case. " +
"Only `TestCoroutineDispatcher` supports pausing; pause it directly, or use a dispatcher that is always " +
"\"paused\", like `StandardTestDispatcher`.",
ReplaceWith(
"(this.coroutineContext[ContinuationInterceptor]!! as DelayController).pauseDispatcher()",
"kotlin.coroutines.ContinuationInterceptor"
),
level = DeprecationLevel.WARNING
)
// Since 1.6.0, ERROR in 1.7.0 and removed as experimental in 1.8.0
public fun TestCoroutineScope.pauseDispatcher() {
delayControllerForPausing.pauseDispatcher()
}
@ExperimentalCoroutinesApi
@Deprecated(
"The test coroutine scope isn't able to pause its dispatchers in the general case. " +
"Only `TestCoroutineDispatcher` supports pausing; pause it directly, or use a dispatcher that is always " +
"\"paused\", like `StandardTestDispatcher`.",
ReplaceWith(
"(this.coroutineContext[ContinuationInterceptor]!! as DelayController).resumeDispatcher()",
"kotlin.coroutines.ContinuationInterceptor"
),
level = DeprecationLevel.WARNING
)
// Since 1.6.0, ERROR in 1.7.0 and removed as experimental in 1.8.0
public fun TestCoroutineScope.resumeDispatcher() {
delayControllerForPausing.resumeDispatcher()
}
/**
* List of uncaught coroutine exceptions, for backward compatibility.
*
* The returned list is a copy of the exceptions caught during execution.
* During [TestCoroutineScope.cleanupTestCoroutines] the first element of this list is rethrown if it is not empty.
*
* Exceptions are only collected in this list if the [UncaughtExceptionCaptor] is in the test context.
*/
@Deprecated(
"This list is only populated if `UncaughtExceptionCaptor` is in the test context, and so can be " +
"easily misused. It is only present for backward compatibility and will be removed in the subsequent " +
"releases. If you need to check the list of exceptions, please consider creating your own " +
"`CoroutineExceptionHandler`.",
level = DeprecationLevel.WARNING
)
public val TestCoroutineScope.uncaughtExceptions: List<Throwable>
get() = (coroutineContext[CoroutineExceptionHandler] as? UncaughtExceptionCaptor)?.uncaughtExceptions
?: emptyList()
private val TestCoroutineScope.delayControllerForPausing: DelayController
get() = coroutineContext.delayController
?: throw IllegalStateException("This scope isn't able to pause its dispatchers")
| apache-2.0 |
leafclick/intellij-community | platform/diff-impl/tests/testSrc/com/intellij/diff/util/DiffUtilTest.kt | 2 | 7105 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.diff.util
import com.intellij.diff.DiffRequestFactoryImpl
import com.intellij.diff.DiffTestCase
import com.intellij.diff.comparison.ComparisonPolicy
import com.intellij.diff.tools.util.text.LineOffsetsUtil
import com.intellij.openapi.diff.DiffBundle
import com.intellij.openapi.editor.impl.DocumentImpl
import com.intellij.util.containers.ContainerUtil
import java.io.File
class DiffUtilTest : DiffTestCase() {
fun `test getSortedIndexes`() {
fun <T> doTest(vararg values: T, comparator: (T, T) -> Int) {
val list = values.toList()
val sortedIndexes = DiffUtil.getSortedIndexes(list, comparator)
val expected = ContainerUtil.sorted(list, comparator)
val actual = (0..values.size - 1).map { values[sortedIndexes[it]] }
assertOrderedEquals(expected, actual)
assertEquals(sortedIndexes.toSet().size, list.size)
}
doTest(1, 2, 3, 4, 5, 6, 7, 8) { v1, v2 -> v1 - v2 }
doTest(8, 7, 6, 5, 4, 3, 2, 1) { v1, v2 -> v1 - v2 }
doTest(1, 3, 5, 7, 8, 6, 4, 2) { v1, v2 -> v1 - v2 }
doTest(1, 2, 3, 4, 5, 6, 7, 8) { v1, v2 -> v2 - v1 }
doTest(8, 7, 6, 5, 4, 3, 2, 1) { v1, v2 -> v2 - v1 }
doTest(1, 3, 5, 7, 8, 6, 4, 2) { v1, v2 -> v2 - v1 }
}
fun `test merge conflict partially resolved confirmation message`() {
fun doTest(changes: Int, conflicts: Int, expected: String) {
val actual = DiffBundle.message("merge.dialog.apply.partially.resolved.changes.confirmation.message", changes, conflicts)
assertTrue(actual.startsWith(expected), actual)
}
doTest(1, 0, "There is one change left")
doTest(0, 1, "There is one conflict left")
doTest(1, 1, "There is one change and one conflict left")
doTest(2, 0, "There are 2 changes left")
doTest(0, 2, "There are 2 conflicts left")
doTest(2, 2, "There are 2 changes and 2 conflicts left")
doTest(1, 2, "There is one change and 2 conflicts left")
doTest(2, 1, "There are 2 changes and one conflict left")
doTest(2, 3, "There are 2 changes and 3 conflicts left")
}
fun `test diff content titles`() {
fun doTest(path: String, expected: String) {
val filePath = createFilePath(path)
val actual1 = DiffRequestFactoryImpl.getContentTitle(filePath)
val actual2 = DiffRequestFactoryImpl.getTitle(filePath, null, " <-> ")
val actual3 = DiffRequestFactoryImpl.getTitle(null, filePath, " <-> ")
val expectedNative = expected.replace('/', File.separatorChar)
assertEquals(expectedNative, actual1)
assertEquals(expectedNative, actual2)
assertEquals(expectedNative, actual3)
}
doTest("file.txt", "file.txt")
doTest("/path/to/file.txt", "file.txt (/path/to)")
doTest("/path/to/dir/", "/path/to/dir")
}
fun `test diff request titles`() {
fun doTest(path1: String, path2: String, expected: String) {
val filePath1 = createFilePath(path1)
val filePath2 = createFilePath(path2)
val actual = DiffRequestFactoryImpl.getTitle(filePath1, filePath2, " <-> ")
assertEquals(expected.replace('/', File.separatorChar), actual)
}
doTest("file1.txt", "file1.txt", "file1.txt")
doTest("/path/to/file1.txt", "/path/to/file1.txt", "file1.txt (/path/to)")
doTest("/path/to/dir1/", "/path/to/dir1/", "/path/to/dir1")
doTest("file1.txt", "file2.txt", "file1.txt <-> file2.txt")
doTest("/path/to/file1.txt", "/path/to/file2.txt", "file1.txt <-> file2.txt (/path/to)")
doTest("/path/to/dir1/", "/path/to/dir2/", "dir1 <-> dir2 (/path/to)")
doTest("/path/to/file1.txt", "/path/to_another/file1.txt", "file1.txt (/path/to <-> /path/to_another)")
doTest("/path/to/file1.txt", "/path/to_another/file2.txt", "file1.txt <-> file2.txt (/path/to <-> /path/to_another)")
doTest("/path/to/dir1/", "/path/to_another/dir2/", "dir1 <-> dir2 (/path/to <-> /path/to_another)")
doTest("file1.txt", "/path/to/file1.txt", "file1.txt <-> /path/to/file1.txt")
doTest("file1.txt", "/path/to/file2.txt", "file1.txt <-> /path/to/file2.txt")
doTest("/path/to/dir1/", "/path/to/file2.txt", "dir1/ <-> file2.txt (/path/to)")
doTest("/path/to/file1.txt", "/path/to/dir2/", "file1.txt <-> dir2/ (/path/to)")
doTest("/path/to/dir1/", "/path/to_another/file2.txt", "dir1/ <-> file2.txt (/path/to <-> /path/to_another)")
}
fun `test applyModification`() {
val runs = 10000
val textLength = 30
doAutoTest(System.currentTimeMillis(), runs) {
val text1 = generateText(textLength)
val text2 = generateText(textLength)
val lineOffsets1 = LineOffsetsUtil.create(text1)
val lineOffsets2 = LineOffsetsUtil.create(text2)
val fragments = MANAGER.compareLines(text1, text2, ComparisonPolicy.DEFAULT, INDICATOR)
val ranges = fragments.map {
Range(it.startLine1, it.endLine1, it.startLine2, it.endLine2)
}
val patched = DiffUtil.applyModification(text1, lineOffsets1, text2, lineOffsets2, ranges)
val base = textToReadableFormat(text1)
val expected = textToReadableFormat(text2)
val actual = textToReadableFormat(patched)
assertEquals(expected, actual, "$base\n$expected\n$actual")
}
}
fun `test getLines`() {
fun doTest(text: String, expectedLines: List<String>) {
val document = DocumentImpl(text)
assertEquals(expectedLines, DiffUtil.getLines(document))
val lineOffsets = LineOffsetsUtil.create(text)
assertEquals(expectedLines, DiffUtil.getLines(text, lineOffsets))
}
doTest("", listOf(""))
doTest(" ", listOf(" "))
doTest("\n", listOf("", ""))
doTest("\na\n", listOf("", "a", ""))
doTest("\na", listOf("", "a"))
doTest("a\n\nb", listOf("a", "", "b"))
doTest("ab\ncd", listOf("ab", "cd"))
doTest("ab\ncd\n", listOf("ab", "cd", ""))
doTest("\nab\ncd", listOf("", "ab", "cd"))
doTest("\nab\ncd\n", listOf("", "ab", "cd", ""))
}
}
| apache-2.0 |
io53/Android_RuuvitagScanner | app/src/main/java/com/ruuvi/station/settings/ui/AppSettingsGraphFragment.kt | 1 | 2605 | package com.ruuvi.station.settings.ui
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.lifecycleScope
import com.flexsentlabs.extensions.viewModel
import com.ruuvi.station.R
import kotlinx.android.synthetic.main.fragment_app_settings_graph.*
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.collect
import org.kodein.di.Kodein
import org.kodein.di.KodeinAware
import org.kodein.di.android.support.closestKodein
class AppSettingsGraphFragment : Fragment(), KodeinAware {
override val kodein: Kodein by closestKodein()
private val viewModel: AppSettingsGraphViewModel by viewModel()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_app_settings_graph, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupViews()
observeInterval()
observePeriod()
observeShowAllPoints()
}
private fun setupViews() {
graphIntervalNumberPicker.minValue = 1
graphIntervalNumberPicker.maxValue = 60
viewPeriodNumberPicker.minValue = 1
viewPeriodNumberPicker.maxValue = 72
graphIntervalNumberPicker.setOnValueChangedListener { _, _, new ->
viewModel.setPointInterval(new)
}
viewPeriodNumberPicker.setOnValueChangedListener { _, _, new ->
viewModel.setViewPeriod(new)
}
graphAllPointsSwitch.setOnCheckedChangeListener { _, isChecked ->
viewModel.setShowAllPoints(isChecked)
}
}
private fun observeInterval() {
lifecycleScope.launch {
viewModel.observePointInterval().collect {
graphIntervalNumberPicker.value = it
}
}
}
private fun observePeriod() {
lifecycleScope.launch {
viewModel.observeViewPeriod().collect {
viewPeriodNumberPicker.value = it
}
}
}
private fun observeShowAllPoints() {
lifecycleScope.launch {
viewModel.showAllPointsFlow.collect{
graphAllPointsSwitch.isChecked = it
graphIntervalNumberPicker.isEnabled = !graphAllPointsSwitch.isChecked
}
}
}
companion object {
fun newInstance() = AppSettingsGraphFragment()
}
} | mit |
leafclick/intellij-community | plugins/settings-repository/src/autoSync.kt | 1 | 6012 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.settingsRepository
import com.intellij.configurationStore.ComponentStoreImpl
import com.intellij.notification.Notification
import com.intellij.notification.Notifications
import com.intellij.openapi.application.AppUIExecutor
import com.intellij.openapi.application.Application
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.impl.coroutineDispatchingContext
import com.intellij.openapi.components.stateStore
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.ShutDownTracker
import com.intellij.openapi.vcs.VcsBundle
import com.intellij.openapi.vcs.VcsNotifier
import com.intellij.openapi.vcs.ui.VcsBalloonProblemNotifier
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import java.util.concurrent.Future
internal class AutoSyncManager(private val icsManager: IcsManager) {
@Volatile
private var autoSyncFuture: Future<*>? = null
@Volatile var enabled = true
fun waitAutoSync(indicator: ProgressIndicator) {
val autoFuture = autoSyncFuture
if (autoFuture != null) {
if (autoFuture.isDone) {
autoSyncFuture = null
}
else if (autoSyncFuture != null) {
LOG.info("Wait for auto sync future")
indicator.text = "Wait for auto sync completion"
while (!autoFuture.isDone) {
if (indicator.isCanceled) {
return
}
Thread.sleep(5)
}
}
}
}
fun registerListeners(project: Project) {
project.messageBus.connect().subscribe(Notifications.TOPIC, object : Notifications {
override fun notify(notification: Notification) {
if (!icsManager.isActive) {
return
}
if (when {
notification.groupId == VcsBalloonProblemNotifier.NOTIFICATION_GROUP.displayId -> {
val message = notification.content
message.startsWith("VCS Update Finished") ||
message == VcsBundle.message("message.text.file.is.up.to.date") ||
message == VcsBundle.message("message.text.all.files.are.up.to.date")
}
notification.groupId == VcsNotifier.NOTIFICATION_GROUP_ID.displayId && notification.title == "Push successful" -> true
else -> false
}) {
autoSync()
}
}
})
}
fun autoSync(onAppExit: Boolean = false, force: Boolean = false) {
if (!enabled || !icsManager.isActive || (!force && !icsManager.settings.autoSync)) {
return
}
autoSyncFuture?.let {
if (!it.isDone) {
return
}
}
val app = ApplicationManager.getApplication()
if (onAppExit) {
runBlocking {
sync(app, onAppExit)
}
return
}
else if (app.isDisposed) {
// will be handled by applicationExiting listener
return
}
autoSyncFuture = app.executeOnPooledThread {
try {
// to ensure that repository will not be in uncompleted state and changes will be pushed
ShutDownTracker.getInstance().registerStopperThread(Thread.currentThread())
runBlocking {
sync(app, onAppExit)
}
}
finally {
autoSyncFuture = null
ShutDownTracker.getInstance().unregisterStopperThread(Thread.currentThread())
}
}
}
private suspend fun sync(app: Application, onAppExit: Boolean) {
catchAndLog {
icsManager.runInAutoCommitDisabledMode {
doSync(app, onAppExit)
}
}
}
private suspend fun doSync(app: Application, onAppExit: Boolean) {
val repositoryManager = icsManager.repositoryManager
val hasUpstream = repositoryManager.hasUpstream()
if (hasUpstream && !repositoryManager.canCommit()) {
LOG.warn("Auto sync skipped: repository is not committable")
return
}
// on app exit fetch and push only if there are commits to push
if (onAppExit) {
// if no upstream - just update cloud schemes
if (hasUpstream && !repositoryManager.commit() && repositoryManager.getAheadCommitsCount() == 0 && icsManager.readOnlySourcesManager.repositories.isEmpty()) {
return
}
// use explicit progress task to sync on app exit to make it clear why app is not exited immediately
icsManager.syncManager.sync(SyncType.MERGE, onAppExit = true)
return
}
// update read-only sources at first (because contain scheme - to ensure that some scheme will exist when it will be set as current by some setting)
updateCloudSchemes(icsManager)
if (hasUpstream) {
val updater = repositoryManager.fetch()
// we merge in EDT non-modal to ensure that new settings will be properly applied
withContext(AppUIExecutor.onUiThread(ModalityState.NON_MODAL).coroutineDispatchingContext()) {
catchAndLog {
val updateResult = updater.merge()
if (!onAppExit &&
!app.isDisposed &&
updateResult != null &&
updateStoragesFromStreamProvider(icsManager, app.stateStore as ComponentStoreImpl, updateResult,
app.messageBus)) {
// force to avoid saveAll & confirmation
app.exit(true, true, true)
}
}
}
if (!updater.definitelySkipPush) {
repositoryManager.push()
}
}
}
}
internal inline fun catchAndLog(asWarning: Boolean = false, runnable: () -> Unit) {
try {
runnable()
}
catch (e: ProcessCanceledException) { }
catch (e: Throwable) {
if (asWarning || e is AuthenticationException || e is NoRemoteRepositoryException) {
LOG.warn(e)
}
else {
LOG.error(e)
}
}
} | apache-2.0 |
bitsydarel/DBWeather | dbweatherdomain/src/main/java/com/dbeginc/dbweatherdomain/entities/weather/Flags.kt | 1 | 794 | /*
* Copyright (C) 2017 Darel Bitsy
* 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.dbeginc.dbweatherdomain.entities.weather
/**
* Created by darel on 15.09.17.
*
* Weather Sources and Flags
*/
data class Flags(val sources: List<String>, val units: String) | gpl-3.0 |
leafclick/intellij-community | plugins/git4idea/tests/git4idea/tests/GitChangeProviderTest.kt | 1 | 5925 | // Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.tests
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vcs.Executor.cd
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.FileStatus
import com.intellij.openapi.vcs.VcsTestUtil.*
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vcs.changes.ChangesUtil
import com.intellij.openapi.vcs.changes.ContentRevision
import com.intellij.openapi.vcs.changes.VcsModifiableDirtyScope
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.testFramework.vcs.MockChangeListManagerGate
import com.intellij.testFramework.vcs.MockChangelistBuilder
import com.intellij.testFramework.vcs.MockDirtyScope
import com.intellij.vcsUtil.VcsUtil
import git4idea.config.GitVersion
import git4idea.status.GitChangeProvider
import git4idea.test.GitSingleRepoTest
import git4idea.test.addCommit
import git4idea.test.createFileStructure
import gnu.trove.THashMap
import junit.framework.TestCase
import org.junit.Assume
import java.io.File
/**
* Tests GitChangeProvider functionality. Scenario is the same for all tests:
* 1. Modifies files on disk (creates, edits, deletes, etc.)
* 2. Manually adds them to a dirty scope.
* 3. Calls ChangeProvider.getChanges() and checks that the changes are there.
*/
abstract class GitChangeProviderTest : GitSingleRepoTest() {
private lateinit var changeProvider: GitChangeProvider
protected lateinit var dirtyScope: VcsModifiableDirtyScope
private lateinit var subDir: VirtualFile
protected lateinit var atxt: VirtualFile
protected lateinit var btxt: VirtualFile
protected lateinit var dir_ctxt: VirtualFile
protected lateinit var subdir_dtxt: VirtualFile
override fun setUp() {
super.setUp()
changeProvider = vcs.changeProvider as GitChangeProvider
createFileStructure(projectRoot, "a.txt", "b.txt", "dir/c.txt", "dir/subdir/d.txt")
addCommit("initial")
atxt = getVirtualFile("a.txt")
btxt = getVirtualFile("b.txt")
dir_ctxt = getVirtualFile("dir/c.txt")
subdir_dtxt = getVirtualFile("dir/subdir/d.txt")
subDir = projectRoot.findChild("dir")!!
dirtyScope = MockDirtyScope(myProject, vcs)
cd(projectPath)
}
override fun makeInitialCommit() = false
private fun getVirtualFile(relativePath: String) = VfsUtil.findFileByIoFile(File(projectPath, relativePath), true)!!
/**
* Checks that the given files have respective statuses in the change list retrieved from myChangesProvider.
* Pass null in the fileStatuses array to indicate that proper file has not changed.
*/
protected fun assertProviderChanges(virtualFiles: List<VirtualFile>, fileStatuses: List<FileStatus?>) {
assertProviderChangesInPaths(virtualFiles.map { VcsUtil.getFilePath(it) }, fileStatuses)
}
protected fun assertProviderChangesInPaths(paths: List<FilePath>, fileStatuses: List<FileStatus?>) {
TestCase.assertEquals(paths.size, fileStatuses.size)
val result = getProviderChanges()
for (i in paths.indices) {
val fp = paths[i]
val status = fileStatuses[i]
if (status == null) {
assertFalse("File [" + tos(fp) + " shouldn't be in the changelist, but it was.", result.containsKey(fp))
continue
}
assertTrue("File [${tos(fp)}] didn't change. Changes: [${result.values.joinToString(",") { tos(it) }}]", result.containsKey(fp))
assertEquals("File statuses don't match for file [${tos(fp)}]", status, result[fp]!!.fileStatus)
}
}
protected fun assertProviderChanges(virtualFile: VirtualFile, fileStatus: FileStatus?) {
assertProviderChanges(listOf(virtualFile), listOf(fileStatus))
}
protected fun assumeWorktreeRenamesSupported() {
Assume.assumeTrue("Worktree renames are not supported by git: ${vcs.version}",
vcs.version.isLaterOrEqual(GitVersion(2, 17, 0, 0)))
}
/**
* It is assumed that only one change for a file has happened.
*/
private fun getProviderChanges(): Map<FilePath, Change> {
val builder = MockChangelistBuilder()
changeProvider.getChanges(dirtyScope, builder, EmptyProgressIndicator(), MockChangeListManagerGate(changeListManager))
val changes = builder.changes
val map = THashMap<FilePath, Change>(ChangesUtil.CASE_SENSITIVE_FILE_PATH_HASHING_STRATEGY)
return changes.associateByTo(map) { ChangesUtil.getFilePath(it) }
}
protected fun create(parent: VirtualFile, name: String): VirtualFile {
val file = parent.createFile(name, "content" + Math.random())
dirty(file)
return file
}
protected fun edit(file: VirtualFile, content: String) {
editFileInCommand(myProject, file, content)
dirty(file)
}
protected fun copy(file: VirtualFile, newParent: VirtualFile): VirtualFile {
dirty(file)
val newFile = copyFileInCommand(myProject, file, newParent, file.name)
dirty(newFile)
return newFile
}
protected fun deleteFile(file: VirtualFile) {
dirty(file)
deleteFileInCommand(myProject, file)
}
protected fun dirty(file: VirtualFile?) {
dirtyScope.addDirtyFile(VcsUtil.getFilePath(file!!))
}
private fun tos(fp: FilePath) = FileUtil.getRelativePath(File(projectPath), fp.ioFile)
private fun tos(change: Change) = when (change.type) {
Change.Type.NEW -> "A: " + tos(change.afterRevision)!!
Change.Type.DELETED -> "D: " + tos(change.beforeRevision)!!
Change.Type.MOVED -> "M: " + tos(change.beforeRevision) + " -> " + tos(change.afterRevision)
Change.Type.MODIFICATION -> "M: " + tos(change.afterRevision)!!
else -> "~: " + tos(change.beforeRevision) + " -> " + tos(change.afterRevision)
}
private fun tos(revision: ContentRevision?) = tos(revision!!.file)
}
| apache-2.0 |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/super/traitproperty.kt | 4 | 540 | interface M {
var backingB : Int
var b : Int
get() = backingB
set(value: Int) {
backingB = value
}
}
class N() : M {
public override var backingB : Int = 0
val a : Int
get() {
super.b = super.b + 1
return super.b + 1
}
override var b: Int = a + 1
val superb : Int
get() = super.b
}
fun box(): String {
val n = N()
n.a
n.b
n.superb
if (n.b == 3 && n.a == 4 && n.superb == 3) return "OK";
return "fail";
}
| apache-2.0 |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/boxInline/anonymousObject/kt9877_2.kt | 3 | 356 | // NO_CHECK_LAMBDA_INLINING
// FILE: 1.kt
package test
inline fun inlineCall(p: () -> Unit) {
p()
}
// FILE: 2.kt
import test.*
fun box(): String {
var gene = "g1"
inlineCall {
val value = 10.0
inlineCall {
{
value
gene = "OK"
}()
}
}
return gene
}
| apache-2.0 |
mrbublos/vkm | app/src/main/java/vkm/vkm/SearchFragment.kt | 1 | 5729 | package vkm.vkm
import android.text.InputType.TYPE_CLASS_TEXT
import android.text.InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.widget.AbsListView
import android.widget.AbsListView.OnScrollListener.SCROLL_STATE_IDLE
import kotlinx.android.synthetic.main.activity_search.*
import kotlinx.android.synthetic.main.composition_list_element.view.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import vkm.vkm.R.layout.*
import vkm.vkm.adapters.AlbumListAdapter
import vkm.vkm.adapters.ArtistListAdapter
import vkm.vkm.adapters.CompositionListAdapter
import vkm.vkm.utils.*
import vkm.vkm.utils.db.Db
class SearchFragment : VkmFragment() {
// private vars
private var filterText: String = ""
private var currentElement = 0
private var tabs: List<Tab<*>> = listOf()
private val currentTab: Tab<*>
get() = tabs[State.currentSearchTab]
init { layout = activity_search }
override fun init() {
tabs = listOf(TracksTab(::drawData),
// NewAlbumsTab(::drawData),
ChartTab(::drawData), ArtistTab(::drawData))
initializeElements()
initializeTabs()
initializeButton()
}
private fun initializeElements() {
showSpinner(false)
search.inputType = if (State.enableTextSuggestions) TYPE_CLASS_TEXT else TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
resultList.setOnScrollListener(object : AbsListView.OnScrollListener {
private var resultVisibleIndex = 0
private var resultVisible = 0
override fun onScroll(view: AbsListView?, firstVisibleItem: Int, visibleItemCount: Int, totalItemCount: Int) {
resultVisibleIndex = firstVisibleItem
resultVisible = visibleItemCount
}
override fun onScrollStateChanged(view: AbsListView?, scrollState: Int) {
if (scrollState == SCROLL_STATE_IDLE && resultVisibleIndex + resultVisible >= currentTab.dataList.size) {
currentElement = resultVisibleIndex + resultVisible
currentTab.onBottomReached()
}
}
})
}
private fun initializeTabs() {
searchTabsSwiper.value = tabs.asSequence().map { it.name }.toMutableList()
searchTabsSwiper.setCurrentString(currentTab.name)
currentTab.activate(null)
searchTabsSwiper.onSwiped = { index, _, prev ->
State.currentSearchTab = index
tabs[index].activate(null)
lockScreen(true)
tabs[prev].deactivate()
searchPanel.visibility = if (currentTab.hideSearch) GONE else VISIBLE
}
}
private fun initializeButton() {
blockSearch(false)
searchButton.setOnClickListener {
filterText = search.text.toString()
if (currentTab.search(filterText)) { lockScreen(true) }
currentElement = 0
return@setOnClickListener
}
}
private fun drawData() {
val me = this
GlobalScope.launch(Dispatchers.Main) {
lockScreen(false)
val data = currentTab.dataList
resultList.adapter = when (currentTab.listType) {
ListType.Composition -> CompositionListAdapter(me, composition_list_element, data as MutableList<Composition>, compositionAction)
ListType.Album -> AlbumListAdapter(me, album_list_element, data as MutableList<Album>, ::compositionContainerAction)
ListType.Artist -> ArtistListAdapter(me, album_list_element, data as MutableList<Artist>, ::compositionContainerAction)
}
resultList.setSelection(currentElement)
// TODO see how slow it is
context?.let { HttpUtils.storeProxies(Db.instance(it).proxyDao()) }
}
}
// actions
private fun blockSearch(locked: Boolean) {
searchButton.isFocusable = !locked
searchButton.isClickable = !locked
}
private fun showSpinner(show: Boolean) {
resultList.visibility = if (!show) VISIBLE else GONE
loadingSpinner.visibility = if (show) VISIBLE else GONE
}
private fun lockScreen(locked: Boolean) {
GlobalScope.launch(Dispatchers.Main) {
blockSearch(currentTab.loading || locked)
showSpinner(currentTab.loading || locked)
}
}
private val compositionAction = { composition: Composition, view: View ->
if (!DownloadManager.getDownloaded().contains(composition)) {
DownloadManager.downloadComposition(composition)
val actionButton = view.imageView
actionButton.setImageDrawable(context!!.getDrawable(R.drawable.ic_downloading))
actionButton.setOnClickListener {}
}
}
private fun compositionContainerAction(item: CompositionContainer, view: View) {
lockScreen(true)
switchTo("tracks")
([email protected] as Tab<Composition>).activate(item.compositionFetcher)
}
private fun switchTo(name: String) {
searchTabsSwiper.setCurrentString(name)
switchTo(getTabIndex(name))
}
private fun switchTo(index: Int) {
State.currentSearchTab = index
searchPanel.visibility = if (currentTab.hideSearch) GONE else VISIBLE
}
private fun getTabIndex(name: String): Int {
return tabs.asSequence().map { it.name }.indexOf(name)
}
override fun onDestroyView() {
super.onDestroyView()
currentTab.deactivate()
tabs.forEach { it.destroy() }
}
}
| gpl-3.0 |
AndroidX/androidx | navigation/navigation-compose-lint/src/test/java/androidx/navigation/compose/lint/Stubs.kt | 3 | 7629 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.navigation.compose.lint
import androidx.compose.lint.test.compiledStub
internal val NAV_BACK_STACK_ENTRY = compiledStub(
filename = "NavBackStackEntry.kt",
filepath = "androidx/navigation",
checksum = 0x6920c3ac,
source = """
package androidx.navigation
public class NavBackStackEntry
""",
"""
META-INF/main.kotlin_module:
H4sIAAAAAAAAAGNgYGBmYGBgBGJWKM3AJcTFnZyfq5dakZhbkJMqxBzvXaLE
oMUAAMRK5d0sAAAA
""",
"""
androidx/navigation/NavBackStackEntry.class:
H4sIAAAAAAAAAI2Ru04CQRSG/zPAoisKKiqosTNeCleMncZEjCYkiIkYGqqB
3eBwmU12hw12PItvYGViYYilD2U8u9rZOMWX8/9nMucyn19v7wBOsU3YldoN
fOVOHC0j1ZNG+dppyKgqu4OmYVxrEzxlQYRCX0bSGUrdc+46fa9rskgRrHOl
lbkgpPYPWjlkYNlII0tIm0cVEvbq/6pwRliuD3wzVNq59Yx0pZHsiVGU4lYp
RoZAA7YmKlbHHLkVws5satuiJGxR4Gg2Lc2mJ+KYqpmPZ0sURHzrhPgFFP/U
PBoYbvPKdz1Cvq601xiPOl7wIDtDdlbqflcOWzJQsf417aY/DrrejYpF+X6s
jRp5LRUqzl5q7ZtkvBAVCN5CfLjpeCnMDVZOonmWw1fMvXAgUGJaiZlGmZn7
uYB52El+M+E6tpIvIyxwLtdGqobFGpaYyMco1LCMlTYoxCqKnA9hh1gLYX0D
+QLjIO8BAAA=
"""
)
internal val NAV_CONTROLLER = compiledStub(
filename = "NavController.kt",
filepath = "androidx/navigation",
checksum = 0xa6eda16e,
source = """
package androidx.navigation
public class NavController {
public fun getBackStackEntry(route: String) = NavBackStackEntry()
}
""",
"""
META-INF/main.kotlin_module:
H4sIAAAAAAAAAGNgYGBmYGBgBGJWKM3AJcTFnZyfq5dakZhbkJMqxBzvXaLE
oMUAAMRK5d0sAAAA
""",
"""
androidx/navigation/NavController.class:
H4sIAAAAAAAAAI1SW08TQRT+Ztru4oJlQbkrioDclAXikzVGIZqU1GrEkBie
pttJmXY7m+xOG3zjt/gL9AmjiSE++qOMZ8pGrGhkkz1nzjnf+WbO5fuPz18B
PMA6w5zQ9SRW9aNAi65qCKNiHVRFdyfWJomjSCYuGIPfFF0RREI3gpe1pgyN
ixyD80hpZR4z5JZX9odQgOMhD5chbw5VyjBf+S97iWGkIc22CFt7hsQzCrxj
KC1Xzm/cM4nSjdLKv9j6k0v23jhpBE1paolQOg2E1rHpwdOgGptqJ4oIVUji
jpEDKDLMtmITKR00u+1AaSMTLaKgrO29qQpTFz7DWHgow1aW/kokoi0JyLD0
+1PPmlP6y+OpP6O45mEE1xkWL1WJi3EPE7afoxcJqW+V7NUvpBF1YQT5eLub
o9EyKwoMrEWuI2WtDTrVNxkenh6Pe3ySe9w/Pfb4AO8Z9ugXJ0+Pt/gG2y58
e+9wn+8W/dw038hvOX6BtGMZthixY+nSo/D7pr3eMrQcO3FdMgxXlJbVTrsm
kzeiFklbZRyKaF8kytqZc+Z1RxvVlmXdVaki19PzYTIs/Bn9NZg+mLcXd5JQ
PleWcSrL2b/Ah01wWmD7caqS9tnWSlZAmtmWrp5g4GMvvEzS6TnzWCE5dAbA
FXikRzBInlwveZvQnHRxbXT4E8a+YOLtCSY/9LE4lGlZxs+QGYs9FTFF8dUM
d5X0Gv0uywyOez15F/dJPyHvNFHNHCBXxo0ybpLErBW3yriNuQOwFHcwfwA3
hZdiIYWTYjDFYooimT8B9qxp7xsEAAA=
"""
)
internal val NAV_GRAPH_BUILDER = compiledStub(
filename = "NavGraphBuilder.kt",
filepath = "androidx/navigation",
checksum = 0xf26bfe8b,
source = """
package androidx.navigation
public class NavGraphBuilder
""",
"""
META-INF/main.kotlin_module:
H4sIAAAAAAAAAGNgYGBmYGBgBGJWKM3AZc0lnZiXUpSfmVKhl5dYlpmeWJKZ
n6eXnJ9bkF+cKiTol1jmXpRYkOFUmpmTklrkXSLECRTyyC8u8S5RYtBiAAA0
5BaVVQAAAA==
""",
"""
androidx/navigation/NavGraphBuilder.class:
H4sIAAAAAAAAAI1RTUsCURQ996ljTVajfWlFmwiqRaPRrggqKAQzqHDT6ukM
+nJ8EzNPcelv6R+0ClqEtOxHRXemVq16i8M951zu1/v8ensHcIRNwrbUXhQq
b+xqOVJdaVSo3aYcXUXyqXc+VIHnR3kQwXmUI+kGUnfdm/aj3zF5ZAjWidLK
nBIyu3utAnKwbGSRJ2RNT8WEncY/6h8Tio1+aAKl3WvfSE8ayZoYjDI8JiWQ
I1CfpbFKWJUjr0bYmk5sW5SFLRyOppPydHIoqnSe+3i2hCOSrEPiCij96XjQ
NzziRej5hMWG0n5zOGj70b1sB6yUGmFHBi0ZqYT/ivZdOIw6/qVKSOV2qI0a
+C0VK3bPtA5NulqMGgRfIHk8cnIQxjVmbsp5k/1XzLxwIFBmtFIxiwpj4ScB
s7BTfz3FVWykn0WYY6/wgEwd83UsMGIxAaeOIkoPoBhLWGY/hh1jJYb1DRVj
VoXpAQAA
"""
)
internal val NAV_GRAPH_COMPOSABLE = compiledStub(
filename = "NavGraphBuilder.kt",
filepath = "androidx/navigation/compose",
checksum = 0x6920624a,
source = """
package androidx.navigation.compose
import androidx.compose.runtime.Composable
import androidx.navigation.NavBackStackEntry
import androidx.navigation.NavGraphBuilder
public fun NavGraphBuilder.composable(
route: String, content: @Composable (NavBackStackEntry) -> Unit
) { }
public fun NavGraphBuilder.navigation(route: String, builder: NavGraphBuilder.() -> Unit) { }
""",
"""
META-INF/main.kotlin_module:
H4sIAAAAAAAAAGNgYGBmYGBgBGJWKM3AZc0lnZiXUpSfmVKhl5dYlpmeWJKZ
n6eXnJ9bkF+cKiTol1jmXpRYkOFUmpmTklrkXSLECRTyyC8u8S7hEuXiBirU
S61IzC3ISRViC0kFCSsxaDEAAFP1RV1sAAAA
""",
"""
androidx/navigation/compose/NavGraphBuilderKt.class:
H4sIAAAAAAAAAL1VS1MTQRD+ZvMkoiYbBQKKqCgvcUN8XGJRJZRaKSM+ohzk
NNmsYfKYpXYmKbxx9WT5F/wH3iwPFuXRH2XZkwRIMBZcdFPb09PT/X090z2b
n7++fQdwF/cZlrmsBL6o7DqSt0WVa+FLx/WbO77ynA3efhLwne21lmhUvOCp
joExJGu8zZ0Gl1XnebnmuWQNMSS6Qbzc8BjezheH4R7DyxePkEo6ELKaL9Z9
3RDSqbWbzruWdE2Ych73tJX8wibDp38E/mD5b7hr3K2XNIlHUgfvD3HeSKHz
q52crhf9oOrUPF0OuCBQLqWveZdgw9cbrUYjzxB9oLeFWo1jhGG6LxkhtRdI
3nAK0mSqhKtiOMNw0d323Hov/gUPeNMjR4a5+eLxGgzZ7sLmKM7iXAKjOM8Q
CfyW9uJIMcRcnwiljiNN1Zw1Oc32V+/Gqc6Xwf6Tk2HmpBJSqxyhMnz879Uc
xP2zlrFydy2OqcPj6c84dRDzzNO8wjWnLVnNdoiuFDMiwsDqRrHIviuMliWt
ssLwYX/vZmJ/L2ElrYQ1YXXVc51hwjp6451xcim5vzdpZdmilbVy0WSI9HBu
PBmZTNth28rGOpJloz8+R614nNxHhngnet7WgPcZk1COUcZUxd52+ks0d8qr
MNAsB5+NoCW1aHrO+mFPkd/0Ac2jXeo9RXAHfK/f7xgH+1hpbtc1Q3jdr1BH
ni8K6W20mmUveN3tUbvou7yxyQNh5j3jSElUJdetgPTZV90sCrItlKDlw/vz
8OhuUi+W/Fbgeo+Fic/0Yja7EX2OWIGFMMxjIYMIogjBodlLmpsKpxftxFck
l2yb5C37AskvHecsyag5ZiQIBJjpuuMixjpwaaQwTutGS2OCInKduBjuGFuI
luKms/pkhn4n8F8awj86wH95CP9UH//k3/kt+usw8jbu0ficrNN0Ile2ECpg
poCrJHGtgOuYLeAGbm6BKcxhfgujChGFBYUxhVRHSSssKiwp3FLIKEwpLP8G
Q1+Sp54GAAA=
"""
)
internal val NAV_HOST = compiledStub(
filename = "NavHost.kt",
filepath = "androidx/navigation/compose",
checksum = 0x72aa34d0,
source = """
package androidx.navigation.compose
import androidx.navigation.NavGraphBuilder
public fun NavHost(route: String, builder: NavGraphBuilder.() -> Unit) { }
""",
"""
META-INF/main.kotlin_module:
H4sIAAAAAAAAAGNgYGBmYGBgBGJWKM3AZc0lnZiXUpSfmVKhl5dYlpmeWJKZ
n6eXnJ9bkF+cKiTol1jmXpRYkOFUmpmTklrkXSLECRTyyC8u8S5RYtBiAAA0
5BaVVQAAAA==
""",
"""
androidx/navigation/compose/NavHostKt.class:
H4sIAAAAAAAAAJVSy24TMRQ9nrxDH0lKXwFKoS19AZNWsApCKhWFqCEgUrLp
ypmY1MnErmY8Udn1W/gDdogFqljyUYg7k6SNVCRgpDn3+vjch33989e37wCe
4CHDGlctT8vWma14X7a5kVrZju6dal/YNd5/rX1zaFJgDLkO73Pb5aptv212
hENsjCE1FDE83aheKerGk6pdrna1caWyO/2e/TFQTpjetw+G3k55s8HQ+f+4
Z4+qf+qbWnnl8dOTF4F0W8K7zPJBSVN+HhVbqWqvbXeEaXpcUkqulDZ8kL6m
TS1w3TJDwtOBEWlkGJbGOpHKCE9x166osE1fOn4KNxhmnRPhdIfh77jHe4KE
DOvjJxvcWfn6WTcbE5jEVBYTmKb7bA6aTyPPULiuZlj+26Uy5EeSN8LwFjec
OKvXj9HUWQgJBtYNHYv4Mxl6JfJaOwyHF+fF7MV51spZAzMVmQVr9BfXcySx
Smw3mbPIxnbnc/HiTCFesErJCFkp8eNz0kqnwpS7jGrSQYYNjXe59k9DpBGM
gl+eGUG3rtUoy9GnU0GC7PANPu7SM4zv65ZgmK5KJWpBrym8I950RdiDdrjb
4J4M10MyU5dtxU3gkb/6PlBG9kRF9aUvaftylHtXr4Sq1XXgOeJAhvGLw5jG
IGJMiB1YiCP8SIYEkohhjVZ7xFtkJ7cK2a/IbRcKhF/CYeABYZLkE4Tr5M8N
hMhgJko0iTxu0v5GpE5hM+QsItJRlXREb0W4im2y+8TOUu25Y8QqmK9ggRCL
FRRxq4LbuHMM5mMJd4+R9pHwsewjE2Hexz0f932s/AYz8VZoLwQAAA==
"""
)
| apache-2.0 |
exponent/exponent | packages/expo-dev-menu-interface/android/src/main/java/expo/interfaces/devmenu/DevMenuDelegateInterface.kt | 2 | 502 | package expo.interfaces.devmenu
import android.os.Bundle
import com.facebook.react.ReactInstanceManager
interface DevMenuDelegateInterface {
/**
* Returns a `Bundle` with the most important information about the current app.
*/
fun appInfo(): Bundle?
/**
* Returns a `ReactInstanceManager` ot the currently shown app. It is a context of what the dev menu displays.
*/
fun reactInstanceManager(): ReactInstanceManager
fun supportsDevelopment(): Boolean {
return true
}
}
| bsd-3-clause |
smmribeiro/intellij-community | platform/diff-impl/src/com/intellij/diff/actions/DiffCustomCommandHandler.kt | 12 | 2665 | // 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.diff.actions
import com.intellij.diff.DiffDialogHints
import com.intellij.diff.DiffManager
import com.intellij.execution.Executor
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.InternalIgnoreDependencyViolation
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.terminal.TerminalShellCommandHandler
import com.intellij.util.execution.ParametersListUtil
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
@InternalIgnoreDependencyViolation
private class DiffCustomCommandHandler : TerminalShellCommandHandler {
override fun execute(project: Project, workingDirectory: String?, localSession: Boolean, command: String, executor: Executor): Boolean {
val parameters = parse(workingDirectory, localSession, command)
if (parameters == null) {
LOG.warn("Command $command should be matched and properly parsed")
return false
}
val file1 = LocalFileSystem.getInstance().findFileByIoFile(parameters.first.toFile())
val file2 = LocalFileSystem.getInstance().findFileByIoFile(parameters.second.toFile())
if (file1 == null || file2 == null) {
LOG.warn("Cannot find virtual file for one of the paths: $file1, $file2")
return false
}
DiffManager.getInstance().showDiff(project,
BaseShowDiffAction.createMutableChainFromFiles(project, file1, file2),
DiffDialogHints.DEFAULT)
return true
}
override fun matches(project: Project, workingDirectory: String?, localSession: Boolean, command: String): Boolean {
return parse(workingDirectory, localSession, command) != null
}
private fun parse(workingDirectory: String?, localSession: Boolean, command: String): Pair<Path, Path>? {
if (!command.startsWith("diff ") || !localSession) {
return null
}
if (workingDirectory == null) {
return null
}
val commands = ParametersListUtil.parse(command)
if (commands.size < 3) {
return null
}
val path1 = Paths.get(workingDirectory, commands[1])
val path2 = Paths.get(workingDirectory, commands[2])
val file1Exists = Files.exists(path1)
val file2Exists = Files.exists(path2)
if (!file1Exists || !file2Exists) {
return null
}
return Pair(path1, path2)
}
companion object {
private val LOG = Logger.getInstance(DiffCustomCommandHandler::class.java)
}
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/redundantCompanionReference/sameNameLocalVariable.kt | 13 | 170 | // PROBLEM: none
class Test {
companion object {
val localVar = 1
}
fun test() {
var localVar = 2
<caret>Companion.localVar
}
} | apache-2.0 |
smmribeiro/intellij-community | platform/projectModel-impl/src/com/intellij/workspaceModel/ide/WorkspaceModelTopics.kt | 1 | 4698 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.ide
import com.intellij.diagnostic.ActivityCategory
import com.intellij.diagnostic.StartUpMeasurer
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.messages.MessageBus
import com.intellij.util.messages.MessageBusConnection
import com.intellij.util.messages.Topic
import com.intellij.workspaceModel.storage.VersionedStorageChange
import java.util.*
interface WorkspaceModelChangeListener : EventListener {
fun beforeChanged(event: VersionedStorageChange) {}
fun changed(event: VersionedStorageChange) {}
}
/**
* Topics to subscribe to Workspace changes
*
* Please use [subscribeImmediately] and [subscribeAfterModuleLoading] to subscribe to changes
*/
class WorkspaceModelTopics : Disposable {
companion object {
/** Please use [subscribeImmediately] and [subscribeAfterModuleLoading] to subscribe to changes */
@Topic.ProjectLevel
private val CHANGED = Topic(WorkspaceModelChangeListener::class.java, Topic.BroadcastDirection.NONE)
@JvmStatic
fun getInstance(project: Project): WorkspaceModelTopics = project.service()
}
private val allEvents = ContainerUtil.createConcurrentList<EventsDispatcher>()
private var sendToQueue = true
var modulesAreLoaded = false
/**
* Subscribe to topic and start to receive changes immediately.
*
* Topic is project-level only without broadcasting - connection expected to be to project message bus only.
*/
fun subscribeImmediately(connection: MessageBusConnection, listener: WorkspaceModelChangeListener) {
connection.subscribe(CHANGED, listener)
}
/**
* Subscribe to the topic and start to receive changes only *after* all the modules get loaded.
* All the events that will be fired before the modules loading, will be collected to the queue. After the modules are loaded, all events
* from the queue will be dispatched to listener under the write action and the further events will be dispatched to listener
* without passing to event queue.
*
* Topic is project-level only without broadcasting - connection expected to be to project message bus only.
*/
fun subscribeAfterModuleLoading(connection: MessageBusConnection, listener: WorkspaceModelChangeListener) {
if (!sendToQueue) {
subscribeImmediately(connection, listener)
}
else {
val queue = EventsDispatcher(listener)
allEvents += queue
subscribeImmediately(connection, queue)
}
}
fun syncPublisher(messageBus: MessageBus): WorkspaceModelChangeListener = messageBus.syncPublisher(CHANGED)
fun notifyModulesAreLoaded() {
val activity = StartUpMeasurer.startActivity("postponed events sending", ActivityCategory.DEFAULT)
sendToQueue = false
if (allEvents.isNotEmpty() && allEvents.any { it.events.isNotEmpty() }) {
val activityInQueue = activity.startChild("events sending (in queue)")
val application = ApplicationManager.getApplication()
application.invokeAndWait {
application.runWriteAction {
val innerActivity = activityInQueue.endAndStart("events sending")
allEvents.forEach { queue ->
queue.collectToQueue = false
queue.events.forEach { (isBefore, event) ->
if (isBefore) queue.originalListener.beforeChanged(event)
else queue.originalListener.changed(event)
}
queue.events.clear()
}
innerActivity.end()
}
}
}
else {
allEvents.forEach { queue -> queue.collectToQueue = false }
}
allEvents.clear()
modulesAreLoaded = true
activity.end()
}
private class EventsDispatcher(val originalListener: WorkspaceModelChangeListener) : WorkspaceModelChangeListener {
val events = mutableListOf<Pair<Boolean, VersionedStorageChange>>()
var collectToQueue = true
override fun beforeChanged(event: VersionedStorageChange) {
if (collectToQueue) {
events += true to event
}
else {
originalListener.beforeChanged(event)
}
}
override fun changed(event: VersionedStorageChange) {
if (collectToQueue) {
events += false to event
}
else {
originalListener.changed(event)
}
}
}
override fun dispose() {
allEvents.forEach { it.events.clear() }
allEvents.clear()
}
}
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/intentions/toOrdinaryStringLiteral/lineBreakInExpression.kt | 13 | 49 | val v = <caret>"""${2 +
2}""" | apache-2.0 |
appmattus/layercache | layercache-android-encryption/src/androidTest/kotlin/com/appmattus/layercache/EncryptionEncryptValuesConnectedTest.kt | 1 | 3812 | /*
* Copyright 2020 Appmattus Limited
*
* 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.appmattus.layercache
import android.content.Context
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotEquals
import org.junit.Assert.assertNull
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import java.security.KeyStore
@RunWith(AndroidJUnit4::class)
class EncryptionEncryptValuesConnectedTest {
private val appContext = ApplicationProvider.getApplicationContext<Context>()
private val cache = MapCache()
private val encrypted = cache.encryptValues(appContext)
@Before
fun clearKeys() {
val keyStore = KeyStore.getInstance("AndroidKeyStore")
keyStore.load(null)
keyStore.aliases().toList().forEach { keyStore.deleteEntry(it) }
val sharedPreferences = appContext.getSharedPreferences("${appContext.packageName}_preferences", Context.MODE_PRIVATE)
sharedPreferences.edit().clear().commit()
}
@Test
fun encrypts_and_decrypts_with_keys_in_memory() {
runBlocking {
// when we set a value
encrypted.set("key", "hello")
// then retrieving returns the original
assertEquals("hello", encrypted.get("key"))
}
}
@Test
fun encrypts_and_decrypts_with_keys_reloaded() {
runBlocking {
// when we set a value
encrypted.set("key", "hello")
// then original value returned
assertEquals("hello", cache.encryptValues(appContext).get("key"))
}
}
@Test
fun fails_decryption_when_key_and_value_keys_corrupted() {
runBlocking {
// when we set a value
encrypted.set("key", "hello")
// and corrupt the key and value keys in shared preferences
val sharedPreferences = appContext.getSharedPreferences("${appContext.packageName}_preferences", Context.MODE_PRIVATE)
sharedPreferences.all.forEach {
sharedPreferences.edit().putString(it.key, it.value.toString().reversed()).apply()
}
// then no value is returned
assertNull(cache.encryptValues(appContext).get("key"))
}
}
@Test
fun fails_decryption_when_all_keys_removed() {
runBlocking {
// when we set a value
encrypted.set("key", "hello")
// and clear all stored keys
clearKeys()
// then no value is returned
assertNull(cache.encryptValues(appContext).get("key"))
}
}
@Test
fun value_is_encrypted_in_backing_map() {
runBlocking {
// when we set a value
encrypted.set("key", "hello")
// then the value is encrypted in the backing map
assertNotEquals("hello", cache.get("key"))
}
}
@Test
fun non_existent_key_returns_null() {
runBlocking {
// when we get a non-existent value
val result = encrypted.get("key")
// then the result is null
assertNull(result)
}
}
}
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/multiFileIntentions/moveToCompanion/moveProperty/after/test.kt | 13 | 908 | package test
inline fun <T, R> with(receiver: T, block: T.() -> R): R = receiver.block()
class A {
class X {
}
inner class OuterY
fun outerFoo(n: Int) {}
val outerBar = 1
companion object {
class Y
fun foo(n: Int) {}
val bar = 1
fun Int.extFoo(n: Int) {}
val Int.extBar: Int get() = 1
var test: Int
get() = 1
set(value: Int) {
X()
Y()
foo(bar)
1.extFoo(1.extBar)
O.Y()
O.foo(O.bar)
with (O) {
Y()
foo(bar)
1.extFoo(1.extBar)
}
}
}
object O {
class Y
fun foo(n: Int) {}
val bar = 1
fun Int.extFoo(n: Int) {}
val Int.extBar: Int get() = 1
}
} | apache-2.0 |
smmribeiro/intellij-community | plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnMergeInfoTest.kt | 12 | 11780 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.svn
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vcs.VcsConfiguration
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.idea.svn.SvnPropertyKeys.MERGE_INFO
import org.jetbrains.idea.svn.SvnUtil.createUrl
import org.jetbrains.idea.svn.SvnUtil.parseUrl
import org.jetbrains.idea.svn.api.Depth
import org.jetbrains.idea.svn.api.Revision
import org.jetbrains.idea.svn.api.Target
import org.jetbrains.idea.svn.api.Url
import org.jetbrains.idea.svn.dialogs.WCInfo
import org.jetbrains.idea.svn.dialogs.WCInfoWithBranches
import org.jetbrains.idea.svn.history.SvnChangeList
import org.jetbrains.idea.svn.history.SvnRepositoryLocation
import org.jetbrains.idea.svn.integrate.MergeContext
import org.jetbrains.idea.svn.mergeinfo.BranchInfo
import org.jetbrains.idea.svn.mergeinfo.MergeCheckResult
import org.jetbrains.idea.svn.mergeinfo.OneShotMergeInfoHelper
import org.junit.Assert.*
import org.junit.Test
import java.io.File
private const val CONTENT1 = "123\n456\n123"
private const val CONTENT2 = "123\n456\n123\n4"
private fun assertRevisions(changeLists: List<SvnChangeList>, vararg expectedTopRevisions: Long) =
assertArrayEquals(expectedTopRevisions, changeLists.take(expectedTopRevisions.size).map { it.number }.toLongArray())
private fun newFile(parent: File, name: String) = File(parent, name).also { it.createNewFile() }
private fun newFolder(parent: String, name: String) = File(parent, name).also { it.mkdir() }
private fun newFolder(parent: File, name: String) = File(parent, name).also { it.mkdir() }
class SvnMergeInfoTest : SvnTestCase() {
private lateinit var myBranchVcsRoot: File
private lateinit var myOneShotMergeInfoHelper: OneShotMergeInfoHelper
private lateinit var myMergeChecker: BranchInfo
private lateinit var trunk: File
private lateinit var folder: File
private lateinit var f1: File
private lateinit var f2: File
private lateinit var myTrunkUrl: String
private lateinit var myBranchUrl: String
private val trunkChangeLists: List<SvnChangeList>
get() {
val provider = vcs.committedChangesProvider
return provider.getCommittedChanges(provider.createDefaultSettings(), SvnRepositoryLocation(parseUrl(myTrunkUrl, false)), 0)
}
override fun before() {
super.before()
myTrunkUrl = "$myRepoUrl/trunk"
myBranchUrl = "$myRepoUrl/branch"
myBranchVcsRoot = File(myTempDirFixture.tempDirPath, "branch")
myBranchVcsRoot.mkdir()
vcsManager.setDirectoryMapping(myBranchVcsRoot.absolutePath, SvnVcs.VCS_NAME)
val vcsRoot = LocalFileSystem.getInstance().findFileByIoFile(myBranchVcsRoot)
val node = Node(vcsRoot!!, createUrl(myBranchUrl), myRepositoryUrl)
val root = RootUrlInfo(node, WorkingCopyFormat.ONE_DOT_EIGHT, vcsRoot, null)
val wcInfo = WCInfo(root, true, Depth.INFINITY)
val mergeContext = MergeContext(vcs, parseUrl(myTrunkUrl, false), wcInfo, Url.tail(myTrunkUrl), vcsRoot)
myOneShotMergeInfoHelper = OneShotMergeInfoHelper(mergeContext)
vcs.svnConfiguration.isCheckNestedForQuickMerge = true
enableSilentOperation(VcsConfiguration.StandardConfirmation.ADD)
enableSilentOperation(VcsConfiguration.StandardConfirmation.REMOVE)
val wcInfoWithBranches = WCInfoWithBranches(wcInfo, emptyList<WCInfoWithBranches.Branch>(), vcsRoot,
WCInfoWithBranches.Branch(myRepositoryUrl.appendPath("trunk", false)))
myMergeChecker = BranchInfo(vcs, wcInfoWithBranches, WCInfoWithBranches.Branch(myRepositoryUrl.appendPath("branch", false)))
}
@Test
fun testSimpleNotMerged() {
createOneFolderStructure()
// rev 3
editAndCommit(trunk, f1)
assertMergeResult(trunkChangeLists, MergeCheckResult.NOT_MERGED)
}
@Test
fun testSimpleMerged() {
createOneFolderStructure()
// rev 3
editAndCommit(trunk, f1)
// rev 4: record as merged into branch
recordMerge(myBranchVcsRoot, myTrunkUrl, "-c", "3")
commitFile(myBranchVcsRoot)
updateFile(myBranchVcsRoot)
assertMergeInfo(myBranchVcsRoot, "/trunk:3")
assertMergeResult(trunkChangeLists, MergeCheckResult.MERGED)
}
@Test
fun testEmptyMergeinfoBlocks() {
createOneFolderStructure()
// rev 3
editAndCommit(trunk, f1)
// rev 4: record as merged into branch
merge(myBranchVcsRoot, myTrunkUrl, "-c", "3")
commitFile(myBranchVcsRoot)
updateFile(myBranchVcsRoot)
// rev5: put blocking empty mergeinfo
//runInAndVerifyIgnoreOutput("merge", "-c", "-3", myRepoUrl + "/trunk/folder", new File(myBranchVcsRoot, "folder").getAbsolutePath(), "--record-only"));
merge(File(myBranchVcsRoot, "folder"), "$myTrunkUrl/folder", "-r", "3:2")
commitFile(myBranchVcsRoot)
updateFile(myBranchVcsRoot)
assertMergeInfo(myBranchVcsRoot, "/trunk:3")
assertMergeInfo(File(myBranchVcsRoot, "folder"), "")
assertMergeResult(trunkChangeLists, MergeCheckResult.NOT_MERGED)
}
@Test
fun testNonInheritableMergeinfo() {
createOneFolderStructure()
// rev 3
editAndCommit(trunk, f1)
// rev 4: record non inheritable merge
setMergeInfo(myBranchVcsRoot, "/trunk:3*")
commitFile(myBranchVcsRoot)
updateFile(myBranchVcsRoot)
assertMergeInfo(myBranchVcsRoot, "/trunk:3*")
assertMergeResult(trunkChangeLists, MergeCheckResult.NOT_MERGED)
}
@Test
fun testOnlyImmediateInheritableMergeinfo() {
createOneFolderStructure()
// rev 3
editAndCommit(trunk, f1, CONTENT1)
// rev4
editAndCommit(trunk, f1, CONTENT2)
updateFile(myBranchVcsRoot)
// rev 4: record non inheritable merge
setMergeInfo(myBranchVcsRoot, "/trunk:3,4")
setMergeInfo(File(myBranchVcsRoot, "folder"), "/trunk:3")
commitFile(myBranchVcsRoot)
updateFile(myBranchVcsRoot)
assertMergeInfo(myBranchVcsRoot, "/trunk:3-4")
assertMergeInfo(File(myBranchVcsRoot, "folder"), "/trunk:3")
val changeLists = trunkChangeLists
assertRevisions(changeLists, 4, 3)
assertMergeResult(changeLists, MergeCheckResult.NOT_MERGED, MergeCheckResult.MERGED)
}
@Test
fun testTwoPaths() {
createTwoFolderStructure(myBranchVcsRoot)
// rev 3
editFile(f1)
editFile(f2)
commitFile(trunk)
updateFile(myBranchVcsRoot)
// rev 4: record non inheritable merge
setMergeInfo(myBranchVcsRoot, "/trunk:3")
// this makes not merged for f2 path
setMergeInfo(File(myBranchVcsRoot, "folder/folder1"), "/trunk:3*")
commitFile(myBranchVcsRoot)
updateFile(myBranchVcsRoot)
assertMergeInfo(myBranchVcsRoot, "/trunk:3")
assertMergeInfo(File(myBranchVcsRoot, "folder/folder1"), "/trunk:3*")
val changeListList = trunkChangeLists
assertRevisions(changeListList, 3)
assertMergeResult(changeListList, MergeCheckResult.NOT_MERGED)
}
@Test
fun testWhenInfoInRepo() {
val fullBranch = newFolder(myTempDirFixture.tempDirPath, "fullBranch")
createTwoFolderStructure(fullBranch)
// folder1 will be taken as branch wc root
checkOutFile("$myBranchUrl/folder/folder1", myBranchVcsRoot)
// rev 3 : f2 changed
editAndCommit(trunk, f2)
// rev 4: record as merged into branch using full branch WC
recordMerge(fullBranch, myTrunkUrl, "-c", "3")
commitFile(fullBranch)
updateFile(myBranchVcsRoot)
val changeListList = trunkChangeLists
assertRevisions(changeListList, 3)
assertMergeResult(changeListList[0], MergeCheckResult.MERGED)
}
@Test
fun testMixedWorkingRevisions() {
createOneFolderStructure()
// rev 3
editAndCommit(trunk, f1)
// rev 4: record non inheritable merge
setMergeInfo(myBranchVcsRoot, "/trunk:3")
commitFile(myBranchVcsRoot)
// ! no update!
assertMergeInfo(myBranchVcsRoot, "/trunk:3")
val f1info = vcs.getInfo(File(myBranchVcsRoot, "folder/f1.txt"))
assertEquals(2, f1info!!.revision.number)
val changeList = trunkChangeLists[0]
assertMergeResult(changeList, MergeCheckResult.NOT_MERGED)
// and after update
updateFile(myBranchVcsRoot)
myMergeChecker.clear()
assertMergeResult(changeList, MergeCheckResult.MERGED)
}
private fun createOneFolderStructure() {
trunk = newFolder(myTempDirFixture.tempDirPath, "trunk")
folder = newFolder(trunk, "folder")
f1 = newFile(folder, "f1.txt")
f2 = newFile(folder, "f2.txt")
importAndCheckOut(trunk)
}
private fun createTwoFolderStructure(branchFolder: File) {
trunk = newFolder(myTempDirFixture.tempDirPath, "trunk")
folder = newFolder(trunk, "folder")
f1 = newFile(folder, "f1.txt")
val folder1 = newFolder(folder, "folder1")
f2 = newFile(folder1, "f2.txt")
importAndCheckOut(trunk, branchFolder)
}
private fun importAndCheckOut(trunk: File, branch: File = myBranchVcsRoot) {
runInAndVerifyIgnoreOutput("import", "-m", "test", trunk.absolutePath, myTrunkUrl)
runInAndVerifyIgnoreOutput("copy", "-m", "test", myTrunkUrl, myBranchUrl)
FileUtil.delete(trunk)
checkOutFile(myTrunkUrl, trunk)
checkOutFile(myBranchUrl, branch)
}
private fun editAndCommit(trunk: File, file: File, content: String = CONTENT1) {
val vf = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file)
editAndCommit(trunk, vf!!, content)
}
private fun editAndCommit(trunk: File, file: VirtualFile, content: String) {
editFileInCommand(file, content)
commitFile(trunk)
}
private fun editFile(file: File) {
val vf = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file)
editFileInCommand(vf!!, CONTENT1)
}
private fun assertMergeInfo(file: File, expectedValue: String) {
val propertyValue = vcs.getFactory(file).createPropertyClient().getProperty(Target.on(file), MERGE_INFO, false, Revision.WORKING)
assertNotNull(propertyValue)
assertEquals(expectedValue, propertyValue!!.toString())
}
private fun assertMergeResult(changeLists: List<SvnChangeList>, vararg mergeResults: MergeCheckResult) {
myOneShotMergeInfoHelper.prepare()
for ((index, mergeResult) in mergeResults.withIndex()) {
assertMergeResult(changeLists[index], mergeResult)
assertMergeResultOneShot(changeLists[index], mergeResult)
}
}
private fun assertMergeResult(changeList: SvnChangeList, mergeResult: MergeCheckResult) =
assertEquals(mergeResult, myMergeChecker.checkList(changeList, myBranchVcsRoot.absolutePath))
private fun assertMergeResultOneShot(changeList: SvnChangeList, mergeResult: MergeCheckResult) =
assertEquals(mergeResult, myOneShotMergeInfoHelper.checkList(changeList))
private fun commitFile(file: File) = runInAndVerifyIgnoreOutput("ci", "-m", "test", file.absolutePath)
private fun updateFile(file: File) = runInAndVerifyIgnoreOutput("up", file.absolutePath)
private fun checkOutFile(url: String, directory: File) = runInAndVerifyIgnoreOutput("co", url, directory.absolutePath)
private fun setMergeInfo(file: File, value: String) = runInAndVerifyIgnoreOutput("propset", "svn:mergeinfo", value, file.absolutePath)
private fun merge(file: File, url: String, vararg revisions: String) = merge(file, url, false, *revisions)
private fun recordMerge(file: File, url: String, vararg revisions: String) = merge(file, url, true, *revisions)
private fun merge(file: File, url: String, recordOnly: Boolean, vararg revisions: String) {
val parameters = mutableListOf<String>("merge", *revisions, url, file.absolutePath)
if (recordOnly) {
parameters.add("--record-only")
}
runInAndVerifyIgnoreOutput(*parameters.toTypedArray())
}
}
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/j2k/new/tests/testData/copyPaste/SeveralMethodsSample.to.kt | 26 | 52 | class A {
fun someOther() = false
<caret>
} | apache-2.0 |
smmribeiro/intellij-community | json/src/com/intellij/jsonpath/ui/JsonPathEvaluateIntentionAction.kt | 12 | 1687 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.jsonpath.ui
import com.intellij.codeInsight.intention.AbstractIntentionAction
import com.intellij.codeInsight.intention.HighPriorityAction
import com.intellij.icons.AllIcons
import com.intellij.json.JsonBundle
import com.intellij.jsonpath.JsonPathLanguage
import com.intellij.jsonpath.ui.JsonPathEvaluateManager.Companion.JSON_PATH_EVALUATE_EXPRESSION_KEY
import com.intellij.lang.injection.InjectedLanguageManager
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Iconable
import com.intellij.psi.PsiFile
import javax.swing.Icon
internal class JsonPathEvaluateIntentionAction : AbstractIntentionAction(), HighPriorityAction, Iconable {
override fun getText(): String = JsonBundle.message("jsonpath.evaluate.intention")
override fun invoke(project: Project, editor: Editor?, file: PsiFile?) {
if (file == null) return
val manager = InjectedLanguageManager.getInstance(project)
val jsonPath = if (manager.isInjectedFragment(file)) {
manager.getUnescapedText(file)
}
else {
file.text
}
JsonPathEvaluateManager.getInstance(project).evaluateExpression(jsonPath)
}
override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?): Boolean {
if (editor == null || file == null) return false
return file.language == JsonPathLanguage.INSTANCE
&& file.getUserData(JSON_PATH_EVALUATE_EXPRESSION_KEY) != true
}
override fun getIcon(flags: Int): Icon = AllIcons.FileTypes.Json
} | apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.