repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
apixandru/intellij-community | platform/script-debugger/debugger-ui/src/VariableView.kt | 5 | 20034 | /*
* 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 org.jetbrains.debugger
import com.intellij.icons.AllIcons
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil
import com.intellij.pom.Navigatable
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import com.intellij.util.SmartList
import com.intellij.util.ThreeState
import com.intellij.xdebugger.XSourcePositionWrapper
import com.intellij.xdebugger.frame.*
import com.intellij.xdebugger.frame.presentation.XKeywordValuePresentation
import com.intellij.xdebugger.frame.presentation.XNumericValuePresentation
import com.intellij.xdebugger.frame.presentation.XStringValuePresentation
import com.intellij.xdebugger.frame.presentation.XValuePresentation
import org.jetbrains.concurrency.*
import org.jetbrains.debugger.values.*
import java.util.*
import java.util.concurrent.atomic.AtomicBoolean
import java.util.regex.Pattern
import javax.swing.Icon
fun VariableView(variable: Variable, context: VariableContext) = VariableView(variable.name, variable, context)
class VariableView(override val variableName: String, private val variable: Variable, private val context: VariableContext) : XNamedValue(variableName), VariableContext {
@Volatile private var value: Value? = null
// lazy computed
private var _memberFilter: MemberFilter? = null
@Volatile private var remainingChildren: List<Variable>? = null
@Volatile private var remainingChildrenOffset: Int = 0
override fun watchableAsEvaluationExpression() = context.watchableAsEvaluationExpression()
override val viewSupport: DebuggerViewSupport
get() = context.viewSupport
override val parent = context
override val memberFilter: Promise<MemberFilter>
get() = context.viewSupport.getMemberFilter(this)
override val evaluateContext: EvaluateContext
get() = context.evaluateContext
override val scope: Scope?
get() = context.scope
override val vm: Vm?
get() = context.vm
override fun computePresentation(node: XValueNode, place: XValuePlace) {
value = variable.value
if (value != null) {
computePresentation(value!!, node)
return
}
if (variable !is ObjectProperty || variable.getter == null) {
// it is "used" expression (WEB-6779 Debugger/Variables: Automatically show used variables)
evaluateContext.evaluate(variable.name)
.done(node) {
if (it.wasThrown) {
setEvaluatedValue(viewSupport.transformErrorOnGetUsedReferenceValue(it.value, null), null, node)
}
else {
value = it.value
computePresentation(it.value, node)
}
}
.rejected(node) { setEvaluatedValue(viewSupport.transformErrorOnGetUsedReferenceValue(null, it.message), it.message, node) }
return
}
node.setPresentation(null, object : XValuePresentation() {
override fun renderValue(renderer: XValuePresentation.XValueTextRenderer) {
renderer.renderValue("\u2026")
}
}, false)
node.setFullValueEvaluator(object : XFullValueEvaluator(" (invoke getter)") {
override fun startEvaluation(callback: XFullValueEvaluator.XFullValueEvaluationCallback) {
var valueModifier = variable.valueModifier
var nonProtoContext = context
while (nonProtoContext is VariableView && nonProtoContext.variableName == PROTOTYPE_PROP) {
valueModifier = nonProtoContext.variable.valueModifier
nonProtoContext = nonProtoContext.parent
}
valueModifier!!.evaluateGet(variable, evaluateContext)
.done(node) {
callback.evaluated("")
setEvaluatedValue(it, null, node)
}
}
}.setShowValuePopup(false))
}
private fun setEvaluatedValue(value: Value?, error: String?, node: XValueNode) {
if (value == null) {
node.setPresentation(AllIcons.Debugger.Db_primitive, null, error ?: "Internal Error", false)
}
else {
this.value = value
computePresentation(value, node)
}
}
private fun computePresentation(value: Value, node: XValueNode) {
when (value.type) {
ValueType.OBJECT, ValueType.NODE -> context.viewSupport.computeObjectPresentation((value as ObjectValue), variable, context, node, icon)
ValueType.FUNCTION -> node.setPresentation(icon, ObjectValuePresentation(trimFunctionDescription(value)), true)
ValueType.ARRAY -> context.viewSupport.computeArrayPresentation(value, variable, context, node, icon)
ValueType.BOOLEAN, ValueType.NULL, ValueType.UNDEFINED -> node.setPresentation(icon, XKeywordValuePresentation(value.valueString!!), false)
ValueType.NUMBER -> node.setPresentation(icon, createNumberPresentation(value.valueString!!), false)
ValueType.STRING -> {
node.setPresentation(icon, XStringValuePresentation(value.valueString!!), false)
// isTruncated in terms of debugger backend, not in our terms (i.e. sometimes we cannot control truncation),
// so, even in case of StringValue, we check value string length
if ((value is StringValue && value.isTruncated) || value.valueString!!.length > XValueNode.MAX_VALUE_LENGTH) {
node.setFullValueEvaluator(MyFullValueEvaluator(value))
}
}
else -> node.setPresentation(icon, null, value.valueString!!, true)
}
}
override fun computeChildren(node: XCompositeNode) {
node.setAlreadySorted(true)
if (value !is ObjectValue) {
node.addChildren(XValueChildrenList.EMPTY, true)
return
}
val list = remainingChildren
if (list != null) {
val to = Math.min(remainingChildrenOffset + XCompositeNode.MAX_CHILDREN_TO_SHOW, list.size)
val isLast = to == list.size
node.addChildren(createVariablesList(list, remainingChildrenOffset, to, this, _memberFilter), isLast)
if (!isLast) {
node.tooManyChildren(list.size - to)
remainingChildrenOffset += XCompositeNode.MAX_CHILDREN_TO_SHOW
}
return
}
val objectValue = value as ObjectValue
val hasNamedProperties = objectValue.hasProperties() != ThreeState.NO
val hasIndexedProperties = objectValue.hasIndexedProperties() != ThreeState.NO
val promises = SmartList<Promise<*>>()
val additionalProperties = viewSupport.computeAdditionalObjectProperties(objectValue, variable, this, node)
if (additionalProperties != null) {
promises.add(additionalProperties)
}
// we don't support indexed properties if additional properties added - behavior is undefined if object has indexed properties and additional properties also specified
if (hasIndexedProperties) {
promises.add(computeIndexedProperties(objectValue as ArrayValue, node, !hasNamedProperties && additionalProperties == null))
}
if (hasNamedProperties) {
// named properties should be added after additional properties
if (additionalProperties == null || additionalProperties.state != Promise.State.PENDING) {
promises.add(computeNamedProperties(objectValue, node, !hasIndexedProperties && additionalProperties == null))
}
else {
promises.add(additionalProperties.thenAsync(node) { computeNamedProperties(objectValue, node, true) })
}
}
if (hasIndexedProperties == hasNamedProperties || additionalProperties != null) {
all(promises).processed(node) { node.addChildren(XValueChildrenList.EMPTY, true) }
}
}
abstract class ObsolescentIndexedVariablesConsumer(protected val node: XCompositeNode) : IndexedVariablesConsumer() {
override val isObsolete: Boolean
get() = node.isObsolete
}
private fun computeIndexedProperties(value: ArrayValue, node: XCompositeNode, isLastChildren: Boolean): Promise<*> {
return value.getIndexedProperties(0, value.length, XCompositeNode.MAX_CHILDREN_TO_SHOW, object : ObsolescentIndexedVariablesConsumer(node) {
override fun consumeRanges(ranges: IntArray?) {
if (ranges == null) {
val groupList = XValueChildrenList()
addGroups(value, ::lazyVariablesGroup, groupList, 0, value.length, XCompositeNode.MAX_CHILDREN_TO_SHOW, this@VariableView)
node.addChildren(groupList, isLastChildren)
}
else {
addRanges(value, ranges, node, this@VariableView, isLastChildren)
}
}
override fun consumeVariables(variables: List<Variable>) {
node.addChildren(createVariablesList(variables, this@VariableView, null), isLastChildren)
}
})
}
private fun computeNamedProperties(value: ObjectValue, node: XCompositeNode, isLastChildren: Boolean) = processVariables(this, value.properties, node) { memberFilter, variables ->
_memberFilter = memberFilter
if (value.type == ValueType.ARRAY && value !is ArrayValue) {
computeArrayRanges(variables, node)
return@processVariables
}
var functionValue = value as? FunctionValue
if (functionValue != null && functionValue.hasScopes() == ThreeState.NO) {
functionValue = null
}
remainingChildren = processNamedObjectProperties(variables, node, this@VariableView, memberFilter, XCompositeNode.MAX_CHILDREN_TO_SHOW, isLastChildren && functionValue == null)
if (remainingChildren != null) {
remainingChildrenOffset = XCompositeNode.MAX_CHILDREN_TO_SHOW
}
if (functionValue != null) {
// we pass context as variable context instead of this variable value - we cannot watch function scopes variables, so, this variable name doesn't matter
node.addChildren(XValueChildrenList.bottomGroup(FunctionScopesValueGroup(functionValue, context)), isLastChildren)
}
}
private fun computeArrayRanges(properties: List<Variable>, node: XCompositeNode) {
val variables = filterAndSort(properties, _memberFilter!!)
var count = variables.size
val bucketSize = XCompositeNode.MAX_CHILDREN_TO_SHOW
if (count <= bucketSize) {
node.addChildren(createVariablesList(variables, this, null), true)
return
}
while (count > 0) {
if (Character.isDigit(variables.get(count - 1).name[0])) {
break
}
count--
}
val groupList = XValueChildrenList()
if (count > 0) {
addGroups(variables, ::createArrayRangeGroup, groupList, 0, count, bucketSize, this)
}
var notGroupedVariablesOffset: Int
if ((variables.size - count) > bucketSize) {
notGroupedVariablesOffset = variables.size
while (notGroupedVariablesOffset > 0) {
if (!variables.get(notGroupedVariablesOffset - 1).name.startsWith("__")) {
break
}
notGroupedVariablesOffset--
}
if (notGroupedVariablesOffset > 0) {
addGroups(variables, ::createArrayRangeGroup, groupList, count, notGroupedVariablesOffset, bucketSize, this)
}
}
else {
notGroupedVariablesOffset = count
}
for (i in notGroupedVariablesOffset..variables.size - 1) {
val variable = variables.get(i)
groupList.add(VariableView(_memberFilter!!.rawNameToSource(variable), variable, this))
}
node.addChildren(groupList, true)
}
private val icon: Icon
get() = getIcon(value!!)
override fun getModifier(): XValueModifier? {
if (!variable.isMutable) {
return null
}
return object : XValueModifier() {
override fun getInitialValueEditorText(): String? {
if (value!!.type == ValueType.STRING) {
val string = value!!.valueString!!
val builder = StringBuilder(string.length)
builder.append('"')
StringUtil.escapeStringCharacters(string.length, string, builder)
builder.append('"')
return builder.toString()
}
else {
return if (value!!.type.isObjectType) null else value!!.valueString
}
}
override fun setValue(expression: String, callback: XValueModifier.XModificationCallback) {
variable.valueModifier!!.setValue(variable, expression, evaluateContext)
.doneRun {
value = null
callback.valueModified()
}
.rejected { callback.errorOccurred(it.message!!) }
}
}
}
fun getValue() = variable.value
override fun canNavigateToSource() = value is FunctionValue || viewSupport.canNavigateToSource(variable, context)
override fun computeSourcePosition(navigatable: XNavigatable) {
if (value is FunctionValue) {
(value as FunctionValue).resolve()
.done { function ->
vm!!.scriptManager.getScript(function)
.done {
navigatable.setSourcePosition(it?.let { viewSupport.getSourceInfo(null, it, function.openParenLine, function.openParenColumn) }?.let {
object : XSourcePositionWrapper(it) {
override fun createNavigatable(project: Project): Navigatable {
return PsiVisitors.visit(myPosition, project) { position, element, positionOffset, document ->
// element will be "open paren", but we should navigate to function name,
// we cannot use specific PSI type here (like JSFunction), so, we try to find reference expression (i.e. name expression)
var referenceCandidate: PsiElement? = element
var psiReference: PsiElement? = null
while (true) {
referenceCandidate = referenceCandidate?.prevSibling ?: break
if (referenceCandidate is PsiReference) {
psiReference = referenceCandidate
break
}
}
if (psiReference == null) {
referenceCandidate = element.parent
while (true) {
referenceCandidate = referenceCandidate?.prevSibling ?: break
if (referenceCandidate is PsiReference) {
psiReference = referenceCandidate
break
}
}
}
(if (psiReference == null) element.navigationElement else psiReference.navigationElement) as? Navigatable
} ?: super.createNavigatable(project)
}
}
})
}
}
}
else {
viewSupport.computeSourcePosition(variableName, value!!, variable, context, navigatable)
}
}
override fun computeInlineDebuggerData(callback: XInlineDebuggerDataCallback) = viewSupport.computeInlineDebuggerData(variableName, variable, context, callback)
override fun getEvaluationExpression(): String? {
if (!watchableAsEvaluationExpression()) {
return null
}
if (context.variableName == null) return variable.name // top level watch expression, may be call etc.
val list = SmartList<String>()
addVarName(list, parent, variable.name)
var parent: VariableContext? = context
while (parent != null && parent.variableName != null) {
addVarName(list, parent.parent, parent.variableName!!)
parent = parent.parent
}
return context.viewSupport.propertyNamesToString(list, false)
}
private fun addVarName(list: SmartList<String>, parent: VariableContext?, name: String) {
if (parent == null || parent.variableName != null) list.add(name)
else list.addAll(name.split(".").reversed())
}
private class MyFullValueEvaluator(private val value: Value) : XFullValueEvaluator(if (value is StringValue) value.length else value.valueString!!.length) {
override fun startEvaluation(callback: XFullValueEvaluator.XFullValueEvaluationCallback) {
if (value !is StringValue || !value.isTruncated) {
callback.evaluated(value.valueString!!)
return
}
val evaluated = AtomicBoolean()
value.fullString
.done {
if (!callback.isObsolete && evaluated.compareAndSet(false, true)) {
callback.evaluated(value.valueString!!)
}
}
.rejected { callback.errorOccurred(it.message!!) }
}
}
companion object {
fun setObjectPresentation(value: ObjectValue, icon: Icon, node: XValueNode) {
node.setPresentation(icon, ObjectValuePresentation(getObjectValueDescription(value)), value.hasProperties() != ThreeState.NO)
}
fun setArrayPresentation(value: Value, context: VariableContext, icon: Icon, node: XValueNode) {
assert(value.type == ValueType.ARRAY)
if (value is ArrayValue) {
val length = value.length
node.setPresentation(icon, ArrayPresentation(length, value.className), length > 0)
return
}
val valueString = value.valueString
// only WIP reports normal description
if (valueString != null && (valueString.endsWith(")") || valueString.endsWith(']')) &&
ARRAY_DESCRIPTION_PATTERN.matcher(valueString).find()) {
node.setPresentation(icon, null, valueString, true)
}
else {
context.evaluateContext.evaluate("a.length", Collections.singletonMap<String, Any>("a", value), false)
.done(node) { node.setPresentation(icon, null, "Array[${it.value.valueString}]", true) }
.rejected(node) {
logger<VariableView>().error("Failed to evaluate array length: $it")
node.setPresentation(icon, null, valueString ?: "Array", true)
}
}
}
fun getIcon(value: Value): Icon {
val type = value.type
return when (type) {
ValueType.FUNCTION -> AllIcons.Nodes.Function
ValueType.ARRAY -> AllIcons.Debugger.Db_array
else -> if (type.isObjectType) AllIcons.Debugger.Value else AllIcons.Debugger.Db_primitive
}
}
}
}
fun getClassName(value: ObjectValue): String {
val className = value.className
return if (className.isNullOrEmpty()) "Object" else className!!
}
fun getObjectValueDescription(value: ObjectValue): String {
val description = value.valueString
return if (description.isNullOrEmpty()) getClassName(value) else description!!
}
internal fun trimFunctionDescription(value: Value): String {
return trimFunctionDescription(value.valueString ?: return "")
}
fun trimFunctionDescription(value: String): String {
var endIndex = 0
while (endIndex < value.length && !StringUtil.isLineBreak(value[endIndex])) {
endIndex++
}
while (endIndex > 0 && Character.isWhitespace(value[endIndex - 1])) {
endIndex--
}
return value.substring(0, endIndex)
}
private fun createNumberPresentation(value: String): XValuePresentation {
return if (value == PrimitiveValue.NA_N_VALUE || value == PrimitiveValue.INFINITY_VALUE) XKeywordValuePresentation(value) else XNumericValuePresentation(value)
}
private val ARRAY_DESCRIPTION_PATTERN = Pattern.compile("^[a-zA-Z\\d]+[\\[(]\\d+[\\])]$")
private class ArrayPresentation(length: Int, className: String?) : XValuePresentation() {
private val length = Integer.toString(length)
private val className = if (className.isNullOrEmpty()) "Array" else className!!
override fun renderValue(renderer: XValuePresentation.XValueTextRenderer) {
renderer.renderSpecialSymbol(className)
renderer.renderSpecialSymbol("[")
renderer.renderSpecialSymbol(length)
renderer.renderSpecialSymbol("]")
}
}
private val PROTOTYPE_PROP = "__proto__" | apache-2.0 | 50af09eb8ff7026d535c0733ed3db7b9 | 38.831014 | 181 | 0.685185 | 5.102904 | false | false | false | false |
edsilfer/star-wars-wiki | app/src/main/java/br/com/edsilfer/android/starwarswiki/model/dictionary/MovieDictionary.kt | 1 | 744 | package br.com.edsilfer.android.starwarswiki.model.dictionary
import br.com.edsilfer.android.starwarswiki.commons.util.SUID
import com.google.gson.Gson
/**
* Created by ferna on 2/21/2017.
*/
class MovieDictionary {
var id: Long = SUID.id()
val edited = ""
val starships = mutableListOf<String>()
val species = mutableListOf<String>()
val episode_id = ""
val opening_crawl = ""
val director = ""
val url = ""
val planets = mutableListOf<String>()
val title = ""
val created = ""
val producer = ""
val release_date = ""
val vehicles = mutableListOf<String>()
val characters = mutableListOf<String>()
override fun toString(): String {
return Gson().toJson(this)
}
} | apache-2.0 | 8637c594aebc0397c9d45c9e027e29da | 24.689655 | 61 | 0.645161 | 3.895288 | false | false | false | false |
panpf/sketch | sketch/src/main/java/com/github/panpf/sketch/datasource/ResourceDataSource.kt | 1 | 1975 | /*
* Copyright (C) 2022 panpf <[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 com.github.panpf.sketch.datasource
import android.content.res.Resources
import androidx.annotation.DrawableRes
import androidx.annotation.RawRes
import androidx.annotation.WorkerThread
import com.github.panpf.sketch.Sketch
import com.github.panpf.sketch.request.ImageRequest
import com.github.panpf.sketch.util.useCompat
import java.io.IOException
import java.io.InputStream
/**
* Provides access to image data in android resources
*/
class ResourceDataSource constructor(
override val sketch: Sketch,
override val request: ImageRequest,
val packageName: String,
val resources: Resources,
@RawRes @DrawableRes val drawableId: Int
) : DataSource {
override val dataFrom: DataFrom
get() = DataFrom.LOCAL
private var _length = -1L
@WorkerThread
@Throws(IOException::class)
override fun length(): Long =
_length.takeIf { it != -1L }
?: (resources.openRawResourceFd(drawableId)?.useCompat {
it.length
} ?: throw IOException("Invalid res id: $drawableId")).apply {
this@ResourceDataSource._length = this
}
@WorkerThread
@Throws(IOException::class)
override fun newInputStream(): InputStream =
resources.openRawResource(drawableId)
override fun toString(): String = "ResourceDataSource($drawableId)"
} | apache-2.0 | 155b580fa43c65cb0166c26fdf0e94aa | 31.933333 | 75 | 0.717975 | 4.478458 | false | false | false | false |
stripe/stripe-android | stripe-core/src/main/java/com/stripe/android/core/exception/StripeException.kt | 1 | 1961 | package com.stripe.android.core.exception
import androidx.annotation.RestrictTo
import com.stripe.android.core.StripeError
import org.json.JSONException
import java.io.IOException
import java.util.Objects
/**
* A base class for Stripe-related exceptions.
*/
abstract class StripeException(
val stripeError: StripeError? = null,
val requestId: String? = null,
val statusCode: Int = 0,
cause: Throwable? = null,
message: String? = stripeError?.message
) : Exception(message, cause) {
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
val isClientError = statusCode in 400..499
override fun toString(): String {
return listOfNotNull(
requestId?.let { "Request-id: $it" },
super.toString()
).joinToString(separator = "\n")
}
override fun equals(other: Any?): Boolean {
return when {
this === other -> true
other is StripeException -> typedEquals(other)
else -> false
}
}
override fun hashCode(): Int {
return Objects.hash(stripeError, requestId, statusCode, message)
}
private fun typedEquals(ex: StripeException): Boolean {
return stripeError == ex.stripeError &&
requestId == ex.requestId &&
statusCode == ex.statusCode &&
message == ex.message
}
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
companion object {
fun create(throwable: Throwable): StripeException {
return when (throwable) {
is StripeException -> throwable
is JSONException -> APIException(throwable)
is IOException -> APIConnectionException.create(throwable)
is IllegalArgumentException -> InvalidRequestException(
message = throwable.message,
cause = throwable
)
else -> APIException(throwable)
}
}
}
}
| mit | 245d601ae5d4b7f6a836e02cedf89034 | 30.126984 | 74 | 0.611423 | 5.015345 | false | false | false | false |
stripe/stripe-android | identity/src/main/java/com/stripe/android/identity/camera/IdentityAggregator.kt | 1 | 3468 | package com.stripe.android.identity.camera
import com.stripe.android.camera.framework.AggregateResultListener
import com.stripe.android.camera.framework.ResultAggregator
import com.stripe.android.camera.framework.time.Clock
import com.stripe.android.camera.framework.time.milliseconds
import com.stripe.android.identity.ml.AnalyzerInput
import com.stripe.android.identity.ml.AnalyzerOutput
import com.stripe.android.identity.networking.models.VerificationPage
import com.stripe.android.identity.states.FaceDetectorTransitioner
import com.stripe.android.identity.states.IDDetectorTransitioner
import com.stripe.android.identity.states.IdentityScanState
import com.stripe.android.identity.states.IdentityScanStateTransitioner
/**
* [ResultAggregator] for Identity.
*
* Initialize the [IdentityScanState.Initial] state with corresponding
* [IdentityScanStateTransitioner] based on [IdentityScanState.ScanType].
*/
internal class IdentityAggregator(
identityScanType: IdentityScanState.ScanType,
aggregateResultListener: AggregateResultListener<InterimResult, FinalResult>,
verificationPage: VerificationPage
) : ResultAggregator<
AnalyzerInput,
IdentityScanState,
AnalyzerOutput,
IdentityAggregator.InterimResult,
IdentityAggregator.FinalResult
>(
aggregateResultListener,
IdentityScanState.Initial(
type = identityScanType,
transitioner =
if (identityScanType == IdentityScanState.ScanType.SELFIE) {
FaceDetectorTransitioner(
requireNotNull(verificationPage.selfieCapture) {
"Failed to initialize FaceDetectorTransitioner - " +
"verificationPage.selfieCapture is null."
}
)
} else {
IDDetectorTransitioner(
timeoutAt = Clock.markNow() + verificationPage.documentCapture.autocaptureTimeout.milliseconds,
iouThreshold = verificationPage.documentCapture.motionBlurMinIou,
timeRequired = verificationPage.documentCapture.motionBlurMinDuration
)
}
),
statsName = null
) {
private var isFirstResultReceived = false
internal data class InterimResult(
val identityState: IdentityScanState
)
internal data class FinalResult(
val frame: AnalyzerInput,
val result: AnalyzerOutput,
val identityState: IdentityScanState
)
override suspend fun aggregateResult(
frame: AnalyzerInput,
result: AnalyzerOutput
): Pair<InterimResult, FinalResult?> {
if (isFirstResultReceived) {
val previousState = state
state = previousState.consumeTransition(frame, result)
val interimResult = InterimResult(state)
return interimResult to
if (state.isFinal) {
FinalResult(
frame,
result,
state
)
} else {
null
}
} else {
// If this is the very first result, don't transition state and post InterimResult with
// current state(IdentityScanState.Initial).
// This makes sure the receiver always receives IdentityScanState.Initial as the first
// callback.
isFirstResultReceived = true
return InterimResult(state) to null
}
}
}
| mit | 6bba45fc23741669e81357c06d1cc111 | 36.695652 | 111 | 0.673587 | 5.062774 | false | false | false | false |
AndroidX/androidx | emoji2/emoji2-emojipicker/src/main/java/androidx/emoji2/emojipicker/EmojiViewHolder.kt | 3 | 5119 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.emoji2.emojipicker
import android.content.Context
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View.GONE
import android.view.View.OnClickListener
import android.view.View.OnLongClickListener
import android.view.View.VISIBLE
import android.view.ViewGroup
import android.view.ViewGroup.LayoutParams
import android.view.accessibility.AccessibilityEvent
import android.widget.GridLayout
import android.widget.ImageView
import android.widget.PopupWindow
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import kotlin.math.roundToInt
/** A [ViewHolder] containing an emoji view and emoji data. */
internal class EmojiViewHolder(
context: Context,
parent: ViewGroup,
layoutInflater: LayoutInflater,
width: Int,
height: Int,
private val stickyVariantProvider: StickyVariantProvider,
private val onEmojiPickedListener: EmojiViewHolder.(EmojiViewItem) -> Unit,
private val onEmojiPickedFromPopupListener: EmojiViewHolder.(String) -> Unit
) : ViewHolder(
layoutInflater
.inflate(R.layout.emoji_view_holder, parent, /* attachToRoot = */false)
) {
private val onEmojiClickListener: OnClickListener = OnClickListener { v ->
v.findViewById<EmojiView>(R.id.emoji_view).emoji?.let {
onEmojiPickedListener(EmojiViewItem(it.toString(), emojiViewItem.variants))
}
}
private val onEmojiLongClickListener: OnLongClickListener = OnLongClickListener {
showPopupWindow(layoutInflater, emojiView) {
PopupViewHelper(context).fillPopupView(
it,
layoutInflater,
emojiView.measuredWidth,
emojiView.measuredHeight,
emojiViewItem.variants,
clickListener = { view ->
val emojiPickedInPopup = (view as EmojiView).emoji.toString()
onEmojiPickedFromPopupListener(emojiPickedInPopup)
onEmojiClickListener.onClick(view)
// variants[0] is always the base (i.e., primary) emoji
stickyVariantProvider.update(emojiViewItem.variants[0], emojiPickedInPopup)
this.dismiss()
// Hover on the base emoji after popup dismissed
emojiView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER)
}
)
}
true
}
private val emojiView: EmojiView
private val indicator: ImageView
private lateinit var emojiViewItem: EmojiViewItem
init {
itemView.layoutParams = LayoutParams(width, height)
emojiView = itemView.findViewById(R.id.emoji_view)
emojiView.isClickable = true
emojiView.setOnClickListener(onEmojiClickListener)
indicator = itemView.findViewById(R.id.variant_availability_indicator)
}
fun bindEmoji(
emojiViewItem: EmojiViewItem,
) {
emojiView.emoji = emojiViewItem.emoji
this.emojiViewItem = emojiViewItem
if (emojiViewItem.variants.isNotEmpty()) {
indicator.visibility = VISIBLE
emojiView.setOnLongClickListener(onEmojiLongClickListener)
emojiView.isLongClickable = true
} else {
indicator.visibility = GONE
emojiView.setOnLongClickListener(null)
emojiView.isLongClickable = false
}
}
private fun showPopupWindow(
layoutInflater: LayoutInflater,
parent: EmojiView,
init: PopupWindow.(GridLayout) -> Unit
) {
val popupView = layoutInflater
.inflate(R.layout.variant_popup, null, false)
.findViewById<GridLayout>(R.id.variant_popup)
PopupWindow(popupView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, false).apply {
init(popupView)
val location = IntArray(2)
parent.getLocationInWindow(location)
// Make the popup view center align with the target emoji view.
val x =
location[0] + parent.width / 2f - popupView.columnCount * parent.width / 2f
val y = location[1] - popupView.rowCount * parent.height
isOutsideTouchable = true
isTouchable = true
animationStyle = R.style.VariantPopupAnimation
showAtLocation(
parent,
Gravity.NO_GRAVITY,
x.roundToInt(),
y
)
}
}
} | apache-2.0 | 19704658f66cceea8363e18830e2e215 | 37.208955 | 99 | 0.666146 | 4.984421 | false | false | false | false |
AndroidX/androidx | compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/staggeredgrid/LazyStaggeredGrid.kt | 3 | 4854 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.foundation.lazy.staggeredgrid
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.clipScrollableContainer
import androidx.compose.foundation.gestures.FlingBehavior
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.ScrollableDefaults
import androidx.compose.foundation.gestures.scrollable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.lazy.layout.LazyLayout
import androidx.compose.foundation.lazy.layout.LazyLayoutItemProvider
import androidx.compose.foundation.lazy.layout.lazyLayoutSemantics
import androidx.compose.foundation.overscroll
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.dp
@ExperimentalFoundationApi
@Composable
internal fun LazyStaggeredGrid(
/** State controlling the scroll position */
state: LazyStaggeredGridState,
/** The layout orientation of the grid */
orientation: Orientation,
/** Prefix sums of cross axis sizes of slots per line, e.g. the columns for vertical grid. */
slotSizesSums: Density.(Constraints) -> IntArray,
/** Modifier to be applied for the inner layout */
modifier: Modifier = Modifier,
/** The inner padding to be added for the whole content (not for each individual item) */
contentPadding: PaddingValues = PaddingValues(0.dp),
/** reverse the direction of scrolling and layout */
reverseLayout: Boolean = false,
/** fling behavior to be used for flinging */
flingBehavior: FlingBehavior = ScrollableDefaults.flingBehavior(),
/** Whether scrolling via the user gestures is allowed. */
userScrollEnabled: Boolean = true,
/** The vertical arrangement for items/lines. */
verticalArrangement: Arrangement.Vertical = Arrangement.Top,
/** The horizontal arrangement for items/lines. */
horizontalArrangement: Arrangement.Horizontal = Arrangement.Start,
/** The content of the grid */
content: LazyStaggeredGridScope.() -> Unit
) {
val overscrollEffect = ScrollableDefaults.overscrollEffect()
val itemProvider = rememberStaggeredGridItemProvider(state, content)
val measurePolicy = rememberStaggeredGridMeasurePolicy(
state,
itemProvider,
contentPadding,
reverseLayout,
orientation,
verticalArrangement,
horizontalArrangement,
slotSizesSums
)
val semanticState = rememberLazyStaggeredGridSemanticState(state, itemProvider, reverseLayout)
ScrollPositionUpdater(itemProvider, state)
LazyLayout(
modifier = modifier
.then(state.remeasurementModifier)
.clipScrollableContainer(orientation)
.overscroll(overscrollEffect)
.scrollable(
orientation = orientation,
reverseDirection = ScrollableDefaults.reverseDirection(
LocalLayoutDirection.current,
orientation,
reverseLayout
),
interactionSource = state.mutableInteractionSource,
flingBehavior = flingBehavior,
state = state,
overscrollEffect = overscrollEffect,
enabled = userScrollEnabled
)
.lazyLayoutSemantics(
itemProvider = itemProvider,
state = semanticState,
orientation = orientation,
userScrollEnabled = userScrollEnabled
),
prefetchState = state.prefetchState,
itemProvider = itemProvider,
measurePolicy = measurePolicy
)
}
/** Extracted to minimize the recomposition scope */
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun ScrollPositionUpdater(
itemProvider: LazyLayoutItemProvider,
state: LazyStaggeredGridState
) {
if (itemProvider.itemCount > 0) {
state.updateScrollPositionIfTheFirstItemWasMoved(itemProvider)
}
} | apache-2.0 | 341d88f2d02035154ab793f7525cbb0b | 39.123967 | 98 | 0.721467 | 5.381375 | false | false | false | false |
exponent/exponent | packages/expo-camera/android/src/main/java/expo/modules/camera/events/FacesDetectedEvent.kt | 2 | 1373 | package expo.modules.camera.events
import android.os.Bundle
import androidx.core.util.Pools
import expo.modules.camera.CameraViewManager
import expo.modules.core.interfaces.services.EventEmitter.BaseEvent
class FacesDetectedEvent private constructor() : BaseEvent() {
private lateinit var faces: List<Bundle>
private var viewTag = 0
private fun init(viewTag: Int, faces: List<Bundle>) {
this.viewTag = viewTag
this.faces = faces
}
/**
* note(@sjchmiela)
* Should events about detected faces coalesce, the best strategy will be
* to ensure that events with different faces count are always being transmitted.
*/
override fun getCoalescingKey() =
if (faces.size > Short.MAX_VALUE) Short.MAX_VALUE
else faces.size.toShort()
override fun getEventName() = CameraViewManager.Events.EVENT_ON_FACES_DETECTED.toString()
override fun getEventBody() = Bundle().apply {
putString("type", "face")
putParcelableArray("faces", faces.toTypedArray())
putInt("target", viewTag)
}
companion object {
private val EVENTS_POOL = Pools.SynchronizedPool<FacesDetectedEvent>(3)
fun obtain(viewTag: Int, faces: List<Bundle>): FacesDetectedEvent {
var event = EVENTS_POOL.acquire()
if (event == null) {
event = FacesDetectedEvent()
}
event.init(viewTag, faces)
return event
}
}
}
| bsd-3-clause | a8af12176c78c8235a1885df13fbb294 | 28.847826 | 91 | 0.709395 | 4.050147 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/typing/RsQuoteHandler.kt | 4 | 4627 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.typing
import com.intellij.codeInsight.editorActions.MultiCharQuoteHandler
import com.intellij.codeInsight.editorActions.SimpleTokenSetQuoteHandler
import com.intellij.openapi.editor.highlighter.HighlighterIterator
import com.intellij.psi.StringEscapesTokenTypes.STRING_LITERAL_ESCAPES
import org.rust.lang.core.psi.RS_RAW_LITERALS
import org.rust.lang.core.psi.RsElementTypes.*
// Remember not to auto-pair `'` in char literals because of lifetimes, which use single `'`: `'a`
class RsQuoteHandler : SimpleTokenSetQuoteHandler(
BYTE_LITERAL,
STRING_LITERAL,
BYTE_STRING_LITERAL,
RAW_STRING_LITERAL,
RAW_BYTE_STRING_LITERAL
), MultiCharQuoteHandler {
override fun isOpeningQuote(iterator: HighlighterIterator, offset: Int): Boolean {
val elementType = iterator.tokenType
val start = iterator.start
// FIXME: Hashes?
return when (elementType) {
RAW_BYTE_STRING_LITERAL ->
offset - start <= 2
BYTE_STRING_LITERAL, RAW_STRING_LITERAL ->
offset - start <= 1
BYTE_LITERAL -> offset == start + 1
else -> super.isOpeningQuote(iterator, offset)
}
}
override fun isClosingQuote(iterator: HighlighterIterator, offset: Int): Boolean {
// FIXME: Hashes?
return super.isClosingQuote(iterator, offset)
}
override fun isInsideLiteral(iterator: HighlighterIterator): Boolean =
if (iterator.tokenType in STRING_LITERAL_ESCAPES)
true
else
super.isInsideLiteral(iterator)
override fun isNonClosedLiteral(iterator: HighlighterIterator, chars: CharSequence): Boolean {
if (iterator.tokenType == BYTE_LITERAL) {
return iterator.end - iterator.start == 2
}
if (iterator.tokenType in RS_RAW_LITERALS) {
val lastChar = chars[iterator.end - 1]
return lastChar != '#' && lastChar != '"'
}
if (super.isNonClosedLiteral(iterator, chars)) return true
// Rust allows multiline literals, so an unclosed quote will
// match with an opening quote of the next literal.
// So we check that the LAST token in the document is
// unclosed string literal
iterator.advanceToTheLastToken()
return iterator.tokenType in myLiteralTokenSet &&
getLiteralDumb(iterator)!!.offsets.closeDelim == null
}
private fun HighlighterIterator.advanceToTheLastToken() {
while (!atEnd()) {
advance()
}
retreat()
}
/**
* Check whether caret is deep inside string literal,
* i.e. it's inside contents itself, not decoration.
*/
fun isDeepInsideLiteral(iterator: HighlighterIterator, offset: Int): Boolean {
// First, filter out unwanted token types
if (!isInsideLiteral(iterator)) return false
val tt = iterator.tokenType
val start = iterator.start
// If we are inside raw literal then we don't have to deal with escapes
if (tt == RAW_STRING_LITERAL || tt == RAW_BYTE_STRING_LITERAL) {
return getLiteralDumb(iterator)?.offsets?.value?.containsOffset(offset - start) ?: false
}
// We have to deal with escapes here as we are inside (byte) string literal;
// we could build huge virtual literal using something like [getLiteralDumb],
// but that is expensive, especially for long strings with numerous escapes
// while we wanna be fast & furious when user notices lags.
// If we are inside escape then we must be deep inside literal
if (tt in STRING_LITERAL_ESCAPES) return true
// We can try to deduce our situation by just looking at neighbourhood...
val (prev, next) = getSiblingTokens(iterator)
// ... as we can be in the first token of the literal ...
if (prev !in STRING_LITERAL_ESCAPES) return !isOpeningQuote(iterator, offset)
// ... or the last one.
if (next !in STRING_LITERAL_ESCAPES) return !isClosingQuote(iterator, offset - 1)
// Otherwise we are inside
return true
}
override fun getClosingQuote(iterator: HighlighterIterator, offset: Int): CharSequence? {
val literal = getLiteralDumb(iterator) ?: return null
if (literal.node.elementType !in RS_RAW_LITERALS) return null
val hashes = literal.offsets.openDelim?.length?.let { it - 1 } ?: 0
return '"' + "#".repeat(hashes)
}
}
| mit | 8ba3fb9c38ce4965b388f2ab8d1950dd | 38.211864 | 100 | 0.657013 | 4.622378 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/cargo/project/workspace/RsAdditionalLibraryRootsProvider.kt | 2 | 5801 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
@file:Suppress("UnstableApiUsage")
package org.rust.cargo.project.workspace
import com.intellij.navigation.ItemPresentation
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.AdditionalLibraryRootsProvider
import com.intellij.openapi.roots.SyntheticLibrary
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import org.rust.cargo.icons.CargoIcons
import org.rust.cargo.project.model.CargoProject
import org.rust.cargo.project.model.cargoProjects
import org.rust.cargo.project.workspace.PackageOrigin.*
import org.rust.cargo.toolchain.impl.RustcVersion
import org.rust.ide.icons.RsIcons
import org.rust.stdext.buildList
import org.rust.stdext.exhaustive
import javax.swing.Icon
/**
* IDEA side of Cargo package from crates.io
*/
class CargoLibrary(
private val name: String,
private val sourceRoots: Set<VirtualFile>,
private val excludedRoots: Set<VirtualFile>,
private val icon: Icon,
private val version: String?
) : SyntheticLibrary(), ItemPresentation {
override fun getSourceRoots(): Collection<VirtualFile> = sourceRoots
override fun getExcludedRoots(): Set<VirtualFile> = excludedRoots
override fun equals(other: Any?): Boolean = other is CargoLibrary && other.sourceRoots == sourceRoots
override fun hashCode(): Int = sourceRoots.hashCode()
override fun getLocationString(): String? = null
override fun getIcon(unused: Boolean): Icon = icon
override fun getPresentableText(): String = if (version != null) "$name $version" else name
}
class GeneratedCodeFakeLibrary(private val sourceRoots: Set<VirtualFile>) : SyntheticLibrary() {
override fun equals(other: Any?): Boolean {
return other is GeneratedCodeFakeLibrary && other.sourceRoots == sourceRoots
}
override fun hashCode(): Int = sourceRoots.hashCode()
override fun getSourceRoots(): Collection<VirtualFile> = sourceRoots
override fun isShowInExternalLibrariesNode(): Boolean = false
companion object {
fun create(cargoProject: CargoProject): GeneratedCodeFakeLibrary? {
val generatedRoots = cargoProject.workspace?.packages.orEmpty().mapNotNullTo(HashSet()) { it.outDir }
return if (generatedRoots.isEmpty()) null else GeneratedCodeFakeLibrary(generatedRoots)
}
}
}
class RsAdditionalLibraryRootsProvider : AdditionalLibraryRootsProvider() {
override fun getAdditionalProjectLibraries(project: Project): Collection<SyntheticLibrary> =
project.cargoProjects.allProjects.smartFlatMap { it.ideaLibraries }
override fun getRootsToWatch(project: Project): Collection<VirtualFile> =
getAdditionalProjectLibraries(project).flatMap { it.sourceRoots }
}
private fun <U, V> Collection<U>.smartFlatMap(transform: (U) -> Collection<V>): Collection<V> =
when (size) {
0 -> emptyList()
1 -> transform(first())
else -> this.flatMap(transform)
}
private val CargoProject.ideaLibraries: Collection<SyntheticLibrary>
get() {
val workspace = workspace ?: return emptyList()
val stdlibPackages = mutableListOf<CargoWorkspace.Package>()
val dependencyPackages = mutableListOf<CargoWorkspace.Package>()
for (pkg in workspace.packages) {
when (pkg.origin) {
STDLIB, STDLIB_DEPENDENCY -> stdlibPackages += pkg
DEPENDENCY -> dependencyPackages += pkg
WORKSPACE -> Unit
}.exhaustive
}
return buildList {
makeStdlibLibrary(stdlibPackages, rustcInfo?.version)?.let(this::add)
for (pkg in dependencyPackages) {
pkg.toCargoLibrary()?.let(this::add)
}
GeneratedCodeFakeLibrary.create(this@ideaLibraries)?.let(::add)
}
}
private fun makeStdlibLibrary(packages: List<CargoWorkspace.Package>, rustcVersion: RustcVersion?): CargoLibrary? {
if (packages.isEmpty()) return null
val sourceRoots = mutableSetOf<VirtualFile>()
val excludedRoots = mutableSetOf<VirtualFile>()
for (pkg in packages) {
val root = pkg.contentRoot ?: continue
sourceRoots += root
sourceRoots += pkg.additionalRoots()
}
for (root in sourceRoots) {
excludedRoots += listOfNotNull(
root.findChild("tests"),
root.findChild("benches"),
root.findChild("examples"),
root.findChild("ci"), // From `backtrace`
root.findChild(".github"), // From `backtrace`
root.findChild("libc-test") // From Rust 1.32.0 `liblibc`
)
}
val version = rustcVersion?.semver?.parsedVersion
return CargoLibrary("stdlib", sourceRoots, excludedRoots, RsIcons.RUST, version)
}
private fun CargoWorkspace.Package.toCargoLibrary(): CargoLibrary? {
val root = contentRoot ?: return null
val sourceRoots = mutableSetOf<VirtualFile>()
val excludedRoots = mutableSetOf<VirtualFile>()
for (target in targets) {
val crateRoot = target.crateRoot ?: continue
if (target.kind.isLib) {
val crateRootDir = crateRoot.parent
when (VfsUtilCore.getCommonAncestor(root, crateRootDir)) {
root -> sourceRoots += root
crateRootDir -> sourceRoots += crateRootDir
else -> {
sourceRoots += root
sourceRoots += crateRootDir
}
}
} else {
// TODO exclude full module hierarchy instead of crate roots only
excludedRoots += crateRoot
}
}
return CargoLibrary(name, sourceRoots, excludedRoots, CargoIcons.ICON, version)
}
| mit | 932acbbe709e4ea9dafa1f7eb01978ff | 37.673333 | 115 | 0.683675 | 4.895359 | false | false | false | false |
androidx/androidx | datastore/datastore-compose-samples/src/main/java/com/example/datastorecomposesamples/CountActivity.kt | 3 | 4624 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.datastorecomposesamples
import android.os.Bundle
import android.os.StrictMode
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material.Button
import androidx.compose.material.Divider
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import com.example.datastorecomposesamples.data.CountRepository
import com.example.datastorecomposesamples.data.CountState
/**
* Main activity for displaying the counts, and allowing them to be changed.
*/
class CountActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val repo = CountRepository.getInstance(applicationContext)
// Strict mode allows us to check that no writes or reads are blocking the UI thread.
StrictMode.setThreadPolicy(
StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.penaltyDeath()
.build()
)
setContent {
val coroutineScope = rememberCoroutineScope()
val countState: CountState by repo.countStateFlow.collectAsState(
CountState(0),
coroutineScope.coroutineContext
)
val countProtoState: CountState by repo.countProtoStateFlow.collectAsState(
CountState(0),
coroutineScope.coroutineContext
)
MaterialTheme {
// A surface container using the 'background' color from the theme
Surface(
color = MaterialTheme.colors.background
) {
Column {
Counters(
title = getString(R.string.preference_counter),
count = countState.count,
onIncrement = repo::incrementPreferenceCount,
onDecrement = repo::decrementPreferenceCount
)
Divider()
Counters(
title = getString(R.string.proto_counter),
count = countProtoState.count,
onIncrement = repo::incrementProtoCount,
onDecrement = repo::decrementProtoCount
)
}
}
}
}
}
}
@Composable
fun Counters(title: String, count: Int, onIncrement: () -> Unit, onDecrement: () -> Unit) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(title, fontWeight = FontWeight.Bold)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceEvenly,
) {
Button(onClick = onDecrement) {
Text(stringResource(id = R.string.count_minus))
}
Text(text = "${stringResource(R.string.count_colon)} $count")
Button(onClick = onIncrement) {
Text(stringResource(id = R.string.count_plus))
}
}
}
}
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
MaterialTheme {
Counters("test", 1, {}, {})
}
} | apache-2.0 | 6670ad7e5949631fbb676cca1e336ba8 | 35.706349 | 93 | 0.639922 | 5.132075 | false | false | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/platform/sponge/reference/SpongeReferenceContributor.kt | 1 | 4250 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.sponge.reference
import com.demonwav.mcdev.insight.uastEventListener
import com.demonwav.mcdev.platform.sponge.util.SpongeConstants
import com.intellij.codeInsight.completion.JavaLookupElementBuilder
import com.intellij.patterns.PlatformPatterns
import com.intellij.psi.CommonClassNames
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiLanguageInjectionHost
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiModifier
import com.intellij.psi.PsiReference
import com.intellij.psi.PsiReferenceBase
import com.intellij.psi.PsiReferenceContributor
import com.intellij.psi.PsiReferenceProvider
import com.intellij.psi.PsiReferenceRegistrar
import com.intellij.psi.PsiSubstitutor
import com.intellij.psi.PsiType
import com.intellij.psi.filters.ElementFilter
import com.intellij.psi.filters.position.FilterPattern
import com.intellij.util.ArrayUtil
import com.intellij.util.ProcessingContext
import com.intellij.util.containers.map2Array
import org.jetbrains.uast.UAnnotation
import org.jetbrains.uast.ULiteralExpression
import org.jetbrains.uast.evaluateString
import org.jetbrains.uast.getParentOfType
import org.jetbrains.uast.toUElement
import org.jetbrains.uast.toUElementOfType
class SpongeReferenceContributor : PsiReferenceContributor() {
override fun registerReferenceProviders(registrar: PsiReferenceRegistrar) {
registrar.registerReferenceProvider(
PlatformPatterns.psiElement(PsiLanguageInjectionHost::class.java)
.and(FilterPattern(GetterAnnotationFilter)),
UastGetterEventListenerReferenceResolver,
PsiReferenceRegistrar.HIGHER_PRIORITY
)
}
}
object UastGetterEventListenerReferenceResolver : PsiReferenceProvider() {
override fun getReferencesByElement(element: PsiElement, context: ProcessingContext): Array<PsiReference> =
arrayOf(GetterReference(element as PsiLanguageInjectionHost))
}
private class GetterReference(element: PsiLanguageInjectionHost) : PsiReferenceBase<PsiLanguageInjectionHost>(element) {
override fun resolve(): PsiElement? {
val literal = element.toUElementOfType<ULiteralExpression>() ?: return null
val targetName = literal.evaluateString() ?: return null
val (eventClass, _) = literal.uastEventListener ?: return null
return eventClass.javaPsi.findMethodsByName(targetName, true).firstOrNull(::isValidCandidate)
}
override fun getVariants(): Array<Any> {
val literal = element.toUElementOfType<ULiteralExpression>() ?: return ArrayUtil.EMPTY_OBJECT_ARRAY
val (eventClass, _) = literal.uastEventListener
?: return ArrayUtil.EMPTY_OBJECT_ARRAY
val methodByClass = mutableMapOf<String, Pair<PsiMethod, PsiClass>>()
for (method in eventClass.javaPsi.allMethods) {
if (!isValidCandidate(method)) {
continue
}
val existingPair = methodByClass[method.name]
if (existingPair == null || method.containingClass!!.isInheritor(existingPair.second, true)) {
methodByClass[method.name] = method to method.containingClass!!
}
}
return methodByClass.values.map2Array { JavaLookupElementBuilder.forMethod(it.first, PsiSubstitutor.EMPTY) }
}
}
private object GetterAnnotationFilter : ElementFilter {
override fun isAcceptable(element: Any, context: PsiElement?): Boolean {
val type = context.toUElement() ?: return false
val annotation = type.getParentOfType<UAnnotation>() ?: return false
return annotation.qualifiedName == SpongeConstants.GETTER_ANNOTATION
}
override fun isClassAcceptable(hintClass: Class<*>): Boolean =
PsiLanguageInjectionHost::class.java.isAssignableFrom(hintClass)
}
private fun isValidCandidate(method: PsiMethod): Boolean = method.returnType != PsiType.VOID &&
!method.isConstructor && method.hasModifierProperty(PsiModifier.PUBLIC) && !method.hasParameters() &&
method.containingClass?.qualifiedName != CommonClassNames.JAVA_LANG_OBJECT
| mit | ca4c66d9ccb1d9eb0647fb5c5e9ab465 | 41.079208 | 120 | 0.761647 | 5.023641 | false | false | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/translations/TranslationConstants.kt | 1 | 1450 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.translations
object TranslationConstants {
const val DEFAULT_LOCALE = "en_us"
const val I18N_CLIENT_CLASS = "net.minecraft.client.resources.I18n"
const val I18N_CLIENT_LANG_CLASS = "net.minecraft.client.resources.language.I18n"
const val TRANSLATABLE_COMPONENT = "net.minecraft.network.chat.TranslatableComponent"
const val KEY_MAPPING = "net.minecraft.client.KeyMapping"
const val INPUT_CONSTANTS_KEY = "com.mojang.blaze3d.platform.InputConstants"
const val TEXT_COMPONENT_HELPER = "net.minecraftforge.server.command.TextComponentHelper"
const val I18N_COMMON_CLASS = "net.minecraft.util.text.translation.I18n"
const val CONSTRUCTOR = "<init>"
const val TRANSLATION_COMPONENT_CLASS = "net.minecraft.util.text.TextComponentTranslation"
const val COMMAND_EXCEPTION_CLASS = "net.minecraft.command.CommandException"
const val FORMAT = "func_135052_a"
const val TRANSLATE_TO_LOCAL = "func_74838_a"
const val TRANSLATE_TO_LOCAL_FORMATTED = "func_74837_a"
const val SET_BLOCK_NAME = "func_149663_c"
const val SET_ITEM_NAME = "func_77655_b"
const val GET = "m_118938_"
const val EXISTS = "m_118936_"
const val INPUT_CONSTANTS_KEY_GET_KEY = "m_84851_"
const val CREATE_COMPONENT_TRANSLATION = "createComponentTranslation"
}
| mit | 46c4412839bc58a2c5b6eed4239f5e2a | 41.647059 | 94 | 0.733103 | 3.510896 | false | false | false | false |
barinek/bigstar | components/rest-support/src/io/barinek/bigstar/rest/BasicApp.kt | 1 | 1110 | package io.barinek.bigstar.rest
import org.eclipse.jetty.server.Server
import org.eclipse.jetty.server.handler.HandlerList
import org.slf4j.LoggerFactory
abstract class BasicApp
constructor() {
private val logger = LoggerFactory.getLogger(BasicApp::class.java)
private val server: Server
init {
val list = handlerList()
server = Server(getPort())
server.handler = list
server.stopAtShutdown = true;
Runtime.getRuntime().addShutdownHook(Thread({
try {
if (server.isRunning) {
server.stop()
}
logger.info("App shutdown.")
} catch (e: Exception) {
logger.info("Error shutting down app.", e)
}
}))
}
protected abstract fun getPort(): Int
protected abstract fun handlerList(): HandlerList
@Throws(Exception::class)
fun start() {
logger.info("App started.")
server.start()
}
@Throws(Exception::class)
fun stop() {
logger.info("App stopped.")
server.stop()
}
} | apache-2.0 | 69a10ca25f359167ce6a7c64acdfc1e6 | 23.152174 | 70 | 0.581982 | 4.644351 | false | false | false | false |
nurkiewicz/ts.class | src/main/kotlin/com/nurkiewicz/tsclass/parser/visitors/MemberFunctionDeclarationVisitor.kt | 1 | 2652 | package com.nurkiewicz.tsclass.parser.visitors
import com.google.common.collect.Lists
import com.nurkiewicz.tsclass.antlr.parser.TypeScriptBaseVisitor
import com.nurkiewicz.tsclass.antlr.parser.TypeScriptParser
import com.nurkiewicz.tsclass.parser.ast.Block
import com.nurkiewicz.tsclass.parser.ast.Method
import com.nurkiewicz.tsclass.parser.ast.Parameter
import com.nurkiewicz.tsclass.parser.ast.Type
import java.util.ArrayList
internal class MemberFunctionDeclarationVisitor : TypeScriptBaseVisitor<Method>() {
override fun visitMemberFunctionDeclaration(ctx: TypeScriptParser.MemberFunctionDeclarationContext): Method {
val sig = ctx.memberFunctionImplementation().functionSignature()
val methodName = sig.IDENT().text
val typeCtx = sig.returnTypeAnnotation().returnType().type()
return Method(methodName, typeOf(typeCtx), parameters(sig), parseBody(ctx))
}
private fun parameters(sig: TypeScriptParser.FunctionSignatureContext): List<Parameter> {
val paramsCtx = sig.parameterList()
return if (paramsCtx != null) {
paramsCtx.accept(ParameterListVisitor())
} else {
emptyList()
}
}
private fun typeOf(typeCtx: TypeScriptParser.TypeContext?) =
Type(typeCtx?.typeName()?.text)
private fun parseBody(ctx: TypeScriptParser.MemberFunctionDeclarationContext) = Block(
ctx
.memberFunctionImplementation()
.functionBody()
.sourceElement()
.map({ se -> se.accept(StatementVisitor()) })
.filter { it != null }
)
private class RequiredParameterListVisitor : TypeScriptBaseVisitor<List<Parameter>>() {
override fun visitRequiredParameter(ctx: TypeScriptParser.RequiredParameterContext): List<Parameter> {
val name = ctx.IDENT().text
val typeName = ctx.typeAnnotation().accept(TypeVisitor)
val parameter = Parameter(name, typeName)
return Lists.newArrayList(parameter)
}
override fun defaultResult(): List<Parameter> {
return ArrayList()
}
override fun aggregateResult(aggregate: List<Parameter>, nextResult: List<Parameter>?): List<Parameter> {
return aggregate + (nextResult ?: emptyList())
}
}
private class ParameterListVisitor : TypeScriptBaseVisitor<List<Parameter>>() {
override fun visitRequiredParameterList(ctx: TypeScriptParser.RequiredParameterListContext): List<Parameter> {
return ctx.accept(RequiredParameterListVisitor())
}
}
}
| apache-2.0 | 622d7299ad55fb8d229f5c559c3a4746 | 38.58209 | 118 | 0.684012 | 5.08046 | false | false | false | false |
y2k/JoyReactor | core/src/main/kotlin/y2k/joyreactor/services/requests/CreateCommentRequest.kt | 1 | 1330 | package y2k.joyreactor.services.requests
import rx.Completable
import y2k.joyreactor.common.http.HttpClient
import y2k.joyreactor.common.ioUnitObservable
import java.util.regex.Pattern
/**
* Created by y2k on 19/10/15.
*/
class CreateCommentRequest(
private val httpClient: HttpClient) : Function2<Long, String, Completable> {
private val commentId: String? = null
override fun invoke(postId: Long, commentText: String): Completable {
return ioUnitObservable {
httpClient
.buildRequest()
.addField("parent_id", commentId ?: "0")
.addField("post_id", "" + postId)
.addField("token", getToken())
.addField("comment_text", commentText)
.putHeader("X-Requested-With", "XMLHttpRequest")
.putHeader("Referer", "http://joyreactor.cc/post/" + postId)
.post("http://joyreactor.cc/post_comment/create")
}.toCompletable()
}
private fun getToken(): String {
val document = httpClient.getText("http://joyreactor.cc/donate")
val m = TOKEN_REGEX.matcher(document)
if (!m.find()) throw IllegalStateException()
return m.group(1)
}
companion object {
val TOKEN_REGEX = Pattern.compile("var token = '(.+?)'")
}
} | gpl-2.0 | 505d562857fb9e9b8c2fd9886521f77a | 31.463415 | 80 | 0.615789 | 4.360656 | false | false | false | false |
lydia-schiff/hella-renderscript | app/src/main/java/com/lydiaschiff/hellaparallel/RsViewfinderActivity.kt | 1 | 6885 | package com.lydiaschiff.hellaparallel
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.renderscript.RenderScript
import android.util.Log
import android.util.Size
import android.view.View
import android.view.WindowManager
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.RequiresApi
import cat.the.lydia.coolalgebralydiathanks.implementation.RsColorCubeRenderer
import cat.the.lydia.coolalgebralydiathanks.utils.CubeFileParser
import com.lydiaschiff.hella.FrameStats
import com.lydiaschiff.hella.Hella
import com.lydiaschiff.hella.RsRenderer
import com.lydiaschiff.hella.RsSurfaceRenderer
import com.lydiaschiff.hella.renderer.BlurRsRenderer
import com.lydiaschiff.hella.renderer.DefaultRsRenderer
import com.lydiaschiff.hella.renderer.GreyscaleRsRenderer
import com.lydiaschiff.hella.renderer.SharpenRenderer
import com.lydiaschiff.hellaparallel.camera.BaseViewfinderActivity
import com.lydiaschiff.hellaparallel.camera.FixedAspectSurfaceView
import com.lydiaschiff.hellaparallel.renderers.AcidRenderer
import com.lydiaschiff.hellaparallel.renderers.ColorFrameRenderer
import com.lydiaschiff.hellaparallel.renderers.HueRotationRenderer
import com.lydiaschiff.hellaparallel.renderers.TrailsRenderer
import kotlin.math.roundToLong
@RequiresApi(21)
class RsViewfinderActivity : BaseViewfinderActivity() {
private lateinit var viewfinderSurfaceView: FixedAspectSurfaceView
private lateinit var rootView: View
private lateinit var textView: TextView
private lateinit var rs: RenderScript
private var cameraPreviewRenderer: RsCameraPreviewRenderer? = null
private lateinit var frameStats: FrameLogger
private var rendererNameToast: Toast? = null
private lateinit var rendererName: String
private var currentRendererIndex = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main)
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
frameStats = FrameLogger()
rootView = findViewById(R.id.panels)
viewfinderSurfaceView = findViewById(R.id.preview)
textView = findViewById(R.id.odd_exposure_label)
findViewById<View>(R.id.next_button).setOnClickListener { view: View ->
cycleRendererType()
updateRsRenderer()
aToast() // !
}
rs = RenderScript.create(this)
Hella.warmUpInBackground(rs)
}
fun aToast() { // to you!
rendererNameToast?.cancel()
rendererNameToast = Toast.makeText(this, rendererName, Toast.LENGTH_LONG)
.apply { show() }
}
override fun onResume() {
super.onResume()
frameStats.clear()
}
private fun cycleRendererType() {
currentRendererIndex++
if (currentRendererIndex == rendererTypes.size) {
currentRendererIndex = 0
}
}
private fun updateText(text: String) {
textView.text = text
}
private fun updateRsRenderer() =
try {
val renderer = rendererTypes[currentRendererIndex].newInstance()
// todo: hack!
if (currentRendererIndex == 2) {
(renderer as RsColorCubeRenderer).setColorCube(CubeFileParser.loadCubeResource(this, R.raw.fg_cine_drama_17))
}
rendererName = renderer.name
cameraPreviewRenderer?.setRsRenderer(renderer)
frameStats.clear()
} catch (e: InstantiationException) {
throw RuntimeException(
"Unable to create renderer for index " + currentRendererIndex +
", make sure it has a no-arg constructor please.", e)
} catch (e: IllegalAccessException) {
throw RuntimeException(
"Unable to create renderer for index " + currentRendererIndex +
", make sure it has a no-arg constructor please.", e)
}
override fun getRootView(): View = rootView
public override fun createNewRendererForCurrentType(outputSize: Size): RsSurfaceRenderer {
if (cameraPreviewRenderer == null) {
cameraPreviewRenderer = RsCameraPreviewRenderer(rs, outputSize.width, outputSize.height)
cameraPreviewRenderer!!.setDroppedFrameLogger(frameStats)
}
updateRsRenderer()
return cameraPreviewRenderer!!
}
override fun getViewfinderSurfaceView(): FixedAspectSurfaceView = viewfinderSurfaceView
private inner class FrameLogger : FrameStats {
private val uiHandler = Handler(Looper.getMainLooper())
@Volatile
private var start: Long = 0
override fun logFrame(tag: String, nDropped: Int, totalDropped: Int, total: Int) {
if (start == 0L) {
start = System.currentTimeMillis()
}
if (total % 10 == 9 || nDropped > 0) {
val avgDroppedFrames = totalDropped / total.toFloat()
val elapsed = System.currentTimeMillis() - start
val fps = (total * 1000 / elapsed.toFloat()).roundToLong()
if (nDropped > 0) {
logDropped(tag, nDropped, avgDroppedFrames, fps.toFloat())
}
updateUi(avgDroppedFrames, fps.toFloat())
}
}
override fun clear() {
start = 0
updateText("avg dropped frames: 0")
}
private fun logDropped(tag: String, nDropped: Int, avgDroppedFrames: Float, fps: Float) {
Log.d(tag, String.format(
"renderer is falling behind, dropping %d frame%s (avg %.2f)",
nDropped, if (nDropped > 1) "s" else "", avgDroppedFrames) + "fps = " + fps)
}
private fun updateUi(avgDroppedFrames: Float, fps: Float) {
uiHandler.post {
updateText("avg dropped frames: " +
"${Math.round(avgDroppedFrames * 100) / 100f} fps = $fps")
}
}
}
companion object {
private const val TAG = "RsViewfinderActivity"
private val rendererTypes: List<Class<out RsRenderer>> =
listOf(
DefaultRsRenderer::class.java,
RsColorCubeRenderer::class.java,
RsColorCubeRenderer::class.java,
GreyscaleRsRenderer::class.java,
SharpenRenderer::class.java,
BlurRsRenderer::class.java,
ColorFrameRenderer::class.java,
HueRotationRenderer::class.java,
TrailsRenderer::class.java,
AcidRenderer::class.java)
}
} | mit | 5caff8d331ab217f71bd249a8acb49f5 | 39.269006 | 129 | 0.64154 | 4.658322 | false | false | false | false |
mapbox/mapbox-java | services-cli/src/main/kotlin/com/mapbox/services/cli/validator/DirectionsResponseValidator.kt | 1 | 1502 | package com.mapbox.services.cli.validator
import com.mapbox.api.directions.v5.models.DirectionsResponse
import java.io.File
import kotlin.text.Charsets.UTF_8
/**
* Validate DirectionsResponse json strings.
*/
class DirectionsResponseValidator {
/**
* @param filePath path to the json file or directory
* @return results for all the files
*/
fun parse(filePath: String): List<ValidatorResult> {
val inputFile = File(filePath)
val results = mutableListOf<ValidatorResult>()
inputFile.forEachFile { file ->
val result = validateJson(file)
results.add(result)
}
return results
}
private fun File.forEachFile(function: (File) -> Unit) = walk()
.filter { !it.isDirectory }
.forEach(function)
private fun validateJson(file: File): ValidatorResult {
val json = file.readText(UTF_8)
return try {
val directionsResponse = DirectionsResponse.fromJson(json)
val toJson = directionsResponse.toJson()
val convertsBack = json == toJson
ValidatorResult(
filename = file.name,
success = true,
convertsBack = convertsBack
)
} catch (throwable: Throwable) {
ValidatorResult(
filename = file.name,
success = false,
convertsBack = false,
throwable = throwable
)
}
}
}
| mit | 530d565fc6b62d10c746866d8c91c830 | 28.45098 | 70 | 0.588549 | 4.814103 | false | false | false | false |
tommybuonomo/dotsindicator | viewpagerdotsindicator-sample/src/main/kotlin/com/tbuonomo/dotsindicatorsample/viewpager2/ViewPager2Activity.kt | 1 | 1692 | package com.tbuonomo.dotsindicatorsample.viewpager2
import android.os.Bundle
import android.view.Window
import android.view.WindowManager
import androidx.appcompat.app.AppCompatActivity
import androidx.viewpager2.widget.ViewPager2
import com.tbuonomo.dotsindicatorsample.R
import com.tbuonomo.dotsindicatorsample.util.ZoomOutPageTransformer
import com.tbuonomo.viewpagerdotsindicator.DotsIndicator
import com.tbuonomo.viewpagerdotsindicator.SpringDotsIndicator
import com.tbuonomo.viewpagerdotsindicator.WormDotsIndicator
class ViewPager2Activity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
requestWindowFeature(Window.FEATURE_NO_TITLE)
window.setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN
)
setContentView(R.layout.activity_view_pager2)
val dotsIndicator = findViewById<DotsIndicator>(R.id.dots_indicator)
val springDotsIndicator = findViewById<SpringDotsIndicator>(R.id.spring_dots_indicator)
val wormDotsIndicator = findViewById<WormDotsIndicator>(R.id.worm_dots_indicator)
val viewPager2 = findViewById<ViewPager2>(R.id.view_pager2)
val adapter = DotIndicatorPager2Adapter()
viewPager2.adapter = adapter
val zoomOutPageTransformer = ZoomOutPageTransformer()
viewPager2.setPageTransformer { page, position ->
zoomOutPageTransformer.transformPage(page, position)
}
dotsIndicator.attachTo(viewPager2)
springDotsIndicator.attachTo(viewPager2)
wormDotsIndicator.attachTo(viewPager2)
}
}
| apache-2.0 | 328914f5272675a8897083d618f5e3fc | 39.285714 | 95 | 0.76773 | 4.417755 | false | false | false | false |
kholland950/pernt | src/main/kotlin/com/pernt/models/Pernting.kt | 1 | 1239 | package com.pernt.models
import java.util.*
import javax.persistence.Column
import javax.persistence.Entity
import javax.persistence.Id
import javax.persistence.Lob
/**
* Model for Perntings (drawings)
*/
@Entity
class Pernting {
//String id: This is a UUID
@Id
var id: String;
//String base64 representation of image. Used to render images when loaded
@Lob
@Column(name="imageDataURL")
var imageDataURL: String;
//Int image width used for scaling to target screen
@Column(name="imageWidth")
var imageWidth: Int = 0;
//Int image height used for scaling to target screen
@Column(name="imageHeight")
var imageHeight: Int = 0;
constructor() {
this.id = UUID.randomUUID().toString();
this.imageDataURL = "";
}
constructor(imageDataURL: String, width: Int, height: Int) {
this.id = UUID.randomUUID().toString();
this.imageDataURL = imageDataURL;
this.imageWidth = width;
this.imageHeight = height;
}
constructor(id: String, imageDataURL: String, width: Int, height: Int) {
this.id = id;
this.imageDataURL = imageDataURL;
this.imageWidth = width;
this.imageHeight = height;
}
}
| apache-2.0 | b580c0f2a1b65684fea8350872b67a04 | 23.78 | 78 | 0.652946 | 4.009709 | false | false | false | false |
DavidHamm/wizard-pager | lib/src/main/kotlin/com/hammwerk/wizardpager/core/WizardTree.kt | 1 | 2721 | package com.hammwerk.wizardpager.core
import android.os.Parcel
import android.os.Parcelable
class WizardTree : Parcelable {
val trunk: Branch
var onTreeChanged: ((Int) -> Unit)? = null
var onPageValid: ((Page, Int) -> Unit)? = null
var onPageInvalid: ((Page, Int) -> Unit)? = null
init {
trunk = Branch()
}
override fun writeToParcel(dest: Parcel?, flags: Int) {
dest?.writeParcelableArray(trunk.pages, 0)
}
override fun describeContents(): Int {
return 0
}
val pages: List<Page>
get() {
val list: MutableList<Page> = mutableListOf()
var branch: Branch? = trunk
while (branch != null) {
list.addAll(branch.pages)
branch = branch.branchPage?.selectedBranch
}
return list.toList()
}
val numberOfAccessablePages: Int
get() {
val pages = this.pages
val numberOfValidPages = pages.takeWhile { it.valid }.count()
return numberOfValidPages + if (numberOfValidPages < pages.count()) 1 else 0
}
fun setPages(vararg pages: Page) {
trunk.pages = pages.apply {
forEach {
it.onPageValid = onPageValid()
it.onPageInvalid = onPageInvalid()
}
}
trunk.branchPage?.onBranchSelected = onBranchSelected()
}
fun <T : Page> getPage(position: Int): T {
val pages = pages
when {
position < pages.count() -> return pages[position] as T
else -> throw PageIndexOutOfBoundsException()
}
}
fun getPositionOfPage(page: Page) = pages.indexOf(page)
fun isLastPage(page: Page): Boolean {
val pages = pages
return when {
pages.isNotEmpty() -> {
val lastPage = pages.last()
lastPage == page && (lastPage !is BranchPage || lastPage.selectedBranch != null)
}
else -> false
}
}
private fun onBranchSelected(): (BranchPage) -> Unit = {
it.selectedBranch?.apply {
pages.forEach {
it.onPageValid = onPageValid()
it.onPageInvalid = onPageInvalid()
}
branchPage?.onBranchSelected = onBranchSelected()
}
}
private fun onPageValid(): (Page) -> Unit = { page ->
onTreeChanged?.let { it(getPositionOfPage(page) + 1) }
onPageValid?.let { it(page, getPositionOfPage(page)) }
}
private fun onPageInvalid(): (Page) -> Unit = { page ->
onTreeChanged?.let { it(getPositionOfPage(page) + 1) }
onPageInvalid?.let { it(page, getPositionOfPage(page)) }
}
companion object {
@JvmField val CREATOR = object : Parcelable.Creator<WizardTree> {
override fun createFromParcel(source: Parcel?): WizardTree {
return WizardTree().apply {
setPages(*source?.readParcelableArray(WizardTree::class.java.classLoader)
?.map { it as Page }
?.toTypedArray()
.orEmpty())
}
}
override fun newArray(size: Int): Array<out WizardTree?> {
return arrayOfNulls(size)
}
}
}
}
| mit | 0a6264bf60b0f1bb4281efbe8518fdd8 | 23.736364 | 84 | 0.667769 | 3.371747 | false | false | false | false |
mgramin/sql-boot | src/main/kotlin/com/github/mgramin/sqlboot/model/connection/CheckedConnection.kt | 1 | 1779 | /*
* The MIT License (MIT)
* <p>
* Copyright (c) 2016-2019 Maksim Gramin
* <p>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* <p>
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
* <p>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.mgramin.sqlboot.model.connection
class CheckedConnection(private val origin: DbConnection) : DbConnection {
private val health: String
init {
health = try {
origin.getDataSource().connection
"Ok"
} catch (e: Exception) {
e.message.toString()
}
}
override fun name() = origin.name()
override fun properties() = origin.properties()
override fun health() = health
override fun paginationQueryTemplate() = origin.paginationQueryTemplate()
override fun getDataSource() = origin.getDataSource()
} | mit | 579a606ea89bd63c138dd594c045a4f6 | 34.6 | 80 | 0.714446 | 4.436409 | false | false | false | false |
kvakil/venus | src/main/kotlin/venus/riscv/insts/dsl/impls/RTypeImplementation32.kt | 1 | 597 | package venus.riscv.insts.dsl.impls
import venus.riscv.InstructionField
import venus.riscv.MachineCode
import venus.simulator.Simulator
class RTypeImplementation32(private val eval: (Int, Int) -> Int) : InstructionImplementation {
override operator fun invoke(mcode: MachineCode, sim: Simulator) {
val rs1 = mcode[InstructionField.RS1]
val rs2 = mcode[InstructionField.RS2]
val rd = mcode[InstructionField.RD]
val vrs1 = sim.getReg(rs1)
val vrs2 = sim.getReg(rs2)
sim.setReg(rd, eval(vrs1, vrs2))
sim.incrementPC(mcode.length)
}
}
| mit | b1b7c852b64dbb9d8bf5ebcf96018eeb | 34.117647 | 94 | 0.701843 | 3.431034 | false | false | false | false |
exponentjs/exponent | android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/expo/modules/adapters/react/permissions/PermissionsService.kt | 2 | 14505 | package abi43_0_0.expo.modules.adapters.react.permissions
import android.Manifest
import android.annotation.TargetApi
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import abi43_0_0.com.facebook.react.modules.core.PermissionAwareActivity
import abi43_0_0.com.facebook.react.modules.core.PermissionListener
import abi43_0_0.expo.modules.interfaces.permissions.Permissions
import abi43_0_0.expo.modules.interfaces.permissions.PermissionsResponse
import abi43_0_0.expo.modules.interfaces.permissions.PermissionsResponseListener
import abi43_0_0.expo.modules.interfaces.permissions.PermissionsStatus
import abi43_0_0.expo.modules.core.ModuleRegistry
import abi43_0_0.expo.modules.core.Promise
import abi43_0_0.expo.modules.core.interfaces.ActivityProvider
import abi43_0_0.expo.modules.core.interfaces.InternalModule
import abi43_0_0.expo.modules.core.interfaces.LifecycleEventListener
import abi43_0_0.expo.modules.core.interfaces.services.UIManager
import java.util.*
import kotlin.collections.HashMap
private const val PERMISSIONS_REQUEST: Int = 13
private const val PREFERENCE_FILENAME = "expo.modules.permissions.asked"
open class PermissionsService(val context: Context) : InternalModule, Permissions, LifecycleEventListener {
private var mActivityProvider: ActivityProvider? = null
// state holders for asking for writing permissions
private var mWriteSettingsPermissionBeingAsked = false // change this directly before calling corresponding startActivity
private var mAskAsyncListener: PermissionsResponseListener? = null
private var mAskAsyncRequestedPermissions: Array<out String>? = null
private val mPendingPermissionCalls: Queue<Pair<Array<out String>, PermissionsResponseListener>> = LinkedList()
private var mCurrentPermissionListener: PermissionsResponseListener? = null
private lateinit var mAskedPermissionsCache: SharedPreferences
private fun didAsk(permission: String): Boolean = mAskedPermissionsCache.getBoolean(permission, false)
private fun addToAskedPermissionsCache(permissions: Array<out String>) {
with(mAskedPermissionsCache.edit()) {
permissions.forEach { putBoolean(it, true) }
apply()
}
}
override fun getExportedInterfaces(): List<Class<out Any>> = listOf(Permissions::class.java)
@Throws(IllegalStateException::class)
override fun onCreate(moduleRegistry: ModuleRegistry) {
mActivityProvider = moduleRegistry.getModule(ActivityProvider::class.java)
?: throw IllegalStateException("Couldn't find implementation for ActivityProvider.")
moduleRegistry.getModule(UIManager::class.java).registerLifecycleEventListener(this)
mAskedPermissionsCache = context.applicationContext.getSharedPreferences(PREFERENCE_FILENAME, Context.MODE_PRIVATE)
}
override fun getPermissionsWithPromise(promise: Promise, vararg permissions: String) {
getPermissions(
PermissionsResponseListener { permissionsMap: MutableMap<String, PermissionsResponse> ->
val areAllGranted = permissionsMap.all { (_, response) -> response.status == PermissionsStatus.GRANTED }
val areAllDenied = permissionsMap.all { (_, response) -> response.status == PermissionsStatus.DENIED }
val canAskAgain = permissionsMap.all { (_, response) -> response.canAskAgain }
promise.resolve(
Bundle().apply {
putString(PermissionsResponse.EXPIRES_KEY, PermissionsResponse.PERMISSION_EXPIRES_NEVER)
putString(
PermissionsResponse.STATUS_KEY,
when {
areAllGranted -> PermissionsStatus.GRANTED.status
areAllDenied -> PermissionsStatus.DENIED.status
else -> PermissionsStatus.UNDETERMINED.status
}
)
putBoolean(PermissionsResponse.CAN_ASK_AGAIN_KEY, canAskAgain)
putBoolean(PermissionsResponse.GRANTED_KEY, areAllGranted)
}
)
},
*permissions
)
}
override fun askForPermissionsWithPromise(promise: Promise, vararg permissions: String) {
askForPermissions(
PermissionsResponseListener {
getPermissionsWithPromise(promise, *permissions)
},
*permissions
)
}
override fun getPermissions(responseListener: PermissionsResponseListener, vararg permissions: String) {
responseListener.onResult(
parseNativeResult(
permissions,
permissions.map {
if (isPermissionGranted(it)) {
PackageManager.PERMISSION_GRANTED
} else {
PackageManager.PERMISSION_DENIED
}
}.toIntArray()
)
)
}
@Throws(IllegalStateException::class)
override fun askForPermissions(responseListener: PermissionsResponseListener, vararg permissions: String) {
if (permissions.contains(Manifest.permission.WRITE_SETTINGS) && isRuntimePermissionsAvailable()) {
val permissionsToAsk = permissions.toMutableList().apply { remove(Manifest.permission.WRITE_SETTINGS) }.toTypedArray()
val newListener = PermissionsResponseListener {
val status = if (hasWriteSettingsPermission()) {
PackageManager.PERMISSION_GRANTED
} else {
PackageManager.PERMISSION_DENIED
}
it[Manifest.permission.WRITE_SETTINGS] = getPermissionResponseFromNativeResponse(Manifest.permission.WRITE_SETTINGS, status)
responseListener.onResult(it)
}
if (!hasWriteSettingsPermission()) {
if (mAskAsyncListener != null) {
throw IllegalStateException("Another permissions request is in progress. Await the old request and then try again.")
}
mAskAsyncListener = newListener
mAskAsyncRequestedPermissions = permissionsToAsk
addToAskedPermissionsCache(arrayOf(Manifest.permission.WRITE_SETTINGS))
askForWriteSettingsPermissionFirst()
} else {
askForManifestPermissions(permissionsToAsk, newListener)
}
} else {
askForManifestPermissions(permissions, responseListener)
}
}
override fun hasGrantedPermissions(vararg permissions: String): Boolean {
return permissions.all { isPermissionGranted(it) }
}
/**
* Checks whether given permission is present in AndroidManifest or not.
*/
override fun isPermissionPresentInManifest(permission: String): Boolean {
try {
context.packageManager.getPackageInfo(context.packageName, PackageManager.GET_PERMISSIONS)?.run {
return requestedPermissions.contains(permission)
}
return false
} catch (e: PackageManager.NameNotFoundException) {
return false
}
}
/**
* Checks status for Android built-in permission
*
* @param permission [android.Manifest.permission]
*/
private fun isPermissionGranted(permission: String): Boolean {
return when (permission) {
// we need to handle this permission in different way
Manifest.permission.WRITE_SETTINGS -> hasWriteSettingsPermission()
else -> getManifestPermission(permission) == PackageManager.PERMISSION_GRANTED
}
}
/**
* Gets status for Android built-in permission
*
* @param permission [android.Manifest.permission]
*/
private fun getManifestPermission(permission: String): Int {
mActivityProvider?.currentActivity?.let {
if (it is PermissionAwareActivity) {
return ContextCompat.checkSelfPermission(it, permission)
}
}
// We are in the headless mode. So, we ask current context.
return getManifestPermissionFromContext(permission)
}
protected open fun getManifestPermissionFromContext(permission: String): Int {
return ContextCompat.checkSelfPermission(context, permission)
}
private fun canAskAgain(permission: String): Boolean {
return mActivityProvider?.currentActivity?.let {
ActivityCompat.shouldShowRequestPermissionRationale(it, permission)
} ?: false
}
private fun parseNativeResult(permissionsString: Array<out String>, grantResults: IntArray): Map<String, PermissionsResponse> {
return HashMap<String, PermissionsResponse>().apply {
grantResults.zip(permissionsString).forEach { (result, permission) ->
this[permission] = getPermissionResponseFromNativeResponse(permission, result)
}
}
}
private fun getPermissionResponseFromNativeResponse(permission: String, result: Int): PermissionsResponse {
val status = when {
result == PackageManager.PERMISSION_GRANTED -> PermissionsStatus.GRANTED
didAsk(permission) -> PermissionsStatus.DENIED
else -> PermissionsStatus.UNDETERMINED
}
return PermissionsResponse(
status,
if (status == PermissionsStatus.DENIED) {
canAskAgain(permission)
} else {
true
}
)
}
protected open fun askForManifestPermissions(permissions: Array<out String>, listener: PermissionsResponseListener) {
if (!isRuntimePermissionsAvailable()) {
// It's not possible to ask for the permissions in the runtime.
// We return to the user the permissions status, which was granted during installation.
addToAskedPermissionsCache(permissions)
val permissionsResult = permissions.map { getManifestPermission(it) }.toIntArray()
listener.onResult(parseNativeResult(permissions, permissionsResult))
return
}
delegateRequestToActivity(permissions, listener)
}
/**
* Asks for Android built-in permission
* According to Android documentation [android.Manifest.permission.WRITE_SETTINGS] need to be handled in different way
*
* @param permissions [android.Manifest.permission]
*/
protected fun delegateRequestToActivity(permissions: Array<out String>, listener: PermissionsResponseListener) {
addToAskedPermissionsCache(permissions)
val currentActivity = mActivityProvider?.currentActivity
if (currentActivity is PermissionAwareActivity) {
synchronized(this@PermissionsService) {
if (mCurrentPermissionListener != null) {
mPendingPermissionCalls.add(permissions to listener)
} else {
mCurrentPermissionListener = listener
currentActivity.requestPermissions(permissions, PERMISSIONS_REQUEST, createListenerWithPendingPermissionsRequest())
}
}
} else {
listener.onResult(parseNativeResult(permissions, IntArray(permissions.size) { PackageManager.PERMISSION_DENIED }))
}
}
private fun createListenerWithPendingPermissionsRequest(): PermissionListener {
return PermissionListener { requestCode, receivePermissions, grantResults ->
if (requestCode == PERMISSIONS_REQUEST) {
synchronized(this@PermissionsService) {
val currentListener = requireNotNull(mCurrentPermissionListener)
currentListener.onResult(parseNativeResult(receivePermissions, grantResults))
mCurrentPermissionListener = null
mPendingPermissionCalls.poll()?.let { pendingCall ->
val activity = mActivityProvider?.currentActivity as? PermissionAwareActivity
if (activity == null) {
// clear all pending calls, because we don't have access to the activity instance
pendingCall.second.onResult(parseNativeResult(pendingCall.first, IntArray(pendingCall.first.size) { PackageManager.PERMISSION_DENIED }))
mPendingPermissionCalls.forEach {
it.second.onResult(parseNativeResult(it.first, IntArray(it.first.size) { PackageManager.PERMISSION_DENIED }))
}
mPendingPermissionCalls.clear()
return@let
}
mCurrentPermissionListener = pendingCall.second
activity.requestPermissions(pendingCall.first, PERMISSIONS_REQUEST, createListenerWithPendingPermissionsRequest())
return@PermissionListener false
}
return@PermissionListener true
}
}
return@PermissionListener false
}
}
/**
* Asking for [android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS] via separate activity
* WARNING: has to be asked first among all permissions being asked in request
* Scenario that forces this order:
* 1. user asks for "systemBrightness" (actual [android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS]) and for some other permission (e.g. [android.Manifest.permission.CAMERA])
* 2. first goes ACTION_MANAGE_WRITE_SETTINGS that moves app into background and launches system-specific fullscreen activity
* 3. upon user action system resumes app and [onHostResume] is being called for the first time and logic for other permission is invoked
* 4. other permission invokes other system-specific activity that is visible as dialog what moves app again into background
* 5. upon user action app is restored and [onHostResume] is being called again, but no further action is invoked and promise is resolved
*/
@TargetApi(Build.VERSION_CODES.M)
private fun askForWriteSettingsPermissionFirst() {
Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS).apply {
data = Uri.parse("package:${context.packageName}")
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}.let {
mWriteSettingsPermissionBeingAsked = true
context.startActivity(it)
}
}
private fun hasWriteSettingsPermission(): Boolean {
return if (isRuntimePermissionsAvailable()) {
Settings.System.canWrite(context.applicationContext)
} else {
true
}
}
private fun isRuntimePermissionsAvailable() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
override fun onHostResume() {
if (!mWriteSettingsPermissionBeingAsked) {
return
}
mWriteSettingsPermissionBeingAsked = false
// cleanup
val askAsyncListener = mAskAsyncListener!!
val askAsyncRequestedPermissions = mAskAsyncRequestedPermissions!!
mAskAsyncListener = null
mAskAsyncRequestedPermissions = null
if (askAsyncRequestedPermissions.isNotEmpty()) {
// invoke actual asking for permissions
askForManifestPermissions(askAsyncRequestedPermissions, askAsyncListener)
} else {
// user asked only for Manifest.permission.WRITE_SETTINGS
askAsyncListener.onResult(mutableMapOf())
}
}
override fun onHostPause() = Unit
override fun onHostDestroy() = Unit
}
| bsd-3-clause | faa27cff377fac4efd03cb61dc0db411 | 39.974576 | 180 | 0.734092 | 5.087689 | false | false | false | false |
onoderis/failchat | src/main/kotlin/failchat/chat/ChatMessageHistory.kt | 2 | 2919 | package failchat.chat
import com.google.common.collect.EvictingQueue
import failchat.chat.ChatMessageHistory.Operation.Add
import failchat.chat.ChatMessageHistory.Operation.Clear
import failchat.chat.ChatMessageHistory.Operation.FindAll
import failchat.chat.ChatMessageHistory.Operation.FindFirst
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineName
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.launch
import java.util.Queue
class ChatMessageHistory(capacity: Int) {
private val history: Queue<ChatMessage> = EvictingQueue.create(capacity)
private val opChannel: Channel<Operation> = Channel(Channel.UNLIMITED)
fun start() {
CoroutineScope(Dispatchers.Default + CoroutineName("ChatMessageHistoryHandler")).launch {
handleOperations()
}
}
private suspend fun handleOperations() {
for (op in opChannel) {
when (op) {
is Add -> history.add(op.message)
is FindFirst -> {
val message = history.find(op.predicate)
op.result.complete(message)
}
is FindAll -> {
val messages = history.filter(op.predicate)
op.result.complete(messages)
}
is Clear -> history.clear()
}
}
}
fun stop() {
opChannel.close()
}
suspend fun add(message: ChatMessage) {
opChannel.send(Add(message))
}
suspend fun findFirst(predicate: (ChatMessage) -> Boolean): ChatMessage? {
val foundFuture = CompletableDeferred<ChatMessage?>()
opChannel.send(FindFirst(predicate, foundFuture))
return foundFuture.await()
}
suspend fun find(predicate: (ChatMessage) -> Boolean): List<ChatMessage> {
val foundFuture = CompletableDeferred<List<ChatMessage>>()
opChannel.send(FindAll(predicate, foundFuture))
return foundFuture.await()
}
suspend fun clear() {
opChannel.send(Clear)
}
private sealed class Operation {
class Add(val message: ChatMessage) : Operation()
class FindFirst(val predicate: (ChatMessage) -> Boolean, val result: CompletableDeferred<ChatMessage?>) : Operation()
class FindAll(val predicate: (ChatMessage) -> Boolean, val result: CompletableDeferred<List<ChatMessage>>) : Operation()
object Clear : Operation()
}
}
suspend inline fun <reified T : ChatMessage> ChatMessageHistory.findFirstTyped(crossinline predicate: (T) -> Boolean): T? {
return findFirst { it is T && predicate(it) } as T?
}
suspend inline fun <reified T : ChatMessage> ChatMessageHistory.findTyped(crossinline predicate: (T) -> Boolean): List<T> {
return find { it is T && predicate(it) } as List<T>
}
| gpl-3.0 | f2a41307289cc13cf84431c32990087b | 34.168675 | 128 | 0.66838 | 4.648089 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/base/project-structure/src/org/jetbrains/kotlin/idea/base/projectStructure/moduleInfo/LibraryInfo.kt | 1 | 4958 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.roots.impl.libraries.LibraryEx
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.util.ModificationTracker
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.util.PathUtil
import org.jetbrains.kotlin.analyzer.*
import org.jetbrains.kotlin.idea.base.projectStructure.*
import org.jetbrains.kotlin.idea.base.projectStructure.compositeAnalysis.findAnalyzerServices
import org.jetbrains.kotlin.idea.base.projectStructure.libraryToSourceAnalysis.ResolutionAnchorCacheService
import org.jetbrains.kotlin.idea.base.projectStructure.libraryToSourceAnalysis.useLibraryToSourceAnalysis
import org.jetbrains.kotlin.idea.base.projectStructure.scope.PoweredLibraryScopeBase
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.platform.*
import org.jetbrains.kotlin.resolve.PlatformDependentAnalyzerServices
abstract class LibraryInfo(
override val project: Project,
val library: Library
) : IdeaModuleInfo, LibraryModuleInfo, BinaryModuleInfo, TrackableModuleInfo {
private val libraryWrapper = LibraryWrapper(library as LibraryEx)
override val moduleOrigin: ModuleOrigin
get() = ModuleOrigin.LIBRARY
override val name: Name = Name.special("<library ${library.name}>")
override val displayedName: String
get() = KotlinBaseProjectStructureBundle.message("library.0", library.name.toString())
override val contentScope: GlobalSearchScope
get() = LibraryWithoutSourceScope(project, library)
override fun dependencies(): List<IdeaModuleInfo> {
val dependencies = LibraryDependenciesCache.getInstance(project).getLibraryDependencies(this)
return LinkedHashSet<IdeaModuleInfo>(dependencies.libraries.size + dependencies.sdk.size + 1).apply {
add(this@LibraryInfo)
addAll(dependencies.sdk)
addAll(dependencies.libraries)
}.toList()
}
abstract override val platform: TargetPlatform // must override
override val analyzerServices: PlatformDependentAnalyzerServices
get() = platform.findAnalyzerServices(project)
private val _sourcesModuleInfo: SourceForBinaryModuleInfo by lazy { LibrarySourceInfo(project, library, this) }
override val sourcesModuleInfo: SourceForBinaryModuleInfo
get() = _sourcesModuleInfo
override fun getLibraryRoots(): Collection<String> =
library.getFiles(OrderRootType.CLASSES).mapNotNull(PathUtil::getLocalPath)
override fun createModificationTracker(): ModificationTracker =
if (!project.useLibraryToSourceAnalysis) {
ModificationTracker.NEVER_CHANGED
} else {
ResolutionAnchorAwareLibraryModificationTracker(this)
}
override fun toString() =
"${this::class.simpleName}(libraryName=${library.name}${if (library !is LibraryEx || !library.isDisposed) ", libraryRoots=${getLibraryRoots()})" else ""}"
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is LibraryInfo) return false
return libraryWrapper == other.libraryWrapper
}
override fun hashCode() = libraryWrapper.hashCode()
}
private class ResolutionAnchorAwareLibraryModificationTracker(private val libraryInfo: LibraryInfo) : ModificationTracker {
override fun getModificationCount(): Long {
val dependencyModules = ResolutionAnchorCacheService.getInstance(libraryInfo.project)
.getDependencyResolutionAnchors(libraryInfo)
.map { it.module }
if (dependencyModules.isEmpty()) {
return ModificationTracker.NEVER_CHANGED.modificationCount
}
val project = dependencyModules.first().project
val modificationTrackerProvider = KotlinModificationTrackerProvider.getInstance(project)
return dependencyModules
.maxOfOrNull(modificationTrackerProvider::getModuleSelfModificationCount)
?: ModificationTracker.NEVER_CHANGED.modificationCount
}
}
@Suppress("EqualsOrHashCode") // DelegatingGlobalSearchScope requires to provide calcHashCode()
private class LibraryWithoutSourceScope(
project: Project,
private val library: Library
) : PoweredLibraryScopeBase(project, library.getFiles(OrderRootType.CLASSES), arrayOf()) {
override fun getFileRoot(file: VirtualFile): VirtualFile? = myIndex.getClassRootForFile(file)
override fun equals(other: Any?) = other is LibraryWithoutSourceScope && library == other.library
override fun calcHashCode(): Int = library.hashCode()
override fun toString() = "LibraryWithoutSourceScope($library)"
} | apache-2.0 | 07fcb5ed50cad0fb4696961474a695c2 | 42.884956 | 162 | 0.762606 | 5.186192 | false | false | false | false |
dmitry-zhuravlev/hotswap-agent-intellij-plugin | src/com/hotswap/agent/plugin/services/HotSwapAgentPluginNotification.kt | 1 | 3609 | /*
* Copyright (c) 2017 Dmitry Zhuravlev, Sergei Stepanov
*
* 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.hotswap.agent.plugin.services
import com.hotswap.agent.plugin.util.Constants.Companion.DCEVM_RELEASES_URL
import com.intellij.ide.BrowserUtil
import com.intellij.notification.Notification
import com.intellij.notification.NotificationGroup
import com.intellij.notification.NotificationListener
import com.intellij.notification.NotificationType
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.project.Project
import javax.swing.event.HyperlinkEvent
/**
* @author Dmitry Zhuravlev
* Date: 10.03.2017
*/
class HotSwapAgentPluginNotification(private val project: Project?) {
companion object {
private val NOTIFICATION_GROUP = NotificationGroup.balloonGroup("HotSwapAgent Notification Group")
private const val DOWNLOAD_AGENT_EVENT_DESCRIPTION = "download_agent"
private const val DOWNLOAD_DCEVM_EVENT_DESCRIPTION = "download_dcevm"
fun getInstance(project: Project? = null) = when (project) {
null -> ServiceManager.getService<HotSwapAgentPluginNotification>(HotSwapAgentPluginNotification::class.java)!!
else -> ServiceManager.getService<HotSwapAgentPluginNotification>(project, HotSwapAgentPluginNotification::class.java)!!
}
}
fun showNotificationAboutNewAgentVersion(downloadAction: () -> Unit) {
val message = """<a href=$DOWNLOAD_AGENT_EVENT_DESCRIPTION>Download and apply</a> new version of HotSwapAgent."""
HotSwapAgentPluginNotification.getInstance(project).showBalloon(
"New HotSwapAgent version available",
message, NotificationType.INFORMATION, object : NotificationListener.Adapter() {
override fun hyperlinkActivated(notification: Notification, e: HyperlinkEvent) {
notification.expire()
if (DOWNLOAD_AGENT_EVENT_DESCRIPTION == e.description) {
downloadAction()
}
}
})
}
fun showNotificationAboutMissingDCEVM() {
val message = """HotSwap will not work. <a href=$DOWNLOAD_DCEVM_EVENT_DESCRIPTION>Download</a> and install DCEVM."""
HotSwapAgentPluginNotification.getInstance(project).showBalloon(
"DCEVM installation not found",
message, NotificationType.WARNING, object : NotificationListener.Adapter() {
override fun hyperlinkActivated(notification: Notification, e: HyperlinkEvent) {
notification.expire()
if (DOWNLOAD_DCEVM_EVENT_DESCRIPTION == e.description) {
BrowserUtil.browse(DCEVM_RELEASES_URL)
}
}
})
}
private fun showBalloon(title: String,
message: String,
type: NotificationType,
listener: NotificationListener? = null) {
NOTIFICATION_GROUP.createNotification(title, message, type, listener).notify(project)
}
} | apache-2.0 | f0cd7a84ad9e505bc81c24bf60428de5 | 44.696203 | 132 | 0.688556 | 5.005548 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/MapGetWithNotNullAssertionOperatorInspection.kt | 2 | 5182 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiDocumentManager
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.intentions.callExpression
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
class MapGetWithNotNullAssertionOperatorInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) =
postfixExpressionVisitor(fun(expression: KtPostfixExpression) {
if (expression.operationToken != KtTokens.EXCLEXCL) return
if (expression.getReplacementData() == null) return
if (expression.baseExpression?.resolveToCall()?.resultingDescriptor?.fqNameSafe != FqName("kotlin.collections.Map.get")) return
holder.registerProblem(
expression.operationReference,
KotlinBundle.message("map.get.with.not.null.assertion.operator"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
ReplaceWithGetValueCallFix(),
ReplaceWithGetOrElseFix(),
ReplaceWithElvisErrorFix()
)
})
private class ReplaceWithGetValueCallFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("replace.with.get.value.call.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val expression = descriptor.psiElement.parent as? KtPostfixExpression ?: return
val (reference, index) = expression.getReplacementData() ?: return
val replaced = expression.replaced(KtPsiFactory(expression).createExpressionByPattern("$0.getValue($1)", reference, index))
replaced.findExistingEditor()?.caretModel?.moveToOffset(replaced.endOffset)
}
}
private class ReplaceWithGetOrElseFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("replace.with.get.or.else.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val expression = descriptor.psiElement.parent as? KtPostfixExpression ?: return
val (reference, index) = expression.getReplacementData() ?: return
val replaced = expression.replaced(KtPsiFactory(expression).createExpressionByPattern("$0.getOrElse($1){}", reference, index))
val editor = replaced.findExistingEditor() ?: return
val offset = (replaced as KtQualifiedExpression).callExpression?.lambdaArguments?.firstOrNull()?.startOffset ?: return
val document = editor.document
PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(document)
document.insertString(offset + 1, " ")
editor.caretModel.moveToOffset(offset + 2)
}
}
private class ReplaceWithElvisErrorFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("replace.with.elvis.error.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val expression = descriptor.psiElement.parent as? KtPostfixExpression ?: return
val (reference, index) = expression.getReplacementData() ?: return
val replaced = expression.replace(KtPsiFactory(expression).createExpressionByPattern("$0[$1] ?: error(\"\")", reference, index))
val editor = replaced.findExistingEditor() ?: return
val offset = (replaced as? KtBinaryExpression)?.right?.endOffset ?: return
editor.caretModel.moveToOffset(offset - 2)
}
}
}
private fun KtPostfixExpression.getReplacementData(): Pair<KtExpression, KtExpression>? {
when (val base = baseExpression) {
is KtQualifiedExpression -> {
if (base.callExpression?.calleeExpression?.text != "get") return null
val reference = base.receiverExpression
val index = base.callExpression?.valueArguments?.firstOrNull()?.getArgumentExpression() ?: return null
return reference to index
}
is KtArrayAccessExpression -> {
val reference = base.arrayExpression ?: return null
val index = base.indexExpressions.firstOrNull() ?: return null
return reference to index
}
else -> return null
}
} | apache-2.0 | 7e6f13ec93183225de407819b20d5ba0 | 52.989583 | 158 | 0.710151 | 5.386694 | false | false | false | false |
JetBrains/ideavim | vim-engine/src/main/kotlin/com/maddyhome/idea/vim/command/MappingMode.kt | 1 | 1911 | /*
* 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.command
import java.util.*
/**
* @author vlan
*
* COMPATIBILITY-LAYER: Do not move this class to a different package
*/
enum class MappingMode {
/**
* Indicates this key mapping applies to Normal mode
*/
NORMAL,
/**
* Indicates this key mapping applies to Visual mode
*/
VISUAL,
/**
* Indicates this key mapping applies to Select mode
*/
SELECT,
/**
* Indicates this key mapping applies to Operator Pending mode
*/
OP_PENDING,
/**
* Indicates this key mapping applies to Insert mode
*/
INSERT,
/**
* Indicates this key mapping applies to Command Line mode
*/
CMD_LINE;
companion object {
@JvmField
val N: EnumSet<MappingMode> = EnumSet.of(NORMAL)
val X: EnumSet<MappingMode> = EnumSet.of(VISUAL)
val O: EnumSet<MappingMode> = EnumSet.of(OP_PENDING)
val I: EnumSet<MappingMode> = EnumSet.of(INSERT)
val C: EnumSet<MappingMode> = EnumSet.of(CMD_LINE)
val S: EnumSet<MappingMode> = EnumSet.of(SELECT)
val V: EnumSet<MappingMode> = EnumSet.of(VISUAL, SELECT)
val NO: EnumSet<MappingMode> = EnumSet.of(NORMAL, OP_PENDING)
@JvmField
val XO: EnumSet<MappingMode> = EnumSet.of(VISUAL, OP_PENDING)
val NX: EnumSet<MappingMode> = EnumSet.of(NORMAL, VISUAL)
val IC: EnumSet<MappingMode> = EnumSet.of(INSERT, CMD_LINE)
val NV: EnumSet<MappingMode> = EnumSet.of(NORMAL, VISUAL, SELECT)
@JvmField
val NXO: EnumSet<MappingMode> = EnumSet.of(NORMAL, VISUAL, OP_PENDING)
@JvmField
val NVO: EnumSet<MappingMode> = EnumSet.of(NORMAL, VISUAL, OP_PENDING, SELECT)
val ALL: EnumSet<MappingMode> = EnumSet.allOf(MappingMode::class.java)
}
}
| mit | 58080503f4c99552cf982601dbc28a6f | 25.541667 | 82 | 0.682889 | 3.732422 | false | false | false | false |
JetBrains/ideavim | vim-engine/src/main/kotlin/com/maddyhome/idea/vim/KeyHandler.kt | 1 | 38948 | /*
* 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
import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.VimActionsInitiator
import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.command.Argument
import com.maddyhome.idea.vim.command.Command
import com.maddyhome.idea.vim.command.CommandBuilder
import com.maddyhome.idea.vim.command.CommandFlags
import com.maddyhome.idea.vim.command.MappingMode
import com.maddyhome.idea.vim.command.MappingState
import com.maddyhome.idea.vim.command.OperatorArguments
import com.maddyhome.idea.vim.command.VimStateMachine
import com.maddyhome.idea.vim.command.VimStateMachine.Companion.getInstance
import com.maddyhome.idea.vim.common.CurrentCommandState
import com.maddyhome.idea.vim.common.DigraphResult
import com.maddyhome.idea.vim.common.argumentCaptured
import com.maddyhome.idea.vim.diagnostic.VimLogger
import com.maddyhome.idea.vim.diagnostic.debug
import com.maddyhome.idea.vim.diagnostic.trace
import com.maddyhome.idea.vim.diagnostic.vimLogger
import com.maddyhome.idea.vim.handler.EditorActionHandlerBase
import com.maddyhome.idea.vim.helper.inNormalMode
import com.maddyhome.idea.vim.helper.inSingleNormalMode
import com.maddyhome.idea.vim.helper.inVisualMode
import com.maddyhome.idea.vim.helper.isCloseKeyStroke
import com.maddyhome.idea.vim.helper.vimStateMachine
import com.maddyhome.idea.vim.key.CommandNode
import com.maddyhome.idea.vim.key.CommandPartNode
import com.maddyhome.idea.vim.key.KeyMappingLayer
import com.maddyhome.idea.vim.key.KeyStack
import com.maddyhome.idea.vim.key.Node
import com.maddyhome.idea.vim.options.OptionConstants
import com.maddyhome.idea.vim.options.OptionScope
import com.maddyhome.idea.vim.vimscript.model.datatypes.VimInt
import java.awt.event.InputEvent
import java.awt.event.KeyEvent
import java.util.function.Consumer
import javax.swing.KeyStroke
/**
* This handles every keystroke that the user can argType except those that are still valid hotkeys for various Idea
* actions. This is a singleton.
*/
class KeyHandler {
private var handleKeyRecursionCount = 0
val keyStack = KeyStack()
val modalEntryKeys: MutableList<KeyStroke> = ArrayList()
/**
* This is the main key handler for the Vim plugin. Every keystroke not handled directly by Idea is sent here for
* processing.
*
* @param editor The editor the key was typed into
* @param key The keystroke typed by the user
* @param context The data context
*/
fun handleKey(editor: VimEditor, key: KeyStroke, context: ExecutionContext) {
handleKey(editor, key, context, allowKeyMappings = true, mappingCompleted = false)
}
/**
* Handling input keys with additional parameters
*
* @param allowKeyMappings - If we allow key mappings or not
* @param mappingCompleted - if true, we don't check if the mapping is incomplete
*
* TODO mappingCompleted and recursionCounter - we should find a more beautiful way to use them
*/
fun handleKey(
editor: VimEditor,
key: KeyStroke,
context: ExecutionContext,
allowKeyMappings: Boolean,
mappingCompleted: Boolean,
) {
LOG.trace {
"""
------- Key Handler -------
Start key processing. allowKeyMappings: $allowKeyMappings, mappingCompleted: $mappingCompleted
Key: $key
""".trimIndent()
}
val mapMapDepth = (
injector.optionService.getOptionValue(
OptionScope.GLOBAL,
OptionConstants.maxmapdepthName,
OptionConstants.maxmapdepthName
) as VimInt
).value
if (handleKeyRecursionCount >= mapMapDepth) {
injector.messages.showStatusBarMessage(injector.messages.message("E223"))
injector.messages.indicateError()
LOG.warn("Key handling, maximum recursion of the key received. maxdepth=$mapMapDepth")
return
}
injector.messages.clearError()
val editorState = editor.vimStateMachine
val commandBuilder = editorState.commandBuilder
// If this is a "regular" character keystroke, get the character
val chKey: Char = if (key.keyChar == KeyEvent.CHAR_UNDEFINED) 0.toChar() else key.keyChar
// We only record unmapped keystrokes. If we've recursed to handle mapping, don't record anything.
var shouldRecord = handleKeyRecursionCount == 0 && editorState.isRecording
handleKeyRecursionCount++
try {
LOG.trace("Start key processing...")
if (!allowKeyMappings || !handleKeyMapping(editor, key, context, mappingCompleted)) {
LOG.trace("Mappings processed, continue processing key.")
if (isCommandCountKey(chKey, editorState)) {
commandBuilder.addCountCharacter(key)
} else if (isDeleteCommandCountKey(key, editorState)) {
commandBuilder.deleteCountCharacter()
} else if (isEditorReset(key, editorState)) {
handleEditorReset(editor, key, context, editorState)
} else if (isExpectingCharArgument(commandBuilder)) {
handleCharArgument(key, chKey, editorState)
} else if (editorState.isRegisterPending) {
LOG.trace("Pending mode.")
commandBuilder.addKey(key)
handleSelectRegister(editorState, chKey)
} else if (!handleDigraph(editor, key, context, editorState)) {
LOG.debug("Digraph is NOT processed")
// Ask the key/action tree if this is an appropriate key at this point in the command and if so,
// return the node matching this keystroke
val node: Node<VimActionsInitiator>? = mapOpCommand(key, commandBuilder.getChildNode(key), editorState)
LOG.trace("Get the node for the current mode")
if (node is CommandNode<VimActionsInitiator>) {
LOG.trace("Node is a command node")
handleCommandNode(editor, context, key, node, editorState)
commandBuilder.addKey(key)
} else if (node is CommandPartNode<VimActionsInitiator>) {
LOG.trace("Node is a command part node")
commandBuilder.setCurrentCommandPartNode(node)
commandBuilder.addKey(key)
} else if (isSelectRegister(key, editorState)) {
LOG.trace("Select register")
editorState.isRegisterPending = true
commandBuilder.addKey(key)
} else {
// node == null
LOG.trace("We are not able to find a node for this key")
// If we are in insert/replace mode send this key in for processing
if (editorState.mode == VimStateMachine.Mode.INSERT || editorState.mode == VimStateMachine.Mode.REPLACE) {
LOG.trace("Process insert or replace")
shouldRecord = injector.changeGroup.processKey(editor, context, key) && shouldRecord
} else if (editorState.mode == VimStateMachine.Mode.SELECT) {
LOG.trace("Process select")
shouldRecord = injector.changeGroup.processKeyInSelectMode(editor, context, key) && shouldRecord
} else if (editorState.mappingState.mappingMode == MappingMode.CMD_LINE) {
LOG.trace("Process cmd line")
shouldRecord = injector.processGroup.processExKey(editor, key) && shouldRecord
} else {
LOG.trace("Set command state to bad_command")
commandBuilder.commandState = CurrentCommandState.BAD_COMMAND
}
partialReset(editor)
}
}
}
} finally {
handleKeyRecursionCount--
}
finishedCommandPreparation(editor, context, editorState, commandBuilder, key, shouldRecord)
}
fun finishedCommandPreparation(
editor: VimEditor,
context: ExecutionContext,
editorState: VimStateMachine,
commandBuilder: CommandBuilder,
key: KeyStroke?,
shouldRecord: Boolean,
) {
// Do we have a fully entered command at this point? If so, let's execute it.
if (commandBuilder.isReady) {
LOG.trace("Ready command builder. Execute command.")
executeCommand(editor, context, editorState)
} else if (commandBuilder.isBad) {
LOG.trace("Command builder is set to BAD")
editorState.resetOpPending()
editorState.resetRegisterPending()
editorState.resetReplaceCharacter()
injector.messages.indicateError()
reset(editor)
}
// Don't record the keystroke that stops the recording (unmapped this is `q`)
if (shouldRecord && editorState.isRecording && key != null) {
injector.registerGroup.recordKeyStroke(key)
modalEntryKeys.forEach { injector.registerGroup.recordKeyStroke(it) }
modalEntryKeys.clear()
}
// This will update immediately, if we're on the EDT (which we are)
injector.messages.updateStatusBar()
LOG.trace("----------- Key Handler Finished -----------")
}
/**
* See the description for [com.maddyhome.idea.vim.action.DuplicableOperatorAction]
*/
private fun mapOpCommand(
key: KeyStroke,
node: Node<VimActionsInitiator>?,
editorState: VimStateMachine,
): Node<VimActionsInitiator>? {
return if (editorState.isDuplicateOperatorKeyStroke(key)) {
editorState.commandBuilder.getChildNode(KeyStroke.getKeyStroke('_'))
} else node
}
private fun handleEditorReset(
editor: VimEditor,
key: KeyStroke,
context: ExecutionContext,
editorState: VimStateMachine,
) {
val commandBuilder = editorState.commandBuilder
if (commandBuilder.isAwaitingCharOrDigraphArgument()) {
editorState.resetReplaceCharacter()
}
if (commandBuilder.isAtDefaultState) {
val register = injector.registerGroup
if (register.currentRegister == register.defaultRegister) {
var indicateError = true
if (key.keyCode == KeyEvent.VK_ESCAPE) {
val executed = arrayOf<Boolean?>(null)
injector.actionExecutor.executeCommand(
editor,
{ executed[0] = injector.actionExecutor.executeEsc(context) },
"", null
)
indicateError = !executed[0]!!
}
if (indicateError) {
injector.messages.indicateError()
}
}
}
reset(editor)
}
private fun handleKeyMapping(
editor: VimEditor,
key: KeyStroke,
context: ExecutionContext,
mappingCompleted: Boolean,
): Boolean {
LOG.debug("Start processing key mappings.")
val commandState = editor.vimStateMachine
val mappingState = commandState.mappingState
val commandBuilder = commandState.commandBuilder
if (commandBuilder.isAwaitingCharOrDigraphArgument() ||
commandBuilder.isBuildingMultiKeyCommand() ||
isMappingDisabledForKey(key, commandState) ||
commandState.isRegisterPending
) {
LOG.debug("Finish key processing, returning false")
return false
}
mappingState.stopMappingTimer()
// Save the unhandled key strokes until we either complete or abandon the sequence.
LOG.trace("Add key to mapping state")
mappingState.addKey(key)
val mapping = injector.keyGroup.getKeyMappingLayer(mappingState.mappingMode)
LOG.trace { "Get keys for mapping mode. mode = " + mappingState.mappingMode }
// Returns true if any of these methods handle the key. False means that the key is unrelated to mapping and should
// be processed as normal.
val mappingProcessed =
handleUnfinishedMappingSequence(editor, mappingState, mapping, mappingCompleted) ||
handleCompleteMappingSequence(editor, context, mappingState, mapping, key) ||
handleAbandonedMappingSequence(editor, mappingState, context)
LOG.debug { "Finish mapping processing. Return $mappingProcessed" }
return mappingProcessed
}
private fun isMappingDisabledForKey(key: KeyStroke, vimStateMachine: VimStateMachine): Boolean {
// "0" can be mapped, but the mapping isn't applied when entering a count. Other digits are always mapped, even when
// entering a count.
// See `:help :map-modes`
val isMappingDisabled = key.keyChar == '0' && vimStateMachine.commandBuilder.count > 0
LOG.debug { "Mapping disabled for key: $isMappingDisabled" }
return isMappingDisabled
}
private fun handleUnfinishedMappingSequence(
editor: VimEditor,
mappingState: MappingState,
mapping: KeyMappingLayer,
mappingCompleted: Boolean,
): Boolean {
LOG.trace("Processing unfinished mappings...")
if (mappingCompleted) {
LOG.trace("Mapping is already completed. Returning false.")
return false
}
// Is there at least one mapping that starts with the current sequence? This does not include complete matches,
// unless a sequence is also a prefix for another mapping. We eagerly evaluate the shortest mapping, so even if a
// mapping is a prefix, it will get evaluated when the next character is entered.
// Note that currentlyUnhandledKeySequence is the same as the state after commandState.getMappingKeys().add(key). It
// would be nice to tidy ths up
if (!mapping.isPrefix(mappingState.keys)) {
LOG.debug("There are no mappings that start with the current sequence. Returning false.")
return false
}
// If the timeout option is set, set a timer that will abandon the sequence and replay the unhandled keys unmapped.
// Every time a key is pressed and handled, the timer is stopped. E.g. if there is a mapping for "dweri", and the
// user has typed "dw" wait for the timeout, and then replay "d" and "w" without any mapping (which will of course
// delete a word)
if (injector.optionService
.isSet(OptionScope.LOCAL(editor), OptionConstants.timeoutName, OptionConstants.timeoutName)
) {
LOG.trace("Timeout is set. Schedule a mapping timer")
// XXX There is a strange issue that reports that mapping state is empty at the moment of the function call.
// At the moment, I see the only one possibility this to happen - other key is handled after the timer executed,
// but before invoke later is handled. This is a rare case, so I'll just add a check to isPluginMapping.
// But this "unexpected behaviour" exists and it would be better not to relay on mutable state with delays.
// https://youtrack.jetbrains.com/issue/VIM-2392
mappingState.startMappingTimer {
injector.application.invokeLater(
{
LOG.debug("Delayed mapping timer call")
val unhandledKeys = mappingState.detachKeys()
if (editor.isDisposed() || isPluginMapping(unhandledKeys)) {
LOG.debug("Abandon mapping timer")
return@invokeLater
}
LOG.trace("Processing unhandled keys...")
for (keyStroke in unhandledKeys) {
handleKey(
editor, keyStroke, injector.executionContextManager.onEditor(editor),
allowKeyMappings = true,
mappingCompleted = true
)
}
}, editor
)
}
}
LOG.trace("Unfinished mapping processing finished")
return true
}
private fun handleCompleteMappingSequence(
editor: VimEditor,
context: ExecutionContext,
mappingState: MappingState,
mapping: KeyMappingLayer,
key: KeyStroke,
): Boolean {
LOG.trace("Processing complete mapping sequence...")
// The current sequence isn't a prefix, check to see if it's a completed sequence.
val currentMappingInfo = mapping.getLayer(mappingState.keys)
var mappingInfo = currentMappingInfo
if (mappingInfo == null) {
LOG.trace("Haven't found any mapping info for the given sequence. Trying to apply mapping to a subsequence.")
// It's an abandoned sequence, check to see if the previous sequence was a complete sequence.
// TODO: This is incorrect behaviour
// What about sequences that were completed N keys ago?
// This should really be handled as part of an abandoned key sequence. We should also consolidate the replay
// of cached keys - this happens in timeout, here and also in abandoned sequences.
// Extract most of this method into handleMappingInfo. If we have a complete sequence, call it and we're done.
// If it's not a complete sequence, handleAbandonedMappingSequence should do something like call
// mappingState.detachKeys and look for the longest complete sequence in the returned list, evaluate it, and then
// replay any keys not yet handled. NB: The actual implementation should be compared to Vim behaviour to see what
// should actually happen.
val previouslyUnhandledKeySequence = ArrayList<KeyStroke>()
mappingState.keys.forEach(Consumer { e: KeyStroke -> previouslyUnhandledKeySequence.add(e) })
if (previouslyUnhandledKeySequence.size > 1) {
previouslyUnhandledKeySequence.removeAt(previouslyUnhandledKeySequence.size - 1)
mappingInfo = mapping.getLayer(previouslyUnhandledKeySequence)
}
}
if (mappingInfo == null) {
LOG.trace("Cannot find any mapping info for the sequence. Return false.")
return false
}
mappingState.resetMappingSequence()
val currentContext = context.updateEditor(editor)
LOG.trace("Executing mapping info")
try {
mappingState.startMapExecution()
mappingInfo.execute(editor, context)
} catch (e: Exception) {
injector.messages.showStatusBarMessage(e.message)
injector.messages.indicateError()
LOG.warn(
"""
Caught exception during ${mappingInfo.getPresentableString()}
${e.message}
""".trimIndent()
)
} catch (e: NotImplementedError) {
injector.messages.showStatusBarMessage(e.message)
injector.messages.indicateError()
LOG.warn(
"""
Caught exception during ${mappingInfo.getPresentableString()}
${e.message}
""".trimIndent()
)
} finally {
mappingState.stopMapExecution()
}
// If we've just evaluated the previous key sequence, make sure to also handle the current key
if (mappingInfo !== currentMappingInfo) {
LOG.trace("Evaluating the current key")
handleKey(editor, key, currentContext, allowKeyMappings = true, false)
}
LOG.trace("Success processing of mapping")
return true
}
private fun handleAbandonedMappingSequence(
editor: VimEditor,
mappingState: MappingState,
context: ExecutionContext,
): Boolean {
LOG.debug("Processing abandoned mapping sequence")
// The user has terminated a mapping sequence with an unexpected key
// E.g. if there is a mapping for "hello" and user enters command "help" the processing of "h", "e" and "l" will be
// prevented by this handler. Make sure the currently unhandled keys are processed as normal.
val unhandledKeyStrokes = mappingState.detachKeys()
// If there is only the current key to handle, do nothing
if (unhandledKeyStrokes.size == 1) {
LOG.trace("There is only one key in mapping. Return false.")
return false
}
// Okay, look at the code below. Why is the first key handled separately?
// Let's assume the next mappings:
// - map ds j
// - map I 2l
// If user enters `dI`, the first `d` will be caught be this handler because it's a prefix for `ds` command.
// After the user enters `I`, the caught `d` should be processed without mapping, and the rest of keys
// should be processed with mappings (to make I work)
if (isPluginMapping(unhandledKeyStrokes)) {
LOG.trace("This is a plugin mapping, process it")
handleKey(
editor, unhandledKeyStrokes[unhandledKeyStrokes.size - 1], context,
allowKeyMappings = true,
mappingCompleted = false
)
} else {
LOG.trace("Process abandoned keys.")
handleKey(editor, unhandledKeyStrokes[0], context, allowKeyMappings = false, mappingCompleted = false)
for (keyStroke in unhandledKeyStrokes.subList(1, unhandledKeyStrokes.size)) {
handleKey(editor, keyStroke, context, allowKeyMappings = true, mappingCompleted = false)
}
}
LOG.trace("Return true from abandoned keys processing.")
return true
}
// The <Plug>mappings are not executed if they fail to map to something.
// E.g.
// - map <Plug>iA someAction
// - map I <Plug>i
// For `IA` someAction should be executed.
// But if the user types `Ib`, `<Plug>i` won't be executed again. Only `b` will be passed to keyHandler.
private fun isPluginMapping(unhandledKeyStrokes: List<KeyStroke>): Boolean {
return unhandledKeyStrokes.isNotEmpty() && unhandledKeyStrokes[0] == injector.parser.plugKeyStroke
}
private fun isCommandCountKey(chKey: Char, editorState: VimStateMachine): Boolean {
// Make sure to avoid handling '0' as the start of a count.
val commandBuilder = editorState.commandBuilder
val notRegisterPendingCommand = editorState.mode.inNormalMode && !editorState.isRegisterPending
val visualMode = editorState.mode.inVisualMode && !editorState.isRegisterPending
val opPendingMode = editorState.mode === VimStateMachine.Mode.OP_PENDING
if (notRegisterPendingCommand || visualMode || opPendingMode) {
if (commandBuilder.isExpectingCount && Character.isDigit(chKey) && (commandBuilder.count > 0 || chKey != '0')) {
LOG.debug("This is a command key count")
return true
}
}
LOG.debug("This is NOT a command key count")
return false
}
private fun isDeleteCommandCountKey(key: KeyStroke, editorState: VimStateMachine): Boolean {
// See `:help N<Del>`
val commandBuilder = editorState.commandBuilder
val isDeleteCommandKeyCount =
(editorState.mode === VimStateMachine.Mode.COMMAND || editorState.mode === VimStateMachine.Mode.VISUAL || editorState.mode === VimStateMachine.Mode.OP_PENDING) &&
commandBuilder.isExpectingCount && commandBuilder.count > 0 && key.keyCode == KeyEvent.VK_DELETE
LOG.debug { "This is a delete command key count: $isDeleteCommandKeyCount" }
return isDeleteCommandKeyCount
}
private fun isEditorReset(key: KeyStroke, editorState: VimStateMachine): Boolean {
val editorReset = editorState.mode == VimStateMachine.Mode.COMMAND && key.isCloseKeyStroke()
LOG.debug { "This is editor reset: $editorReset" }
return editorReset
}
private fun isSelectRegister(key: KeyStroke, editorState: VimStateMachine): Boolean {
if (editorState.mode != VimStateMachine.Mode.COMMAND && editorState.mode != VimStateMachine.Mode.VISUAL) {
return false
}
return if (editorState.isRegisterPending) {
true
} else key.keyChar == '"' && !editorState.isOperatorPending && editorState.commandBuilder.expectedArgumentType == null
}
private fun handleSelectRegister(vimStateMachine: VimStateMachine, chKey: Char) {
LOG.trace("Handle select register")
vimStateMachine.resetRegisterPending()
if (injector.registerGroup.isValid(chKey)) {
LOG.trace("Valid register")
vimStateMachine.commandBuilder.pushCommandPart(chKey)
} else {
LOG.trace("Invalid register, set command state to BAD_COMMAND")
vimStateMachine.commandBuilder.commandState = CurrentCommandState.BAD_COMMAND
}
}
private fun isExpectingCharArgument(commandBuilder: CommandBuilder): Boolean {
val expectingCharArgument = commandBuilder.expectedArgumentType === Argument.Type.CHARACTER
LOG.debug { "Expecting char argument: $expectingCharArgument" }
return expectingCharArgument
}
private fun handleCharArgument(key: KeyStroke, chKey: Char, vimStateMachine: VimStateMachine) {
var mutableChKey = chKey
LOG.trace("Handling char argument")
// We are expecting a character argument - is this a regular character the user typed?
// Some special keys can be handled as character arguments - let's check for them here.
if (mutableChKey.code == 0) {
when (key.keyCode) {
KeyEvent.VK_TAB -> mutableChKey = '\t'
KeyEvent.VK_ENTER -> mutableChKey = '\n'
}
}
val commandBuilder = vimStateMachine.commandBuilder
if (mutableChKey.code != 0) {
LOG.trace("Add character argument to the current command")
// Create the character argument, add it to the current command, and signal we are ready to process the command
commandBuilder.completeCommandPart(Argument(mutableChKey))
} else {
LOG.trace("This is not a valid character argument. Set command state to BAD_COMMAND")
// Oops - this isn't a valid character argument
commandBuilder.commandState = CurrentCommandState.BAD_COMMAND
}
vimStateMachine.resetReplaceCharacter()
}
private fun handleDigraph(
editor: VimEditor,
key: KeyStroke,
context: ExecutionContext,
editorState: VimStateMachine,
): Boolean {
LOG.debug("Handling digraph")
// Support starting a digraph/literal sequence if the operator accepts one as an argument, e.g. 'r' or 'f'.
// Normally, we start the sequence (in Insert or CmdLine mode) through a VimAction that can be mapped. Our
// VimActions don't work as arguments for operators, so we have to special case here. Helpfully, Vim appears to
// hardcode the shortcuts, and doesn't support mapping, so everything works nicely.
val commandBuilder = editorState.commandBuilder
if (commandBuilder.expectedArgumentType == Argument.Type.DIGRAPH) {
LOG.trace("Expected argument is digraph")
if (editorState.digraphSequence.isDigraphStart(key)) {
editorState.startDigraphSequence()
editorState.commandBuilder.addKey(key)
return true
}
if (editorState.digraphSequence.isLiteralStart(key)) {
editorState.startLiteralSequence()
editorState.commandBuilder.addKey(key)
return true
}
}
val res = editorState.processDigraphKey(key, editor)
if (injector.exEntryPanel.isActive()) {
when (res.result) {
DigraphResult.RES_HANDLED -> setPromptCharacterEx(if (commandBuilder.isPuttingLiteral()) '^' else key.keyChar)
DigraphResult.RES_DONE, DigraphResult.RES_BAD -> if (key.keyCode == KeyEvent.VK_C && key.modifiers and InputEvent.CTRL_DOWN_MASK != 0) {
return false
} else {
injector.exEntryPanel.clearCurrentAction()
}
}
}
when (res.result) {
DigraphResult.RES_HANDLED -> {
editorState.commandBuilder.addKey(key)
return true
}
DigraphResult.RES_DONE -> {
if (commandBuilder.expectedArgumentType === Argument.Type.DIGRAPH) {
commandBuilder.fallbackToCharacterArgument()
}
val stroke = res.stroke ?: return false
editorState.commandBuilder.addKey(key)
handleKey(editor, stroke, context)
return true
}
DigraphResult.RES_BAD -> {
// BAD is an error. We were expecting a valid character, and we didn't get it.
if (commandBuilder.expectedArgumentType != null) {
commandBuilder.commandState = CurrentCommandState.BAD_COMMAND
}
return true
}
DigraphResult.RES_UNHANDLED -> {
// UNHANDLED means the key stroke made no sense in the context of a digraph, but isn't an error in the current
// state. E.g. waiting for {char} <BS> {char}. Let the key handler have a go at it.
if (commandBuilder.expectedArgumentType === Argument.Type.DIGRAPH) {
commandBuilder.fallbackToCharacterArgument()
handleKey(editor, key, context)
return true
}
return false
}
}
return false
}
private fun executeCommand(
editor: VimEditor,
context: ExecutionContext,
editorState: VimStateMachine,
) {
LOG.trace("Command execution")
val command = editorState.commandBuilder.buildCommand()
val operatorArguments = OperatorArguments(
editorState.mappingState.mappingMode == MappingMode.OP_PENDING,
command.rawCount, editorState.mode, editorState.subMode
)
// If we were in "operator pending" mode, reset back to normal mode.
editorState.resetOpPending()
// Save off the command we are about to execute
editorState.setExecutingCommand(command)
val type = command.type
if (type.isWrite) {
if (!editor.isWritable()) {
injector.messages.indicateError()
reset(editor)
LOG.warn("File is not writable")
return
}
}
if (injector.application.isMainThread()) {
val action: Runnable = ActionRunner(editor, context, command, operatorArguments)
val cmdAction = command.action
val name = cmdAction.id
if (type.isWrite) {
injector.application.runWriteCommand(editor, name, action, action)
} else if (type.isRead) {
injector.application.runReadCommand(editor, name, action, action)
} else {
injector.actionExecutor.executeCommand(editor, action, name, action)
}
}
}
private fun handleCommandNode(
editor: VimEditor,
context: ExecutionContext,
key: KeyStroke,
node: CommandNode<VimActionsInitiator>,
editorState: VimStateMachine,
) {
LOG.trace("Handle command node")
// The user entered a valid command. Create the command and add it to the stack.
val action = node.actionHolder.getInstance()
val commandBuilder = editorState.commandBuilder
val expectedArgumentType = commandBuilder.expectedArgumentType
commandBuilder.pushCommandPart(action)
if (!checkArgumentCompatibility(expectedArgumentType, action)) {
LOG.trace("Return from command node handling")
commandBuilder.commandState = CurrentCommandState.BAD_COMMAND
return
}
if (action.argumentType == null || stopMacroRecord(node, editorState)) {
LOG.trace("Set command state to READY")
commandBuilder.commandState = CurrentCommandState.READY
} else {
LOG.trace("Set waiting for the argument")
val argumentType = action.argumentType
startWaitingForArgument(editor, context, key.keyChar, action, argumentType!!, editorState)
partialReset(editor)
}
// TODO In the name of God, get rid of EX_STRING, FLAG_COMPLETE_EX and all the related staff
if (expectedArgumentType === Argument.Type.EX_STRING && action.flags.contains(CommandFlags.FLAG_COMPLETE_EX)) {
/* The only action that implements FLAG_COMPLETE_EX is ProcessExEntryAction.
* When pressing ':', ExEntryAction is chosen as the command. Since it expects no arguments, it is invoked and
calls ProcessGroup#startExCommand, pushes CMD_LINE mode, and the action is popped. The ex handler will push
the final <CR> through handleKey, which chooses ProcessExEntryAction. Because we're not expecting EX_STRING,
this branch does NOT fire, and ProcessExEntryAction handles the ex cmd line entry.
* When pressing '/' or '?', SearchEntry(Fwd|Rev)Action is chosen as the command. This expects an argument of
EX_STRING, so startWaitingForArgument calls ProcessGroup#startSearchCommand. The ex handler pushes the final
<CR> through handleKey, which chooses ProcessExEntryAction, and we hit this branch. We don't invoke
ProcessExEntryAction, but pop it, set the search text as an argument on SearchEntry(Fwd|Rev)Action and invoke
that instead.
* When using '/' or '?' as part of a motion (e.g. "d/foo"), the above happens again, and all is good. Because
the text has been applied as an argument on the last command, '.' will correctly repeat it.
It's hard to see how to improve this. Removing EX_STRING means starting ex input has to happen in ExEntryAction
and SearchEntry(Fwd|Rev)Action, and the ex command invoked in ProcessExEntryAction, but that breaks any initial
operator, which would be invoked first (e.g. 'd' in "d/foo").
*/
LOG.trace("Processing ex_string")
val text = injector.processGroup.endSearchCommand()
commandBuilder.popCommandPart() // Pop ProcessExEntryAction
commandBuilder.completeCommandPart(Argument(text)) // Set search text on SearchEntry(Fwd|Rev)Action
editorState.popModes() // Pop CMD_LINE
}
}
private fun stopMacroRecord(node: CommandNode<VimActionsInitiator>, editorState: VimStateMachine): Boolean {
// TODO
// return editorState.isRecording && node.actionHolder.getInstance() is ToggleRecordingAction
return editorState.isRecording && node.actionHolder.getInstance().id == "VimToggleRecordingAction"
}
private fun startWaitingForArgument(
editor: VimEditor,
context: ExecutionContext,
key: Char,
action: EditorActionHandlerBase,
argument: Argument.Type,
editorState: VimStateMachine,
) {
val commandBuilder = editorState.commandBuilder
when (argument) {
Argument.Type.MOTION -> {
if (editorState.isDotRepeatInProgress && argumentCaptured != null) {
commandBuilder.completeCommandPart(argumentCaptured!!)
}
editorState.pushModes(VimStateMachine.Mode.OP_PENDING, VimStateMachine.SubMode.NONE)
}
Argument.Type.DIGRAPH -> // Command actions represent the completion of a command. Showcmd relies on this - if the action represents a
// part of a command, the showcmd output is reset part way through. This means we need to special case entering
// digraph/literal input mode. We have an action that takes a digraph as an argument, and pushes it back through
// the key handler when it's complete.
// TODO
// if (action is InsertCompletedDigraphAction) {
if (action.id == "VimInsertCompletedDigraphAction") {
editorState.startDigraphSequence()
setPromptCharacterEx('?')
} else if (action.id == "VimInsertCompletedLiteralAction") {
editorState.startLiteralSequence()
setPromptCharacterEx('^')
}
Argument.Type.EX_STRING -> {
// The current Command expects an EX_STRING argument. E.g. SearchEntry(Fwd|Rev)Action. This won't execute until
// state hits READY. Start the ex input field, push CMD_LINE mode and wait for the argument.
injector.processGroup.startSearchCommand(editor, context, commandBuilder.count, key)
commandBuilder.commandState = CurrentCommandState.NEW_COMMAND
editorState.pushModes(VimStateMachine.Mode.CMD_LINE, VimStateMachine.SubMode.NONE)
}
else -> Unit
}
// Another special case. Force a mode change to update the caret shape
// This was a typed solution
// if (action is ChangeCharacterAction || action is ChangeVisualCharacterAction)
if (action.id == "VimChangeCharacterAction" || action.id == "VimChangeVisualCharacterAction") {
editorState.isReplaceCharacter = true
}
}
private fun checkArgumentCompatibility(
expectedArgumentType: Argument.Type?,
action: EditorActionHandlerBase,
): Boolean {
return !(expectedArgumentType === Argument.Type.MOTION && action.type !== Command.Type.MOTION)
}
/**
* Partially resets the state of this handler. Resets the command count, clears the key list, resets the key tree
* node to the root for the current mode we are in.
*
* @param editor The editor to reset.
*/
fun partialReset(editor: VimEditor) {
val editorState = getInstance(editor)
editorState.mappingState.resetMappingSequence()
editorState.commandBuilder.resetInProgressCommandPart(getKeyRoot(editorState.mappingState.mappingMode))
}
/**
* Resets the state of this handler. Does a partial reset then resets the mode, the command, and the argument.
*
* @param editor The editor to reset.
*/
fun reset(editor: VimEditor) {
partialReset(editor)
val editorState = getInstance(editor)
editorState.commandBuilder.resetAll(getKeyRoot(editorState.mappingState.mappingMode))
}
private fun getKeyRoot(mappingMode: MappingMode): CommandPartNode<VimActionsInitiator> {
return injector.keyGroup.getKeyRoot(mappingMode)
}
/**
* Completely resets the state of this handler. Resets the command mode to normal, resets, and clears the selected
* register.
*
* @param editor The editor to reset.
*/
fun fullReset(editor: VimEditor) {
injector.messages.clearError()
getInstance(editor).reset()
reset(editor)
injector.registerGroupIfCreated?.resetRegister()
editor.removeSelection()
}
private fun setPromptCharacterEx(promptCharacter: Char) {
val exEntryPanel = injector.exEntryPanel
if (exEntryPanel.isActive()) {
exEntryPanel.setCurrentActionPromptCharacter(promptCharacter)
}
}
/**
* This was used as an experiment to execute actions as a runnable.
*/
internal class ActionRunner(
val editor: VimEditor,
val context: ExecutionContext,
val cmd: Command,
val operatorArguments: OperatorArguments,
) : Runnable {
override fun run() {
val editorState = getInstance(editor)
editorState.commandBuilder.commandState = CurrentCommandState.NEW_COMMAND
val register = cmd.register
if (register != null) {
injector.registerGroup.selectRegister(register)
}
injector.actionExecutor.executeVimAction(editor, cmd.action, context, operatorArguments)
if (editorState.mode === VimStateMachine.Mode.INSERT || editorState.mode === VimStateMachine.Mode.REPLACE) {
injector.changeGroup.processCommand(editor, cmd)
}
// Now the command has been executed let's clean up a few things.
// By default, the "empty" register is used by all commands, so we want to reset whatever the last register
// selected by the user was to the empty register
injector.registerGroup.resetRegister()
// If, at this point, we are not in insert, replace, or visual modes, we need to restore the previous
// mode we were in. This handles commands in those modes that temporarily allow us to execute normal
// mode commands. An exception is if this command should leave us in the temporary mode such as
// "select register"
if (editorState.mode.inSingleNormalMode &&
!cmd.flags.contains(CommandFlags.FLAG_EXPECT_MORE)
) {
editorState.popModes()
}
if (editorState.commandBuilder.isDone()) {
getInstance().reset(editor)
}
}
}
companion object {
private val LOG: VimLogger = vimLogger<KeyHandler>()
fun <T> isPrefix(list1: List<T>, list2: List<T>): Boolean {
if (list1.size > list2.size) {
return false
}
for (i in list1.indices) {
if (list1[i] != list2[i]) {
return false
}
}
return true
}
private val instance = KeyHandler()
@JvmStatic
fun getInstance() = instance
}
}
| mit | 65e4ed64ae1fd7aef93d6e53bd79fe39 | 41.847085 | 168 | 0.698752 | 4.522002 | false | false | false | false |
ingokegel/intellij-community | platform/platform-tests/testSrc/com/intellij/ui/jcef/JBCefBrowserJsCallTest.kt | 5 | 4433 | // 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.ui.jcef
import com.intellij.testFramework.ApplicationRule
import com.intellij.ui.scale.TestScaleHelper
import org.intellij.lang.annotations.Language
import org.junit.After
import org.junit.Assert.*
import org.junit.Before
import org.junit.ClassRule
import org.junit.Test
import java.util.concurrent.CountDownLatch
/**
* Tests the [JBCefBrowserJsCall] class and [executeJavaScriptAsync] method.
*/
class JBCefBrowserJsCallTest {
companion object {
@ClassRule @JvmStatic fun getAppRule() = ApplicationRule()
}
@Before
fun before() {
TestScaleHelper.assumeStandalone()
TestScaleHelper.setSystemProperty("java.awt.headless", "false")
}
@After
fun after() {
TestScaleHelper.restoreProperties()
}
@Test
fun `execute unresolved expression`() {
doTest("""foo.bar""")
}
@Test
fun `execute throw expression`() {
doTest("""
let r = 2 + 2
throw 'error'
return r
""".trimIndent()
)
}
@Test
fun `execute math operation`() {
doTest("""2+2""", "4")
}
// IDEA-290310, IDEA-292709
@Test
fun `obtain a stringified JSON with emoji`() {
doTest(javaScript = """
let json = JSON.stringify({ "a": "foo", "cookie": "🍪"})
return json;
""".trimIndent(), expectedResult = """{"a":"foo","cookie":"🍪"}""")
}
// IDEA-290310, IDEA-292709
@Test
fun `obtain a string with emoji`() {
doTest(javaScript = """
let emoji = `🍪`
return emoji;
""".trimIndent(), expectedResult = """🍪""")
}
// IDEA-288813
@Test
fun `obtain a string decoded from base64`() {
// NOTE: non-latin symbols in JS.atob should be handled in special way, see:
// https://stackoverflow.com/questions/3626183/javascript-base64-encoding-utf8-string-fails-in-webkit-safari
// https://stackoverflow.com/questions/30106476/using-javascripts-atob-to-decode-base64-doesnt-properly-decode-utf-8-strings
doTest(javaScript = """
let decoded_string = atob("U29tZSB0ZXh0INC4INC60LDQutC+0Lkt0YLQviDRgtC10LrRgdGC");
return decodeURIComponent(escape(decoded_string))
""".trimIndent(), expectedResult = """Some text и какой-то текст""")
}
@Test
fun `execute multiline expression`() {
val js = """
function myFunction(p1, p2) {
return p1 * p2; // The function returns the product of p1 and p2
};
return myFunction(2,2)
""".trimIndent()
doTest(js, "4")
}
@Test
fun `execute the same call twice and simultaneously`() {
val browser = prepareBrowser()
val jsCall = JBCefBrowserJsCall("""2+2""", browser)
val latch = CountDownLatch(2)
var r1: String? = null
var r2: String? = null
JBCefTestHelper.invokeAndWaitForLatch(latch) {
jsCall().onProcessed { latch.countDown() }.onSuccess { r1 = it }
jsCall().onProcessed { latch.countDown() }.onSuccess { r2 = it }
}
assertEquals("4", r1)
assertEquals("4", r2)
}
private fun doTest(@Language("JavaScript") javaScript: String,
expectedResult: String? = null,
isExpectedToSucceed: Boolean = expectedResult != null) {
val latch = CountDownLatch(1)
val browser = prepareBrowser()
var isSucceeded: Boolean? = null
var actualResult: String? = null
JBCefTestHelper.invokeAndWaitForLatch(latch) {
browser.executeJavaScriptAsync(javaScript)
.onError {
println(it.message)
isSucceeded = false
}.onSuccess {
isSucceeded = true
actualResult = it
}.onProcessed {
latch.countDown()
}
}
assertEquals(isExpectedToSucceed, isSucceeded)
if (isExpectedToSucceed) {
assertEquals(expectedResult, actualResult)
}
}
private fun prepareBrowser(): JBCefBrowser {
val browser = JBCefApp.getInstance().createClient().also {
it.setProperty(JBCefClient.Properties.JS_QUERY_POOL_SIZE, 24)
}.let { jbCefClient ->
JBCefBrowser.createBuilder()
.setClient(jbCefClient)
.setUrl("about:blank")
.build()
}
JBCefTestHelper.showAndWaitForLoad(browser, "DISPATCH")
assertNotNull(browser.component)
assertTrue(browser.isCefBrowserCreated)
return browser
}
}
| apache-2.0 | 064ed62c2dcdc1d40bdf63255e2b47e1 | 26.378882 | 128 | 0.646325 | 3.939231 | false | true | false | false |
mdaniel/intellij-community | platform/vcs-impl/src/com/intellij/vcs/commit/SingleChangeListCommitWorkflow.kt | 2 | 5308 | // 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.vcs.commit
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vcs.AbstractVcs
import com.intellij.openapi.vcs.VcsBundle.message
import com.intellij.openapi.vcs.changes.*
import com.intellij.openapi.vcs.changes.ui.CommitChangeListDialog.DIALOG_TITLE
import com.intellij.openapi.vcs.checkin.CheckinChangeListSpecificComponent
import com.intellij.openapi.vcs.impl.PartialChangesUtil
import com.intellij.util.ui.UIUtil.removeMnemonic
import com.intellij.vcs.commit.SingleChangeListCommitter.Companion.moveToFailedList
import org.jetbrains.annotations.Nls
private val LOG = logger<SingleChangeListCommitWorkflow>()
private val CommitOptions.changeListSpecificOptions: Sequence<CheckinChangeListSpecificComponent>
get() = allOptions.filterIsInstance<CheckinChangeListSpecificComponent>()
internal fun CommitOptions.changeListChanged(changeList: LocalChangeList) = changeListSpecificOptions.forEach {
it.onChangeListSelected(changeList)
}
internal fun CommitOptions.saveChangeListSpecificOptions() = changeListSpecificOptions.forEach { it.saveState() }
@Nls
internal fun String.removeEllipsisSuffix() = StringUtil.removeEllipsisSuffix(this)
@Nls
internal fun CommitExecutor.getPresentableText() = removeMnemonic(actionText).removeEllipsisSuffix()
open class SingleChangeListCommitWorkflow(
project: Project,
affectedVcses: Set<AbstractVcs>,
val initiallyIncluded: Collection<*>,
val initialChangeList: LocalChangeList? = null,
executors: List<CommitExecutor> = emptyList(),
final override val isDefaultCommitEnabled: Boolean = executors.isEmpty(),
private val isDefaultChangeListFullyIncluded: Boolean = true,
val initialCommitMessage: String? = null,
private val resultHandler: CommitResultHandler? = null
) : AbstractCommitWorkflow(project) {
init {
updateVcses(affectedVcses)
initCommitExecutors(executors)
}
val isPartialCommitEnabled: Boolean =
vcses.any { it.arePartialChangelistsSupported() } && (isDefaultCommitEnabled || commitExecutors.any { it.supportsPartialCommit() })
internal val commitMessagePolicy: SingleChangeListCommitMessagePolicy = SingleChangeListCommitMessagePolicy(project, initialCommitMessage)
internal lateinit var commitState: ChangeListCommitState
override fun processExecuteDefaultChecksResult(result: CommitChecksResult) = when {
result.shouldCommit -> DefaultNameChangeListCleaner(project, commitState).use { doCommit(commitState) }
result.shouldCloseWindow ->
moveToFailedList(project, commitState, message("commit.dialog.rejected.commit.template", commitState.changeList.name))
else -> Unit
}
override fun executeCustom(executor: CommitExecutor, session: CommitSession): Boolean =
executeCustom(executor, session, commitState.changes, commitState.commitMessage)
override fun processExecuteCustomChecksResult(executor: CommitExecutor, session: CommitSession, result: CommitChecksResult) =
when {
result.shouldCommit -> doCommitCustom(executor, session)
result.shouldCloseWindow ->
moveToFailedList(project, commitState, message("commit.dialog.rejected.commit.template", commitState.changeList.name))
else -> Unit
}
override fun doRunBeforeCommitChecks(checks: Runnable) =
PartialChangesUtil.runUnderChangeList(project, commitState.changeList, checks)
protected open fun doCommit(commitState: ChangeListCommitState) {
LOG.debug("Do actual commit")
with(object : SingleChangeListCommitter(project, commitState, commitContext, DIALOG_TITLE, isDefaultChangeListFullyIncluded) {
override fun afterRefreshChanges() = endExecution { super.afterRefreshChanges() }
}) {
addResultHandler(CommitHandlersNotifier(commitHandlers))
addResultHandler(getCommitEventDispatcher())
addResultHandler(resultHandler ?: ShowNotificationCommitResultHandler(this))
runCommit(DIALOG_TITLE, false)
}
}
private fun doCommitCustom(executor: CommitExecutor, session: CommitSession) {
val cleaner = DefaultNameChangeListCleaner(project, commitState)
with(CustomCommitter(project, session, commitState.changes, commitState.commitMessage)) {
addResultHandler(CommitHandlersNotifier(commitHandlers))
addResultHandler(CommitResultHandler { cleaner.clean() })
addResultHandler(getCommitCustomEventDispatcher())
resultHandler?.let { addResultHandler(it) }
addResultHandler(getEndExecutionHandler())
runCommit(executor.actionText)
}
}
}
private class DefaultNameChangeListCleaner(val project: Project, commitState: ChangeListCommitState) {
private val isChangeListFullyIncluded = commitState.changeList.changes.size == commitState.changes.size
private val isDefaultNameChangeList = commitState.changeList.hasDefaultName()
private val listName = commitState.changeList.name
fun use(block: () -> Unit) {
block()
clean()
}
fun clean() {
if (isDefaultNameChangeList && isChangeListFullyIncluded) {
ChangeListManager.getInstance(project).editComment(listName, "")
}
}
} | apache-2.0 | 5f4831aeaa0553fdb6cee560f2f7f5c2 | 42.162602 | 140 | 0.795215 | 5.198825 | false | false | false | false |
VTUZ-12IE1bzud/TruckMonitor-Android | app/src/androidTest/kotlin/ru/annin/truckmonitor/network/RestApiRepositoryTest.kt | 1 | 1481 | package ru.annin.truckmonitor.network
import android.support.test.runner.AndroidJUnit4
import junit.framework.TestCase
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.notNullValue
import org.junit.After
import org.junit.Before
import org.junit.BeforeClass
import org.junit.Test
import org.junit.runner.RunWith
import ru.annin.truckmonitor.data.repository.RestApiRepository
import ru.annin.truckmonitor.domain.model.LoginResponse
import rx.observers.TestSubscriber
/**
* Тест REST API.
*
* @author Pavel Annin.
*/
@RunWith(AndroidJUnit4::class)
class RestApiRepositoryTest : TestCase() {
companion object {
lateinit var repository: RestApiRepository
@JvmStatic
@BeforeClass
fun setUpClass() {
repository = RestApiRepository
}
}
@Before
public override fun setUp() {
super.setUp()
}
@After
public override fun tearDown() {
super.tearDown()
}
@Test
fun testLogin() {
val subscriber: TestSubscriber<LoginResponse> = TestSubscriber()
val email = "[email protected]"
val password = "annin"
repository.login(email, password).subscribe(subscriber)
// Request
subscriber.assertNoErrors()
subscriber.assertCompleted()
assertTrue(subscriber.onNextEvents.isNotEmpty())
// Data
val data = subscriber.onNextEvents[0]
assertThat(data, notNullValue())
}
} | apache-2.0 | 941d86d642dba991544f860fddc8e384 | 22.83871 | 72 | 0.688558 | 4.630094 | false | true | false | false |
byu-oit/android-byu-suite-v2 | support/src/main/java/edu/byu/support/ByuSwipeOnlyCallback.kt | 1 | 4596 | package edu.byu.support
import android.content.Context
import android.graphics.Canvas
import android.graphics.drawable.ColorDrawable
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.helper.ItemTouchHelper
import edu.byu.support.adapter.ByuRecyclerAdapter
import edu.byu.support.utils.getColorFromRes
import edu.byu.support.utils.getDrawableFromRes
/**
* Created by geogor37 on 5/29/18
*/
// We pass in 0 for the first argument of the parent constructor so that the viewHolders will not be draggable
abstract class ByuSwipeOnlyCallback<T>(protected val adapter: ByuRecyclerAdapter<*>, val context: Context, swipeDirs: Int): ItemTouchHelper.SimpleCallback(0, swipeDirs) {
companion object {
const val LEFT = ItemTouchHelper.LEFT
const val RIGHT = ItemTouchHelper.RIGHT
const val LEFT_AND_RIGHT = ItemTouchHelper.LEFT.or(ItemTouchHelper.RIGHT)
const val NEITHER_DIRECTION = 0
}
@Suppress("UNCHECKED_CAST")
// When deleting the swiped item, it's possible for onChildDraw to be called after the item is already deleted, which causes the below line of code to
// throw an ArrayIndexOutOfBoundsException. When this happens we return null to stop drawing the background since the item is being deleted anyway.
private fun getSwipedItem(viewHolder: RecyclerView.ViewHolder) = try {
adapter.list[viewHolder.adapterPosition] as? T
} catch (e: ArrayIndexOutOfBoundsException) {
null
}
// This function should return either LEFT, RIGHT, LEFT_AND_RIGHT, or NEITHER_DIRECTION depending on whether viewHolder should be swipeable or not
abstract fun getSwipeFlags(viewHolder: RecyclerView.ViewHolder): Int
override fun getMovementFlags(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) = makeMovementFlags(0, getSwipeFlags(viewHolder))
override fun onMove(recyclerView: RecyclerView?, viewHolder: RecyclerView.ViewHolder?, target: RecyclerView.ViewHolder?) = false
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
getSwipedItem(viewHolder)?.let { onSwiped(it, direction) }
}
// This function executes whatever action is supposed to occur when the user swipes viewHolder
abstract fun onSwiped(swipedItem: T, direction: Int)
// If the values returned from these first two functions are non-null then we will use them even if the other functions return something else, so make sure these return null
// if you want to display different background colors or icons depending on the swipe direction.
open fun getColorForBothDirections(swipedItem: T): Int? = null
open fun getIconResForBothDirections(swipedItem: T): Int? = null
open fun getColorForSwipeLeft(swipedItem: T): Int? = getColorForBothDirections(swipedItem)
open fun getIconResForSwipeLeft(swipedItem: T): Int? = getIconResForBothDirections(swipedItem)
open fun getColorForSwipeRight(swipedItem: T): Int? = getColorForBothDirections(swipedItem)
open fun getIconResForSwipeRight(swipedItem: T): Int? = getIconResForBothDirections(swipedItem)
override fun onChildDraw(c: Canvas?, recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, dX: Float, dY: Float, actionState: Int, isCurrentlyActive: Boolean) {
val swipeLeft = dX < 0
val swipedItem = getSwipedItem(viewHolder)
val backgroundColor = swipedItem?.let { if (swipeLeft) getColorForSwipeLeft(it) else getColorForSwipeRight(it) }
val iconResource = swipedItem?.let { if (swipeLeft) getIconResForSwipeLeft(it) else getIconResForSwipeRight(it) }
val cell = viewHolder.itemView
if (backgroundColor != null) {
val background = ColorDrawable()
background.color = context.getColorFromRes(backgroundColor)
background.setBounds(cell.left, cell.top, cell.right, cell.bottom)
background.draw(c)
}
if (iconResource != null) {
val cellHeight = cell.height
context.getDrawableFromRes(iconResource)?.let { icon ->
// Center the icon vertically in the cell and set the margin equal to the space left between the top of the cell and the top of the icon.
val margin = (cellHeight - icon.intrinsicHeight) / 2
val top = cell.top + margin
val bottom = top + icon.intrinsicHeight
// Place the icon on either the left or the right, depending on which way the user is swiping.
val left = if (swipeLeft) cell.right - margin - icon.intrinsicWidth else cell.left + margin
val right = if (swipeLeft) cell.right - margin else cell.left + margin + icon.intrinsicWidth
icon.setBounds(left, top, right, bottom)
icon.draw(c)
}
}
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
}
} | apache-2.0 | 2254ecdd070b418cc7a7213c99dc2815 | 49.516484 | 174 | 0.778721 | 4.110912 | false | false | false | false |
GunoH/intellij-community | notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/r/inlays/InlayEditorManager.kt | 8 | 16199 | /*
* 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.notebooks.visualization.r.inlays
import com.intellij.ide.ui.UISettings
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.FoldRegion
import com.intellij.openapi.editor.Inlay
import com.intellij.openapi.editor.event.CaretEvent
import com.intellij.openapi.editor.event.CaretListener
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.editor.ex.EditorGutterComponentEx
import com.intellij.openapi.editor.ex.FoldingListener
import com.intellij.openapi.editor.ex.util.EditorScrollingPositionKeeper
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.util.concurrency.FutureResult
import com.intellij.util.concurrency.NonUrgentExecutor
import com.intellij.util.ui.update.MergingUpdateQueue
import com.intellij.util.ui.update.Update
import org.jetbrains.annotations.TestOnly
import org.jetbrains.concurrency.CancellablePromise
import org.jetbrains.plugins.notebooks.visualization.r.inlays.components.InlayProgressStatus
import java.awt.Point
import java.awt.event.ComponentAdapter
import java.awt.event.ComponentEvent
import java.util.concurrent.Future
import kotlin.math.max
import kotlin.math.min
/**
* Manages inlays.
*
* On project load subscribes
* on editor opening/closing.
* on adding/removing notebook cells
* on any document changes
* on folding actions
*
* On editor open checks the PSI structure and restores saved inlays.
*
* ToDo should be split into InlaysManager with all basics and NotebookInlaysManager with all specific.
*/
class EditorInlaysManager(val project: Project, private val editor: EditorImpl, val descriptor: InlayElementDescriptor) {
private val inlays: MutableMap<PsiElement, NotebookInlayComponentPsi> = LinkedHashMap()
private val inlayElements = LinkedHashSet<PsiElement>()
private val scrollKeeper: EditorScrollingPositionKeeper = EditorScrollingPositionKeeper(editor)
private val viewportQueue = MergingUpdateQueue(VIEWPORT_TASK_NAME, VIEWPORT_TIME_SPAN, true, null, project)
@Volatile private var toolbarUpdateScheduled: Boolean = false
init {
addResizeListener()
addCaretListener()
addFoldingListener()
addDocumentListener()
addViewportListener()
editor.settings.isRightMarginShown = false
UISettings.getInstance().showEditorToolTip = false
MouseWheelUtils.wrapEditorMouseWheelListeners(editor)
restoreToolbars().onSuccess { restoreOutputs() }
onCaretPositionChanged()
ApplicationManager.getApplication().invokeLater {
if (editor.isDisposed) return@invokeLater
updateInlayComponentsWidth()
}
}
fun dispose() {
inlays.values.forEach {
it.disposeInlay()
it.dispose()
}
inlays.clear()
inlayElements.clear()
}
fun updateCell(psi: PsiElement, inlayOutputs: List<InlayOutput>? = null, createTextOutput: Boolean = false): Future<Unit> {
val result = FutureResult<Unit>()
if (ApplicationManager.getApplication().isUnitTestMode && !isEnabledInTests) return result.apply { set(Unit) }
ApplicationManager.getApplication().invokeLater {
try {
if (editor.isDisposed) {
result.set(Unit)
return@invokeLater
}
if (!psi.isValid) {
getInlayComponent(psi)?.let { oldInlay -> removeInlay(oldInlay, cleanup = false) }
result.set(Unit)
return@invokeLater
}
if (isOutputPositionCollapsed(psi)) {
result.set(Unit)
return@invokeLater
}
val outputs = inlayOutputs ?: descriptor.getInlayOutputs(psi)
if (outputs == null) {
result.set(Unit)
return@invokeLater
}
scrollKeeper.savePosition()
getInlayComponent(psi)?.let { oldInlay -> removeInlay(oldInlay, cleanup = false) }
if (outputs.isEmpty() && !createTextOutput) {
result.set(Unit)
return@invokeLater
}
val component = addInlayComponent(psi)
if (outputs.isNotEmpty()) addInlayOutputs(component, outputs)
if (createTextOutput) component.createOutputComponent()
scrollKeeper.restorePosition(true)
} catch (e: Throwable) {
result.set(Unit)
throw e
}
ApplicationManager.getApplication().invokeLater {
try {
scrollKeeper.savePosition()
updateInlays()
scrollKeeper.restorePosition(true)
}
finally {
result.set(Unit)
}
}
}
return result
}
private fun isOutputPositionCollapsed(psiCell: PsiElement): Boolean =
editor.foldingModel.isOffsetCollapsed(descriptor.getInlayOffset(psiCell))
fun addTextToInlay(psi: PsiElement, message: String, outputType: Key<*>) {
invokeLater {
scrollKeeper.savePosition()
getInlayComponent(psi)?.addText(message, outputType)
scrollKeeper.restorePosition(true)
}
}
fun updateInlayProgressStatus(psi: PsiElement, progressStatus: InlayProgressStatus): Future<Unit> {
val result = FutureResult<Unit>()
ApplicationManager.getApplication().invokeLater {
getInlayComponent(psi)?.updateProgressStatus(progressStatus)
result.set(Unit)
}
return result
}
private fun updateInlaysForViewport() {
invokeLater {
if (editor.isDisposed) return@invokeLater
val viewportRange = calculateViewportRange(editor)
val expansionRange = calculateInlayExpansionRange(editor, viewportRange)
for (element in inlayElements) {
updateInlayForViewport(element, viewportRange, expansionRange)
}
}
}
private fun updateInlayForViewport(element: PsiElement, viewportRange: IntRange, expansionRange: IntRange) {
val inlay = inlays[element]
if (inlay != null) {
val bounds = inlay.bounds
val isInViewport = bounds.y <= viewportRange.last && bounds.y + bounds.height >= viewportRange.first
inlay.onViewportChange(isInViewport)
} else {
if (element.textRange.startOffset in expansionRange) {
updateCell(element)
}
}
}
private fun addInlayOutputs(inlayComponent: NotebookInlayComponentPsi,
inlayOutputs: List<InlayOutput>) {
inlayComponent.addInlayOutputs(inlayOutputs) { removeInlay(inlayComponent) }
}
private fun removeInlay(inlayComponent: NotebookInlayComponentPsi, cleanup: Boolean = true) {
val cell = inlayComponent.cell
if (cleanup && cell.isValid) descriptor.cleanup(cell)
inlayComponent.parent?.remove(inlayComponent)
inlayComponent.disposeInlay()
inlayComponent.dispose()
inlays.remove(cell)
}
private fun addFoldingListener() {
data class Region(val textRange: TextRange, val isExpanded: Boolean)
val listener = object : FoldingListener {
private val regions = ArrayList<Region>()
override fun onFoldRegionStateChange(region: FoldRegion) {
if(region.isValid) {
regions.add(Region(TextRange.create(region.startOffset, region.endOffset), region.isExpanded))
}
}
override fun onFoldProcessingEnd() {
inlays.filter { pair -> isOutputPositionCollapsed(pair.key) }.forEach {
removeInlay(it.value, cleanup = false)
}
inlayElements.filter { key -> regions.filter { it.isExpanded }.any { key.textRange.intersects(it.textRange) } }.forEach {
updateCell(it)
}
regions.clear()
updateInlays()
}
}
editor.foldingModel.addListener(listener, editor.disposable)
}
private fun addDocumentListener() {
editor.document.addDocumentListener(object : DocumentListener {
override fun documentChanged(event: DocumentEvent) {
if (project.isDisposed()) return
if (!toolbarUpdateScheduled) {
toolbarUpdateScheduled = true
PsiDocumentManager.getInstance(project).performForCommittedDocument(editor.document) {
try {
scheduleIntervalUpdate(event.offset, event.newFragment.length)
} finally {
toolbarUpdateScheduled = false
}
}
}
if (!descriptor.shouldUpdateInlays(event)) return
PsiDocumentManager.getInstance(project).performForCommittedDocument(editor.document) {
updateInlays()
}
}
}, editor.disposable)
}
private fun scheduleIntervalUpdate(offset: Int, length: Int) {
val psiFile = descriptor.psiFile
var node = psiFile.node.findLeafElementAt(offset)?.psi
while (node != null && node.parent != psiFile) {
node = node.parent
}
inlayElements.filter { !it.isValid }.forEach { getInlayComponent(it)?.let { inlay -> removeInlay(inlay) } }
inlayElements.removeIf { !it.isValid }
while (node != null && node.textRange.startOffset < offset + length) {
PsiTreeUtil.collectElements(node) { psi -> descriptor.isInlayElement(psi) }.forEach { psi ->
inlayElements.add(psi)
}
node = node.nextSibling
}
}
/** On editor resize all inlays got width of editor. */
private fun addResizeListener() {
editor.component.addComponentListener(object : ComponentAdapter() {
override fun componentResized(e: ComponentEvent) {
updateInlayComponentsWidth()
}
})
}
private fun addViewportListener() {
editor.scrollPane.viewport.addChangeListener {
viewportQueue.queue(object : Update(VIEWPORT_TASK_IDENTITY) {
override fun run() {
updateInlaysForViewport()
}
})
}
}
private fun restoreOutputs() {
updateInlaysForViewport()
}
private fun restoreToolbars(): CancellablePromise<*> {
val inlaysPsiElements = ArrayList<PsiElement>()
return ReadAction.nonBlocking {
PsiTreeUtil.processElements(descriptor.psiFile) { element ->
if (descriptor.isInlayElement(element)) inlaysPsiElements.add(element)
true
}
}.finishOnUiThread(ModalityState.NON_MODAL) {
inlayElements.clear()
inlayElements.addAll(inlaysPsiElements)
}.inSmartMode(project).submit(NonUrgentExecutor.getInstance())
}
private fun getInlayComponentByOffset(offset: Int): NotebookInlayComponentPsi? {
return if (offset == editor.document.textLength)
inlays.entries.firstOrNull { it.key.textRange.containsOffset(offset) }?.value
else
inlays.entries.firstOrNull { it.key.textRange.contains(offset) }?.value
}
/** Add caret listener for editor to draw highlighted background for psiCell under caret. */
private fun addCaretListener() {
editor.caretModel.addCaretListener(object : CaretListener {
override fun caretPositionChanged(e: CaretEvent) {
if (editor.caretModel.primaryCaret != e.caret) return
onCaretPositionChanged()
}
}, editor.disposable)
}
private fun onCaretPositionChanged() {
if (editor.isDisposed) {
return
}
val cellUnderCaret = getInlayComponentByOffset(editor.logicalPositionToOffset(editor.caretModel.logicalPosition))
if (cellUnderCaret == null) {
inlays.values.forEach { it.selected = false }
}
else {
if (!cellUnderCaret.selected) {
inlays.values.forEach { it.selected = false }
cellUnderCaret.selected = true
}
}
}
/** When we are adding or removing paragraphs, old cells can change their text ranges*/
private fun updateInlays() {
inlays.values.forEach { updateInlayPosition(it) }
}
private fun setupInlayComponent(inlayComponent: NotebookInlayComponentPsi) {
fun updateInlaysInEditor(editor: Editor) {
val end = editor.xyToLogicalPosition(Point(0, Int.MAX_VALUE))
val offsetEnd = editor.logicalPositionToOffset(end)
val inlays = editor.inlayModel.getBlockElementsInRange(0, offsetEnd)
inlays.forEach { inlay ->
if (inlay.renderer is InlayComponent) {
(inlay.renderer as InlayComponent).updateComponentBounds(inlay)
}
}
}
inlayComponent.beforeHeightChanged = {
scrollKeeper.savePosition()
}
inlayComponent.afterHeightChanged = {
updateInlaysInEditor(editor)
scrollKeeper.restorePosition(true)
}
}
/** Aligns all editor inlays to fill full width of editor. */
private fun updateInlayComponentsWidth() {
val inlayWidth = InlayDimensions.calculateInlayWidth(editor)
if (inlayWidth > 0) {
inlays.values.forEach {
it.setSize(inlayWidth, it.height)
it.inlay?.updateSize()
}
}
}
/** It could be that user started to type below inlay. In this case we will detect new position and perform inlay repositioning. */
private fun updateInlayPosition(inlayComponent: NotebookInlayComponentPsi) {
// editedCell here contains old text. This event will be processed by PSI later.
val offset = descriptor.getInlayOffset(inlayComponent.cell)
if (inlayComponent.inlay!!.offset != offset) {
inlayComponent.disposeInlay()
val inlay = addBlockElement(offset, inlayComponent)
inlayComponent.assignInlay(inlay)
}
inlayComponent.updateComponentBounds(inlayComponent.inlay!!)
}
private fun addBlockElement(offset: Int, inlayComponent: NotebookInlayComponentPsi): Inlay<NotebookInlayComponentPsi> {
return editor.inlayModel.addBlockElement(offset, true, false, INLAY_PRIORITY, inlayComponent)
}
private fun addInlayComponent(cell: PsiElement): NotebookInlayComponentPsi {
val existingInlay = inlays[cell]
if (existingInlay != null) {
throw Exception("Cell already added.")
}
InlayDimensions.init(editor)
val offset = descriptor.getInlayOffset(cell)
val inlayComponent = NotebookInlayComponentPsi(cell, editor)
// On editor creation it has 0 width
val gutterWidth = (editor.gutter as EditorGutterComponentEx).width
var editorWideWidth = editor.component.width - inlayComponent.width - gutterWidth - InlayDimensions.rightBorder
if (editorWideWidth <= 0) {
editorWideWidth = InlayDimensions.width
}
inlayComponent.setBounds(0, editor.offsetToXY(offset).y + editor.lineHeight, editorWideWidth, InlayDimensions.smallHeight)
editor.contentComponent.add(inlayComponent)
val inlay = addBlockElement(offset, inlayComponent)
inlayComponent.assignInlay(inlay)
inlays[cell] = inlayComponent
setupInlayComponent(inlayComponent)
return inlayComponent
}
private fun getInlayComponent(cell: PsiElement): NotebookInlayComponentPsi? {
return inlays[cell]
}
companion object {
private const val VIEWPORT_TASK_NAME = "On viewport change"
private const val VIEWPORT_TASK_IDENTITY = "On viewport change task"
private const val VIEWPORT_TIME_SPAN = 50
const val INLAY_PRIORITY = 0
@TestOnly
var isEnabledInTests: Boolean = false
}
}
const val VIEWPORT_INLAY_RANGE = 20
fun calculateViewportRange(editor: EditorImpl): IntRange {
val viewport = editor.scrollPane.viewport
val yMin = viewport.viewPosition.y
val yMax = yMin + viewport.height
return yMin until yMax
}
fun calculateInlayExpansionRange(editor: EditorImpl, viewportRange: IntRange): IntRange {
val startLine = editor.xyToLogicalPosition(Point(0, viewportRange.first)).line
val endLine = editor.xyToLogicalPosition(Point(0, viewportRange.last + 1)).line
val startOffset = editor.document.getLineStartOffset(max(startLine - VIEWPORT_INLAY_RANGE, 0))
val endOffset = editor.document.getLineStartOffset(max(min(endLine + VIEWPORT_INLAY_RANGE, editor.document.lineCount - 1), 0))
return startOffset..endOffset
} | apache-2.0 | b3f9b0fcab95a6780f9e848e06cfa93b | 34.840708 | 140 | 0.715785 | 4.75044 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/jvm-debugger/test/test/org/jetbrains/kotlin/idea/debugger/test/KotlinDfaAssistTest.kt | 2 | 6876 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.debugger.test
import com.intellij.debugger.engine.dfaassist.DfaAssistTest
import com.intellij.debugger.mockJDI.MockLocalVariable
import com.intellij.debugger.mockJDI.MockStackFrame
import com.intellij.debugger.mockJDI.MockVirtualMachine
import com.intellij.debugger.mockJDI.values.MockBooleanValue
import com.intellij.debugger.mockJDI.values.MockIntegerValue
import com.intellij.debugger.mockJDI.values.MockObjectReference
import com.intellij.debugger.mockJDI.values.MockValue
import com.intellij.testFramework.LightProjectDescriptor
import org.jetbrains.kotlin.idea.test.ProjectDescriptorWithStdlibSources
import java.lang.annotation.ElementType
import java.util.function.BiConsumer
class KotlinDfaAssistTest : DfaAssistTest() {
override fun getProjectDescriptor(): LightProjectDescriptor = ProjectDescriptorWithStdlibSources.getInstanceWithStdlibSources()
fun testSimple() {
doTest("""fun test(x: Int) {
<caret>if (x > 0/*TRUE*/) {
}
if (x in 1..6/*TRUE*/) {
}
if (1 in x..10/*FALSE*/) {
}
}
fun main() {
test(5)
}""") { vm, frame -> frame.addVariable("x", MockIntegerValue(vm, 5)) }
}
fun testSuppression() {
doTest("""fun test(x: Boolean, y: Boolean) {
<caret>if(!x/*FALSE*/) {}
if (x/*TRUE*/ || y) {}
if (y || x/*TRUE*/) {}
var z: Boolean
z = x/*TRUE*/
var b = true
}""") { vm, frame -> frame.addVariable("x", MockBooleanValue(vm, true)) }
}
fun testWhen() {
doTest("""fun obj(x: Any) {
<caret>when(x) {
is String/*FALSE*/ -> {}
is Int/*TRUE*/ -> {}
}
}
fun main() {
obj(5)
}""") { vm, frame -> frame.addVariable("x", MockValue.createValue(1, Integer::class.java, vm)) }
}
fun testWrapped() {
doTest("""fun test(x: Int) {
var y = x
val fn = { y++ }
fn()
<caret>if (y > 0/*TRUE*/) {
}
if (y == 0/*FALSE*/) {}
if (y < 0/*FALSE*/) {}
}
fun main() {
test(5)
}""") { vm, frame ->
val cls = Class.forName("kotlin.jvm.internal.Ref\$IntRef")
val box = cls.getConstructor().newInstance()
cls.getDeclaredField("element").set(box, 6)
frame.addVariable("y", MockValue.createValue(box, cls, vm))
}
}
class Nested(@Suppress("unused") val x:Int)
fun testThis() {
doTest("""package org.jetbrains.kotlin.idea.debugger.test
class KotlinDfaAssistTest {
class Nested(val x:Int) {
fun test() {
<caret>if (x == 5/*TRUE*/) {}
}
}
}
""") { vm, frame ->
frame.setThisValue(MockObjectReference.createObjectReference(Nested(5), Nested::class.java, vm))
}
}
fun testQualified() {
doTest("""package org.jetbrains.kotlin.idea.debugger.test
class KotlinDfaAssistTest {
class Nested(val x:Int)
}
fun use(n : KotlinDfaAssistTest.Nested) {
<caret>if (n.x > 5/*TRUE*/) {}
}
""") { vm, frame ->
frame.addVariable("n", MockValue.createValue(Nested(6), Nested::class.java, vm))
}
}
fun testExtensionMethod() {
doTest("""fun String.isLong(): Boolean {
<caret>return this.length > 5/*FALSE*/
}
fun main() {
"xyz".isLong()
}""") { vm, frame ->
frame.addVariable("\$this\$isLong", MockValue.createValue("xyz", String::class.java, vm))
}
}
fun testDeconstruction() {
doTest("""fun test(x: Pair<Int, Int>) {
val (a, b) = x
<caret>if (a > b/*FALSE*/) {}
}
fun main() {
test(3 to 5)
}""") { vm, frame ->
frame.addVariable("a", MockIntegerValue(vm, 3))
frame.addVariable("b", MockIntegerValue(vm, 5))
}
}
fun testNPE() {
doTest("""
fun test(x: String?) {
<caret>println(x/*NPE*/!!)
}
""".trimIndent()) { vm, frame ->
frame.addVariable(MockLocalVariable(vm, "x", vm.createReferenceType(String::class.java), null))
}
}
fun testAsNull() {
doTest("""
fun test(x: Any?) {
<caret>println(x as String?)
println(x as/*NPE*/ String)
}
""".trimIndent()) { vm, frame ->
frame.addVariable(MockLocalVariable(vm, "x", vm.createReferenceType(String::class.java), null))
}
}
fun testAs() {
doTest("""
fun test(x: Any?) {
<caret>println(x as/*CCE*/ Int)
}
""".trimIndent()) { vm, frame ->
frame.addVariable("x", MockValue.createValue("", vm))
}
}
fun testNull() {
doTest("""
fun main() {
test("hello", null)
}
fun test(x: Any, y: String?) {
<caret>println(x as? Int/*NULL*/)
println(y/*NULL*/ ?: "oops")
}
""".trimIndent()) { vm, frame ->
frame.addVariable("x", MockValue.createValue("xyz", vm))
frame.addVariable(MockLocalVariable(vm, "y", vm.createReferenceType(String::class.java), null))
}
}
fun testEnum() {
val text = """import java.lang.annotation.ElementType
class Test {
fun test(t : ElementType) {
<caret>if (t == ElementType.PARAMETER/*FALSE*/) {}
if (t == ElementType.METHOD/*TRUE*/) {}
}
}"""
doTest(text) { vm, frame ->
frame.addVariable("t", MockValue.createValue(ElementType.METHOD, ElementType::class.java, vm))
}
}
private fun doTest(text: String, mockValues: BiConsumer<MockVirtualMachine, MockStackFrame>) {
doTest(text, mockValues, "Test.kt")
}
} | apache-2.0 | a062e1ed1b652aaa28782fb4c9aff58a | 32.710784 | 131 | 0.477749 | 4.53562 | false | true | false | false |
shogo4405/HaishinKit.java | haishinkit/src/main/java/com/haishinkit/media/MediaLink.kt | 1 | 8828 | package com.haishinkit.media
import android.media.AudioTrack
import android.os.Handler
import android.os.HandlerThread
import android.os.SystemClock
import android.util.Log
import android.view.Choreographer
import com.haishinkit.BuildConfig
import com.haishinkit.codec.AudioCodec
import com.haishinkit.codec.MediaCodec
import com.haishinkit.codec.VideoCodec
import com.haishinkit.lang.Running
import com.haishinkit.metric.FrameTracker
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import java.nio.ByteBuffer
import java.util.concurrent.LinkedBlockingDeque
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.coroutines.CoroutineContext
/**
* MediaLink class can be used to synchronously play audio and video streams.
*/
class MediaLink(val audio: AudioCodec, val video: VideoCodec) :
Running,
CoroutineScope,
Choreographer.FrameCallback {
data class Buffer(
val index: Int,
val payload: ByteBuffer? = null,
val timestamp: Long = 0L,
val sync: Boolean = false
)
override val isRunning = AtomicBoolean(false)
override val coroutineContext: CoroutineContext
get() = Dispatchers.IO
/**
* The instance of an AudioTrack.
*/
var audioTrack: AudioTrack? = null
set(value) {
syncMode = if (value == null) {
field?.stop()
field?.flush()
field?.release()
SYNC_MODE_CLOCK
} else {
SYNC_MODE_AUDIO
}
field = value
}
/**
* Paused audio playback of a media.
*/
var paused: Boolean
get() = audioTrack?.playState == AudioTrack.PLAYSTATE_PAUSED
set(value) {
when (audioTrack?.playState) {
AudioTrack.PLAYSTATE_STOPPED -> {
}
AudioTrack.PLAYSTATE_PLAYING -> {
if (value) {
audioTrack?.pause()
}
}
AudioTrack.PLAYSTATE_PAUSED -> {
if (!value) {
audioTrack?.play()
}
}
}
}
/**
* Video are present.
*/
var hasVideo = false
/**
* Audio are present.
*/
var hasAudio = false
private var syncMode = SYNC_MODE_CLOCK
private var hasKeyframe = false
private val videoBuffers = LinkedBlockingDeque<Buffer>()
private val audioBuffers = LinkedBlockingDeque<Buffer>()
private var choreographer: Choreographer? = null
private var videoTimestamp = Timestamp(1000L)
private var handler: Handler? = null
get() {
if (field == null) {
val thread =
HandlerThread(javaClass.name, android.os.Process.THREAD_PRIORITY_DISPLAY)
thread.start()
field = Handler(thread.looper)
}
return field
}
set(value) {
field?.looper?.quitSafely()
field = value
}
@Volatile
private var keepAlive = true
private var frameTracker: FrameTracker? = null
get() {
if (field == null && BuildConfig.DEBUG) {
field = FrameTracker()
}
return field
}
private val audioDuration: Long
get() {
val track = audioTrack ?: return 0
return (track.playbackHeadPosition.toLong() * 1000 / track.sampleRate) * 1000L + audioCorrection
}
private var audioCorrection = 0L
private var audioPlaybackJob: Job? = null
@Synchronized
override fun startRunning() {
if (isRunning.get()) return
if (BuildConfig.DEBUG) {
Log.d(TAG, "startRunning()")
}
audio.mode = MediaCodec.Mode.DECODE
audio.startRunning()
video.mode = MediaCodec.Mode.DECODE
video.startRunning()
keepAlive = true
audioPlaybackJob = launch(coroutineContext) {
doAudio()
}
isRunning.set(true)
}
@Synchronized
override fun stopRunning() {
if (!isRunning.get()) return
if (BuildConfig.DEBUG) {
Log.d(TAG, "stopRunning()")
}
hasAudio = false
hasVideo = false
hasKeyframe = false
handler = null
choreographer?.removeFrameCallback(this)
choreographer = null
keepAlive = false
audioPlaybackJob?.cancel()
audioPlaybackJob = null
syncMode = SYNC_MODE_CLOCK
audioCorrection = 0
videoTimestamp.clear()
frameTracker?.clear()
audio.release(audioBuffers)
audio.stopRunning()
video.release(videoBuffers)
video.stopRunning()
isRunning.set(false)
}
/**
* Queues the audio data asynchronously for playback.
*/
fun queueAudio(buffer: Buffer) {
audioBuffers.add(buffer)
if (!hasVideo) {
val track = audioTrack ?: return
if (track.playbackHeadPosition <= 0) {
if (track.playState != AudioTrack.PLAYSTATE_PLAYING) {
track.play()
}
return
}
}
}
/**
* Queues the video data asynchronously for playback.
*/
fun queueVideo(buffer: Buffer) {
videoBuffers.add(buffer)
if (choreographer == null) {
handler?.post {
choreographer = Choreographer.getInstance()
choreographer?.postFrameCallback(this)
}
}
}
override fun doFrame(frameTimeNanos: Long) {
choreographer?.postFrameCallback(this)
val duration: Long
if (syncMode == SYNC_MODE_AUDIO) {
val track = audioTrack ?: return
if (track.playbackHeadPosition <= 0) {
if (track.playState != AudioTrack.PLAYSTATE_PLAYING) {
track.play()
audioCorrection = videoTimestamp.duration
}
return
}
duration = audioDuration
} else {
videoTimestamp.nanoTime = frameTimeNanos
duration = videoTimestamp.duration
}
try {
val it = videoBuffers.iterator()
var frameCount = 0
while (it.hasNext()) {
val buffer = it.next()
if (!hasKeyframe) {
hasKeyframe = buffer.sync
}
if (buffer.timestamp <= duration) {
if (frameCount == 0 && hasKeyframe) {
frameTracker?.track(FrameTracker.TYPE_VIDEO, SystemClock.uptimeMillis())
video.codec?.releaseOutputBuffer(buffer.index, buffer.timestamp * 1000)
} else {
video.codec?.releaseOutputBuffer(buffer.index, false)
}
frameCount++
it.remove()
} else {
if (VERBOSE && 2 < frameCount) {
Log.d(TAG, "droppedFrame: ${frameCount - 1}")
}
break
}
}
} catch (e: IllegalStateException) {
if (BuildConfig.DEBUG) {
Log.w(TAG, "", e)
}
}
}
private fun doAudio() {
while (keepAlive) {
try {
val audio = audioBuffers.take()
val payload = audio.payload ?: continue
frameTracker?.track(FrameTracker.TYPE_AUDIO, SystemClock.uptimeMillis())
while (payload.hasRemaining()) {
if (keepAlive) {
audioTrack?.write(
payload,
payload.remaining(),
AudioTrack.WRITE_NON_BLOCKING
)
} else {
break
}
}
this.audio.codec?.releaseOutputBuffer(audio.index, false)
} catch (e: InterruptedException) {
if (BuildConfig.DEBUG) {
Log.w(TAG, "", e)
}
} catch (e: IllegalStateException) {
if (BuildConfig.DEBUG) {
Log.w(TAG, "", e)
}
}
}
}
companion object {
private const val SYNC_MODE_AUDIO = 0
private const val SYNC_MODE_VSYNC = 1
private const val SYNC_MODE_CLOCK = 2
private const val VERBOSE = true
private val TAG = MediaLink::class.java.simpleName
}
}
| bsd-3-clause | d37d72520cccca0999133e968290a07a | 29.867133 | 108 | 0.526507 | 5.147522 | false | false | false | false |
uramonk/AndroidTemplateApp | app/src/androidTest/java/com/uramonk/androidtemplateapp/domain/NotifyWeatherUseCaseTest.kt | 1 | 1595 | package com.uramonk.androidtemplateapp.domain
import com.uramonk.androidtemplateapp.domain.interactor.NotifyWeatherUseCase
import com.uramonk.androidtemplateapp.domain.model.Weather
import com.uramonk.androidtemplateapp.domain.model.WeatherList
import com.uramonk.androidtemplateapp.domain.store.WeatherStore
import io.reactivex.Observable
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.TestScheduler
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Test
import org.mockito.Mockito
import org.mockito.Mockito.`when`
import org.mockito.Mockito.verify
import java.util.*
/**
* Created by uramonk on 2017/02/28.
*/
class NotifyWeatherUseCaseTest {
private lateinit var useCase: NotifyWeatherUseCase
private lateinit var testScheduler: TestScheduler
private lateinit var weatherList: WeatherList
private val weatherStore: WeatherStore = Mockito.mock(WeatherStore::class.java)
@Before
fun setUp() {
testScheduler = TestScheduler()
useCase = NotifyWeatherUseCase(weatherStore)
weatherList = WeatherList("base", ArrayList<Weather>(), 100L)
}
@Test
fun testOnUpdatedNotifyStoreUpdated() {
`when`(weatherStore.onUpdated()).thenReturn(Observable.just(weatherList))
useCase.executionScheduler(testScheduler).postScheduler(testScheduler).execute(
onNext = Consumer {
verify(weatherStore).onUpdated()
assertThat(it).isEqualTo(weatherList)
})
testScheduler.triggerActions()
}
} | mit | 2b53a9b0f1bed626f4663fe884a29941 | 34.466667 | 87 | 0.749216 | 4.418283 | false | true | false | false |
evanchooly/kobalt | modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/misc/NewRunCommand.kt | 1 | 4310 | package com.beust.kobalt.misc
import java.io.BufferedReader
import java.io.File
import java.io.InputStream
import java.io.InputStreamReader
import java.util.concurrent.TimeUnit
class RunCommandInfo {
lateinit var command: String
var args : List<String> = arrayListOf()
var directory : File = File("")
var env : Map<String, String> = hashMapOf()
/**
* Some commands fail but return 0, so the only way to find out if they failed is to look
* at the error stream. However, some commands succeed but output text on the error stream.
* This field is used to specify how errors are caught.
*/
var useErrorStreamAsErrorIndicator : Boolean = true
var useInputStreamAsErrorIndicator : Boolean = false
var errorCallback: Function1<List<String>, Unit> = NewRunCommand.DEFAULT_ERROR
var successCallback: Function1<List<String>, Unit> = NewRunCommand.DEFAULT_SUCCESS
var isSuccess: (Boolean, List<String>, List<String>) -> Boolean = {
isSuccess: Boolean,
input: List<String>,
error: List<String> ->
var hasErrors = ! isSuccess
if (useErrorStreamAsErrorIndicator && ! hasErrors) {
hasErrors = hasErrors || error.size > 0
}
if (useInputStreamAsErrorIndicator && ! hasErrors) {
hasErrors = hasErrors || input.size > 0
}
! hasErrors
}
}
fun runCommand(init: RunCommandInfo.() -> Unit) = NewRunCommand(RunCommandInfo().apply { init() }).invoke()
open class NewRunCommand(val info: RunCommandInfo) {
companion object {
val DEFAULT_SUCCESS = { output: List<String> -> }
// val DEFAULT_SUCCESS_VERBOSE = { output: List<String> -> log(2, "Success:\n " + output.joinToString("\n"))}
// val defaultSuccess = DEFAULT_SUCCESS
val DEFAULT_ERROR = {
output: List<String> ->
kotlin.error(output.joinToString("\n "))
}
}
// fun useErrorStreamAsErrorIndicator(f: Boolean) : RunCommand {
// useErrorStreamAsErrorIndicator = f
// return this
// }
fun invoke() : Int {
val allArgs = arrayListOf<String>()
allArgs.add(info.command)
allArgs.addAll(info.args)
val pb = ProcessBuilder(allArgs)
pb.directory(info.directory)
log(2, "Running command in directory ${info.directory.absolutePath}" +
"\n " + allArgs.joinToString(" ").replace("\\", "/"))
pb.environment().let { pbEnv ->
info.env.forEach {
pbEnv.put(it.key, it.value)
}
}
val process = pb.start()
// Run the command and collect the return code and streams
val returnCode = process.waitFor(30, TimeUnit.SECONDS)
val input = if (process.inputStream.available() > 0) fromStream(process.inputStream)
else listOf()
val error = if (process.errorStream.available() > 0) fromStream(process.errorStream)
else listOf()
// Check to see if the command succeeded
val isSuccess = isSuccess(returnCode, input, error)
if (isSuccess) {
info.successCallback(input)
} else {
info.errorCallback(error + input)
}
return if (isSuccess) 0 else 1
}
/**
* Subclasses can override this method to do their own error handling, since commands can
* have various ways to signal errors.
*/
open protected fun isSuccess(isSuccess: Boolean, input: List<String>, error: List<String>) : Boolean {
var hasErrors = ! isSuccess
if (info.useErrorStreamAsErrorIndicator && ! hasErrors) {
hasErrors = hasErrors || error.size > 0
}
if (info.useInputStreamAsErrorIndicator && ! hasErrors) {
hasErrors = hasErrors || input.size > 0
}
return ! hasErrors
}
/**
* Turn the given InputStream into a list of strings.
*/
private fun fromStream(ins: InputStream) : List<String> {
val result = arrayListOf<String>()
val br = BufferedReader(InputStreamReader(ins))
var line = br.readLine()
while (line != null) {
result.add(line)
line = br.readLine()
}
return result
}
}
| apache-2.0 | d6b5ab536dfb1fd5d6b2fed5a7297d3d | 32.937008 | 120 | 0.608585 | 4.560847 | false | false | false | false |
google/android-fhir | datacapture/src/main/java/com/google/android/fhir/datacapture/validation/MaxValueConstraintValidator.kt | 1 | 1902 | /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.fhir.datacapture.validation
import android.content.Context
import com.google.android.fhir.compareTo
import com.google.android.fhir.datacapture.R
import org.hl7.fhir.r4.model.Extension
import org.hl7.fhir.r4.model.Questionnaire
import org.hl7.fhir.r4.model.QuestionnaireResponse
import org.hl7.fhir.r4.model.Type
internal const val MAX_VALUE_EXTENSION_URL = "http://hl7.org/fhir/StructureDefinition/maxValue"
/** A validator to check if the value of an answer exceeded the permitted value. */
internal object MaxValueConstraintValidator :
ValueConstraintExtensionValidator(
url = MAX_VALUE_EXTENSION_URL,
predicate = {
extension: Extension,
answer: QuestionnaireResponse.QuestionnaireResponseItemAnswerComponent ->
answer.value > extension.value?.valueOrCalculateValue()!!
},
{ extension: Extension, context: Context ->
context.getString(
R.string.max_value_validation_error_msg,
extension.value?.valueOrCalculateValue()?.primitiveValue()
)
}
) {
fun getMaxValue(questionnaireItemComponent: Questionnaire.QuestionnaireItemComponent): Type? {
return questionnaireItemComponent.extension
.firstOrNull { it.url == MAX_VALUE_EXTENSION_URL }
?.let { it.value?.valueOrCalculateValue() }
}
}
| apache-2.0 | 4d60670f296112841225eb772d1d0124 | 36.294118 | 96 | 0.747634 | 4.189427 | false | false | false | false |
jovr/imgui | core/src/main/kotlin/imgui/api/widgetsMenus.kt | 2 | 22503 | package imgui.api
import gli_.has
import glm_.glm
import glm_.max
import glm_.vec2.Vec2
import glm_.vec2.Vec2i
import imgui.*
import imgui.ImGui.alignTextToFramePadding
import imgui.ImGui.begin
import imgui.ImGui.beginGroup
import imgui.ImGui.beginPopupEx
import imgui.ImGui.calcTextSize
import imgui.ImGui.closePopupToLevel
import imgui.ImGui.contentRegionAvail
import imgui.ImGui.currentWindow
import imgui.ImGui.end
import imgui.ImGui.endGroup
import imgui.ImGui.endPopup
import imgui.ImGui.focusTopMostWindowUnderOne
import imgui.ImGui.focusWindow
import imgui.ImGui.io
import imgui.ImGui.isPopupOpen
import imgui.ImGui.itemHoverable
import imgui.ImGui.navMoveRequestButNoResultYet
import imgui.ImGui.navMoveRequestCancel
import imgui.ImGui.openPopup
import imgui.ImGui.popClipRect
import imgui.ImGui.popID
import imgui.ImGui.popStyleColor
import imgui.ImGui.popStyleVar
import imgui.ImGui.pushClipRect
import imgui.ImGui.pushID
import imgui.ImGui.pushStyleColor
import imgui.ImGui.pushStyleVar
import imgui.ImGui.renderText
import imgui.ImGui.selectable
import imgui.ImGui.setNavIDWithRectRel
import imgui.ImGui.setNextWindowPos
import imgui.ImGui.setNextWindowSize
import imgui.ImGui.style
import imgui.internal.*
import imgui.internal.classes.Rect
import imgui.internal.classes.Window
import imgui.internal.sections.*
import kotlin.math.abs
import kotlin.math.max
import kotlin.reflect.KMutableProperty0
import imgui.SelectableFlag as Sf
import imgui.WindowFlag as Wf
import imgui.internal.sections.LayoutType as Lt
/** Menu
* - Use BeginMenuBar() on a window ImGuiWindowFlags_MenuBar to append to its menu bar.
* - Use BeginMainMenuBar() to create a menu bar at the top of the screen and append to it.
* - Use BeginMenu() to create a menu. You can call BeginMenu() multiple time with the same identifier to append more items to it. */
interface widgetsMenus {
/** Append to menu-bar of current window (requires WindowFlag.MenuBar flag set on parent window).
* Only call endMenuBar() if this returns true!
*
* FIXME: Provided a rectangle perhaps e.g. a BeginMenuBarEx() could be used anywhere..
* Currently the main responsibility of this function being to setup clip-rect + horizontal layout + menu navigation layer.
* Ideally we also want this to be responsible for claiming space out of the main window scrolling rectangle, in which case ImGuiWindowFlags_MenuBar will become unnecessary.
* Then later the same system could be used for multiple menu-bars, scrollbars, side-bars. */
fun beginMenuBar(): Boolean {
val window = currentWindow
if (window.skipItems) return false
if (window.flags hasnt Wf.MenuBar) return false
assert(!window.dc.menuBarAppending)
beginGroup() // Backup position on layer 0 // FIXME: Misleading to use a group for that backup/restore
pushID("##menubar")
// We don't clip with current window clipping rectangle as it is already set to the area below. However we clip with window full rect.
// We remove 1 worth of rounding to Max.x to that text in long menus and small windows don't tend to display over the lower-right rounded area, which looks particularly glitchy.
val barRect = window.menuBarRect()
val clipRect = Rect(round(barRect.min.x + window.windowBorderSize), round(barRect.min.y + window.windowBorderSize),
round(barRect.min.x max (barRect.max.x - (window.windowRounding max window.windowBorderSize))), round(barRect.max.y))
clipRect clipWith window.outerRectClipped
pushClipRect(clipRect.min, clipRect.max, false)
with(window.dc) {
// We overwrite CursorMaxPos because BeginGroup sets it to CursorPos (essentially the .EmitItem hack in EndMenuBar() would need something analoguous here, maybe a BeginGroupEx() with flags).
cursorMaxPos.put(barRect.min.x + window.dc.menuBarOffset.x, barRect.min.y + window.dc.menuBarOffset.y)
cursorPos put cursorMaxPos
layoutType = Lt.Horizontal
navLayerCurrent = NavLayer.Menu
menuBarAppending = true
}
alignTextToFramePadding()
return true
}
/** Only call EndMenuBar() if BeginMenuBar() returns true! */
fun endMenuBar() {
val window = currentWindow
if (window.skipItems) return
// Nav: When a move request within one of our child menu failed, capture the request to navigate among our siblings.
if (navMoveRequestButNoResultYet() && (g.navMoveDir == Dir.Left || g.navMoveDir == Dir.Right) && g.navWindow!!.flags has Wf._ChildMenu) {
var navEarliestChild = g.navWindow!!
tailrec fun Window.getParent(): Window {
val parent = parentWindow
return when {
parent != null && parent.flags has Wf._ChildMenu -> parent.getParent()
else -> this
}
}
navEarliestChild = navEarliestChild.getParent()
if (navEarliestChild.parentWindow == window && navEarliestChild.dc.parentLayoutType == Lt.Horizontal && g.navMoveRequestForward == NavForward.None) {
/* To do so we claim focus back, restore NavId and then process the movement request for yet another
frame. This involve a one-frame delay which isn't very problematic in this situation.
We could remove it by scoring in advance for multiple window (probably not worth the hassle/cost) */
val layer = NavLayer.Menu
assert(window.dc.navLayerActiveMaskNext has (1 shl layer)) { "Sanity check" }
focusWindow(window)
setNavIDWithRectRel(window.navLastIds[layer], layer, 0, window.navRectRel[layer])
g.navLayer = layer
g.navDisableHighlight = true // Hide highlight for the current frame so we don't see the intermediary selection.
g.navMoveRequestForward = NavForward.ForwardQueued
navMoveRequestCancel()
}
}
assert(window.flags has Wf.MenuBar && window.dc.menuBarAppending)
popClipRect()
popID()
with(window.dc) {
// Save horizontal position so next append can reuse it. This is kinda equivalent to a per-layer CursorPos.
menuBarOffset.x = cursorPos.x - window.menuBarRect().min.x
g.groupStack.last().emitItem = false
endGroup() // Restore position on layer 0
layoutType = Lt.Vertical
navLayerCurrent = NavLayer.Main
menuBarAppending = false
}
}
/** Create and append to a full screen menu-bar.
* For the main menu bar, which cannot be moved, we honor g.Style.DisplaySafeAreaPadding to ensure text can be visible on a TV set. */
fun beginMainMenuBar(): Boolean {
g.nextWindowData.menuBarOffsetMinVal.put(style.displaySafeAreaPadding.x, max(style.displaySafeAreaPadding.y - style.framePadding.y, 0f))
setNextWindowPos(Vec2())
setNextWindowSize(Vec2(io.displaySize.x, g.nextWindowData.menuBarOffsetMinVal.y + g.fontBaseSize + style.framePadding.y))
pushStyleVar(StyleVar.WindowRounding, 0f)
pushStyleVar(StyleVar.WindowMinSize, Vec2i())
val windowFlags = Wf.NoTitleBar or Wf.NoResize or Wf.NoMove or Wf.NoScrollbar or Wf.NoSavedSettings or Wf.MenuBar
val isOpen = begin("##MainMenuBar", null, windowFlags) && beginMenuBar()
popStyleVar(2)
g.nextWindowData.menuBarOffsetMinVal put 0f
return when {
!isOpen -> {
end()
false
}
else -> true
}
}
/** Only call EndMainMenuBar() if BeginMainMenuBar() returns true! */
fun endMainMenuBar() {
endMenuBar()
// When the user has left the menu layer (typically: closed menus through activation of an item), we restore focus to the previous window
// FIXME: With this strategy we won't be able to restore a NULL focus.
if (g.currentWindow == g.navWindow && g.navLayer == NavLayer.Main && !g.navAnyRequest)
focusTopMostWindowUnderOne(g.navWindow)
end()
}
/** create a sub-menu entry. only call EndMenu() if this returns true! */
fun beginMenu(label: String, enabled: Boolean = true): Boolean {
val window = currentWindow
if (window.skipItems) return false
val id = window.getID(label)
var menuIsOpen = isPopupOpen(id)
// Sub-menus are ChildWindow so that mouse can be hovering across them (otherwise top-most popup menu would steal focus and not allow hovering on parent menu)
var flags = Wf._ChildMenu or Wf.AlwaysAutoResize or Wf.NoMove or Wf.NoTitleBar or Wf.NoSavedSettings or Wf.NoNavFocus
if (window.flags has (Wf._Popup or Wf._ChildMenu))
flags = flags or Wf._ChildWindow
// If a menu with same the ID was already submitted, we will append to it, matching the behavior of Begin().
// We are relying on a O(N) search - so O(N log N) over the frame - which seems like the most efficient for the expected small amount of BeginMenu() calls per frame.
// If somehow this is ever becoming a problem we can switch to use e.g. ImGuiStorage mapping key to last frame used.
if (id in g.menusIdSubmittedThisFrame) {
if (menuIsOpen)
menuIsOpen = beginPopupEx(id, flags) // menu_is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
else
g.nextWindowData.clearFlags() // we behave like Begin() and need to consume those values
return menuIsOpen
}
// Tag menu as used. Next time BeginMenu() with same ID is called it will append to existing menu
g.menusIdSubmittedThisFrame += id
val labelSize = calcTextSize(label, hideTextAfterDoubleHash = true)
val pressed: Boolean
val menusetIsOpen = window.flags hasnt Wf._Popup && g.openPopupStack.size > g.beginPopupStack.size &&
g.openPopupStack[g.beginPopupStack.size].openParentId == window.idStack.last()
val backedNavWindow = g.navWindow
if (menusetIsOpen)
// Odd hack to allow hovering across menus of a same menu-set (otherwise we wouldn't be able to hover parent)
g.navWindow = window
/* The reference position stored in popup_pos will be used by Begin() to find a suitable position for the child menu,
However the final position is going to be different! It is chosen by FindBestWindowPosForPopup().
e.g. Menus tend to overlap each other horizontally to amplify relative Z-ordering. */
val popupPos = Vec2()
val pos = Vec2(window.dc.cursorPos)
if (window.dc.layoutType == Lt.Horizontal) {
/* Menu inside an horizontal menu bar
Selectable extend their highlight by half ItemSpacing in each direction.
For ChildMenu, the popup position will be overwritten by the call to FindBestWindowPosForPopup() in begin() */
popupPos.put(pos.x - 1f - floor(style.itemSpacing.x * 0.5f), pos.y - style.framePadding.y + window.menuBarHeight)
window.dc.cursorPos.x += floor(style.itemSpacing.x * 0.5f)
pushStyleVar(StyleVar.ItemSpacing, Vec2(style.itemSpacing.x * 2f, style.itemSpacing.y))
val w = labelSize.x
val f = Sf._NoHoldingActiveId or Sf._SelectOnClick or Sf.DontClosePopups or if (enabled) 0 else Sf.Disabled.i
pressed = selectable(label, menuIsOpen, f, Vec2(w, 0f))
popStyleVar()
/* -1 spacing to compensate the spacing added when selectable() did a sameLine(). It would also work
to call sameLine() ourselves after the popStyleVar(). */
window.dc.cursorPos.x += floor(style.itemSpacing.x * (-1f + 0.5f))
} else {
// Menu inside a menu
// (In a typical menu window where all items are BeginMenu() or MenuItem() calls, extra_w will always be 0.0f.
// Only when they are other items sticking out we're going to add spacing, yet only register minimum width into the layout system.
popupPos.put(pos.x, pos.y - style.windowPadding.y)
val minW = window.dc.menuColumns.declColumns(labelSize.x, 0f, floor(g.fontSize * 1.2f)) // Feedback to next frame
val extraW = glm.max(0f, contentRegionAvail.x - minW)
val f = Sf._NoHoldingActiveId or Sf._SelectOnClick or Sf.DontClosePopups or Sf._SpanAvailWidth
pressed = selectable(label, menuIsOpen, f or if (enabled) Sf.None else Sf.Disabled, Vec2(minW, 0f))
val textCol = if (enabled) Col.Text else Col.TextDisabled
window.drawList.renderArrow(pos + Vec2(window.dc.menuColumns.pos[2] + extraW + g.fontSize * 0.3f, 0f), textCol.u32, Dir.Right)
}
val hovered = enabled && itemHoverable(window.dc.lastItemRect, id)
if (menusetIsOpen)
g.navWindow = backedNavWindow
var wantOpen = false
var wantClose = false
if (window.dc.layoutType == Lt.Vertical) { // (window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu))
/* Close menu when not hovering it anymore unless we are moving roughly in the direction of the menu
Implement http://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown to avoid using timers,
so menus feels more reactive. */
var movingTowardOtherChildMenu = false
val childMenuWindow = when {
g.beginPopupStack.size < g.openPopupStack.size && g.openPopupStack[g.beginPopupStack.size].sourceWindow == window -> g.openPopupStack[g.beginPopupStack.size].window
else -> null
}
if (g.hoveredWindow === window && childMenuWindow != null && window.flags hasnt Wf.MenuBar) {
// FIXME-DPI: Values should be derived from a master "scale" factor.
val nextWindowRect = childMenuWindow.rect()
val ta = io.mousePos - io.mouseDelta
val tb = if (window.pos.x < childMenuWindow.pos.x) nextWindowRect.tl else nextWindowRect.tr
val tc = if (window.pos.x < childMenuWindow.pos.x) nextWindowRect.bl else nextWindowRect.br
val extra = glm.clamp(abs(ta.x - tb.x) * 0.3f, 5f, 30f) // add a bit of extra slack.
ta.x += if (window.pos.x < childMenuWindow.pos.x) -0.5f else +0.5f // to avoid numerical issues
tb.y = ta.y + max((tb.y - extra) - ta.y, -100f) // triangle is maximum 200 high to limit the slope and the bias toward large sub-menus // FIXME: Multiply by fb_scale?
tc.y = ta.y + min((tc.y + extra) - ta.y, +100f)
movingTowardOtherChildMenu = triangleContainsPoint(ta, tb, tc, io.mousePos)
//GetForegroundDrawList()->AddTriangleFilled(ta, tb, tc, moving_within_opened_triangle ? IM_COL32(0,128,0,128) : IM_COL32(128,0,0,128)); // [DEBUG]
}
if (menuIsOpen && !hovered && g.hoveredWindow === window && g.hoveredIdPreviousFrame != 0 && g.hoveredIdPreviousFrame != id && !movingTowardOtherChildMenu)
wantClose = true
if (!menuIsOpen && hovered && pressed) // Click to open
wantOpen = true
else if (!menuIsOpen && hovered && !movingTowardOtherChildMenu) // Hover to open
wantOpen = true
if (g.navActivateId == id) {
wantClose = menuIsOpen
wantOpen = !menuIsOpen
}
if (g.navId == id && g.navMoveRequest && g.navMoveDir == Dir.Right) { // Nav-Right to open
wantOpen = true
navMoveRequestCancel()
}
} else // Menu bar
if (menuIsOpen && pressed && menusetIsOpen) { // Click an open menu again to close it
wantClose = true
wantOpen = false
menuIsOpen = false
} else if (pressed || (hovered && menusetIsOpen && !menuIsOpen)) // First click to open, then hover to open others
wantOpen = true
else if (g.navId == id && g.navMoveRequest && g.navMoveDir == Dir.Down) { // Nav-Down to open
wantOpen = true
navMoveRequestCancel()
}
/* explicitly close if an open menu becomes disabled, facilitate users code a lot in pattern such as
'if (BeginMenu("options", has_object)) { ..use object.. }' */
if (!enabled)
wantClose = true
if (wantClose && isPopupOpen(id))
closePopupToLevel(g.beginPopupStack.size, true)
val f = ItemStatusFlag.Openable or if(menuIsOpen) ItemStatusFlag.Opened else ItemStatusFlag.None
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window.dc.itemFlags or f)
if (!menuIsOpen && wantOpen && g.openPopupStack.size > g.beginPopupStack.size) {
// Don't recycle same menu level in the same frame, first close the other menu and yield for a frame.
openPopup(label)
return false
}
menuIsOpen = menuIsOpen || wantOpen
if (wantOpen) openPopup(label)
if (menuIsOpen) {
setNextWindowPos(popupPos, Cond.Always)
menuIsOpen = beginPopupEx(id, flags) // menu_is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
} else
g.nextWindowData.clearFlags() // We behave like Begin() and need to consume those values
return menuIsOpen
}
/** Only call EndMenu() if BeginMenu() returns true! */
fun endMenu() {
/* Nav: When a left move request _within our child menu_ failed, close ourselves (the _parent_ menu).
A menu doesn't close itself because EndMenuBar() wants the catch the last Left<>Right inputs.
However, it means that with the current code, a beginMenu() from outside another menu or a menu-bar won't be
closable with the Left direction. */
val window = g.currentWindow!!
g.navWindow?.let {
if (it.parentWindow === window && g.navMoveDir == Dir.Left && navMoveRequestButNoResultYet() && window.dc.layoutType == Lt.Vertical) {
closePopupToLevel(g.beginPopupStack.size, true)
navMoveRequestCancel()
}
}
endPopup()
}
/** return true when activated. shortcuts are displayed for convenience but not processed by ImGui at the moment */
fun menuItem(label: String, shortcut: String = "", selected: Boolean = false, enabled: Boolean = true): Boolean {
val window = currentWindow
if (window.skipItems) return false
val pos = Vec2(window.dc.cursorPos)
val labelSize = calcTextSize(label, hideTextAfterDoubleHash = true)
// We've been using the equivalent of ImGuiSelectableFlags_SetNavIdOnHover on all Selectable() since early Nav system days (commit 43ee5d73),
// but I am unsure whether this should be kept at all. For now moved it to be an opt-in feature used by menus only.
val flags = Sf._SelectOnRelease or Sf._SetNavIdOnHover or if (enabled) Sf.None else Sf.Disabled
val pressed: Boolean
if (window.dc.layoutType == Lt.Horizontal) {
/* Mimic the exact layout spacing of beginMenu() to allow menuItem() inside a menu bar, which is a little
misleading but may be useful
Note that in this situation we render neither the shortcut neither the selected tick mark */
val w = labelSize.x
window.dc.cursorPos.x += floor(style.itemSpacing.x * 0.5f)
pushStyleVar(StyleVar.ItemSpacing, Vec2(style.itemSpacing.x * 2f, style.itemSpacing.y))
pressed = selectable(label, false, flags, Vec2(w, 0f))
popStyleVar()
/* -1 spacing to compensate the spacing added when selectable() did a sameLine(). It would also work
to call sameLine() ourselves after the popStyleVar(). */
window.dc.cursorPos.x += floor(style.itemSpacing.x * (-1f + 0.5f))
} else {
// Menu item inside a vertical menu
// (In a typical menu window where all items are BeginMenu() or MenuItem() calls, extra_w will always be 0.0f.
// Only when they are other items sticking out we're going to add spacing, yet only register minimum width into the layout system.
val shortcutW = if(shortcut.isNotEmpty()) calcTextSize(shortcut).x else 0f
val minW = window.dc.menuColumns.declColumns(labelSize.x, shortcutW, floor(g.fontSize * 1.2f)) // Feedback for next frame
val extraW = max(0f, contentRegionAvail.x - minW)
pressed = selectable(label, false, flags or Sf._SpanAvailWidth, Vec2(minW, 0f))
if (shortcutW > 0f) {
pushStyleColor(Col.Text, style.colors[Col.TextDisabled])
renderText(pos + Vec2(window.dc.menuColumns.pos[1] + extraW, 0f), shortcut, false)
popStyleColor()
}
if (selected)
window.drawList.renderCheckMark(pos + Vec2(window.dc.menuColumns.pos[2] + extraW + g.fontSize * 0.4f, g.fontSize * 0.134f * 0.5f),
(if (enabled) Col.Text else Col.TextDisabled).u32, g.fontSize * 0.866f)
}
val f = ItemStatusFlag.Checkable or if(selected) ItemStatusFlag.Checked else ItemStatusFlag.None
IMGUI_TEST_ENGINE_ITEM_INFO(window.dc.lastItemId, label, window.dc.itemFlags or f)
return pressed
}
/** return true when activated + toggle (*p_selected) if p_selected != NULL */
fun menuItem(label: String, shortcut: String = "", pSelected: BooleanArray?, enabled: Boolean = true): Boolean =
if (menuItem(label, shortcut, pSelected?.get(0) == true, enabled)) {
pSelected?.let { it[0] = !it[0] }
true
} else false
fun menuItem(label: String, shortcut: String = "", selected: KMutableProperty0<Boolean>?, enabled: Boolean = true): Boolean =
menuItem(label, shortcut, selected?.get() == true, enabled)
.also { if (it) selected?.apply { set(!get()) } }
} | mit | b3952eff85a0e31eabd52462c5c287bd | 54.292383 | 202 | 0.649247 | 4.173405 | false | false | false | false |
code-disaster/lwjgl3 | modules/lwjgl/shaderc/src/templates/kotlin/shaderc/templates/Shaderc.kt | 4 | 32292 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package shaderc.templates
import shaderc.*
import org.lwjgl.generator.*
val SHADERC_BINDING = simpleBinding(
Module.SHADERC,
libraryExpression = """Configuration.SHADERC_LIBRARY_NAME.get(Platform.mapLibraryNameBundled("shaderc"))""",
bundledWithLWJGL = true
)
val Shaderc = "Shaderc".nativeClass(Module.SHADERC, prefix = "shaderc_", prefixMethod = "shaderc_", binding = SHADERC_BINDING) {
documentation =
"Native bindings to the libshaderc C API of the ${url("https://github.com/google/shaderc/", "shaderc")} library."
EnumConstant(
"{@code shaderc_target_env}",
"target_env_vulkan".enum("SPIR-V under Vulkan semantics", "0"),
"target_env_opengl".enum("SPIR-V under OpenGL semantics. SPIR-V code generation is not supported for shaders under OpenGL compatibility profile."),
"target_env_opengl_compat".enum("SPIR-V under OpenGL semantics, including compatibility profile functions"),
"target_env_webgpu".enum("deprecated, SPIR-V under WebGPU semantics"),
"target_env_default".enum("", "shaderc_target_env_vulkan")
)
EnumConstant(
"{@code shaderc_env_version}",
"env_version_vulkan_1_0".enum("", "((1 << 22))"),
"env_version_vulkan_1_1".enum("", "((1 << 22) | (1 << 12))"),
"env_version_vulkan_1_2".enum("", "((1 << 22) | (2 << 12))"),
"env_version_vulkan_1_3".enum("", "((1 << 22) | (3 << 12))"),
"env_version_opengl_4_5".enum("", "450"),
"env_version_webgpu".enum("deprecated, WebGPU env never defined versions")
)
EnumConstant(
"The known versions of SPIR-V. ({@code shaderc_spirv_version}",
"spirv_version_1_0".enum("", 0x010000),
"spirv_version_1_1".enum("", 0x010100),
"spirv_version_1_2".enum("", 0x010200),
"spirv_version_1_3".enum("", 0x010300),
"spirv_version_1_4".enum("", 0x010400),
"spirv_version_1_5".enum("", 0x010500),
"spirv_version_1_6".enum("", 0x010600)
)
EnumConstant(
"Indicate the status of a compilation. ({@code shaderc_compilation_status})",
"compilation_status_success".enum("", "0"),
"compilation_status_invalid_stage".enum("error stage deduction"),
"compilation_status_compilation_error".enum,
"compilation_status_internal_error".enum("unexpected failure"),
"compilation_status_null_result_object".enum,
"compilation_status_invalid_assembly".enum,
"compilation_status_validation_error".enum,
"compilation_status_transformation_error".enum,
"compilation_status_configuration_error".enum
)
EnumConstant(
"Source language kind. ({@code shaderc_source_language})",
"source_language_glsl".enum,
"source_language_hlsl".enum
)
EnumConstant(
"{@code shaderc_shader_kind}",
"vertex_shader".enum("", "0"),
"fragment_shader".enum("Forced the compiler to compile the source code as a fragment shader."),
"compute_shader".enum("Forced the compiler to compile the source code as a compute shader."),
"geometry_shader".enum("Forced the compiler to compile the source code as a geometry shader."),
"tess_control_shader".enum("Forced the compiler to compile the source code as a tessellation control shader."),
"tess_evaluation_shader".enum("Forced the compiler to compile the source code as a tessellation evaluation shader."),
"glsl_vertex_shader".enum("Forced the compiler to compile the source code as a GLSL vertex shader.", "shaderc_vertex_shader"),
"glsl_fragment_shader".enum("Forced the compiler to compile the source code as a GLSL fragment shader.", "shaderc_fragment_shader"),
"glsl_compute_shader".enum("Forced the compiler to compile the source code as a GLSL compute shader.", "shaderc_compute_shader"),
"glsl_geometry_shader".enum("Forced the compiler to compile the source code as a GLSL geometry shader.", "shaderc_geometry_shader"),
"glsl_tess_control_shader".enum(
"Forced the compiler to compile the source code as a GLSL tessellation control shader.",
"shaderc_tess_control_shader"
),
"glsl_tess_evaluation_shader".enum(
"Forced the compiler to compile the source code as a GLSL tessellation evaluation shader.",
"shaderc_tess_evaluation_shader"
),
"glsl_infer_from_source".enum(
"Deduce the shader kind from \\#pragma annotation in the source code. Compiler will emit error if \\#pragma annotation is not found.",
"6"
),
"glsl_default_vertex_shader".enum(
"""
Default shader kinds. Compiler will fall back to compile the source code as the specified kind of shader when \#pragma annotation is not found in
the source code.
"""
),
"glsl_default_fragment_shader".enum(
"""
Default shader kinds. Compiler will fall back to compile the source code as the specified kind of shader when \#pragma annotation is not found in
the source code.
"""
),
"glsl_default_compute_shader".enum(
"""
Default shader kinds. Compiler will fall back to compile the source code as the specified kind of shader when \#pragma annotation is not found in
the source code.
"""
),
"glsl_default_geometry_shader".enum(
"""
Default shader kinds. Compiler will fall back to compile the source code as the specified kind of shader when \#pragma annotation is not found in
the source code.
"""
),
"glsl_default_tess_control_shader".enum(
"""
Default shader kinds. Compiler will fall back to compile the source code as the specified kind of shader when \#pragma annotation is not found in
the source code.
"""
),
"glsl_default_tess_evaluation_shader".enum(
"""
Default shader kinds. Compiler will fall back to compile the source code as the specified kind of shader when \#pragma annotation is not found in
the source code.
"""
),
"spirv_assembly".enum(
"""
Default shader kinds. Compiler will fall back to compile the source code as the specified kind of shader when \#pragma annotation is not found in
the source code.
"""
),
"raygen_shader".enum,
"anyhit_shader".enum,
"closesthit_shader".enum,
"miss_shader".enum,
"intersection_shader".enum,
"callable_shader".enum,
"glsl_raygen_shader".enum("", "shaderc_raygen_shader"),
"glsl_anyhit_shader".enum("", "shaderc_anyhit_shader"),
"glsl_closesthit_shader".enum("", "shaderc_closesthit_shader"),
"glsl_miss_shader".enum("", "shaderc_miss_shader"),
"glsl_intersection_shader".enum("", "shaderc_intersection_shader"),
"glsl_callable_shader".enum("", "shaderc_callable_shader"),
"glsl_default_raygen_shader".enum("", "20"),
"glsl_default_anyhit_shader".enum,
"glsl_default_closesthit_shader".enum,
"glsl_default_miss_shader".enum,
"glsl_default_intersection_shader".enum,
"glsl_default_callable_shader".enum,
"task_shader".enum,
"mesh_shader".enum,
"glsl_task_shader".enum("", "shaderc_task_shader"),
"glsl_mesh_shader".enum("", "shaderc_mesh_shader"),
"glsl_default_task_shader".enum("", "28"),
"glsl_default_mesh_shader".enum
)
EnumConstant(
"{@code shaderc_profile}",
"profile_none".enum("Used if and only if GLSL version did not specify profiles.", "0"),
"profile_core".enum,
"profile_compatibility".enum("Disabled. This generates an error."),
"profile_es".enum
)
EnumConstant(
"Optimization level. ({@code shaderc_optimization_level})",
"optimization_level_zero".enum("no optimization", "0"),
"optimization_level_size".enum("optimize towards reducing code size"),
"optimization_level_performance".enum("optimize towards performance")
)
EnumConstant(
"Resource limits. ({@code shaderc_limit})",
"limit_max_lights".enum("", "0"),
"limit_max_clip_planes".enum,
"limit_max_texture_units".enum,
"limit_max_texture_coords".enum,
"limit_max_vertex_attribs".enum,
"limit_max_vertex_uniform_components".enum,
"limit_max_varying_floats".enum,
"limit_max_vertex_texture_image_units".enum,
"limit_max_combined_texture_image_units".enum,
"limit_max_texture_image_units".enum,
"limit_max_fragment_uniform_components".enum,
"limit_max_draw_buffers".enum,
"limit_max_vertex_uniform_vectors".enum,
"limit_max_varying_vectors".enum,
"limit_max_fragment_uniform_vectors".enum,
"limit_max_vertex_output_vectors".enum,
"limit_max_fragment_input_vectors".enum,
"limit_min_program_texel_offset".enum,
"limit_max_program_texel_offset".enum,
"limit_max_clip_distances".enum,
"limit_max_compute_work_group_count_x".enum,
"limit_max_compute_work_group_count_y".enum,
"limit_max_compute_work_group_count_z".enum,
"limit_max_compute_work_group_size_x".enum,
"limit_max_compute_work_group_size_y".enum,
"limit_max_compute_work_group_size_z".enum,
"limit_max_compute_uniform_components".enum,
"limit_max_compute_texture_image_units".enum,
"limit_max_compute_image_uniforms".enum,
"limit_max_compute_atomic_counters".enum,
"limit_max_compute_atomic_counter_buffers".enum,
"limit_max_varying_components".enum,
"limit_max_vertex_output_components".enum,
"limit_max_geometry_input_components".enum,
"limit_max_geometry_output_components".enum,
"limit_max_fragment_input_components".enum,
"limit_max_image_units".enum,
"limit_max_combined_image_units_and_fragment_outputs".enum,
"limit_max_combined_shader_output_resources".enum,
"limit_max_image_samples".enum,
"limit_max_vertex_image_uniforms".enum,
"limit_max_tess_control_image_uniforms".enum,
"limit_max_tess_evaluation_image_uniforms".enum,
"limit_max_geometry_image_uniforms".enum,
"limit_max_fragment_image_uniforms".enum,
"limit_max_combined_image_uniforms".enum,
"limit_max_geometry_texture_image_units".enum,
"limit_max_geometry_output_vertices".enum,
"limit_max_geometry_total_output_components".enum,
"limit_max_geometry_uniform_components".enum,
"limit_max_geometry_varying_components".enum,
"limit_max_tess_control_input_components".enum,
"limit_max_tess_control_output_components".enum,
"limit_max_tess_control_texture_image_units".enum,
"limit_max_tess_control_uniform_components".enum,
"limit_max_tess_control_total_output_components".enum,
"limit_max_tess_evaluation_input_components".enum,
"limit_max_tess_evaluation_output_components".enum,
"limit_max_tess_evaluation_texture_image_units".enum,
"limit_max_tess_evaluation_uniform_components".enum,
"limit_max_tess_patch_components".enum,
"limit_max_patch_vertices".enum,
"limit_max_tess_gen_level".enum,
"limit_max_viewports".enum,
"limit_max_vertex_atomic_counters".enum,
"limit_max_tess_control_atomic_counters".enum,
"limit_max_tess_evaluation_atomic_counters".enum,
"limit_max_geometry_atomic_counters".enum,
"limit_max_fragment_atomic_counters".enum,
"limit_max_combined_atomic_counters".enum,
"limit_max_atomic_counter_bindings".enum,
"limit_max_vertex_atomic_counter_buffers".enum,
"limit_max_tess_control_atomic_counter_buffers".enum,
"limit_max_tess_evaluation_atomic_counter_buffers".enum,
"limit_max_geometry_atomic_counter_buffers".enum,
"limit_max_fragment_atomic_counter_buffers".enum,
"limit_max_combined_atomic_counter_buffers".enum,
"limit_max_atomic_counter_buffer_size".enum,
"limit_max_transform_feedback_buffers".enum,
"limit_max_transform_feedback_interleaved_components".enum,
"limit_max_cull_distances".enum,
"limit_max_combined_clip_and_cull_distances".enum,
"limit_max_samples".enum
)
EnumConstant(
"""
Uniform resource kinds. In Vulkan, uniform resources are bound to the pipeline via descriptors with numbered bindings and sets.
({@code shaderc_uniform_kind})
""",
"uniform_kind_image".enum("Image and image buffer.", "0"),
"uniform_kind_sampler".enum("Pure sampler."),
"uniform_kind_texture".enum("Sampled texture in GLSL, and Shader Resource View in HLSL."),
"uniform_kind_buffer".enum("Uniform Buffer Object (UBO) in GLSL. Cbuffer in HLSL."),
"uniform_kind_storage_buffer".enum("Shader Storage Buffer Object (SSBO) in GLSL."),
"uniform_kind_unordered_access_view".enum("Unordered Access View, in HLSL. (Writable storage image or storage buffer.)")
)
EnumConstant(
"""
The kinds of include requests.
({@code enum shaderc_include_type})
""",
"include_type_relative".enum("E.g. \\#include \"source\"", "0"),
"include_type_standard".enum("E.g. \\#include <source>")
)
shaderc_compiler_t(
"compiler_initialize",
"""
Returns a {@code shaderc_compiler_t} that can be used to compile modules.
A return of #NULL indicates that there was an error initializing the compiler. Any function operating on {@code shaderc_compiler_t} must offer the
${url("http://herbsutter.com/2014/01/13/gotw-95-solution-thread-safety-and-synchronization/", "basic thread-safety guarantee")}. That is: concurrent
invocation of these functions on DIFFERENT objects needs no synchronization; concurrent invocation of these functions on the SAME object requires
synchronization IF AND ONLY IF some of them take a non-const argument.
""",
void()
)
void(
"compiler_release",
"""
Releases the resources held by the {@code shaderc_compiler_t}.
After this call it is invalid to make any future calls to functions involving this {@code shaderc_compiler_t}.
""",
shaderc_compiler_t("compiler", "")
)
shaderc_compile_options_t(
"compile_options_initialize",
"""
Returns a default-initialized {@code shaderc_compile_options_t} that can be used to modify the functionality of a compiled module.
A return of #NULL indicates that there was an error initializing the options. Any function operating on {@code shaderc_compile_options_t} must offer
the basic thread-safety guarantee.
""",
void()
)
shaderc_compile_options_t(
"compile_options_clone",
"""
Returns a copy of the given {@code shaderc_compile_options_t}.
If #NULL is passed as the parameter the call is the same as #compile_options_initialize().
""",
nullable..shaderc_compile_options_t.const("options", "")
)
void(
"compile_options_release",
"""
Releases the compilation options.
It is invalid to use the given {@code shaderc_compile_options_t} object in any future calls. It is safe to pass #NULL to this function, and doing such
will have no effect.
""",
nullable..shaderc_compile_options_t("options", "")
)
void(
"compile_options_add_macro_definition",
"""
Adds a predefined macro to the compilation options.
This has the same effect as passing {@code -Dname=value} to the command-line compiler. If {@code value} is #NULL, it has the same effect as passing
{@code -Dname} to the command-line compiler. If a macro definition with the same name has previously been added, the value is replaced with the new
value. The macro name and value are passed in with char pointers, which point to their data, and the lengths of their data. The strings {@code name}
and {@code value} must remain valid for the duration of the call, but can be modified or deleted after this function has returned. In case of adding a
valueless macro, the {@code value} argument should be {@code null}.
""",
shaderc_compile_options_t("options", ""),
charUTF8.const.p("name", ""),
AutoSize("name")..size_t("name_length", ""),
nullable..charUTF8.const.p("value", ""),
AutoSize("value")..size_t("value_length", "")
)
void(
"compile_options_set_source_language",
"""
Sets the source language.
The default is GLSL.
""",
shaderc_compile_options_t("options", ""),
shaderc_source_language("lang", "")
)
void(
"compile_options_set_generate_debug_info",
"Sets the compiler mode to generate debug information in the output.",
shaderc_compile_options_t("options", "")
)
void(
"compile_options_set_optimization_level",
"""
Sets the compiler optimization level to the given level.
Only the last one takes effect if multiple calls of this function exist.
""",
shaderc_compile_options_t("options", ""),
shaderc_optimization_level("level", "")
)
void(
"compile_options_set_forced_version_profile",
"""
Forces the GLSL language version and profile to a given pair.
The {@code version} number is the same as would appear in the \#version annotation in the source. The {@code version} and {@code profile} specified
here override the \#version annotation in the source. Use {@code profile: 'shaderc_profile_none'} for GLSL versions that do not define profiles, e.g.
versions below 150.
""",
shaderc_compile_options_t("options", ""),
int("version", ""),
shaderc_profile("profile", "")
)
void(
"compile_options_set_include_callbacks",
"Sets includer callback functions.",
shaderc_compile_options_t("options", ""),
nullable..shaderc_include_resolve_fn("resolver", ""),
nullable..shaderc_include_result_release_fn("result_releaser", ""),
nullable..opaque_p("user_data", "")
)
void(
"compile_options_set_suppress_warnings",
"""
Sets the compiler mode to suppress warnings, overriding warnings-as-errors mode.
When both suppress-warnings and warnings-as-errors modes are turned on, warning messages will be inhibited, and will not be emitted as error messages.
""",
shaderc_compile_options_t("options", "")
)
void(
"compile_options_set_target_env",
"""
Sets the target shader environment, affecting which warnings or errors will be issued.
The {@code version} will be for distinguishing between different versions of the target environment. The {@code version} value should be either 0 or a
value listed in {@code shaderc_env_version}. The 0 value maps to Vulkan 1.0 if {@code target} is Vulkan, and it maps to OpenGL 4.5 if {@code target} is
OpenGL.
""",
shaderc_compile_options_t("options", ""),
shaderc_target_env("target", ""),
uint32_t("version", "")
)
void(
"compile_options_set_target_spirv",
"""
Sets the target SPIR-V version.
The generated module will use this version of SPIR-V. Each target environment determines what versions of SPIR-V it can consume. Defaults to the
highest version of SPIR-V 1.0 which is required to be supported by the target environment. E.g. Default to SPIR-V 1.0 for Vulkan 1.0 and SPIR-V 1.3 for
Vulkan 1.1.
""",
shaderc_compile_options_t("options", ""),
shaderc_spirv_version("version", "")
)
void(
"compile_options_set_warnings_as_errors",
"""
Sets the compiler mode to treat all warnings as errors.
Note the suppress-warnings mode overrides this option, i.e. if both warning-as-errors and suppress-warnings modes are set, warnings will not be emitted
as error messages.
""",
shaderc_compile_options_t("options", "")
)
void(
"compile_options_set_limit",
"Sets a resource limit.",
shaderc_compile_options_t("options", ""),
shaderc_limit("limit", ""),
int("value", "")
)
void(
"compile_options_set_auto_bind_uniforms",
"Sets whether the compiler should automatically assign bindings to uniforms that aren't already explicitly bound in the shader source.",
shaderc_compile_options_t("options", ""),
bool("auto_bind", "")
)
void(
"compile_options_set_auto_combined_image_sampler",
"Sets whether the compiler should automatically remove sampler variables and convert image variables to combined image-sampler variables.",
shaderc_compile_options_t("options", ""),
bool("upgrade", "")
)
void(
"compile_options_set_hlsl_io_mapping",
"""
Sets whether the compiler should use HLSL IO mapping rules for bindings.
Defaults to {@code false}.
""",
shaderc_compile_options_t("options", ""),
bool("hlsl_iomap", "")
)
void(
"compile_options_set_hlsl_offsets",
"""
Sets whether the compiler should determine block member offsets using HLSL packing rules instead of standard GLSL rules.
Defaults to {@code false}. Only affects GLSL compilation. HLSL rules are always used when compiling HLSL.
""",
shaderc_compile_options_t("options", ""),
bool("hlsl_offsets", "")
)
void(
"compile_options_set_binding_base",
"""
Sets the base binding number used for for a uniform resource type when automatically assigning bindings.
For GLSL compilation, sets the lowest automatically assigned number. For HLSL compilation, the register number assigned to the resource is added to
this specified base.
""",
shaderc_compile_options_t("options", ""),
shaderc_uniform_kind("kind", ""),
uint32_t("base", "")
)
void(
"compile_options_set_binding_base_for_stage",
"""
Like #compile_options_set_binding_base(), but only takes effect when compiling a given shader stage.
The stage is assumed to be one of vertex, fragment, tessellation evaluation, tesselation control, geometry, or compute.
""",
shaderc_compile_options_t("options", ""),
shaderc_shader_kind("shader_kind", ""),
shaderc_uniform_kind("kind", ""),
uint32_t("base", "")
)
void(
"compile_options_set_auto_map_locations",
"Sets whether the compiler should automatically assign locations to uniform variables that don't have explicit locations in the shader source.",
shaderc_compile_options_t("options", ""),
bool("auto_map", "")
)
void(
"compile_options_set_hlsl_register_set_and_binding_for_stage",
"Sets a descriptor set and binding for an HLSL register in the given stage. This method keeps a copy of the string data.",
shaderc_compile_options_t("options", ""),
shaderc_shader_kind("shader_kind", ""),
charUTF8.const.p("reg", ""),
charUTF8.const.p("set", ""),
charUTF8.const.p("binding", "")
)
void(
"compile_options_set_hlsl_register_set_and_binding",
"Like #compile_options_set_hlsl_register_set_and_binding_for_stage(), but affects all shader stages.",
shaderc_compile_options_t("options", ""),
charUTF8.const.p("reg", ""),
charUTF8.const.p("set", ""),
charUTF8.const.p("binding", "")
)
void(
"compile_options_set_hlsl_functionality1",
"Sets whether the compiler should enable extension {@code SPV_GOOGLE_hlsl_functionality1}.",
shaderc_compile_options_t("options", ""),
bool("enable", "")
)
void(
"compile_options_set_hlsl_16bit_types",
"Sets whether 16-bit types are supported in HLSL or not.",
shaderc_compile_options_t("options", ""),
bool("enable", "")
)
void(
"compile_options_set_invert_y",
"Sets whether the compiler should invert {@code position.Y} output in vertex shader.",
shaderc_compile_options_t("options", ""),
bool("enable", "")
)
void(
"compile_options_set_nan_clamp",
"""
Sets whether the compiler generates code for {@code max} and {@code min} builtins which, if given a {@code NaN} operand, will return the other operand.
Similarly, the {@code clamp} builtin will favour the non-{@code NaN} operands, as if {@code clamp} were implemented as a composition of {@code max} and
{@code min}.
""",
shaderc_compile_options_t("options", ""),
bool("enable", "")
)
shaderc_compilation_result_t(
"compile_into_spv",
"""
Takes a GLSL source string and the associated shader kind, input file name, compiles it according to the given {@code additional_options}.
If the shader kind is not set to a specified kind, but #glsl_infer_from_source, the compiler will try to deduce the shader kind from the source string
and a failure in deducing will generate an error. Currently only \#pragma annotation is supported. If the shader kind is set to one of the default
shader kinds, the compiler will fall back to the default shader kind in case it failed to deduce the shader kind from source string. The
{@code input_file_name} is a null-termintated string. It is used as a tag to identify the source string in cases like emitting error messages. It
doesn't have to be a 'file name'. The source string will be compiled into SPIR-V binary and a {@code shaderc_compilation_result_t} will be returned to
hold the results. The {@code entry_point_name} null-terminated string defines the name of the entry point to associate with this GLSL source. If the
{@code additional_options} parameter is not #NULL, then the compilation is modified by any options present. May be safely called from multiple threads
without explicit synchronization. If there was failure in allocating the compiler object, #NULL will be returned.
""",
shaderc_compiler_t.const("compiler", ""),
charUTF8.const.p("source_text", ""),
AutoSize("source_text")..size_t("source_text_size", ""),
shaderc_shader_kind("shader_kind", ""),
charUTF8.const.p("input_file_name", ""),
charUTF8.const.p("entry_point_name", ""),
nullable..shaderc_compile_options_t.const("additional_options", "")
)
shaderc_compilation_result_t(
"compile_into_spv_assembly",
"""
Like #compile_into_spv(), but the result contains SPIR-V assembly text instead of a SPIR-V binary module.
The SPIR-V assembly syntax is as defined by the SPIRV-Tools open source project.
""",
shaderc_compiler_t.const("compiler", ""),
charUTF8.const.p("source_text", ""),
AutoSize("source_text")..size_t("source_text_size", ""),
shaderc_shader_kind("shader_kind", ""),
charUTF8.const.p("input_file_name", ""),
charUTF8.const.p("entry_point_name", ""),
nullable..shaderc_compile_options_t.const("additional_options", "")
)
shaderc_compilation_result_t(
"compile_into_preprocessed_text",
"Like #compile_into_spv(), but the result contains preprocessed source code instead of a SPIR-V binary module",
shaderc_compiler_t.const("compiler", ""),
charUTF8.const.p("source_text", ""),
AutoSize("source_text")..size_t("source_text_size", ""),
shaderc_shader_kind("shader_kind", ""),
charUTF8.const.p("input_file_name", ""),
charUTF8.const.p("entry_point_name", ""),
nullable..shaderc_compile_options_t.const("additional_options", "")
)
shaderc_compilation_result_t(
"assemble_into_spv",
"""
Takes an assembly string of the format defined in the ${url("https://github.com/KhronosGroup/SPIRV-Tools/blob/master/syntax.md", "SPIRV-Tools project")},
assembles it into SPIR-V binary and a {@code shaderc_compilation_result_t} will be returned to hold the results. The assembling will pick options
suitable for assembling specified in the {@code additional_options} parameter. May be safely called from multiple threads without explicit
synchronization. If there was failure in allocating the compiler object, #NULL will be returned.
""",
shaderc_compiler_t.const("compiler", ""),
charUTF8.const.p("source_assembly", ""),
AutoSize("source_assembly")..size_t("source_assembly_size", ""),
nullable..shaderc_compile_options_t.const("additional_options", "")
)
void(
"result_release",
"""
Releases the resources held by the {@code result} object.
It is invalid to use the result object for any further operations.
""",
shaderc_compilation_result_t("result", "")
)
size_t(
"result_get_length",
"Returns the number of bytes of the compilation output data in the given {@code result} object.",
shaderc_compilation_result_t.const("result", "")
)
size_t(
"result_get_num_warnings",
"Returns the number of warnings generated during the compilation.",
shaderc_compilation_result_t.const("result", "")
)
size_t(
"result_get_num_errors",
"Returns the number of errors generated during the compilation.",
shaderc_compilation_result_t.const("result", "")
)
shaderc_compilation_status(
"result_get_compilation_status",
"""
Returns the compilation status, indicating whether the compilation succeeded, or failed due to some reasons, like invalid shader stage or compilation
errors.
""",
shaderc_compilation_result_t.const("result", "")
)
MapPointer("shaderc_result_get_length(result)")..char.const.p(
"result_get_bytes",
"""
Returns the compilation output data bytes, either SPIR-V binary or char string.
When the source string is compiled into SPIR-V binary, this is guaranteed to be castable to a {@code uint32_t*}. If the result contains assembly text
or preprocessed source text, the pointer will point to the resulting array of characters.
""",
shaderc_compilation_result_t.const("result", "")
)
charUTF8.const.p(
"result_get_error_message",
"Returns a null-terminated string that contains any error messages generated during the compilation.",
shaderc_compilation_result_t.const("result", "")
)
void(
"get_spv_version",
"Provides the version and revision of the SPIR-V which will be produced",
Check(1)..unsigned_int.p("version", ""),
Check(1)..unsigned_int.p("revision", "")
)
bool(
"parse_version_profile",
"""
Parses the version and profile from a given null-terminated string containing both version and profile, like: {@code '450core'}.
Returns false if the string can not be parsed. Returns true when the parsing succeeds. The parsed version and profile are returned through arguments.
""",
charUTF8.const.p("str", ""),
Check(1)..int.p("version", ""),
Check(1)..shaderc_profile.p("profile", "")
)
} | bsd-3-clause | f37d15fe9e7c65eaa3ebdb7632c11223 | 40.561133 | 161 | 0.633934 | 4.122558 | false | false | false | false |
dhis2/dhis2-android-sdk | core/src/androidTest/java/org/hisp/dhis/android/localanalytics/dbgeneration/LocalAnalyticsDatabaseFiller.kt | 1 | 6987 | /*
* 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.localanalytics.dbgeneration
import org.hisp.dhis.android.core.D2
import org.hisp.dhis.android.core.D2DIComponentAccessor
import org.hisp.dhis.android.core.arch.call.executors.internal.D2CallExecutor
import org.hisp.dhis.android.core.category.CategoryOptionCombo
import org.hisp.dhis.android.core.category.internal.CategoryComboStore
import org.hisp.dhis.android.core.category.internal.CategoryOptionComboStoreImpl
import org.hisp.dhis.android.core.dataelement.DataElement
import org.hisp.dhis.android.core.dataelement.internal.DataElementStore
import org.hisp.dhis.android.core.datavalue.internal.DataValueStore
import org.hisp.dhis.android.core.enrollment.internal.EnrollmentStoreImpl
import org.hisp.dhis.android.core.event.internal.EventStoreImpl
import org.hisp.dhis.android.core.organisationunit.OrganisationUnit
import org.hisp.dhis.android.core.organisationunit.internal.OrganisationUnitStore
import org.hisp.dhis.android.core.period.Period
import org.hisp.dhis.android.core.period.PeriodType
import org.hisp.dhis.android.core.program.Program
import org.hisp.dhis.android.core.program.ProgramStage
import org.hisp.dhis.android.core.program.internal.ProgramStageStore
import org.hisp.dhis.android.core.program.internal.ProgramStore
import org.hisp.dhis.android.core.trackedentity.TrackedEntityAttribute
import org.hisp.dhis.android.core.trackedentity.internal.TrackedEntityAttributeStore
import org.hisp.dhis.android.core.trackedentity.internal.TrackedEntityAttributeValueStoreImpl
import org.hisp.dhis.android.core.trackedentity.internal.TrackedEntityDataValueStoreImpl
import org.hisp.dhis.android.core.trackedentity.internal.TrackedEntityInstanceStoreImpl
internal data class MetadataForDataFilling(
val organisationUnits: List<OrganisationUnit>,
val periods: List<Period>,
val categoryOptionCombos: List<CategoryOptionCombo>,
val aggregatedDataElements: List<DataElement>,
val trackerDataElements: List<DataElement>,
val programs: List<Program>,
val programStages: List<ProgramStage>,
val trackedEntityAttributes: List<TrackedEntityAttribute>
)
internal class LocalAnalyticsDatabaseFiller(private val d2: D2) {
private val da = d2.databaseAdapter()
private val d2DIComponent = D2DIComponentAccessor.getD2DIComponent(d2)
fun fillDatabase(metadataParams: LocalAnalyticsMetadataParams, dataParams: LocalAnalyticsDataParams) {
D2CallExecutor.create(da).executeD2CallTransactionally {
val metadata = fillMetadata(metadataParams)
fillData(dataParams, metadata)
}
}
private fun fillMetadata(metadataParams: LocalAnalyticsMetadataParams): MetadataForDataFilling {
val generator = LocalAnalyticsMetadataGenerator(metadataParams)
val organisationUnits = generator.getOrganisationUnits()
OrganisationUnitStore.create(da).insert(organisationUnits)
val categoryCombos = generator.getCategoryCombos()
CategoryComboStore.create(da).insert(categoryCombos)
val categoryOptionCombos = generator.getCategoryOptionCombos(categoryCombos)
CategoryOptionComboStoreImpl.create(da).insert(categoryOptionCombos)
val defaultCategoryCombo = categoryCombos.first()
val aggregatedDataElements = generator.getDataElementsAggregated(categoryCombos)
val trackerDataElements = generator.getDataElementsTracker(defaultCategoryCombo)
DataElementStore.create(da).insert(aggregatedDataElements + trackerDataElements)
d2DIComponent.periodHandler().generateAndPersist()
val programs = generator.getPrograms(defaultCategoryCombo)
ProgramStore.create(da).insert(programs)
val programStages = generator.getProgramStages(programs)
ProgramStageStore.create(da).insert(programStages)
val trackedEntityAttributes = generator.getTrackedEntityAttributes()
TrackedEntityAttributeStore.create(da).insert(trackedEntityAttributes)
val periods = d2.periodModule().periods().byPeriodType().eq(PeriodType.Daily).blockingGet()
return MetadataForDataFilling(
organisationUnits, periods, categoryOptionCombos, aggregatedDataElements,
trackerDataElements, programs, programStages, trackedEntityAttributes
)
}
private fun fillData(dataParams: LocalAnalyticsDataParams, metadata: MetadataForDataFilling) {
val generator = LocalAnalyticsDataGenerator(dataParams)
val dv = generator.generateDataValues(metadata)
DataValueStore.create(da).insert(dv)
val teis = generator.generateTrackedEntityInstances(metadata.organisationUnits)
TrackedEntityInstanceStoreImpl.create(da).insert(teis)
val enrollments = generator.generateEnrollments(teis, metadata.programs.first())
EnrollmentStoreImpl.create(da).insert(enrollments)
val events = generator.generateEventsWithoutRegistration(metadata) +
generator.generateEventsRegistration(metadata, enrollments)
EventStoreImpl.create(da).insert(events)
TrackedEntityAttributeValueStoreImpl.create(da).insert(
generator.generateTrackedEntityAttributeValues(metadata.trackedEntityAttributes, teis)
)
TrackedEntityDataValueStoreImpl.create(da).insert(
generator.generateTrackedEntityDataValues(metadata.trackerDataElements, events)
)
}
}
| bsd-3-clause | 89ac19babafad6ce9afd02b87e715768 | 50 | 106 | 0.786747 | 4.714575 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/quickfix/AbstractQuickFixMultiFileTest.kt | 4 | 16268 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.CodeInsightSettings
import com.intellij.codeInsight.daemon.impl.HighlightInfo
import com.intellij.codeInsight.daemon.quickFix.ActionHint
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInsight.intention.impl.CachedIntentions
import com.intellij.codeInsight.intention.impl.ShowIntentionActionsHandler
import com.intellij.codeInspection.InspectionEP
import com.intellij.codeInspection.LocalInspectionEP
import com.intellij.ide.highlighter.JavaFileType
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.fileTypes.PlainTextFileType
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.CharsetToolkit
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiFile
import com.intellij.testFramework.fixtures.impl.CodeInsightTestFixtureImpl
import com.intellij.util.ArrayUtil
import com.intellij.util.PathUtil
import com.intellij.util.ThrowableRunnable
import junit.framework.ComparisonFailure
import junit.framework.TestCase
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.quickfix.utils.findInspectionFile
import org.jetbrains.kotlin.idea.test.DirectiveBasedActionUtils
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.idea.test.runAll
import org.jetbrains.kotlin.idea.test.withCustomCompilerOptions
import org.jetbrains.kotlin.idea.util.application.executeCommand
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.idea.test.Directives
import org.jetbrains.kotlin.idea.test.KotlinTestUtils
import org.jetbrains.kotlin.idea.test.TestFiles
import java.io.File
import java.util.regex.Pattern
abstract class AbstractQuickFixMultiFileTest : KotlinLightCodeInsightFixtureTestCase() {
protected open fun doTestWithExtraFile(beforeFileName: String) {
enableInspections(beforeFileName)
if (beforeFileName.endsWith(".test")) {
doMultiFileTest(beforeFileName)
} else {
doTest(beforeFileName)
}
}
private fun enableInspections(beforeFileName: String) {
val inspectionFile = findInspectionFile(File(beforeFileName).parentFile)
if (inspectionFile != null) {
val className = FileUtil.loadFile(inspectionFile).trim { it <= ' ' }
val inspectionClass = Class.forName(className)
enableInspectionTools(inspectionClass)
}
}
private fun enableInspectionTools(klass: Class<*>) {
val eps = mutableListOf<InspectionEP>().apply {
addAll(LocalInspectionEP.LOCAL_INSPECTION.extensions)
addAll(InspectionEP.GLOBAL_INSPECTION.extensions)
}
val tool = eps.firstOrNull { it.implementationClass == klass.name }?.instantiateTool()
?: error("Could not find inspection tool for class: $klass")
myFixture.enableInspections(tool)
}
override fun setUp() {
super.setUp()
CodeInsightSettings.getInstance().EXCLUDED_PACKAGES = arrayOf("excludedPackage", "somePackage.ExcludedClass")
}
override fun tearDown() {
runAll(
ThrowableRunnable { CodeInsightSettings.getInstance().EXCLUDED_PACKAGES = ArrayUtil.EMPTY_STRING_ARRAY },
ThrowableRunnable { super.tearDown() }
)
}
/**
* @param subFiles subFiles of multiFile test
* *
* @param beforeFile will be added last, as subFiles are dependencies of it
*/
private fun configureMultiFileTest(subFiles: List<TestFile>, beforeFile: TestFile): List<VirtualFile> {
val vFiles = subFiles.map(this::createTestFile).toMutableList()
val beforeVFile = createTestFile(beforeFile)
vFiles.add(beforeVFile)
myFixture.configureFromExistingVirtualFile(beforeVFile)
TestCase.assertEquals(guessFileType(beforeFile), myFixture.file.virtualFile.fileType)
TestCase.assertTrue("\"<caret>\" is probably missing in file \"" + beforeFile.path + "\"", myFixture.editor.caretModel.offset != 0)
return vFiles
}
private fun createTestFile(testFile: TestFile): VirtualFile {
return runWriteAction {
val vFile = myFixture.tempDirFixture.createFile(testFile.path)
vFile.charset = CharsetToolkit.UTF8_CHARSET
VfsUtil.saveText(vFile, testFile.content)
vFile
}
}
private fun doMultiFileTest(beforeFileName: String) {
val mainFile = File(beforeFileName)
val multiFileText = FileUtil.loadFile(mainFile, true)
val subFiles = TestFiles.createTestFiles(
"single.kt",
multiFileText,
object : TestFiles.TestFileFactoryNoModules<TestFile>() {
override fun create(fileName: String, text: String, directives: Directives): TestFile {
val linesWithoutDirectives = text.lines().filter {
!it.startsWith("// LANGUAGE_VERSION") && !it.startsWith("// FILE")
}
return TestFile(fileName, linesWithoutDirectives.joinToString(separator = "\n"))
}
}
)
val afterFile = subFiles.firstOrNull { file -> file.path.contains(".after") }
val beforeFile = subFiles.firstOrNull { file -> file.path.contains(".before") }!!
subFiles.remove(beforeFile)
if (afterFile != null) {
subFiles.remove(afterFile)
}
configureMultiFileTest(subFiles, beforeFile)
withCustomCompilerOptions(multiFileText, project, module) {
project.executeCommand("") {
try {
val psiFile = file
val actionHint = ActionHint.parse(psiFile, beforeFile.content)
val text = actionHint.expectedText
val actionShouldBeAvailable = actionHint.shouldPresent()
if (psiFile is KtFile) {
checkForUnexpectedErrors(psiFile)
}
doAction(
mainFile,
text,
file,
editor,
actionShouldBeAvailable,
getTestName(false),
this::availableActions,
myFixture::doHighlighting,
checkAvailableActionsAreExpected = this::checkAvailableActionsAreExpected
)
val actualText = file.text
val afterText = StringBuilder(actualText).insert(editor.caretModel.offset, "<caret>").toString()
if (actionShouldBeAvailable) {
TestCase.assertNotNull(".after file should exist", afterFile)
if (afterText != afterFile!!.content) {
val actualTestFile = StringBuilder()
if (multiFileText.startsWith("// LANGUAGE_VERSION")) {
actualTestFile.append(multiFileText.lineSequence().first())
}
actualTestFile.append("// FILE: ").append(beforeFile.path).append("\n").append(beforeFile.content)
for (file in subFiles) {
actualTestFile.append("// FILE: ").append(file.path).append("\n").append(file.content)
}
actualTestFile.append("// FILE: ").append(afterFile.path).append("\n").append(afterText)
KotlinTestUtils.assertEqualsToFile(mainFile, actualTestFile.toString())
}
} else {
TestCase.assertNull(".after file should not exist", afterFile)
}
} catch (e: ComparisonFailure) {
throw e
} catch (e: AssertionError) {
throw e
} catch (e: Throwable) {
e.printStackTrace()
TestCase.fail(getTestName(true))
}
}
}
}
private fun doTest(beforeFileName: String) {
val mainFile = File(beforeFileName)
val originalFileText = FileUtil.loadFile(mainFile, true)
val mainFileDir = mainFile.parentFile!!
val mainFileName = mainFile.name
val extraFiles = mainFileDir.listFiles { _, name ->
name.startsWith(extraFileNamePrefix(mainFileName))
&& name != mainFileName
&& PathUtil.getFileExtension(name).let { it == "kt" || it == "java" || it == "groovy" }
}!!
val testFiles = ArrayList<String>()
testFiles.add(mainFile.name)
extraFiles.mapTo(testFiles) { file -> file.name }
myFixture.configureByFiles(*testFiles.toTypedArray())
withCustomCompilerOptions(originalFileText, project, module) {
project.executeCommand("") {
try {
val psiFile = file
val actionHint = ActionHint.parse(psiFile, originalFileText)
val text = actionHint.expectedText
val actionShouldBeAvailable = actionHint.shouldPresent()
if (psiFile is KtFile) {
checkForUnexpectedErrors(psiFile)
}
doAction(
mainFile,
text,
file,
editor,
actionShouldBeAvailable,
beforeFileName,
this::availableActions,
myFixture::doHighlighting,
checkAvailableActionsAreExpected = this::checkAvailableActionsAreExpected
)
if (actionShouldBeAvailable) {
val afterFilePath = beforeFileName.replace(".before.Main.", ".after.")
try {
myFixture.checkResultByFile(mainFile.name.replace(".before.Main.", ".after."))
} catch (e: ComparisonFailure) {
KotlinTestUtils.assertEqualsToFile(File(afterFilePath), editor)
}
for (file in myFixture.file.containingDirectory.files) {
val fileName = file.name
if (fileName == myFixture.file.name || !fileName.startsWith(
extraFileNamePrefix(
myFixture.file
.name,
),
)
) continue
val extraFileFullPath = beforeFileName.replace(myFixture.file.name, fileName)
val afterFile = File(extraFileFullPath.replace(".before.", ".after."))
if (afterFile.exists()) {
KotlinTestUtils.assertEqualsToFile(afterFile, file.text)
} else {
KotlinTestUtils.assertEqualsToFile(File(extraFileFullPath), file.text)
}
}
}
} catch (e: ComparisonFailure) {
throw e
} catch (e: AssertionError) {
throw e
} catch (e: Throwable) {
e.printStackTrace()
TestCase.fail(getTestName(true))
}
}
}
}
protected open fun checkForUnexpectedErrors(file: KtFile) {
DirectiveBasedActionUtils.checkForUnexpectedErrors(file)
}
protected open fun checkAvailableActionsAreExpected(file: File, actions: Collection<IntentionAction>) {
DirectiveBasedActionUtils.checkAvailableActionsAreExpected(file, availableActions)
}
private val availableActions: List<IntentionAction>
get() {
myFixture.doHighlighting()
val intentions = ShowIntentionActionsHandler.calcIntentions(project, editor, file)
val cachedIntentions = CachedIntentions.create(project, file, editor, intentions)
cachedIntentions.wrapAndUpdateGutters()
return cachedIntentions.allActions.map { it.action }
}
class TestFile internal constructor(val path: String, val content: String)
companion object {
private fun getActionsTexts(availableActions: List<IntentionAction>): List<String> =
availableActions.map(IntentionAction::getText)
private fun extraFileNamePrefix(mainFileName: String): String =
mainFileName.replace(".Main.kt", ".").replace(".Main.java", ".")
protected fun guessFileType(file: TestFile): FileType = when {
file.path.contains("." + KotlinFileType.EXTENSION) -> KotlinFileType.INSTANCE
file.path.contains("." + JavaFileType.DEFAULT_EXTENSION) -> JavaFileType.INSTANCE
else -> PlainTextFileType.INSTANCE
}
private fun findActionByPattern(pattern: Pattern, availableActions: List<IntentionAction>): IntentionAction? =
availableActions.firstOrNull { pattern.matcher(it.text).matches() }
fun doAction(
mainFile: File,
text: String,
file: PsiFile,
editor: Editor,
actionShouldBeAvailable: Boolean,
testFilePath: String,
getAvailableActions: () -> List<IntentionAction>,
doHighlighting: () -> List<HighlightInfo>,
shouldBeAvailableAfterExecution: Boolean = false,
checkAvailableActionsAreExpected: (File, Collection<IntentionAction>) -> Unit =
DirectiveBasedActionUtils::checkAvailableActionsAreExpected
) {
val pattern = if (text.startsWith("/"))
Pattern.compile(text.substring(1, text.length - 1))
else
Pattern.compile(StringUtil.escapeToRegexp(text))
val availableActions = getAvailableActions()
val action = findActionByPattern(pattern, availableActions)
if (action == null) {
if (actionShouldBeAvailable) {
val texts = getActionsTexts(availableActions)
val infos = doHighlighting()
TestCase.fail(
"Action with text '" + text + "' is not available in test " + testFilePath + "\n" +
"Available actions (" + texts.size + "): \n" +
StringUtil.join(texts, "\n") +
"\nActions:\n" +
StringUtil.join(availableActions, "\n") +
"\nInfos:\n" +
StringUtil.join(infos, "\n")
)
} else {
checkAvailableActionsAreExpected(mainFile, availableActions)
}
} else {
if (!actionShouldBeAvailable) {
TestCase.fail("Action '$text' is available (but must not) in test $testFilePath")
}
CodeInsightTestFixtureImpl.invokeIntention(action, file, editor)
if (!shouldBeAvailableAfterExecution) {
val afterAction = findActionByPattern(pattern, getAvailableActions())
if (afterAction != null) {
TestCase.fail("Action '$text' is still available after its invocation in test $testFilePath")
}
}
}
}
}
}
| apache-2.0 | 82bfc9cc4d91031da503c2d78c739f34 | 42.731183 | 158 | 0.584768 | 5.619344 | false | true | false | false |
tateisu/SubwayTooter | app/src/main/java/jp/juggler/subwaytooter/MyAppGlideModule.kt | 1 | 4194 | package jp.juggler.subwaytooter
import android.content.Context
import android.graphics.drawable.PictureDrawable
import androidx.annotation.Nullable
import com.bumptech.glide.Glide
import com.bumptech.glide.GlideBuilder
import com.bumptech.glide.Registry
import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.load.Options
import com.bumptech.glide.load.ResourceDecoder
import com.bumptech.glide.load.engine.Resource
import com.bumptech.glide.load.resource.SimpleResource
import com.bumptech.glide.load.resource.transcode.ResourceTranscoder
import com.bumptech.glide.module.AppGlideModule
import com.caverock.androidsvg.SVG
import com.caverock.androidsvg.SVGParseException
import java.io.IOException
import java.io.InputStream
import kotlin.math.min
@GlideModule
class MyAppGlideModule : AppGlideModule() {
companion object {
private val svgSig = "<svg".toByteArray(Charsets.UTF_8)
private fun findBytes(data: ByteArray, dataSize: Int = data.size, key: ByteArray): Int {
fun check(start: Int): Boolean {
for (j in key.indices) {
if (data[start + j] != key[j]) return false
}
return true
}
for (i in 0..dataSize - key.size) {
if (check(i)) return i
}
return -1
}
}
// Decodes an SVG internal representation from an [InputStream].
inner class SvgDecoder : ResourceDecoder<InputStream, SVG> {
@Throws(IOException::class)
override fun handles(source: InputStream, options: Options): Boolean {
val size = min(source.available(), 1024)
if (size <= 0) return false
val buf = ByteArray(size)
val nRead = source.read(buf, 0, size)
return -1 != findBytes(buf, nRead, svgSig)
}
@Throws(IOException::class)
override fun decode(
source: InputStream,
width: Int,
height: Int,
options: Options,
): Resource<SVG> {
try {
val svg = SVG.getFromInputStream(source)
return SimpleResource(svg)
} catch (ex: SVGParseException) {
throw IOException("Cannot load SVG from stream", ex)
}
}
}
// Convert the [SVG]'s internal representation to an Android-compatible one ([Picture]).
class SvgDrawableTranscoder : ResourceTranscoder<SVG, PictureDrawable> {
@Nullable
override fun transcode(
toTranscode: Resource<SVG>,
options: Options,
): Resource<PictureDrawable> {
val svg = toTranscode.get()
val picture = svg.renderToPicture()
val drawable = PictureDrawable(picture)
return SimpleResource(drawable)
}
}
// v3との互換性のためにAndroidManifestを読むかどうか(デフォルトtrue)
override fun isManifestParsingEnabled(): Boolean {
return false
}
override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
// デフォルト実装は何もしないらしい
super.registerComponents(context, glide, registry)
// App1を初期化してからOkHttp3Factoryと連動させる
App1.prepare(context.applicationContext, "MyAppGlideModule.registerComponents()")
App1.registerGlideComponents(context, glide, registry)
//SVGデコーダーの追加
registry
.register(SVG::class.java, PictureDrawable::class.java, SvgDrawableTranscoder())
.append(InputStream::class.java, SVG::class.java, SvgDecoder())
}
override fun applyOptions(context: Context, builder: GlideBuilder) {
// デフォルト実装は何もしないらしい
super.applyOptions(context, builder)
// App1を初期化してから色々する
App1.prepare(context.applicationContext, "MyAppGlideModule.applyOptions()")
App1.applyGlideOptions(context, builder)
}
}
| apache-2.0 | bf3c2bf7e38436e391dce597db66c5de | 32.956522 | 96 | 0.628607 | 4.37432 | false | false | false | false |
Gark/bassblog_kotlin | app/src/main/java/pixel/kotlin/bassblog/service/PlaybackService.kt | 1 | 8383 | package pixel.kotlin.bassblog.service
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.net.wifi.WifiManager
import android.os.Binder
import android.os.Build
import android.os.IBinder
import android.support.annotation.RequiresApi
import android.support.v4.app.NotificationCompat
import android.support.v4.content.ContextCompat
import android.widget.RemoteViews
import com.squareup.picasso.Picasso
import pixel.kotlin.bassblog.R
import pixel.kotlin.bassblog.network.Mix
import pixel.kotlin.bassblog.player.Player
import pixel.kotlin.bassblog.ui.PagerActivity
private const val CHANNEL_ID = "channel_id"
class PlaybackService : Service(), IPlayback, IPlayback.PlayerCallback {
private val ACTION_PLAY_TOGGLE = "pixel.kotlin.bassblog.ACTION.PLAY_TOGGLE"
private val ACTION_PLAY_LAST = "pixel.kotlin.bassblog.ACTION.PLAY_LAST"
private val ACTION_PLAY_NEXT = "pixel.kotlin.bassblog.ACTION.PLAY_NEXT"
private val ACTION_STOP_SERVICE = "pixel.kotlin.bassblog.ACTION.STOP_SERVICE"
private val NOTIFICATION_ID = 1
private var mPlayer: Player? = null
private val mBinder = LocalBinder()
inner class LocalBinder : Binder() {
val service: PlaybackService
get() = this@PlaybackService
}
override fun onBind(intent: Intent?): IBinder? = mBinder
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
handleRemoteAction(intent?.action)
return START_NOT_STICKY
}
private fun handleRemoteAction(action: String?) {
when (action) {
ACTION_PLAY_LAST -> playLast()
ACTION_PLAY_NEXT -> playNext()
ACTION_STOP_SERVICE -> stopThePlanet()
ACTION_PLAY_TOGGLE -> toggle()
}
}
override fun requestDataOnBind() {
mPlayer?.requestData()
}
private fun stopThePlanet() {
mPlayer?.pause()
stopForeground(true)
stopSelf()
android.os.Process.killProcess(android.os.Process.myPid())
}
override fun onDestroy() {
mPlayer?.pause()
mPlayer?.releasePlayer()
unregisterCallback(this)
super.onDestroy()
}
//------------------------------------------------------------------------------------------------------------//
override fun onCreate() {
super.onCreate()
val wifi = applicationContext.getSystemService(Context.WIFI_SERVICE)
mPlayer = Player(wifi as WifiManager, applicationContext)
registerCallback(this)
}
override fun toggle() = mPlayer!!.toggle()
override fun play(mix: Mix, tab: Int) = mPlayer!!.play(mix, tab)
override fun playLast() {
mPlayer?.playLast()
}
override fun playNext() = mPlayer!!.playNext()
override fun getPlayingState(): Int = mPlayer!!.getPlayingState()
override fun getPlayingMix(): Mix? = mPlayer!!.getPlayingMix()
override fun seekTo(progress: Int) = mPlayer!!.seekTo(progress)
override fun registerCallback(callback: IPlayback.PlayerCallback) {
mPlayer?.registerCallback(callback)
}
override fun unregisterCallback(callback: IPlayback.PlayerCallback) {
mPlayer?.unregisterCallback(callback)
}
override fun releasePlayer() {
// do nothing
}
override fun onTick(progress: Int, duration: Int, secondaryProgress: Int) {
// do nothing
}
override fun onPlayStatusChanged(state: Int) = showNotification()
// Notification
/**
* Show a notification while this service is running.
*/
private var mContentViewBig: RemoteViews? = null
private var mContentViewSmall: RemoteViews? = null
private fun showNotification() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createNotificationChannel(applicationContext)
}
// The PendingIntent to launch our activity if the user selects this notification
val contentIntent = PendingIntent.getActivity(this, 0, Intent(this, PagerActivity::class.java), 0)
// Set the info for the views that show in the notification panel.
val small = getSmallContentView()
val big = getBigContentView()
val notification = NotificationCompat.Builder(applicationContext, CHANNEL_ID)
// val notification = NotificationCompat.Builder(this)
.setSmallIcon(
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
R.mipmap.ic_launcher
} else {
R.drawable.ic_bb_mixes_new
}
)
.setContentIntent(contentIntent) // The intent to send when the entry is clicked
.setCustomContentView(small)
.setCustomBigContentView(big)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setOngoing(true)
.build()
val mix = mPlayer?.getPlayingMix()
mix?.image?.let {
Picasso.with(applicationContext)
.load(mix.image)
.into(small, R.id.image_view_album, NOTIFICATION_ID, notification)
Picasso.with(applicationContext)
.load(mix.image)
.into(big, R.id.image_view_album, NOTIFICATION_ID, notification)
}
// Send the notification.
startForeground(NOTIFICATION_ID, notification)
}
private fun getBigContentView(): RemoteViews? {
if (mContentViewBig == null) {
mContentViewBig = RemoteViews(packageName, R.layout.remote_view_music_player)
setUpRemoteView(mContentViewBig)
}
updateRemoteViews(mContentViewBig as RemoteViews)
return mContentViewBig
}
private fun getSmallContentView(): RemoteViews? {
if (mContentViewSmall == null) {
mContentViewSmall = RemoteViews(packageName, R.layout.remote_view_music_player_small)
setUpRemoteView(mContentViewSmall)
}
updateRemoteViews(mContentViewSmall as RemoteViews)
return mContentViewSmall
}
private fun setUpRemoteView(remoteView: RemoteViews?) {
remoteView?.setImageViewResource(R.id.image_view_close, R.drawable.ic_remote_view_close)
remoteView?.setImageViewResource(R.id.image_view_play_last, R.drawable.ic_previous_mix)
remoteView?.setImageViewResource(R.id.image_view_play_next, R.drawable.ic_next_mix)
remoteView?.setOnClickPendingIntent(R.id.button_close, getPendingIntent(ACTION_STOP_SERVICE))
remoteView?.setOnClickPendingIntent(R.id.button_play_last, getPendingIntent(ACTION_PLAY_LAST))
remoteView?.setOnClickPendingIntent(R.id.button_play_next, getPendingIntent(ACTION_PLAY_NEXT))
remoteView?.setOnClickPendingIntent(R.id.button_play_toggle, getPendingIntent(ACTION_PLAY_TOGGLE))
}
private fun updateRemoteViews(remoteView: RemoteViews) {
val mix = mPlayer!!.getPlayingMix()
remoteView.setTextViewText(R.id.text_view_name, mix?.title)
remoteView.setTextViewText(R.id.text_view_artist, mix?.label)
remoteView.setImageViewResource(R.id.image_view_play_toggle,
when (mPlayer!!.getPlayingState()) {
Player.PLAYING -> R.drawable.ic_pause
Player.NOT_PLAYING -> R.drawable.ic_play
else -> R.drawable.ic_play // TODO
})
}
private fun getPendingIntent(action: String): PendingIntent = PendingIntent.getService(this, 0, Intent(action), 0)
@RequiresApi(api = Build.VERSION_CODES.O)
private fun createNotificationChannel(context: Context) {
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val channelName = "BassBlog Channel"
val importance = NotificationManager.IMPORTANCE_LOW
val notificationChannel = NotificationChannel(CHANNEL_ID, channelName, importance)
// notificationChannel.enableLights(true)
// notificationChannel.lightColor = ContextCompat.getColor(context, R.color.colorPrimary)
notificationManager.createNotificationChannel(notificationChannel)
}
}
| agpl-3.0 | 102d32a14c0bc96668b83cfc51615924 | 36.257778 | 118 | 0.661696 | 4.714848 | false | false | false | false |
Seancheey/Ark-Sonah | src/com/seancheey/game/model/RobotModel.kt | 1 | 10396 | package com.seancheey.game.model
import com.seancheey.game.*
import com.seancheey.resources.Resources
import javafx.scene.image.Image
import javafx.scene.image.PixelWriter
import javafx.scene.image.WritableImage
/**
* Created by Seancheey on 23/05/2017.
* GitHub: https://github.com/Seancheey
*/
/**
* Designed as an immutable class as robot model
*/
@Suppress("VAL_REASSIGNMENT_VIA_BACKING_FIELD")
open class RobotModel(var name: String, val components: List<ComponentNode>) : Model {
override final val actionTree: ActionTree = ActionTree(Action.MOVE_ACTION to Action.moveAction())
override val width: Double
get() = Config.botPixelSize
override val height: Double
get() = Config.botPixelSize
@Suppress("SENSELESS_COMPARISON")
@Transient final
override val image: Image = immutableImage()
get() {
if (field == null) {
field = immutableImage()
}
return field
}
@Suppress("SENSELESS_COMPARISON")
@Transient
val idleImage: Image = idleImage()
get() {
if (field == null) {
field = idleImage()
}
return field
}
val price: Int
val maxSpeed: Double
val maxAcceleration: Double
val turnSpeed: Double
val health: Int
val weight: Int
val empty: Boolean
get() = components.isEmpty()
val valid: Boolean
get() = _valid
private var _valid: Boolean = false
get() {
if (!field) {
verify()
}
return field
}
init {
val movementModels = components.filter { it.type == ComponentType.movement }.map { it.getModel<MovementModel>()!! }
val allModels = components.map { it.model }
health = allModels.sumBy { it.health }
weight = allModels.sumBy { it.weight }
price = allModels.sumBy { it.price }
maxSpeed = movementModels.sumByDouble { it.force }
maxAcceleration = movementModels.sumByDouble { it.force } / 20
turnSpeed = movementModels.sumByDouble { it.turn }
}
constructor() : this("", arrayListOf())
private fun immutableImage(): WritableImage {
val writeImage = WritableImage(Config.botPixelSize.toInt(), Config.botPixelSize.toInt())
val writer = writeImage.pixelWriter
components
.filter { it.type != ComponentType.weapon }
.forEach { writer.setPixels(it) }
return writeImage
}
/**
* write a image to pixel writer
*/
private fun PixelWriter.setPixels(node: ComponentNode) {
val x = node.leftX.toInt()
val y = node.upperY.toInt()
val image = node.image
val reader = image.pixelReader
for (readY in 0 until image.height.toInt()) {
for (readX in 0 until image.width.toInt()) {
val color = reader.getColor(readX, readY)
if (color.isOpaque) {
val xPos = x + readX
val yPos = y + readY
setColor(xPos, yPos, color)
}
}
}
}
private fun idleImage(): Image {
// return "no robot" image if there is no components in robot
if (components.isEmpty()) {
return Image(Resources.noRobotImageInStream)
}
// add all moving mutableNodes to immutableImage
val writableImage = immutableImage()
val writer = writableImage.pixelWriter
components.forEach { writer.setPixels(it) }
return writableImage
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is RobotModel) return false
if (name != other.name) return false
if (components != other.components) return false
if (maxSpeed != other.maxSpeed) return false
if (maxAcceleration != other.maxAcceleration) return false
if (turnSpeed != other.turnSpeed) return false
if (health != other.health) return false
if (weight != other.weight) return false
return true
}
override fun hashCode(): Int {
var result = name.hashCode()
result = 31 * result + components.hashCode()
result = 31 * result + maxSpeed.hashCode()
result = 31 * result + maxAcceleration.hashCode()
result = 31 * result + turnSpeed.hashCode()
result = 31 * result + health
result = 31 * result + weight
return result
}
fun verify(): List<WrongMessage> {
return Verifier().verify()
}
data class Point(val x: Int, val y: Int)
data class WrongMessage(val message: String, val points: ArrayList<Point> = arrayListOf())
private inner class Verifier {
private val verifyList: ArrayList<() -> WrongMessage?> = arrayListOf()
init {
verifyList.add { verifyMovements() }
verifyList.add { verifyOverlap() }
verifyList.add { verifyConnection() }
verifyList.add { verifyWeaponConnection() }
}
fun verifyWeaponConnection(): WrongMessage? {
val wrongPoints = arrayListOf<Point>()
components.filter { it.type == ComponentType.weapon }.forEach { weapon ->
val hasMount: Boolean = components.filter { Attribute.weapon_mount in it.model.attributes }.filter { it.gridX == weapon.gridX }.any { mount ->
mount.gridY - weapon.gridY == (weapon.model.gridHeight - mount.model.gridHeight) / 2
}
if (!hasMount) {
wrongPoints.addAll(weapon.allPoints())
}
}
if (wrongPoints.isEmpty()) {
return null
} else {
return WrongMessage("Weapon not connected to a mount", wrongPoints)
}
}
fun verifyMovements(): WrongMessage? {
if (components.isEmpty()) return null
if (components.any { it.type == ComponentType.movement }) return null else return WrongMessage("The robot can't move! put some movement components")
}
fun verifyOverlap(): WrongMessage? {
val overlapPoints: ArrayList<Point> = arrayListOf()
val pointMap: HashMap<Point, ComponentNode> = hashMapOf()
for (comp in components) {
// record all point that the component has
val points: ArrayList<Point> = arrayListOf()
for (y in comp.gridY until comp.gridY + comp.model.gridHeight) {
(comp.gridX until comp.gridX + comp.model.gridWidth).mapTo(points) { x -> Point(x, y) }
}
for (point in points) {
if (pointMap.containsKey(point)) {
// except for weapon & mount
if (comp.model.attributes.contains(Attribute.weapon_mount) && pointMap[point]!!.model is WeaponModel) {
continue
}
if (pointMap[point]!!.model.attributes.contains(Attribute.weapon_mount) && comp.model is WeaponModel) {
continue
}
if (!overlapPoints.contains(point))
overlapPoints.add(point)
} else {
pointMap.put(point, comp)
}
}
}
if (overlapPoints.isEmpty()) return null else return WrongMessage("Overlapped components found", overlapPoints)
}
fun verifyConnection(): WrongMessage? {
if (components.size <= 1) {
return null
}
val disconnectedPoints = arrayListOf<Point>()
var remainingNode = components.map { it }
val connectionGroup = arrayListOf<List<ComponentNode>>()
while (remainingNode.isNotEmpty()) {
val newGroup = allConnectedComponents(remainingNode[0])
connectionGroup.add(newGroup)
remainingNode = remainingNode.filter { it !in newGroup }
}
val largestGroup = connectionGroup.maxBy { it.size }
connectionGroup.filter { it != largestGroup }.forEach {
for (comp in it) disconnectedPoints.addAll(comp.allPoints())
}
if (disconnectedPoints.isEmpty()) return null else return WrongMessage("Disconnect component found", disconnectedPoints)
}
fun allConnectedComponents(me: ComponentNode, connectedList: ArrayList<ComponentNode> = arrayListOf(me)): ArrayList<ComponentNode> {
var conList = connectedList
val newNodes = arrayListOf<ComponentNode>()
for (other in components.filter { it != me && it !in conList }) {
if (other.adjacentWith(me)) {
conList.add(other)
newNodes.add(other)
}
}
for (node in newNodes) {
conList = allConnectedComponents(node, conList)
}
return conList
}
fun ComponentNode.adjacentWith(other: ComponentNode): Boolean {
val myList = allPoints()
val otherList = other.allPoints()
for ((x1, y1) in myList) {
for ((x2, y2) in otherList) {
if (x1 == x2) {
if (y1 - y2 <= 1 && y2 - y1 <= 1) {
return true
}
} else if (y1 == y2) {
if (x1 - x2 <= 1 && x2 - x1 <= 1) {
return true
}
}
}
}
return false
}
fun ComponentNode.allPoints(): ArrayList<Point> {
val pointList = arrayListOf<Point>()
for (y in gridY until gridY + model.gridHeight) {
for (x in gridX until gridX + model.gridWidth) {
pointList.add(Point(x, y))
}
}
return pointList
}
fun verify(): List<WrongMessage> {
val messages = verifyList.mapNotNull { it() }
_valid = messages.isEmpty()
return messages
}
}
}
| mit | d4ca4507906d297a22addcda53ef3197 | 36.128571 | 160 | 0.548192 | 4.770996 | false | false | false | false |
google/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/settings/MarkdownSettingsConfigurable.kt | 5 | 12381 | // 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.settings
import com.intellij.ide.highlighter.HighlighterFactory
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.EditorSettings
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.fileEditor.TextEditorWithPreview
import com.intellij.openapi.fileTypes.FileTypeManager
import com.intellij.openapi.fileTypes.UnknownFileType
import com.intellij.openapi.options.BoundSearchableConfigurable
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.ui.EnumComboBoxModel
import com.intellij.ui.SimpleListCellRenderer
import com.intellij.ui.components.ActionLink
import com.intellij.ui.components.JBCheckBox
import com.intellij.ui.dsl.builder.*
import com.intellij.ui.dsl.builder.Cell
import com.intellij.ui.dsl.builder.Row
import com.intellij.ui.dsl.builder.panel
import com.intellij.ui.dsl.gridLayout.HorizontalAlign
import com.intellij.ui.layout.*
import com.intellij.util.application
import org.intellij.plugins.markdown.MarkdownBundle
import org.intellij.plugins.markdown.extensions.*
import org.intellij.plugins.markdown.extensions.jcef.commandRunner.CommandRunnerExtension
import org.intellij.plugins.markdown.settings.pandoc.PandocSettingsPanel
import org.intellij.plugins.markdown.ui.preview.MarkdownHtmlPanelProvider
import org.jetbrains.annotations.Nls
import javax.swing.DefaultComboBoxModel
class MarkdownSettingsConfigurable(private val project: Project): BoundSearchableConfigurable(
MarkdownBundle.message("markdown.settings.name"),
MarkdownBundle.message("markdown.settings.name"),
_id = ID
) {
private val settings
get() = MarkdownSettings.getInstance(project)
private var customStylesheetEditor: Editor? = null
private fun isPreviewAvailable(): Boolean {
return MarkdownHtmlPanelProvider.hasAvailableProviders()
}
private fun previewDependentOptionsBlock(block: () -> Unit) {
if (isPreviewAvailable()) {
block.invoke()
}
}
private fun Panel.showPreviewUnavailableWarningIfNeeded() {
if (!isPreviewAvailable()) {
row {
label(MarkdownBundle.message("markdown.settings.no.providers"))
}
}
}
override fun createPanel(): DialogPanel {
return panel {
showPreviewUnavailableWarningIfNeeded()
previewDependentOptionsBlock {
if (MarkdownHtmlPanelProvider.getAvailableProviders().size > 1) {
htmlPanelProvidersRow()
}
row(MarkdownBundle.message("markdown.settings.default.layout")) {
comboBox(
model = EnumComboBoxModel(TextEditorWithPreview.Layout::class.java),
renderer = SimpleListCellRenderer.create("") { it?.getName() ?: "" }
).bindItem(settings::splitLayout.toNullableProperty())
}
row(MarkdownBundle.message("markdown.settings.preview.layout.label")) {
comboBox(
model = DefaultComboBoxModel(arrayOf(false, true)),
renderer = SimpleListCellRenderer.create("", ::presentSplitLayout)
).bindItem(settings::isVerticalSplit.toNullableProperty())
}.bottomGap(BottomGap.SMALL)
row {
checkBox(MarkdownBundle.message("markdown.settings.preview.auto.scroll.checkbox"))
.bindSelected(settings::isAutoScrollEnabled)
}
}
row {
checkBox(MarkdownBundle.message("markdown.settings.enable.injections"))
.bindSelected(settings::areInjectionsEnabled)
}
row {
checkBox(MarkdownBundle.message("markdown.settings.enable.enhance.editing.experience"))
.bindSelected(settings::isEnhancedEditingEnabled)
}
row {
checkBox(MarkdownBundle.message("markdown.settings.show.problems"))
.bindSelected(settings::showProblemsInCodeBlocks)
}
row {
checkBox(MarkdownBundle.message("markdown.settings.commandrunner.text")).apply {
bindSelected(
getter = { CommandRunnerExtension.isExtensionEnabled() },
setter = { MarkdownExtensionsSettings.getInstance().extensionsEnabledState[CommandRunnerExtension.extensionId] = it }
)
onApply { notifyExtensionsChanged() }
}
}.bottomGap(BottomGap.SMALL)
extensionsListRow().apply {
onApply { notifyExtensionsChanged() }
}
previewDependentOptionsBlock {
customCssRow()
}
pandocSettingsRow()
}
}
private fun notifyExtensionsChanged() {
val publisher = application.messageBus.syncPublisher(MarkdownExtensionsSettings.ChangeListener.TOPIC)
publisher.extensionsSettingsChanged(fromSettingsDialog = true)
}
private fun Panel.htmlPanelProvidersRow(): Row {
return row(MarkdownBundle.message("markdown.settings.preview.providers.label")) {
val providers = MarkdownHtmlPanelProvider.getProviders().map { it.providerInfo }
comboBox(model = DefaultComboBoxModel(providers.toTypedArray()))
.bindItem(settings::previewPanelProviderInfo.toNullableProperty())
}
}
private fun validateCustomStylesheetPath(builder: ValidationInfoBuilder, textField: TextFieldWithBrowseButton): ValidationInfo? {
return builder.run {
val fieldText = textField.text
when {
!FileUtil.exists(fieldText) -> error(MarkdownBundle.message("dialog.message.path.error", fieldText))
else -> null
}
}
}
private fun Panel.customCssRow() {
collapsibleGroup(MarkdownBundle.message("markdown.settings.css.title.name")) {
row {
val externalCssCheckBox = checkBox(MarkdownBundle.message("markdown.settings.external.css.path.label"))
.bindSelected(settings::useCustomStylesheetPath)
.gap(RightGap.SMALL)
textFieldWithBrowseButton()
.applyToComponent {
text = settings.customStylesheetPath ?: ""
}
.horizontalAlign(HorizontalAlign.FILL)
.enabledIf(externalCssCheckBox.selected)
.applyIfEnabled()
.validationOnInput(::validateCustomStylesheetPath)
.validationOnApply(::validateCustomStylesheetPath)
.apply {
onApply { settings.customStylesheetPath = component.text.takeIf { externalCssCheckBox.component.isSelected } }
onIsModified { externalCssCheckBox.component.isSelected && settings.customStylesheetPath != component.text }
}
}
lateinit var editorCheckbox: Cell<JBCheckBox>
row {
editorCheckbox = checkBox(MarkdownBundle.message("markdown.settings.custom.css.text.label"))
.bindSelected(settings::useCustomStylesheetText)
.applyToComponent {
addActionListener { setEditorReadonlyState(isReadonly = !isSelected) }
}
}
row {
val editor = createCustomStylesheetEditor()
cell(editor.component)
.horizontalAlign(HorizontalAlign.FILL)
.onApply { settings.customStylesheetText = runReadAction { editor.document.text } }
.onIsModified { settings.customStylesheetText != runReadAction { editor.document.text.takeIf { it.isNotEmpty() } } }
.onReset { resetEditorText(settings.customStylesheetText ?: "") }
customStylesheetEditor = editor
setEditorReadonlyState(isReadonly = !editorCheckbox.component.isSelected)
}
}
}
private fun setEditorReadonlyState(isReadonly: Boolean) {
customStylesheetEditor?.let {
it.document.setReadOnly(isReadonly)
it.contentComponent.isEnabled = !isReadonly
}
}
private fun Panel.pandocSettingsRow() {
collapsibleGroup(MarkdownBundle.message("markdown.settings.pandoc.name")) {
row {
cell(PandocSettingsPanel(project))
.horizontalAlign(HorizontalAlign.FILL)
.apply {
onApply { component.apply() }
onIsModified { component.isModified() }
onReset { component.reset() }
}
}
}
}
override fun apply() {
settings.update {
super.apply()
}
}
override fun disposeUIResources() {
customStylesheetEditor?.let(EditorFactory.getInstance()::releaseEditor)
customStylesheetEditor = null
super.disposeUIResources()
}
private fun Panel.extensionsListRow(): ButtonsGroup? {
val extensions = MarkdownExtensionsUtil.collectConfigurableExtensions()
val actualExtensions = when {
isPreviewAvailable() -> extensions
else -> extensions.filterNot { it is MarkdownBrowserPreviewExtension.Provider }
}
if (actualExtensions.none()) {
return null
}
return buttonsGroup(MarkdownBundle.message("markdown.settings.preview.extensions.name")) {
for (extension in actualExtensions) {
createExtensionEntry(extension)
}
}
}
private fun Panel.createExtensionEntry(extension: MarkdownConfigurableExtension) {
row {
val extensionsSettings = MarkdownExtensionsSettings.getInstance()
val extensionCheckBox = checkBox(text = extension.displayName).bindSelected(
{ extensionsSettings.extensionsEnabledState[extension.id] ?: false },
{ extensionsSettings.extensionsEnabledState[extension.id] = it}
).gap(RightGap.SMALL)
extensionCheckBox.enabled((extension as? MarkdownExtensionWithExternalFiles)?.isAvailable ?: true)
contextHelp(extension.description).gap(RightGap.SMALL)
if ((extension as? MarkdownExtensionWithDownloadableFiles)?.isAvailable == false) {
lateinit var installLink: Cell<ActionLink>
installLink = link(MarkdownBundle.message("markdown.settings.extension.install.label")) {
MarkdownSettingsUtil.downloadExtension(
extension,
enableAfterDownload = false
)
extensionCheckBox.enabled(extension.isAvailable)
installLink.component.isVisible = !extension.isAvailable
installLink.component.isEnabled = !extension.isAvailable
}
}
}
}
private fun createCustomStylesheetEditor(): EditorEx {
val editorFactory = EditorFactory.getInstance()
val editorDocument = editorFactory.createDocument(settings.customStylesheetText ?: "")
val editor = editorFactory.createEditor(editorDocument) as EditorEx
fillEditorSettings(editor.settings)
setEditorHighlighting(editor)
return editor
}
private fun setEditorHighlighting(editor: EditorEx) {
val cssFileType = FileTypeManager.getInstance().getFileTypeByExtension("css")
if (cssFileType === UnknownFileType.INSTANCE) {
return
}
val editorHighlighter = HighlighterFactory.createHighlighter(
cssFileType,
EditorColorsManager.getInstance().globalScheme,
null
)
editor.highlighter = editorHighlighter
}
private fun resetEditorText(cssText: String) {
customStylesheetEditor?.let { editor ->
if (!editor.isDisposed) {
runWriteAction {
val writable = editor.document.isWritable
editor.document.setReadOnly(false)
editor.document.setText(cssText)
editor.document.setReadOnly(!writable)
}
}
}
}
private fun fillEditorSettings(editorSettings: EditorSettings) {
with(editorSettings) {
isWhitespacesShown = false
isLineMarkerAreaShown = false
isIndentGuidesShown = false
isLineNumbersShown = true
isFoldingOutlineShown = false
additionalColumnsCount = 1
additionalLinesCount = 3
isUseSoftWraps = false
}
}
companion object {
const val ID = "Settings.Markdown"
private fun presentSplitLayout(splitLayout: Boolean?): @Nls String {
return when (splitLayout) {
false -> MarkdownBundle.message("markdown.settings.preview.layout.horizontal")
true -> MarkdownBundle.message("markdown.settings.preview.layout.vertical")
else -> ""
}
}
}
}
| apache-2.0 | 6568e4978b00105fdd43fbcf76c824f5 | 37.811912 | 158 | 0.714159 | 4.998385 | false | false | false | false |
RuneSuite/client | updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/StructType.kt | 1 | 2371 | package org.runestar.client.updater.mapper.std.classes
import org.runestar.client.common.startsWith
import org.objectweb.asm.Opcodes.PUTFIELD
import org.objectweb.asm.Type.INT_TYPE
import org.objectweb.asm.Type.VOID_TYPE
import org.runestar.client.updater.mapper.IdentityMapper
import org.runestar.client.updater.mapper.DependsOn
import org.runestar.client.updater.mapper.MethodParameters
import org.runestar.client.updater.mapper.and
import org.runestar.client.updater.mapper.predicateOf
import org.runestar.client.updater.mapper.type
import org.runestar.client.updater.mapper.Class2
import org.runestar.client.updater.mapper.Field2
import org.runestar.client.updater.mapper.Method2
@DependsOn(DualNode::class, IterableNodeHashTable::class)
class StructType : IdentityMapper.Class() {
override val predicate = predicateOf<Class2> { it.superType == type<DualNode>() }
.and { it.instanceFields.size == 1 }
.and { it.instanceFields.all { it.type == type<IterableNodeHashTable>() } }
@DependsOn(IterableNodeHashTable::class)
class params : IdentityMapper.InstanceField() {
override val predicate = predicateOf<Field2> { it.type == type<IterableNodeHashTable>() }
}
@MethodParameters()
class postDecode : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.arguments.isEmpty() }
}
@DependsOn(Packet::class)
class decode : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.arguments.startsWith(type<Packet>()) }
.and { it.instructions.none { it.opcode == PUTFIELD } }
}
@DependsOn(Packet::class)
class decode0 : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.arguments.startsWith(type<Packet>()) }
.and { it.instructions.any { it.opcode == PUTFIELD } }
}
class getIntParam : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == INT_TYPE }
}
class getStringParam : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == String::class.type }
}
} | mit | 65f204d6c39a85f3ee998b5b4ceea099 | 41.357143 | 97 | 0.706031 | 4.226381 | false | false | false | false |
google/intellij-community | platform/vcs-impl/src/com/intellij/vcs/commit/SingleChangeListCommitWorkflowHandler.kt | 2 | 5202 | // 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.vcs.commit
import com.intellij.openapi.Disposable
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vcs.CheckinProjectPanel
import com.intellij.openapi.vcs.changes.ChangeListManager
import com.intellij.openapi.vcs.changes.ChangesUtil.getAffectedVcses
import com.intellij.openapi.vcs.changes.ChangesUtil.getAffectedVcsesForFilePaths
import com.intellij.openapi.vcs.changes.CommitExecutor
import com.intellij.openapi.vcs.impl.LineStatusTrackerManager
class SingleChangeListCommitWorkflowHandler(
override val workflow: CommitChangeListDialogWorkflow,
override val ui: SingleChangeListCommitWorkflowUi
) : AbstractCommitWorkflowHandler<CommitChangeListDialogWorkflow, SingleChangeListCommitWorkflowUi>(),
CommitWorkflowUiStateListener,
SingleChangeListCommitWorkflowUi.ChangeListListener {
override val commitPanel: CheckinProjectPanel = object : CommitProjectPanelAdapter(this) {
override fun setCommitMessage(currentDescription: String?) {
commitMessagePolicy.defaultNameChangeListMessage = currentDescription
super.setCommitMessage(currentDescription)
}
}
override val amendCommitHandler: AmendCommitHandlerImpl = AmendCommitHandlerImpl(this)
private fun getChangeList() = ui.getChangeList()
private fun getCommitState() = ChangeListCommitState(getChangeList(), getIncludedChanges(), getCommitMessage())
private val commitMessagePolicy get() = workflow.commitMessagePolicy
init {
Disposer.register(this, Disposable { workflow.disposeCommitOptions() })
Disposer.register(ui, this)
workflow.addListener(this, this)
workflow.addCommitCustomListener(CommitCustomListener(), this)
ui.addStateListener(this, this)
ui.addExecutorListener(this, this)
ui.addDataProvider(createDataProvider())
ui.addChangeListListener(this, this)
}
fun activate(): Boolean {
initCommitHandlers()
ui.addInclusionListener(this, this)
updateDefaultCommitActionName()
initCommitMessage()
initCommitOptions()
amendCommitHandler.initialMessage = getCommitMessage()
return ui.activate()
}
override fun cancelled() {
commitOptions.saveChangeListSpecificOptions()
saveCommitMessage(false)
LineStatusTrackerManager.getInstanceImpl(project).resetExcludedFromCommitMarkers()
}
override fun changeListChanged() {
updateCommitMessage()
updateCommitOptions()
}
override fun beforeCommitChecksEnded(sessionInfo: CommitSessionInfo, result: CommitChecksResult) {
super.beforeCommitChecksEnded(sessionInfo, result)
if (result.shouldCommit) {
// commit message could be changed during before-commit checks - ensure updated commit message is used for commit
workflow.commitState = workflow.commitState.copy(getCommitMessage())
if (sessionInfo.isVcsCommit) ui.deactivate()
}
}
override fun isExecutorEnabled(executor: CommitExecutor): Boolean =
super.isExecutorEnabled(executor) && (!executor.areChangesRequired() || !isCommitEmpty())
override fun checkCommit(sessionInfo: CommitSessionInfo): Boolean =
super.checkCommit(sessionInfo) &&
(
getCommitMessage().isNotEmpty() ||
ui.confirmCommitWithEmptyMessage()
)
override fun updateWorkflow(sessionInfo: CommitSessionInfo): Boolean {
workflow.commitState = getCommitState()
return configureCommitSession(project, sessionInfo,
workflow.commitState.changes,
workflow.commitState.commitMessage)
}
override fun prepareForCommitExecution(sessionInfo: CommitSessionInfo): Boolean {
if (sessionInfo.isVcsCommit) {
if (!addUnversionedFiles(project, getIncludedUnversionedFiles(), getChangeList(), ui.getInclusionModel())) return false
}
return super.prepareForCommitExecution(sessionInfo)
}
private fun initCommitMessage() {
commitMessagePolicy.init(getChangeList(), getIncludedChanges())
setCommitMessage(commitMessagePolicy.commitMessage)
}
private fun updateCommitMessage() {
commitMessagePolicy.update(getChangeList(), getCommitMessage())
setCommitMessage(commitMessagePolicy.commitMessage)
}
override fun saveCommitMessage(success: Boolean) = commitMessagePolicy.save(getCommitState(), success)
private fun initCommitOptions() {
workflow.initCommitOptions(createCommitOptions())
ui.commitOptionsUi.setOptions(commitOptions)
commitOptions.restoreState()
updateCommitOptions()
}
private fun updateCommitOptions() {
commitOptions.changeListChanged(getChangeList())
updateCommitOptionsVisibility()
}
private fun updateCommitOptionsVisibility() {
val unversionedFiles = ChangeListManager.getInstance(project).unversionedFilesPaths
val vcses = getAffectedVcses(getChangeList().changes, project) + getAffectedVcsesForFilePaths(unversionedFiles, project)
ui.commitOptionsUi.setVisible(vcses)
}
private inner class CommitCustomListener : CommitterResultHandler {
override fun onSuccess() = ui.deactivate()
}
} | apache-2.0 | a0d7038a0d8c83626c2b2cef8a156e0a | 35.384615 | 140 | 0.774702 | 5.281218 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ConvertNaNEqualityInspection.kt | 1 | 2817 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
class ConvertNaNEqualityInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return binaryExpressionVisitor { expression ->
if (expression.left.isNaNExpression() || expression.right.isNaNExpression()) {
val inverted = when (expression.operationToken) {
KtTokens.EXCLEQ -> true
KtTokens.EQEQ -> false
else -> return@binaryExpressionVisitor
}
holder.registerProblem(
expression,
KotlinBundle.message("equality.check.with.nan.should.be.replaced.with.isnan"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
ConvertNaNEqualityQuickFix(inverted)
)
}
}
}
}
private class ConvertNaNEqualityQuickFix(val inverted: Boolean) : LocalQuickFix {
override fun getName() = KotlinBundle.message("convert.na.n.equality.quick.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement as? KtBinaryExpression ?: return
val other = when {
element.left.isNaNExpression() -> element.right ?: return
element.right.isNaNExpression() -> element.left ?: return
else -> return
}
val pattern = if (inverted) "!$0.isNaN()" else "$0.isNaN()"
element.replace(KtPsiFactory(project).createExpressionByPattern(pattern, other))
}
}
private val NaNSet = setOf("kotlin.Double.Companion.NaN", "java.lang.Double.NaN", "kotlin.Float.Companion.NaN", "java.lang.Float.NaN")
private fun KtExpression?.isNaNExpression(): Boolean {
if (this?.text?.endsWith("NaN") != true) return false
val fqName = this.resolveToCall()?.resultingDescriptor?.fqNameUnsafe?.asString()
return NaNSet.contains(fqName)
}
| apache-2.0 | e2f7562237a9c27321e574f355b68988 | 43.714286 | 134 | 0.70536 | 4.873702 | false | false | false | false |
Atsky/haskell-idea-plugin | plugin/src/org/jetbrains/cabal/CabalInterface.kt | 1 | 9787 | package org.jetbrains.cabal
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.Document
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ToolWindowId
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.ui.content.Content
import com.intellij.ui.content.ContentFactory
import com.intellij.ui.content.MessageView
import org.jetbrains.cabal.tool.CabalMessageView
import org.jetbrains.haskell.util.ProcessRunner
import javax.swing.*
import java.io.IOException
import com.intellij.openapi.util.Key
import com.intellij.notification.Notifications
import com.intellij.notification.Notification
import com.intellij.notification.NotificationType
import com.intellij.psi.PsiFile
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.module.Module
import com.intellij.psi.PsiManager
import java.util.ArrayList
import java.util.TreeMap
import org.jetbrains.haskell.util.*
import java.io.File
import java.util.LinkedList
import com.intellij.openapi.util.SystemInfo
import org.jetbrains.haskell.config.HaskellSettings
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.psi.PsiElement
private val KEY: Key<CabalMessageView> = Key.create("CabalMessageView.KEY")
class CabalPackageShort(
val name: String,
val availableVersions: List<String>,
val isInstalled: Boolean)
val cabalLock = Object()
class CabalInterface(val project: Project) {
companion object {
fun findCabal(module: Module): VirtualFile? {
val children = module.moduleFile?.parent?.children
var cabalFile: VirtualFile? = null
if (children != null) {
for (file in children) {
if ("cabal" == file.extension) {
cabalFile = file
break
}
}
}
if (cabalFile != null) {
return cabalFile
}
return null
}
fun findCabal(file: PsiElement): VirtualFile? {
val module = ModuleUtilCore.findModuleForPsiElement(file)
return findCabal(module!!)
}
}
fun getProgramPath(): String {
return HaskellSettings.getInstance().state.cabalPath!!
}
fun getDataPath(): String {
return HaskellSettings.getInstance().state.cabalDataPath!!
}
private fun runCommand(canonicalPath: String, vararg commands: String): Process {
val command = LinkedList<String>()
command.add(getProgramPath())
for (c in commands) {
command.add(c)
}
val process = ProcessRunner(canonicalPath).getProcess(command)
ApplicationManager.getApplication()!!.invokeLater({
val ijMessageView = MessageView.SERVICE.getInstance(project)!!
for (content in ijMessageView.contentManager!!.contents) {
val cabalMessageView = content.getUserData(KEY)
if (cabalMessageView != null) {
ijMessageView.contentManager?.removeContent(content, true)
}
}
val cabalMessageView = CabalMessageView(project, process)
val content: Content = ContentFactory.SERVICE.getInstance()!!.createContent(cabalMessageView.component, "Cabal console", true)
content.putUserData(KEY, cabalMessageView)
ijMessageView.contentManager!!.addContent(content)
ijMessageView.contentManager!!.setSelectedContent(content)
val messageToolWindow = ToolWindowManager.getInstance(project)?.getToolWindow(ToolWindowId.MESSAGES_WINDOW)
messageToolWindow?.activate(null)
})
return process
}
fun checkVersion(): Boolean {
try {
ProcessRunner(null).executeOrFail(getProgramPath(), "-V")
return true
} catch (e: IOException) {
return false
}
}
fun configure(cabalFile: VirtualFile): Process {
return runCommand(cabalFile.parent!!.canonicalPath!!, "configure")
}
fun build(cabalFile: VirtualFile): Process {
return runCommand(cabalFile.parent!!.canonicalPath!!, "build")
}
fun clean(cabalFile: VirtualFile): Process {
return runCommand(cabalFile.parent!!.canonicalPath!!, "clean")
}
private fun findCabal(): String? {
for (file: VirtualFile in project.baseDir!!.children!!) {
if ("cabal".equals(file.extension)) {
val cachedDocument: Document? = FileDocumentManager.getInstance().getCachedDocument(file)
if (cachedDocument != null) {
ApplicationManager.getApplication()!!.runWriteAction(object : Runnable {
override fun run(): Unit {
FileDocumentManager.getInstance().saveDocument(cachedDocument)
}
})
}
return file.parent?.canonicalPath!!
}
}
Notifications.Bus.notify(Notification("Cabal.Error", "Cabal error", "Can't find cabal file.", NotificationType.ERROR))
return null
}
fun getPsiFile(cabalFile: VirtualFile): CabalFile {
return PsiManager.getInstance(project).findFile(cabalFile) as CabalFile
}
fun getPackagesList(): List<CabalPackageShort> {
try {
val path = joinPath(getRepo(), "00-index.cache")
val result = ArrayList<CabalPackageShort>()
val map = TreeMap<String, MutableList<String>>()
for (str in readLines(File(path))) {
val strings = str.split(' ')
if (strings[0] == "pkg:") {
val key = strings[1]
val value = strings[2]
map.getOrPut(key) { ArrayList<String>() }.add(value)
}
}
// Checking for packages installation
for ((key, value) in map) {
result.add(CabalPackageShort(key, value, false))
}
return result
} catch (e: IOException) {
Notifications.Bus.notify(Notification(
"Cabal error",
"cabal",
"Can't read cabal package list.",
NotificationType.ERROR))
return listOf()
}
}
fun getDefaultRepo() =
if (SystemInfo.isMac) {
joinPath(getDataPath(), "repo-cache")
} else {
joinPath(getDataPath(), "packages")
}
fun getRepo(): String {
val repoCache = CabalApplicationComponent.getInstance().getCabalConfiguration().remoteRepoCache
return joinPath(repoCache, "hackage.haskell.org")
}
fun getInstalledPackagesList(): List<CabalPackageShort> {
try {
val ghcPkg = if (OSUtil.isMac && File("/usr/local/bin/ghc-pkg").exists()) {
"/usr/local/bin/ghc-pkg"
} else {
"ghc-pkg"
}
var output = ProcessRunner().executeOrFail(ghcPkg, "--simple-output", "list")
if (output.startsWith("WARNING:")) {
val indexOf = output.indexOf(".\n")
if (indexOf != -1) {
val warning = output.substring(0, indexOf + 2)
Notifications.Bus.notify(Notification("Gghc.Pkg", "Warning", warning, NotificationType.INFORMATION))
output = output.substring(indexOf + 2)
}
}
val map = TreeMap<String, MutableList<String>>()
output.split("\\s".toRegex()).toTypedArray().forEach { pkgVer ->
val lastIndexOf = pkgVer.lastIndexOf('-')
if (lastIndexOf != -1) {
val pkg = pkgVer.substring(0, lastIndexOf)
val ver = pkgVer.substring(lastIndexOf + 1)
map.getOrPut(pkg) { ArrayList<String>() }.add(ver)
} else {
System.out.println(pkgVer)
}
}
val result = ArrayList<CabalPackageShort>()
for ((key, value) in map) {
result.add(CabalPackageShort(key, value, true))
}
return result
} catch (e: IOException) {
Notifications.Bus.notify(Notification("Cabal error",
"cabal",
"Can't read installed package list using ghc-pkg.",
NotificationType.ERROR))
return listOf()
}
}
fun update(): Unit {
ProgressManager.getInstance().run(object : Task.Backgroundable(project, "cabal update", false) {
override fun run(indicator: ProgressIndicator) {
synchronized(cabalLock) {
val process = runCommand(project.basePath!!.toString(), "update")
process.waitFor()
}
}
})
}
fun install(pkg: String) {
ProgressManager.getInstance().run(object : Task.Backgroundable(project, "cabal install " + pkg, false) {
override fun run(indicator: ProgressIndicator) {
synchronized(cabalLock) {
val process = runCommand(project.basePath!!.toString(), "install", pkg)
process.waitFor()
}
}
})
}
}
| apache-2.0 | 37fddc355d6a7f64b0ac6d41693b9093 | 34.078853 | 138 | 0.593645 | 5.006138 | false | false | false | false |
square/okio | okio/src/jvmMain/kotlin/okio/Throttler.kt | 1 | 6068 | /*
* Copyright (C) 2018 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okio
import java.io.IOException
import java.io.InterruptedIOException
/**
* Enables limiting of Source and Sink throughput. Attach to this throttler via [source] and [sink]
* and set the desired throughput via [bytesPerSecond]. Multiple Sources and Sinks can be
* attached to a single Throttler and they will be throttled as a group, where their combined
* throughput will not exceed the desired throughput. The same Source or Sink can be attached to
* multiple Throttlers and its throughput will not exceed the desired throughput of any of the
* Throttlers.
*
* This class has these tuning parameters:
*
* * `bytesPerSecond`: Maximum sustained throughput. Use 0 for no limit.
* * `waitByteCount`: When the requested byte count is greater than this many bytes and isn't
* immediately available, only wait until we can allocate at least this many bytes. Use this to
* set the ideal byte count during sustained throughput.
* * `maxByteCount`: Maximum number of bytes to allocate on any call. This is also the number of
* bytes that will be returned before any waiting.
*/
class Throttler internal constructor(
/**
* The nanoTime that we've consumed all bytes through. This is never greater than the current
* nanoTime plus nanosForMaxByteCount.
*/
private var allocatedUntil: Long
) {
private var bytesPerSecond: Long = 0L
private var waitByteCount: Long = 8 * 1024 // 8 KiB.
private var maxByteCount: Long = 256 * 1024 // 256 KiB.
constructor() : this(allocatedUntil = System.nanoTime())
/** Sets the rate at which bytes will be allocated. Use 0 for no limit. */
@JvmOverloads
fun bytesPerSecond(
bytesPerSecond: Long,
waitByteCount: Long = this.waitByteCount,
maxByteCount: Long = this.maxByteCount
) {
synchronized(this) {
require(bytesPerSecond >= 0)
require(waitByteCount > 0)
require(maxByteCount >= waitByteCount)
this.bytesPerSecond = bytesPerSecond
this.waitByteCount = waitByteCount
this.maxByteCount = maxByteCount
(this as Object).notifyAll()
}
}
/**
* Take up to `byteCount` bytes, waiting if necessary. Returns the number of bytes that were
* taken.
*/
internal fun take(byteCount: Long): Long {
require(byteCount > 0)
synchronized(this) {
while (true) {
val now = System.nanoTime()
val byteCountOrWaitNanos = byteCountOrWaitNanos(now, byteCount)
if (byteCountOrWaitNanos >= 0) return byteCountOrWaitNanos
waitNanos(-byteCountOrWaitNanos)
}
}
throw AssertionError() // Unreachable, but synchronized() doesn't know that.
}
/**
* Returns the byte count to take immediately or -1 times the number of nanos to wait until the
* next attempt. If the returned value is negative it should be interpreted as a duration in
* nanos; if it is positive it should be interpreted as a byte count.
*/
internal fun byteCountOrWaitNanos(now: Long, byteCount: Long): Long {
if (bytesPerSecond == 0L) return byteCount // No limits.
val idleInNanos = maxOf(allocatedUntil - now, 0L)
val immediateBytes = maxByteCount - idleInNanos.nanosToBytes()
// Fulfill the entire request without waiting.
if (immediateBytes >= byteCount) {
allocatedUntil = now + idleInNanos + byteCount.bytesToNanos()
return byteCount
}
// Fulfill a big-enough block without waiting.
if (immediateBytes >= waitByteCount) {
allocatedUntil = now + maxByteCount.bytesToNanos()
return immediateBytes
}
// Looks like we'll need to wait until we can take the minimum required bytes.
val minByteCount = minOf(waitByteCount, byteCount)
val minWaitNanos = idleInNanos + (minByteCount - maxByteCount).bytesToNanos()
// But if the wait duration truncates to zero nanos after division, don't wait.
if (minWaitNanos == 0L) {
allocatedUntil = now + maxByteCount.bytesToNanos()
return minByteCount
}
return -minWaitNanos
}
private fun Long.nanosToBytes() = this * bytesPerSecond / 1_000_000_000L
private fun Long.bytesToNanos() = this * 1_000_000_000L / bytesPerSecond
private fun waitNanos(nanosToWait: Long) {
val millisToWait = nanosToWait / 1_000_000L
val remainderNanos = nanosToWait - (millisToWait * 1_000_000L)
(this as Object).wait(millisToWait, remainderNanos.toInt())
}
/** Create a Source which honors this Throttler. */
fun source(source: Source): Source {
return object : ForwardingSource(source) {
override fun read(sink: Buffer, byteCount: Long): Long {
try {
val toRead = take(byteCount)
return super.read(sink, toRead)
} catch (e: InterruptedException) {
Thread.currentThread().interrupt()
throw InterruptedIOException("interrupted")
}
}
}
}
/** Create a Sink which honors this Throttler. */
fun sink(sink: Sink): Sink {
return object : ForwardingSink(sink) {
@Throws(IOException::class)
override fun write(source: Buffer, byteCount: Long) {
try {
var remaining = byteCount
while (remaining > 0L) {
val toWrite = take(remaining)
super.write(source, toWrite)
remaining -= toWrite
}
} catch (e: InterruptedException) {
Thread.currentThread().interrupt()
throw InterruptedIOException("interrupted")
}
}
}
}
}
| apache-2.0 | 545ad712de113f3d4d3fa8bd8510b6ed | 35.119048 | 99 | 0.688365 | 4.334286 | false | false | false | false |
ursjoss/sipamato | core/core-persistence-jooq/src/test/kotlin/ch/difty/scipamato/core/persistence/JooqReadOnlyRepoTest.kt | 1 | 4832 | @file:Suppress("SpellCheckingInspection")
package ch.difty.scipamato.core.persistence
import ch.difty.scipamato.common.config.ApplicationProperties
import ch.difty.scipamato.common.entity.filter.ScipamatoFilter
import ch.difty.scipamato.common.persistence.GenericFilterConditionMapper
import ch.difty.scipamato.common.persistence.JooqSortMapper
import ch.difty.scipamato.common.persistence.paging.PaginationContext
import ch.difty.scipamato.common.persistence.paging.Sort
import ch.difty.scipamato.core.entity.IdScipamatoEntity
import io.mockk.confirmVerified
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import org.amshove.kluent.shouldBeEqualTo
import org.jooq.Condition
import org.jooq.DSLContext
import org.jooq.Record
import org.jooq.Record1
import org.jooq.RecordMapper
import org.jooq.SelectConditionStep
import org.jooq.SelectJoinStep
import org.jooq.SelectSeekStepN
import org.jooq.SelectSelectStep
import org.jooq.SelectWhereStep
import org.jooq.SortField
import org.jooq.TableField
import org.jooq.impl.TableImpl
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
abstract class JooqReadOnlyRepoTest<
R : Record,
T : IdScipamatoEntity<ID>,
ID : Number,
TI : TableImpl<R>,
M : RecordMapper<R, T>,
F : ScipamatoFilter> {
protected val dsl = mockk<DSLContext>()
protected var filterConditionMapper = mockk<GenericFilterConditionMapper<F>>()
protected val sortMapper = mockk<JooqSortMapper<R, T, TI>>()
private val selectWhereStepMock = mockk<SelectWhereStep<R>>()
private val selectConditionStepMock = mockk<SelectConditionStep<R>>()
private val selectSelectStepMock = mockk<SelectSelectStep<Record1<Int>>>()
private val selectJoinStepMock = mockk<SelectJoinStep<Record1<Int>>>()
private val selectConditionStepMock2 = mockk<SelectConditionStep<Record1<Int>>>()
private val paginationContextMock = mockk<PaginationContext>()
private val sortMock = mockk<Sort>()
private val sortFieldsMock = mockk<Collection<SortField<T>>>()
private val selectSeekStepNMock = mockk<SelectSeekStepN<R>>()
protected val conditionMock = mockk<Condition>()
protected val applicationProperties = mockk<ApplicationProperties>()
protected abstract val persistedEntity: T
protected abstract val unpersistedEntity: T
protected abstract val persistedRecord: R
protected abstract val unpersistedRecord: R
protected abstract val mapper: M
protected abstract val table: TI
protected abstract val tableId: TableField<R, ID>
protected abstract val filter: F
protected abstract val repo: ReadOnlyRepository<T, ID, F>
/**
* Hand-rolled spy that returns the provided entity in the method `findById(ID id)`
*/
protected abstract fun makeRepoFindingEntityById(entity: T): ReadOnlyRepository<T, ID, F>
protected abstract fun expectEntityIdsWithValues()
protected abstract fun expectUnpersistedEntityIdNull()
protected abstract fun verifyUnpersistedEntityId()
protected abstract fun verifyPersistedRecordId()
private val entities = mutableListOf<T>()
private val records = mutableListOf<R>()
@BeforeEach
internal fun setUp() {
entities.add(persistedEntity)
entities.add(persistedEntity)
records.add(persistedRecord)
records.add(persistedRecord)
specificSetUp()
}
protected open fun specificSetUp() {}
@AfterEach
internal fun tearDown() {
specificTearDown()
confirmVerified(dsl, mapper, sortMapper)
confirmVerified(unpersistedEntity, persistedEntity, unpersistedRecord, persistedRecord)
confirmVerified(selectWhereStepMock, selectConditionStepMock)
confirmVerified(selectSelectStepMock, selectJoinStepMock)
confirmVerified(paginationContextMock, sortMock, sortFieldsMock, selectSeekStepNMock)
confirmVerified(filter, conditionMock)
confirmVerified(applicationProperties)
}
protected open fun specificTearDown() {}
protected open fun specificNullCheck() {}
@Test
internal fun countingByFilter() {
every { filterConditionMapper.map(filter) } returns conditionMock
every { dsl.selectOne() } returns selectSelectStepMock
every { selectSelectStepMock.from(table) } returns selectJoinStepMock
every { selectJoinStepMock.where(any<Condition>()) } returns selectConditionStepMock2
every { dsl.fetchCount(selectConditionStepMock2) } returns 2
repo.countByFilter(filter) shouldBeEqualTo 2
verify { dsl.selectOne() }
verify { selectSelectStepMock.from(table) }
verify { selectJoinStepMock.where(any<Condition>()) }
verify { dsl.fetchCount(selectConditionStepMock2) }
}
}
| gpl-3.0 | a746de8f236966e4727e16fb2aae3821 | 34.529412 | 95 | 0.757243 | 4.619503 | false | false | false | false |
allotria/intellij-community | platform/external-system-impl/src/com/intellij/openapi/externalSystem/autoimport/changes/DocumentsChangesProvider.kt | 4 | 2501 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.autoimport.changes
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.externalSystem.autoimport.ProjectStatus
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.observable.operations.CompoundParallelOperationTrace
import com.intellij.psi.ExternalChangeAction
import com.intellij.util.EventDispatcher
class DocumentsChangesProvider(private val isIgnoreExternalChanges: Boolean) : FilesChangesProvider, DocumentListener {
private val eventDispatcher = EventDispatcher.create(FilesChangesListener::class.java)
override fun subscribe(listener: FilesChangesListener, parentDisposable: Disposable) {
eventDispatcher.addListener(listener, parentDisposable)
}
private val bulkUpdateOperation = CompoundParallelOperationTrace<Document>(debugName = "Bulk document update operation")
private fun isExternalModification() =
ApplicationManager.getApplication().hasWriteAction(ExternalChangeAction::class.java)
override fun documentChanged(event: DocumentEvent) {
if (isIgnoreExternalChanges && isExternalModification()) return
val document = event.document
val fileDocumentManager = FileDocumentManager.getInstance()
val file = fileDocumentManager.getFile(document) ?: return
when (bulkUpdateOperation.isOperationCompleted()) {
true -> {
eventDispatcher.multicaster.init()
eventDispatcher.multicaster.onFileChange(file.path, document.modificationStamp, ProjectStatus.ModificationType.INTERNAL)
eventDispatcher.multicaster.apply()
}
else -> {
eventDispatcher.multicaster.onFileChange(file.path, document.modificationStamp, ProjectStatus.ModificationType.INTERNAL)
}
}
}
override fun bulkUpdateStarting(document: Document) {
bulkUpdateOperation.startTask(document)
}
override fun bulkUpdateFinished(document: Document) {
bulkUpdateOperation.finishTask(document)
}
init {
bulkUpdateOperation.beforeOperation { eventDispatcher.multicaster.init() }
bulkUpdateOperation.afterOperation { eventDispatcher.multicaster.apply() }
}
} | apache-2.0 | 537550925932ef3334c776844a83d64f | 43.678571 | 140 | 0.803279 | 5.321277 | false | false | false | false |
DmytroTroynikov/aemtools | aem-intellij-core/src/main/kotlin/com/aemtools/completion/htl/provider/option/HtlDataSlyResourceOptionCompletionProvider.kt | 1 | 1717 | package com.aemtools.completion.htl.provider.option
import com.aemtools.common.util.findParentByType
import com.aemtools.completion.htl.CompletionPriority.RESOURCE_TYPE
import com.aemtools.completion.model.htl.HtlOption
import com.aemtools.service.repository.inmemory.HtlAttributesRepository
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.CompletionProvider
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.codeInsight.completion.PrioritizedLookupElement
import com.intellij.util.ProcessingContext
/**
* @author Dmytro Troynikov
*/
object HtlDataSlyResourceOptionCompletionProvider : CompletionProvider<CompletionParameters>() {
override fun addCompletions(
parameters: CompletionParameters,
context: ProcessingContext,
result: CompletionResultSet) {
val currentPosition = parameters.position
val hel = currentPosition.findParentByType(com.aemtools.lang.htl.psi.mixin.HtlElExpressionMixin::class.java)
?: return
val names = hel.getOptions().map { it.name() }
.filterNot { it == "" }
// todo temporary solution
val resourceType = HtlOption("resourceType", "string", "", emptyList(), "")
val options = listOf(resourceType) + HtlAttributesRepository.getHtlOptions()
val completionVariants = options
.filterNot { names.contains(it.name) }
.map(HtlOption::toLookupElement)
.map {
if (it.lookupString == "resourceType") {
PrioritizedLookupElement.withPriority(it, RESOURCE_TYPE)
} else {
it
}
}
result.addAllElements(completionVariants)
result.stopHere()
}
}
| gpl-3.0 | 12551d78e4317df6e593525392577808 | 34.770833 | 112 | 0.740827 | 4.850282 | false | false | false | false |
square/okio | okio/src/commonMain/kotlin/okio/Buffer.kt | 1 | 16906 | /*
* Copyright (C) 2019 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okio
import kotlin.jvm.JvmField
/**
* A collection of bytes in memory.
*
* **Moving data from one buffer to another is fast.** Instead of copying bytes from one place in
* memory to another, this class just changes ownership of the underlying byte arrays.
*
* **This buffer grows with your data.** Just like ArrayList, each buffer starts small. It consumes
* only the memory it needs to.
*
* **This buffer pools its byte arrays.** When you allocate a byte array in Java, the runtime must
* zero-fill the requested array before returning it to you. Even if you're going to write over that
* space anyway. This class avoids zero-fill and GC churn by pooling byte arrays.
*/
expect class Buffer() : BufferedSource, BufferedSink {
internal var head: Segment?
var size: Long
internal set
override val buffer: Buffer
override fun emitCompleteSegments(): Buffer
override fun emit(): Buffer
/** Copy `byteCount` bytes from this, starting at `offset`, to `out`. */
fun copyTo(
out: Buffer,
offset: Long = 0L,
byteCount: Long
): Buffer
/**
* Overload of [copyTo] with byteCount = size - offset, work around for
* https://youtrack.jetbrains.com/issue/KT-30847
*/
fun copyTo(
out: Buffer,
offset: Long = 0L
): Buffer
/**
* Returns the number of bytes in segments that are not writable. This is the number of bytes that
* can be flushed immediately to an underlying sink without harming throughput.
*/
fun completeSegmentByteCount(): Long
/** Returns the byte at `pos`. */
operator fun get(pos: Long): Byte
/**
* Discards all bytes in this buffer. Calling this method when you're done with a buffer will
* return its segments to the pool.
*/
fun clear()
/** Discards `byteCount` bytes from the head of this buffer. */
override fun skip(byteCount: Long)
override fun write(byteString: ByteString): Buffer
override fun write(byteString: ByteString, offset: Int, byteCount: Int): Buffer
override fun writeUtf8(string: String): Buffer
override fun writeUtf8(string: String, beginIndex: Int, endIndex: Int): Buffer
override fun writeUtf8CodePoint(codePoint: Int): Buffer
override fun write(source: ByteArray): Buffer
/**
* Returns a tail segment that we can write at least `minimumCapacity`
* bytes to, creating it if necessary.
*/
internal fun writableSegment(minimumCapacity: Int): Segment
fun md5(): ByteString
fun sha1(): ByteString
fun sha256(): ByteString
fun sha512(): ByteString
/** Returns the 160-bit SHA-1 HMAC of this buffer. */
fun hmacSha1(key: ByteString): ByteString
/** Returns the 256-bit SHA-256 HMAC of this buffer. */
fun hmacSha256(key: ByteString): ByteString
/** Returns the 512-bit SHA-512 HMAC of this buffer. */
fun hmacSha512(key: ByteString): ByteString
override fun write(source: ByteArray, offset: Int, byteCount: Int): Buffer
override fun write(source: Source, byteCount: Long): Buffer
override fun writeByte(b: Int): Buffer
override fun writeShort(s: Int): Buffer
override fun writeShortLe(s: Int): Buffer
override fun writeInt(i: Int): Buffer
override fun writeIntLe(i: Int): Buffer
override fun writeLong(v: Long): Buffer
override fun writeLongLe(v: Long): Buffer
override fun writeDecimalLong(v: Long): Buffer
override fun writeHexadecimalUnsignedLong(v: Long): Buffer
/** Returns a deep copy of this buffer. */
fun copy(): Buffer
/** Returns an immutable copy of this buffer as a byte string. */
fun snapshot(): ByteString
/** Returns an immutable copy of the first `byteCount` bytes of this buffer as a byte string. */
fun snapshot(byteCount: Int): ByteString
fun readUnsafe(unsafeCursor: UnsafeCursor = DEFAULT__new_UnsafeCursor): UnsafeCursor
fun readAndWriteUnsafe(unsafeCursor: UnsafeCursor = DEFAULT__new_UnsafeCursor): UnsafeCursor
/**
* A handle to the underlying data in a buffer. This handle is unsafe because it does not enforce
* its own invariants. Instead, it assumes a careful user who has studied Okio's implementation
* details and their consequences.
*
* Buffer Internals
* ----------------
*
* Most code should use `Buffer` as a black box: a class that holds 0 or more bytes of
* data with efficient APIs to append data to the end and to consume data from the front. Usually
* this is also the most efficient way to use buffers because it allows Okio to employ several
* optimizations, including:
*
* * **Fast Allocation:** Buffers use a shared pool of memory that is not zero-filled before use.
* * **Fast Resize:** A buffer's capacity can change without copying its contents.
* * **Fast Move:** Memory ownership can be reassigned from one buffer to another.
* * **Fast Copy:** Multiple buffers can share the same underlying memory.
* * **Fast Encoding and Decoding:** Common operations like UTF-8 encoding and decimal decoding
* do not require intermediate objects to be allocated.
*
* These optimizations all leverage the way Okio stores data internally. Okio Buffers are
* implemented using a doubly-linked list of segments. Each segment is a contiguous range within a
* 8 KiB `ByteArray`. Each segment has two indexes, `start`, the offset of the first byte of the
* array containing application data, and `end`, the offset of the first byte beyond `start` whose
* data is undefined.
*
* New buffers are empty and have no segments:
*
* ```
* val buffer = Buffer()
* ```
*
* We append 7 bytes of data to the end of our empty buffer. Internally, the buffer allocates a
* segment and writes its new data there. The lone segment has an 8 KiB byte array but only 7
* bytes of data:
*
* ```
* buffer.writeUtf8("sealion")
*
* // [ 's', 'e', 'a', 'l', 'i', 'o', 'n', '?', '?', '?', ...]
* // ^ ^
* // start = 0 end = 7
* ```
*
* When we read 4 bytes of data from the buffer, it finds its first segment and returns that data
* to us. As bytes are read the data is consumed. The segment tracks this by adjusting its
* internal indices.
*
* ```
* buffer.readUtf8(4) // "seal"
*
* // [ 's', 'e', 'a', 'l', 'i', 'o', 'n', '?', '?', '?', ...]
* // ^ ^
* // start = 4 end = 7
* ```
*
* As we write data into a buffer we fill up its internal segments. When a write doesn't fit into
* a buffer's last segment, additional segments are allocated and appended to the linked list of
* segments. Each segment has its own start and end indexes tracking where the user's data begins
* and ends.
*
* ```
* val xoxo = new Buffer()
* xoxo.writeUtf8("xo".repeat(5_000))
*
* // [ 'x', 'o', 'x', 'o', 'x', 'o', 'x', 'o', ..., 'x', 'o', 'x', 'o']
* // ^ ^
* // start = 0 end = 8192
* //
* // [ 'x', 'o', 'x', 'o', ..., 'x', 'o', 'x', 'o', '?', '?', '?', ...]
* // ^ ^
* // start = 0 end = 1808
* ```
*
* The start index is always **inclusive** and the end index is always **exclusive**. The data
* preceding the start index is undefined, and the data at and following the end index is
* undefined.
*
* After the last byte of a segment has been read, that segment may be returned to an internal
* segment pool. In addition to reducing the need to do garbage collection, segment pooling also
* saves the JVM from needing to zero-fill byte arrays. Okio doesn't need to zero-fill its arrays
* because it always writes memory before it reads it. But if you look at a segment in a debugger
* you may see its effects. In this example, one of the "xoxo" segments above is reused in an
* unrelated buffer:
*
* ```
* val abc = new Buffer()
* abc.writeUtf8("abc")
*
* // [ 'a', 'b', 'c', 'o', 'x', 'o', 'x', 'o', ...]
* // ^ ^
* // start = 0 end = 3
* ```
*
* There is an optimization in `Buffer.clone()` and other methods that allows two segments to
* share the same underlying byte array. Clones can't write to the shared byte array; instead they
* allocate a new (private) segment early.
*
* ```
* val nana = new Buffer()
* nana.writeUtf8("na".repeat(2_500))
* nana.readUtf8(2) // "na"
*
* // [ 'n', 'a', 'n', 'a', ..., 'n', 'a', 'n', 'a', '?', '?', '?', ...]
* // ^ ^
* // start = 2 end = 5000
*
* nana2 = nana.clone()
* nana2.writeUtf8("batman")
*
* // [ 'n', 'a', 'n', 'a', ..., 'n', 'a', 'n', 'a', '?', '?', '?', ...]
* // ^ ^
* // start = 2 end = 5000
* //
* // [ 'b', 'a', 't', 'm', 'a', 'n', '?', '?', '?', ...]
* // ^ ^
* // start = 0 end = 6
* ```
*
* Segments are not shared when the shared region is small (ie. less than 1 KiB). This is intended
* to prevent fragmentation in sharing-heavy use cases.
*
* Unsafe Cursor API
* -----------------
*
* This class exposes privileged access to the internal byte arrays of a buffer. A cursor either
* references the data of a single segment, it is before the first segment (`offset == -1`), or it
* is after the last segment (`offset == buffer.size`).
*
* Call [UnsafeCursor.seek] to move the cursor to the segment that contains a specified offset.
* After seeking, [UnsafeCursor.data] references the segment's internal byte array,
* [UnsafeCursor.start] is the segment's start and [UnsafeCursor.end] is its end.
*
* Call [UnsafeCursor.next] to advance the cursor to the next segment. This returns -1 if there
* are no further segments in the buffer.
*
* Use [Buffer.readUnsafe] to create a cursor to read buffer data and [Buffer.readAndWriteUnsafe]
* to create a cursor to read and write buffer data. In either case, always call
* [UnsafeCursor.close] when done with a cursor. This is convenient with Kotlin's
* [use] extension function. In this example we read all of the bytes in a buffer into a byte
* array:
*
* ```
* val bufferBytes = ByteArray(buffer.size.toInt())
*
* buffer.readUnsafe().use { cursor ->
* while (cursor.next() != -1) {
* System.arraycopy(cursor.data, cursor.start,
* bufferBytes, cursor.offset.toInt(), cursor.end - cursor.start);
* }
* }
* ```
*
* Change the capacity of a buffer with [resizeBuffer]. This is only permitted for read+write
* cursors. The buffer's size always changes from the end: shrinking it removes bytes from the
* end; growing it adds capacity to the end.
*
* Warnings
* --------
*
* Most application developers should avoid this API. Those that must use this API should
* respect these warnings.
*
* **Don't mutate a cursor.** This class has public, non-final fields because that is convenient
* for low-level I/O frameworks. Never assign values to these fields; instead use the cursor API
* to adjust these.
*
* **Never mutate `data` unless you have read+write access.** You are on the honor system to never
* write the buffer in read-only mode. Read-only mode may be more efficient than read+write mode
* because it does not need to make private copies of shared segments.
*
* **Only access data in `[start..end)`.** Other data in the byte array is undefined! It may
* contain private or sensitive data from other parts of your process.
*
* **Always fill the new capacity when you grow a buffer.** New capacity is not zero-filled and
* may contain data from other parts of your process. Avoid leaking this information by always
* writing something to the newly-allocated capacity. Do not assume that new capacity will be
* filled with `0`; it will not be.
*
* **Do not access a buffer while is being accessed by a cursor.** Even simple read-only
* operations like [Buffer.clone] are unsafe because they mark segments as shared.
*
* **Do not hard-code the segment size in your application.** It is possible that segment sizes
* will change with advances in hardware. Future versions of Okio may even have heterogeneous
* segment sizes.
*
* These warnings are intended to help you to use this API safely. It's here for developers
* that need absolutely the most throughput. Since that's you, here's one final performance tip.
* You can reuse instances of this class if you like. Use the overloads of [Buffer.readUnsafe] and
* [Buffer.readAndWriteUnsafe] that take a cursor and close it after use.
*/
class UnsafeCursor constructor() {
@JvmField var buffer: Buffer?
@JvmField var readWrite: Boolean
internal var segment: Segment?
@JvmField var offset: Long
@JvmField var data: ByteArray?
@JvmField var start: Int
@JvmField var end: Int
/**
* Seeks to the next range of bytes, advancing the offset by `end - start`. Returns the size of
* the readable range (at least 1), or -1 if we have reached the end of the buffer and there are
* no more bytes to read.
*/
fun next(): Int
/**
* Reposition the cursor so that the data at [offset] is readable at `data[start]`.
* Returns the number of bytes readable in [data] (at least 1), or -1 if there are no data
* to read.
*/
fun seek(offset: Long): Int
/**
* Change the size of the buffer so that it equals [newSize] by either adding new capacity at
* the end or truncating the buffer at the end. Newly added capacity may span multiple segments.
*
* As a side-effect this cursor will [seek][UnsafeCursor.seek]. If the buffer is being enlarged
* it will move [UnsafeCursor.offset] to the first byte of newly-added capacity. This is the
* size of the buffer prior to the `resizeBuffer()` call. If the buffer is being shrunk it will move
* [UnsafeCursor.offset] to the end of the buffer.
*
* Warning: it is the caller’s responsibility to write new data to every byte of the
* newly-allocated capacity. Failure to do so may cause serious security problems as the data
* in the returned buffers is not zero filled. Buffers may contain dirty pooled segments that
* hold very sensitive data from other parts of the current process.
*
* @return the previous size of the buffer.
*/
fun resizeBuffer(newSize: Long): Long
/**
* Grow the buffer by adding a **contiguous range** of capacity in a single segment. This adds
* at least [minByteCount] bytes but may add up to a full segment of additional capacity.
*
* As a side-effect this cursor will [seek][UnsafeCursor.seek]. It will move
* [offset][UnsafeCursor.offset] to the first byte of newly-added capacity. This is the size of
* the buffer prior to the `expandBuffer()` call.
*
* If [minByteCount] bytes are available in the buffer's current tail segment that will be used;
* otherwise another segment will be allocated and appended. In either case this returns the
* number of bytes of capacity added to this buffer.
*
* Warning: it is the caller’s responsibility to either write new data to every byte of the
* newly-allocated capacity, or to [shrink][UnsafeCursor.resizeBuffer] the buffer to the data
* written. Failure to do so may cause serious security problems as the data in the returned
* buffers is not zero filled. Buffers may contain dirty pooled segments that hold very
* sensitive data from other parts of the current process.
*
* @param minByteCount the size of the contiguous capacity. Must be positive and not greater
* than the capacity size of a single segment (8 KiB).
* @return the number of bytes expanded by. Not less than `minByteCount`.
*/
fun expandBuffer(minByteCount: Int): Long
fun close()
}
}
| apache-2.0 | 8a9b626e924a8681d2c914bcec71ce68 | 40.426471 | 104 | 0.645249 | 4.190925 | false | false | false | false |
allotria/intellij-community | platform/vcs-log/impl/src/com/intellij/vcs/log/ui/actions/GoToParentOrChildAction.kt | 3 | 4254 | // 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.vcs.log.ui.actions
import com.intellij.openapi.actionSystem.ActionGroup
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.util.NlsActions
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.text.DateFormatUtil
import com.intellij.vcs.log.VcsCommitMetadata
import com.intellij.vcs.log.VcsLogBundle
import com.intellij.vcs.log.VcsLogDataKeys
import com.intellij.vcs.log.data.LoadingDetails
import com.intellij.vcs.log.statistics.VcsLogUsageTriggerCollector
import com.intellij.vcs.log.ui.VcsLogUiEx
import com.intellij.vcs.log.ui.frame.CommitPresentationUtil
import com.intellij.vcs.log.util.VcsLogUtil.jumpToRow
import java.awt.event.KeyEvent
open class GoToParentOrChildAction(val parent: Boolean) : DumbAwareAction() {
override fun update(e: AnActionEvent) {
val ui = e.getData(VcsLogDataKeys.VCS_LOG_UI) as? VcsLogUiEx
if (ui == null) {
e.presentation.isEnabledAndVisible = false
return
}
e.presentation.isVisible = true
if (e.inputEvent is KeyEvent) {
e.presentation.isEnabled = ui.table.isFocusOwner
}
else {
e.presentation.isEnabled = getRowsToJump(ui).isNotEmpty()
}
}
override fun actionPerformed(e: AnActionEvent) {
triggerUsage(e)
val ui = e.getRequiredData(VcsLogDataKeys.VCS_LOG_UI) as VcsLogUiEx
val rows = getRowsToJump(ui)
if (rows.isEmpty()) {
// can happen if the action was invoked by shortcut
return
}
if (rows.size == 1) {
jumpToRow(ui, rows.single(), false)
}
else {
val popup = JBPopupFactory.getInstance().createActionGroupPopup(
if (parent) VcsLogBundle.message("action.go.to.select.parent.to.navigate")
else VcsLogBundle.message("action.go.to.select.child.to.navigate"),
createGroup(ui, rows), e.dataContext,
JBPopupFactory.ActionSelectionAid.NUMBERING, false)
popup.showInBestPositionFor(e.dataContext)
}
}
private fun createGroup(ui: VcsLogUiEx, rows: List<Int>): ActionGroup {
val actions = rows.mapTo(mutableListOf()) { row ->
val text = getActionText(ui.table.model.getCommitMetadata(row))
object : DumbAwareAction(text, VcsLogBundle.message("action.go.to.navigate.to", text), null) {
override fun actionPerformed(e: AnActionEvent) {
triggerUsage(e)
jumpToRow(ui, row, false)
}
}
}
return DefaultActionGroup(actions)
}
private fun DumbAwareAction.triggerUsage(e: AnActionEvent) {
VcsLogUsageTriggerCollector.triggerUsage(e, this) { data -> data.addData("parent_commit", parent) }
}
@NlsActions.ActionText
private fun getActionText(commitMetadata: VcsCommitMetadata): String {
if (commitMetadata !is LoadingDetails) {
val time: Long = commitMetadata.authorTime
val commitMessage = "\"" + StringUtil.shortenTextWithEllipsis(commitMetadata.subject,
40, 0,
"...") + "\""
return VcsLogBundle.message("action.go.to.select.hash.subject.author.date.time",
commitMetadata.id.toShortString(),
commitMessage,
CommitPresentationUtil.getAuthorPresentation(commitMetadata),
DateFormatUtil.formatDate(time),
DateFormatUtil.formatTime(time))
}
return commitMetadata.id.toShortString()
}
private fun getRowsToJump(ui: VcsLogUiEx): List<Int> {
val selectedRows = ui.table.selectedRows
if (selectedRows.size != 1) return emptyList()
return ui.dataPack.visibleGraph.getRowInfo(selectedRows.single()).getAdjacentRows(parent).sorted()
}
}
class GoToParentRowAction : GoToParentOrChildAction(true)
class GoToChildRowAction : GoToParentOrChildAction(false) | apache-2.0 | f3655a76e7e7f3bee9008d5309f7a9bb | 38.766355 | 140 | 0.689469 | 4.56928 | false | false | false | false |
qkuronekop/MovingView | gesturetransformableview/src/main/java/jp/gr/java_conf/qkuronekop/gesturetransformableview/detector/PinchGestureDetector.kt | 1 | 2114 | package jp.gr.java_conf.qkuronekop.gesturetransformableview.detector
import android.view.MotionEvent
import jp.gr.java_conf.qkuronekop.gesturetransformableview.listener.PinchGestureListener
class PinchGestureDetector() {
var scale = 1.0f
var distance = 0f
var preDistance = 0f
var pinchGestureListener: PinchGestureListener? = null
@Synchronized fun onTouchEvent(event: MotionEvent): Boolean {
val eventX = event.x * scale
val eventY = event.y * scale
val count = event.pointerCount
val action = event.action and MotionEvent.ACTION_MASK
val actionPointerIndex = event.action and MotionEvent.ACTION_POINTER_INDEX_MASK
when (action) {
MotionEvent.ACTION_DOWN -> {
}
/** 最初のpointしか来ない */
MotionEvent.ACTION_MOVE -> {
if (count == 2) {
val multiTouchX = event.getX(1) * scale
val multiTouchY = event.getY(1) * scale
distance = circleDistance(eventX, eventY, multiTouchX, multiTouchY)
pinchGestureListener?.onPinchGestureListener(this)
scale *= distance / preDistance
preDistance = distance
}
}
MotionEvent.ACTION_POINTER_DOWN -> {
/** 2本の位置を記録 以後、moveにて距離の差分を算出 */
if (count == 2) {
val downId = actionPointerIndex shr MotionEvent.ACTION_POINTER_INDEX_SHIFT
val multiTouchX = event.getX(downId) * scale
val multiTouchY = event.getY(downId) * scale
distance = circleDistance(eventX, eventY, multiTouchX, multiTouchY)
pinchGestureListener?.onPinchGestureListener(this)
preDistance = distance
}
}
MotionEvent.ACTION_POINTER_UP -> {
distance = 0f
preDistance = 0f
scale = 1.0f
}
}
return false
}
private fun circleDistance(x1: Float, y1: Float, x2: Float, y2: Float): Float {
val dx = x1 - x2
val dy = y1 - y2
return Math.sqrt((dx * dx + dy * dy).toDouble()).toFloat()
}
}
| mit | 0c66112153324458205770a8163efe9b | 26.164384 | 88 | 0.621109 | 3.864662 | false | false | false | false |
zpao/buck | src/com/facebook/buck/multitenant/service/Includes.kt | 1 | 7973 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("MatchingDeclarationName")
package com.facebook.buck.multitenant.service
import com.facebook.buck.core.path.ForwardRelativePath
import com.facebook.buck.multitenant.collect.Generation
import com.facebook.buck.multitenant.fs.FsAgnosticPath
typealias Include = ForwardRelativePath
/**
* Processes parse-time includes changes - calculates new includes map state based on the previous state and new changes [internalChanges].
* @param internalChanges data class for internal changes (added, modified, removed packages)
* @param generation [Generation] that defines a current state of [Index]
* @param indexGenerationData thread-safe, read-only access to the underlying data in an [Index]
* @return [IncludesMapChange] that represents a new state for include maps or an empty [IncludesMapChange] if a new state is the same as previous one.
*/
internal fun processIncludes(
internalChanges: InternalChanges,
generation: Generation,
indexGenerationData: IndexGenerationData
): IncludesMapChange {
/** Copying previous state under a lock to read-only [IncludesMapChange] object*/
val previousState =
indexGenerationData.withIncludesMap { (forwardIncludesMap, reverseIncludesMap) ->
IncludesMapChange(
forwardMap = forwardIncludesMap.toMap(generation),
reverseMap = reverseIncludesMap.toMap(generation)
)
}
val includesMapChangeBuilder = IncludesMapChangeBuilder(previousState)
internalChanges.addedBuildPackages.forEach { added ->
includesMapChangeBuilder.processAddedPackage(
packagePath = added.buildFileDirectory,
includes = added.includes
)
}
internalChanges.modifiedBuildPackages.forEach { modified ->
includesMapChangeBuilder.processModifiedPackage(
packagePath = modified.buildFileDirectory,
includes = modified.includes
)
}
internalChanges.removedBuildPackages.forEach { removed ->
includesMapChangeBuilder.processRemovedPackage(packageToRemove = removed)
}
val newState = includesMapChangeBuilder.build()
return if (newState != previousState) newState
else IncludesMapChange(forwardMap = emptyMap(), reverseMap = emptyMap())
}
private typealias EmptyValue = Unit
/**
* Builder that allows to process parse-time includes changes.
*/
class IncludesMapChangeBuilder(private val prevState: IncludesMapChange) {
private val forwardMapValues: MutableMap<ForwardRelativePath, EmptyValue?> = mutableMapOf()
private val forwardMapDeltas: MutableList<Pair<ForwardRelativePath, SetDelta>> = mutableListOf()
private val reverseMapDeltas: MutableList<Pair<Include, SetDelta>> = mutableListOf()
/**
* Processes includes from the added package.
* If includes are not empty then add them to forward and reverse include maps.
*
* @param packagePath build file directory path that corresponds to the added package
* @param includes parse time includes that corresponds to the added package
*/
fun processAddedPackage(packagePath: ForwardRelativePath, includes: HashSet<ForwardRelativePath>) {
// verification that the package is new
require(prevState.forwardMap[packagePath] == null) {
"New package $packagePath already existed"
}
if (includes.isEmpty()){
forwardMapValues[packagePath] = EmptyValue
}
includes.forEach {
appendForwardMap(buildFilePath = packagePath, include = it)
appendReverseMap(buildFilePath = packagePath, include = it)
}
}
/**
* Processes includes from the modified package.
* If includes changed (comparing to the previous state for this modified package)
* then remove the package from forward and reverse maps and append maps with new package includes
*
* @param packagePath build file directory path that corresponds to the modified package
* @param includes parse time includes that corresponds to the modified package
*/
fun processModifiedPackage(packagePath: ForwardRelativePath, includes: HashSet<ForwardRelativePath>) {
val previousIncludes = prevState.forwardMap[packagePath]
val brandNewIncludes = previousIncludes.isNullOrEmpty() && includes.isNotEmpty()
val previousIncludesHashSet =
previousIncludes?.asSequence()?.map { FsAgnosticPath.fromIndex(it) }?.toHashSet()
?: hashSetOf()
if (brandNewIncludes || previousIncludesHashSet != includes) {
processRemovedPackage(packageToRemove = packagePath)
includes.forEach {
appendForwardMap(buildFilePath = packagePath, include = it)
appendReverseMap(buildFilePath = packagePath, include = it)
}
}
}
/**
* Processes includes from the removed package.
* Removes the package from forward and reverse maps
*
* @param packageToRemove build file directory path that corresponds to the removed package
*/
fun processRemovedPackage(packageToRemove: ForwardRelativePath) {
forwardMapValues[packageToRemove] = null
val previousIncludes = prevState.forwardMap[packageToRemove]
previousIncludes?.forEach {
removeFromReverseMap(buildFilePath = packageToRemove, include = FsAgnosticPath.fromIndex(it))
}
}
/**
* @return [IncludesMapChange] that represents a new read-only state for include maps.
*/
fun build(): IncludesMapChange =
IncludesMapChange(forwardMap = getForwardMap(), reverseMap = getReverseMap())
private fun getForwardMap(): Map<Include, MemorySharingIntSet?> =
applyUpdates(
map = prevState.forwardMap,
deltas = forwardMapDeltas,
valuesMap = forwardMapValues
)
private fun getReverseMap(): Map<Include, MemorySharingIntSet?> =
applyUpdates(map = prevState.reverseMap, deltas = reverseMapDeltas)
private fun applyUpdates(
map: Map<ForwardRelativePath, MemorySharingIntSet?>,
deltas: List<Pair<ForwardRelativePath, SetDelta>>,
valuesMap: Map<ForwardRelativePath, Unit?> = emptyMap()
): Map<ForwardRelativePath, MemorySharingIntSet?> {
if (valuesMap.isEmpty() && deltas.isEmpty()) {
return map
}
val out = map.toMutableMap()
valuesMap.forEach { (path, values) ->
out[path] = if (values == null) null else MemorySharingIntSet.empty()
}
val derivedDeltas = deriveDeltas(deltas) { out[it] }
derivedDeltas.forEach { (path, newSet) ->
out[path] = newSet ?: MemorySharingIntSet.empty()
}
return out
}
private fun appendForwardMap(buildFilePath: ForwardRelativePath, include: Include) {
forwardMapDeltas.add(buildFilePath to SetDelta.Add(FsAgnosticPath.toIndex(include)))
}
private fun appendReverseMap(buildFilePath: ForwardRelativePath, include: Include) {
reverseMapDeltas.add(include to SetDelta.Add(FsAgnosticPath.toIndex(buildFilePath)))
}
private fun removeFromReverseMap(buildFilePath: ForwardRelativePath, include: Include) {
reverseMapDeltas.add(include to SetDelta.Remove(FsAgnosticPath.toIndex(buildFilePath)))
}
}
| apache-2.0 | e249ecd1419ab494819800d957eac6b1 | 40.743455 | 151 | 0.706008 | 5.097826 | false | false | false | false |
Kotlin/kotlinx.coroutines | kotlinx-coroutines-core/common/src/channels/Channels.common.kt | 1 | 4715 | /*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
@file:JvmMultifileClass
@file:JvmName("ChannelsKt")
@file:Suppress("DEPRECATION_ERROR")
@file:OptIn(ExperimentalContracts::class)
package kotlinx.coroutines.channels
import kotlinx.coroutines.*
import kotlinx.coroutines.selects.*
import kotlin.contracts.*
import kotlin.coroutines.*
import kotlin.jvm.*
internal const val DEFAULT_CLOSE_MESSAGE = "Channel was closed"
// -------- Operations on BroadcastChannel --------
/**
* Opens subscription to this [BroadcastChannel] and makes sure that the given [block] consumes all elements
* from it by always invoking [cancel][ReceiveChannel.cancel] after the execution of the block.
*
* **Note: This API will become obsolete in future updates with introduction of lazy asynchronous streams.**
* See [issue #254](https://github.com/Kotlin/kotlinx.coroutines/issues/254).
*/
@ObsoleteCoroutinesApi
public inline fun <E, R> BroadcastChannel<E>.consume(block: ReceiveChannel<E>.() -> R): R {
val channel = openSubscription()
try {
return channel.block()
} finally {
channel.cancel()
}
}
/**
* This function is deprecated in the favour of [ReceiveChannel.receiveCatching].
*
* This function is considered error-prone for the following reasons;
* * Is throwing if the channel has failed even though its signature may suggest it returns 'null'
* * It is easy to forget that exception handling still have to be explicit
* * During code reviews and code reading, intentions of the code are frequently unclear:
* are potential exceptions ignored deliberately or not?
*
* @suppress doc
*/
@Deprecated(
"Deprecated in the favour of 'receiveCatching'",
ReplaceWith("receiveCatching().getOrNull()"),
DeprecationLevel.ERROR
) // Warning since 1.5.0, ERROR in 1.6.0, HIDDEN in 1.7.0
@Suppress("EXTENSION_SHADOWED_BY_MEMBER")
public suspend fun <E : Any> ReceiveChannel<E>.receiveOrNull(): E? {
@Suppress("DEPRECATION", "UNCHECKED_CAST")
return (this as ReceiveChannel<E?>).receiveOrNull()
}
/**
* This function is deprecated in the favour of [ReceiveChannel.onReceiveCatching]
*/
@Deprecated(
"Deprecated in the favour of 'onReceiveCatching'",
level = DeprecationLevel.ERROR
) // Warning since 1.5.0, ERROR in 1.6.0, HIDDEN in 1.7.0
public fun <E : Any> ReceiveChannel<E>.onReceiveOrNull(): SelectClause1<E?> {
@Suppress("DEPRECATION", "UNCHECKED_CAST")
return (this as ReceiveChannel<E?>).onReceiveOrNull
}
/**
* Makes sure that the given [block] consumes all elements from the given channel
* by always invoking [cancel][ReceiveChannel.cancel] after the execution of the block.
*
* The operation is _terminal_.
*/
public inline fun <E, R> ReceiveChannel<E>.consume(block: ReceiveChannel<E>.() -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
var cause: Throwable? = null
try {
return block()
} catch (e: Throwable) {
cause = e
throw e
} finally {
cancelConsumed(cause)
}
}
/**
* Performs the given [action] for each received element and [cancels][ReceiveChannel.cancel]
* the channel after the execution of the block.
* If you need to iterate over the channel without consuming it, a regular `for` loop should be used instead.
*
* The operation is _terminal_.
* This function [consumes][ReceiveChannel.consume] all elements of the original [ReceiveChannel].
*/
public suspend inline fun <E> ReceiveChannel<E>.consumeEach(action: (E) -> Unit): Unit =
consume {
for (e in this) action(e)
}
/**
* Returns a [List] containing all elements.
*
* The operation is _terminal_.
* This function [consumes][ReceiveChannel.consume] all elements of the original [ReceiveChannel].
*/
@OptIn(ExperimentalStdlibApi::class)
public suspend fun <E> ReceiveChannel<E>.toList(): List<E> = buildList {
consumeEach {
add(it)
}
}
/**
* Subscribes to this [BroadcastChannel] and performs the specified action for each received element.
*
* **Note: This API will become obsolete in future updates with introduction of lazy asynchronous streams.**
* See [issue #254](https://github.com/Kotlin/kotlinx.coroutines/issues/254).
*/
@ObsoleteCoroutinesApi
public suspend inline fun <E> BroadcastChannel<E>.consumeEach(action: (E) -> Unit): Unit =
consume {
for (element in this) action(element)
}
@PublishedApi
internal fun ReceiveChannel<*>.cancelConsumed(cause: Throwable?) {
cancel(cause?.let {
it as? CancellationException ?: CancellationException("Channel was consumed, consumer had failed", it)
})
}
| apache-2.0 | efd6875ba805fccc0d7e5b5f7a73cb69 | 32.920863 | 110 | 0.706045 | 4.154185 | false | false | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit-result/src/main/kotlin/slatekit/results/Err.kt | 1 | 3025 | /**
* <slate_header>
* url: www.slatekit.com
* git: www.github.com/code-helix/slatekit
* org: www.codehelix.co
* author: Kishore Reddy
* copyright: 2016 CodeHelix Solutions Inc.
* license: refer to website and/or github
* about: A Kotlin Tool-Kit for Server + Android
* </slate_header>
*/
package slatekit.results
/**
* Err is an error representation for [Outcome] and can be created from
* 1. simple strings
* 2. exceptions
* 3. field with name/value
* 4. list of strings or Errs
*/
sealed class Err {
abstract val msg: String
abstract val err: Throwable?
abstract val ref: Any?
/**
* Different implementations for Error
*/
/**
* Default Error implementation to represent an error with message and optional throwable
*/
data class ErrorInfo(override val msg: String, override val err: Throwable? = null, override val ref: Any? = null) : Err()
/**
* Error implementation to represent an error on a specific field
* @param field: Name of the field causing the error e.g. "email"
* @param value: Value of the field causing the error e.g. "some_invalid_value"
*/
data class ErrorField(val field: String, val value: String, override val msg: String, override val err: Throwable? = null, override val ref: Any? = null) : Err()
/**
* Error implementation to store list of errors
* @param errors: List of all the errors
*/
data class ErrorList(val errors: List<Err>, override val msg: String, override val err: Throwable? = null, override val ref: Any? = null) : Err()
/**
* Provides easy ways to build the Err type from various sources such as strings, exceptions, field errors
*/
companion object {
@JvmStatic
fun of(msg: String, ex: Throwable? = null): Err {
return ErrorInfo(msg, ex)
}
@JvmStatic
fun on(field: String, value: String, msg: String, ex: Throwable? = null): Err {
return ErrorField(field, value, msg, ex)
}
@JvmStatic
fun ex(ex: Throwable): Err {
return ErrorInfo(ex.message ?: "", ex)
}
@JvmStatic
fun obj(err: Any): Err {
return ErrorInfo(err.toString(), null, err)
}
@JvmStatic
fun code(status: Status): Err {
return ErrorInfo(status.desc)
}
@JvmStatic
fun list(errors: List<String>, msg: String?): ErrorList {
return ErrorList(errors.map { ErrorInfo(it) }, msg ?: "Error occurred")
}
@JvmStatic
fun build(error: Any?): Err {
return when (error) {
null -> Err.of(Codes.UNEXPECTED.desc)
is Err -> error
is String -> Err.of(error)
is Exception -> Err.ex(error)
else -> Err.obj(error)
}
}
}
}
/**
* Error implementation extending from exception
*/
data class ExceptionErr(val msg: String, val err: Err) : Exception(msg)
| apache-2.0 | 605a5fb0b2b84537432d0dfa4c2de74c | 28.950495 | 165 | 0.600992 | 4.160935 | false | false | false | false |
VREMSoftwareDevelopment/WiFiAnalyzer | app/src/main/kotlin/com/vrem/wifianalyzer/wifi/graphutils/GraphColors.kt | 1 | 2305 | /*
* WiFiAnalyzer
* Copyright (C) 2015 - 2022 VREM Software Development <[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.vrem.wifianalyzer.wifi.graphutils
import com.vrem.annotation.OpenClass
import com.vrem.wifianalyzer.MainContext
import com.vrem.wifianalyzer.R
private fun String.toColor(): Long = this.substring(1).toLong(16)
data class GraphColor(val primary: Long, val background: Long)
internal val transparent = GraphColor(0x009E9E9E, 0x009E9E9E)
@OpenClass
class GraphColors {
private val availableGraphColors: MutableList<GraphColor> = mutableListOf()
private val currentGraphColors: ArrayDeque<GraphColor> = ArrayDeque()
private fun availableGraphColors(): List<GraphColor> {
if (availableGraphColors.isEmpty()) {
val colors = MainContext.INSTANCE.resources.getStringArray(R.array.graph_colors)
.filterNotNull()
.withIndex()
.groupBy { it.index / 2 }
.map { GraphColor(it.value[0].value.toColor(), it.value[1].value.toColor()) }
.reversed()
availableGraphColors.addAll(colors)
}
return availableGraphColors
}
fun graphColor(): GraphColor {
if (currentGraphColors.isEmpty()) {
currentGraphColors.addAll(availableGraphColors())
}
return currentGraphColors.removeFirst()
}
fun addColor(primaryColor: Long) {
availableGraphColors().firstOrNull { primaryColor == it.primary }?.let {
if (!currentGraphColors.contains(it)) {
currentGraphColors.addFirst(it)
}
}
}
}
| gpl-3.0 | 4cb70339c3c5e4197e59aa837d9c7936 | 34.461538 | 97 | 0.68026 | 4.382129 | false | false | false | false |
faceofcat/Tesla-Core-Lib | src/main/kotlin/net/ndrei/teslacorelib/render/selfrendering/baking-utils.kt | 1 | 8987 | package net.ndrei.teslacorelib.render.selfrendering
import net.minecraft.client.renderer.texture.TextureAtlasSprite
import net.minecraft.client.renderer.vertex.VertexFormatElement
import net.minecraft.util.EnumFacing
import net.minecraft.util.math.Vec2f
import net.minecraft.util.math.Vec3d
import net.minecraftforge.client.model.pipeline.UnpackedBakedQuad
import net.minecraftforge.common.model.TRSRTransformation
import javax.vecmath.Vector3f
/**
* Created by CF on 2017-07-16.
*/
fun UnpackedBakedQuad.Builder.putVertex(sprite: TextureAtlasSprite, normal: Vec3d, x: Double, y: Double, z: Double, u: Float, v: Float, color: Int, transform: TRSRTransformation?) {
for (e in 0 until this.vertexFormat.elementCount) {
when (this.vertexFormat.getElement(e).usage) {
VertexFormatElement.EnumUsage.POSITION -> {
val v = Vector3f(x.toFloat() - .5f, y.toFloat() - .5f, z.toFloat() - .5f)
if (transform != null) {
transform.matrix.transform(v)
}
this.put(e, v.x + .5f, v.y + .5f, v.z + .5f)
}
VertexFormatElement.EnumUsage.COLOR -> this.put(e,
((color ushr 16) and 0xFF) / 255.0f,
((color ushr 8) and 0xFF) / 255.0f,
(color and 0xFF) / 255.0f,
((color ushr 24) and 0xFF) / 255.0f)
VertexFormatElement.EnumUsage.UV -> this.put(e, u, v, 0f, 1f)
VertexFormatElement.EnumUsage.NORMAL -> this.put(e, normal.x.toFloat(), normal.y.toFloat(), normal.z.toFloat(), 0f)
else -> this.put(e)
}
}
}
fun TextureAtlasSprite.buildInfo(from: Vec2f, to: Vec2f, bothSides: Boolean = false, color: Int = -1)
= RawCubeSideInfo(this, from, to, bothSides, color)
fun TextureAtlasSprite.buildInfo(u1: Float, v1: Float, u2: Float, v2: Float, bothSides: Boolean = false, color: Int = -1)
= RawCubeSideInfo(this, Vec2f(u1, v1), Vec2f(u2, v2), bothSides, color)
fun MutableList<RawQuad>.addQuad(side: EnumFacing, sprite: TextureAtlasSprite, color: Int,
x1: Double, y1: Double, z1: Double, u1: Float, v1: Float,
x2: Double, y2: Double, z2: Double, u2: Float, v2: Float,
x3: Double, y3: Double, z3: Double, u3: Float, v3: Float,
x4: Double, y4: Double, z4: Double, u4: Float, v4: Float,
transform: TRSRTransformation?, tintIndex: Int = -1) {
this.add(RawQuad(
Vec3d(x1, y1, z1), u1, v1,
Vec3d(x2, y2, z2), u2, v2,
Vec3d(x3, y3, z3), u3, v3,
Vec3d(x4, y4, z4), u4, v4,
side, sprite, color, transform, tintIndex))
}
fun MutableList<RawQuad>.addDoubleQuad(side: EnumFacing, sprite: TextureAtlasSprite, color: Int,
x1: Double, y1: Double, z1: Double, u1: Float, v1: Float,
x2: Double, y2: Double, z2: Double, u2: Float, v2: Float,
x3: Double, y3: Double, z3: Double, u3: Float, v3: Float,
x4: Double, y4: Double, z4: Double, u4: Float, v4: Float,
transform: TRSRTransformation?, tintIndex: Int = -1) {
this.addQuad(side, sprite, color,
x1, y1, z1, u1, v1,
x2, y2, z2, u2, v2,
x3, y3, z3, u3, v3,
x4, y4, z4, u4, v4,
transform, tintIndex)
this.addQuad(side, sprite, color,
x4, y4, z4, u4, v4,
x3, y3, z3, u3, v3,
x2, y2, z2, u2, v2,
x1, y1, z1, u1, v1,
transform, tintIndex)
}
fun MutableList<RawQuad>.addFullQuad(side: EnumFacing, sprite: TextureAtlasSprite, color: Int,
x1: Double, y1: Double, z1: Double,
x2: Double, y2: Double, z2: Double,
x3: Double, y3: Double, z3: Double,
x4: Double, y4: Double, z4: Double, transform: TRSRTransformation?) {
this.addQuad(side, sprite, color,
x1, y1, z1, 0.0f, 0.0f,
x2, y2, z2, 16.0f, 0.0f,
x3, y3, z3, 16.0f, 16.0f,
x4, y4, z4, 0.0f, 16.0f,
transform)
}
fun MutableList<RawQuad>.addFullDoubleQuad(side: EnumFacing, sprite: TextureAtlasSprite, color: Int,
x1: Double, y1: Double, z1: Double,
x2: Double, y2: Double, z2: Double,
x3: Double, y3: Double, z3: Double,
x4: Double, y4: Double, z4: Double, transform: TRSRTransformation?) {
this.addDoubleQuad(side, sprite, color,
x1, y1, z1, 0.0f, 0.0f,
x2, y2, z2, 16.0f, 0.0f,
x3, y3, z3, 16.0f, 16.0f,
x4, y4, z4, 0.0f, 16.0f, transform)
}
fun MutableList<RawQuad>.addDoubleFace(facing: EnumFacing, sprite: TextureAtlasSprite, color: Int, transform: TRSRTransformation?) {
this.addDoubleFace(facing, sprite, color,
Vec3d(0.0, 0.0, 0.0),
Vec3d(32.0, 32.0, 32.0),
Vec2f(0.0f, 0.0f),
Vec2f(16.0f, 16.0f),
transform)
}
fun MutableList<RawQuad>.addDoubleFace(facing: EnumFacing, sprite: TextureAtlasSprite, color: Int, p1: Vec3d, p2: Vec3d, t1: Vec2f, t2: Vec2f, transform: TRSRTransformation?, tintIndex: Int = -1) {
addFace(facing, sprite, color, p1, p2, t1, t2) {
p1, t1,
p2, t2,
p3, t3,
p4, t4,
f, s, a ->
this.addDoubleQuad(f, s, a,
p1.x, p1.y, p1.z, t1.x, t1.y,
p2.x, p2.y, p2.z, t2.x, t2.y,
p3.x, p3.y, p3.z, t3.x, t3.y,
p4.x, p4.y, p4.z, t4.x, t4.y,
transform, tintIndex)
}
}
fun MutableList<RawQuad>.addSingleFace(facing: EnumFacing, sprite: TextureAtlasSprite, color: Int, p1: Vec3d, p2: Vec3d, t1: Vec2f, t2: Vec2f, transform: TRSRTransformation, tintIndex: Int = -1) {
addFace(facing, sprite, color, p1, p2, t1, t2) {
p1, t1,
p2, t2,
p3, t3,
p4, t4,
f, s, a ->
this.addQuad(f, s, a,
p1.x, p1.y, p1.z, t1.x, t1.y,
p2.x, p2.y, p2.z, t2.x, t2.y,
p3.x, p3.y, p3.z, t3.x, t3.y,
p4.x, p4.y, p4.z, t4.x, t4.y,
transform, tintIndex)
}
}
fun addFace(facing: EnumFacing, sprite: TextureAtlasSprite, color: Int, p1: Vec3d, p2: Vec3d, t1: Vec2f, t2: Vec2f,
thingy: (p1: Vec3d, t1: Vec2f,
p2: Vec3d, t2: Vec2f,
p3: Vec3d, t3: Vec2f,
p4: Vec3d, t4: Vec2f,
facing: EnumFacing, sprite: TextureAtlasSprite, color: Int) -> Unit) {
when (facing) {
EnumFacing.DOWN -> thingy(
Vec3d(p1.x, p1.y, p1.z), Vec2f(t1.x, t1.y),
Vec3d(p2.x, p1.y, p1.z), Vec2f(t2.x, t1.y),
Vec3d(p2.x, p1.y, p2.z), Vec2f(t2.x, t2.y),
Vec3d(p1.x, p1.y, p2.z), Vec2f(t1.x, t2.y),
facing, sprite, color)
EnumFacing.UP -> thingy(
Vec3d(p2.x, p2.y, p1.z), Vec2f(t2.x, t1.y),
Vec3d(p1.x, p2.y, p1.z), Vec2f(t1.x, t1.y),
Vec3d(p1.x, p2.y, p2.z), Vec2f(t1.x, t2.y),
Vec3d(p2.x, p2.y, p2.z), Vec2f(t2.x, t2.y),
facing, sprite, color)
EnumFacing.NORTH -> thingy(
Vec3d(p1.x, p2.y, p1.z), Vec2f(t1.x, t2.y),
Vec3d(p2.x, p2.y, p1.z), Vec2f(t2.x, t2.y),
Vec3d(p2.x, p1.y, p1.z), Vec2f(t2.x, t1.y),
Vec3d(p1.x, p1.y, p1.z), Vec2f(t1.x, t1.y),
facing, sprite, color)
EnumFacing.SOUTH -> thingy(
Vec3d(p2.x, p2.y, p2.z), Vec2f(t2.x, t2.y),
Vec3d(p1.x, p2.y, p2.z), Vec2f(t1.x, t2.y),
Vec3d(p1.x, p1.y, p2.z), Vec2f(t1.x, t1.y),
Vec3d(p2.x, p1.y, p2.z), Vec2f(t2.x, t1.y),
facing, sprite, color)
EnumFacing.EAST -> thingy(
Vec3d(p2.x, p2.y, p1.z), Vec2f(t1.x, t2.y),
Vec3d(p2.x, p2.y, p2.z), Vec2f(t2.x, t2.y),
Vec3d(p2.x, p1.y, p2.z), Vec2f(t2.x, t1.y),
Vec3d(p2.x, p1.y, p1.z), Vec2f(t1.x, t1.y),
facing, sprite, color)
EnumFacing.WEST -> thingy(
Vec3d(p1.x, p2.y, p2.z), Vec2f(t2.x, t2.y),
Vec3d(p1.x, p2.y, p1.z), Vec2f(t1.x, t2.y),
Vec3d(p1.x, p1.y, p1.z), Vec2f(t1.x, t1.y),
Vec3d(p1.x, p1.y, p2.z), Vec2f(t2.x, t1.y),
facing, sprite, color)
}
} | mit | e23927c638e437c9ad8967f5e43617e6 | 47.322581 | 197 | 0.50217 | 2.811073 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/extensionProperties/kt9897_topLevel.kt | 5 | 622 | var z = "0"
var l = 0L
fun changeObject(): String {
"1".someProperty += 1
return z
}
fun changeLong(): Long {
2L.someProperty -= 1
return l
}
var String.someProperty: Int
get() {
return this.length
}
set(left) {
z += this + left
}
var Long.someProperty: Long
get() {
return l
}
set(left) {
l += this + left
}
fun box(): String {
val changeObject = changeObject()
if (changeObject != "012") return "fail 1: $changeObject"
val changeLong = changeLong()
if (changeLong != 1L) return "fail 1: $changeLong"
return "OK"
} | apache-2.0 | 3384e59e3faac447e258e1ff0fc64122 | 15.394737 | 61 | 0.554662 | 3.344086 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/reflection/properties/mutatePrivateJavaInstanceField.kt | 2 | 456 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// WITH_REFLECT
// FILE: J.java
public class J {
private String result = "Fail";
}
// FILE: K.kt
import kotlin.reflect.*
import kotlin.reflect.jvm.*
fun box(): String {
val a = J()
val p = J::class.members.single { it.name == "result" } as KMutableProperty1<J, String>
p.isAccessible = true
p.set(a, "OK")
return p.get(a)
}
| apache-2.0 | 27d749180059be41c9e159e55c70a5d4 | 19.727273 | 91 | 0.642544 | 3.166667 | false | false | false | false |
smmribeiro/intellij-community | platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/SdkLookupUtil.kt | 10 | 1708 | // 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.
@file:JvmName("SdkLookupUtil")
package com.intellij.openapi.roots.ui.configuration
import com.intellij.openapi.application.WriteAction
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.projectRoots.SdkType
import com.intellij.util.ThrowableRunnable
import java.util.concurrent.CompletableFuture
/**
* Finds sdk at everywhere with parameters that defined by [configure]
*
* Note: this function block current thread until sdk is resolved
*/
fun lookupSdk(configure: (SdkLookupBuilder) -> SdkLookupBuilder): Sdk? {
val provider = SdkLookupProviderImpl()
var builder = provider.newLookupBuilder()
builder = configure(builder)
builder.executeLookup()
return provider.blockingGetSdk()
}
fun findAndSetupSdk(project: Project, indicator: ProgressIndicator, sdkType: SdkType, applySdk: (Sdk) -> Unit) {
val future = CompletableFuture<Sdk>()
SdkLookup.newLookupBuilder()
.withProgressIndicator(indicator)
.withSdkType(sdkType)
.withVersionFilter { true }
.withProject(project)
.onDownloadableSdkSuggested { SdkLookupDecision.STOP }
.onSdkResolved {
future.complete(it)
}
.executeLookup()
try {
val sdk = future.get()
if (sdk != null) {
WriteAction.runAndWait(
ThrowableRunnable { applySdk.invoke(sdk) }
)
}
}
catch (t: Throwable) {
Logger.getInstance("sdk.lookup").warn("Couldn't lookup for a SDK", t)
}
} | apache-2.0 | e5784e983bc9a41a8fc32d5c6e0218dc | 32.509804 | 140 | 0.747658 | 4.206897 | false | true | false | false |
kickstarter/android-oss | app/src/test/java/com/kickstarter/viewmodels/MessageThreadHolderViewModelTest.kt | 1 | 5876 | package com.kickstarter.viewmodels
import com.kickstarter.KSRobolectricTestCase
import com.kickstarter.libs.Environment
import com.kickstarter.libs.utils.NumberUtils
import com.kickstarter.mock.factories.MessageThreadFactory.messageThread
import com.kickstarter.models.MessageThread
import org.joda.time.DateTime
import org.junit.Test
import rx.observers.TestSubscriber
class MessageThreadHolderViewModelTest : KSRobolectricTestCase() {
private lateinit var vm: MessageThreadHolderViewModel.ViewModel
private val cardViewIsElevated = TestSubscriber<Boolean>()
private val dateDateTime = TestSubscriber<DateTime>()
private val dateTextViewIsBold = TestSubscriber<Boolean>()
private val messageBodyTextIsBold = TestSubscriber<Boolean>()
private val messageBodyTextViewText = TestSubscriber<String>()
private val participantAvatarUrl = TestSubscriber<String>()
private val participantNameTextViewIsBold = TestSubscriber<Boolean>()
private val participantNameTextViewText = TestSubscriber<String>()
private val startMessagesActivity = TestSubscriber<MessageThread>()
private val unreadCountTextViewIsGone = TestSubscriber<Boolean>()
private val unreadCountTextViewText = TestSubscriber<String>()
private fun setUpEnvironment(env: Environment) {
vm = MessageThreadHolderViewModel.ViewModel(env)
vm.outputs.cardViewIsElevated().subscribe(cardViewIsElevated)
vm.outputs.dateDateTime().subscribe(dateDateTime)
vm.outputs.dateTextViewIsBold().subscribe(dateTextViewIsBold)
vm.outputs.messageBodyTextIsBold().subscribe(messageBodyTextIsBold)
vm.outputs.messageBodyTextViewText().subscribe(messageBodyTextViewText)
vm.outputs.participantAvatarUrl().subscribe(participantAvatarUrl)
vm.outputs.participantNameTextViewIsBold().subscribe(participantNameTextViewIsBold)
vm.outputs.participantNameTextViewText().subscribe(participantNameTextViewText)
vm.outputs.startMessagesActivity().subscribe(startMessagesActivity)
vm.outputs.unreadCountTextViewIsGone().subscribe(unreadCountTextViewIsGone)
vm.outputs.unreadCountTextViewText().subscribe(unreadCountTextViewText)
}
@Test
fun testEmitsDateTime() {
val messageThread = messageThread()
setUpEnvironment(environment())
// Configure the view model with a message thread.
vm.inputs.configureWith(messageThread)
dateDateTime.assertValues(messageThread.lastMessage()?.createdAt()!!)
}
@Test
fun testEmitsMessageBodyTextViewText() {
val messageThread = messageThread()
setUpEnvironment(environment())
// Configure the view model with a message thread.
vm.inputs.configureWith(messageThread)
messageBodyTextViewText.assertValues(messageThread.lastMessage()?.body()!!)
}
@Test
fun testEmitsParticipantData() {
val messageThread = messageThread()
setUpEnvironment(environment())
// Configure the view model with a message thread.
vm.inputs.configureWith(messageThread)
// Emits participant's avatar url and name.
participantAvatarUrl.assertValues(messageThread.participant()?.avatar()?.medium()!!)
participantNameTextViewText.assertValues(messageThread.participant()?.name()!!)
}
@Test
fun testMessageThread_Clicked() {
val messageThread = messageThread()
.toBuilder()
.id(12345)
.unreadMessagesCount(1)
.build()
setUpEnvironment(environment())
vm.inputs.configureWith(messageThread)
cardViewIsElevated.assertValues(true)
dateTextViewIsBold.assertValues(true)
messageBodyTextIsBold.assertValues(true)
unreadCountTextViewIsGone.assertValues(false)
vm.inputs.messageThreadCardViewClicked()
cardViewIsElevated.assertValues(true, false)
dateTextViewIsBold.assertValues(true, false)
messageBodyTextIsBold.assertValues(true, false)
unreadCountTextViewIsGone.assertValues(false, true)
}
@Test
fun testMessageThread_HasNoUnreadMessages() {
val messageThreadWithNoUnread = messageThread()
.toBuilder()
.unreadMessagesCount(0)
.build()
setUpEnvironment(environment())
// Configure the view model with a message thread with no unread messages.
vm.inputs.configureWith(messageThreadWithNoUnread)
dateTextViewIsBold.assertValues(false)
messageBodyTextIsBold.assertValues(false)
participantNameTextViewIsBold.assertValues(false)
unreadCountTextViewIsGone.assertValues(true)
unreadCountTextViewText.assertValues(NumberUtils.format(messageThreadWithNoUnread.unreadMessagesCount()!!))
}
@Test
fun testMessageThread_HasUnreadMessages() {
val messageThreadWithUnread = messageThread()
.toBuilder()
.unreadMessagesCount(2)
.build()
setUpEnvironment(environment())
// Configure the view model with a message thread with unread messages.
vm.inputs.configureWith(messageThreadWithUnread)
dateTextViewIsBold.assertValues(true)
messageBodyTextIsBold.assertValues(true)
participantNameTextViewIsBold.assertValues(true)
unreadCountTextViewIsGone.assertValues(false)
unreadCountTextViewText.assertValues(NumberUtils.format(messageThreadWithUnread.unreadMessagesCount()!!))
}
@Test
fun testStartMessagesActivity() {
val messageThread = messageThread()
setUpEnvironment(environment())
// Configure the view model with a message thread.
vm.inputs.configureWith(messageThread)
vm.inputs.messageThreadCardViewClicked()
startMessagesActivity.assertValues(messageThread)
}
}
| apache-2.0 | 8a7d4a12af87db2b746d807ad8f499b5 | 37.657895 | 115 | 0.73162 | 5.435708 | false | true | false | false |
DroidSmith/TirePressureGuide | tireguide/src/test/java/com/droidsmith/tireguide/calcengine/CalculatorSpecTest.kt | 1 | 7598 | package com.droidsmith.tireguide.calcengine
import io.kotlintest.matchers.plusOrMinus
import io.kotlintest.matchers.shouldBe
import io.kotlintest.properties.forAll
import io.kotlintest.properties.headers
import io.kotlintest.properties.row
import io.kotlintest.properties.table
import io.kotlintest.specs.ShouldSpec
import kotlin.math.roundToLong
class CalculatorSpecTest : ShouldSpec() {
init {
val calculator = Calculator()
"supported tire widths" {
should("return correct psi for 20mm tire") {
val psiTable = table(headers("loadWeight", " tireWidth", "psi"),
row(0.0, "20", -11),
row(8.0, "20", 0),
row(50.0, "20", 57),
row(100.0, "20", 125),
row(63.9, "20", 76),
row(77.4, "20", 95),
row(84.15, "20", 104),
row(85.2, "20", 105),
row(91.8, "20", 114),
row(102.6, "20", 129),
row(103.2, "20", 130),
row(105.3, "20", 133),
row(112.2, "20", 142),
row(122.4, "20", 156),
row(136.9, "20", 176),
row(140.4, "20", 180))
forAll(psiTable) { loadWeight, tireWidth, psi ->
calculator.psi(loadWeight,
tireWidth) shouldBe (psi.toDouble().roundToLong().toDouble() plusOrMinus 0.5)
}
}
should("return correct psi for 21mm tire") {
val psiTable = table(headers("loadWeight", " tireWidth", "psi"),
row(0.0, "21", 0),
row(50.0, "21", 59),
row(100.0, "21", 118),
row(63.9, "21", 76),
row(77.4, "21", 91),
row(84.15, "21", 99),
row(85.2, "21", 101),
row(91.8, "21", 108),
row(102.6, "21", 121),
row(103.2, "21", 122),
row(105.3, "21", 124),
row(112.2, "21", 133),
row(122.4, "21", 145),
row(136.9, "21", 162),
row(140.4, "21", 166))
forAll(psiTable) { loadWeight, tireWidth, psi ->
calculator.psi(loadWeight,
tireWidth) shouldBe (psi.toDouble().roundToLong().toDouble() plusOrMinus 0.5)
}
}
should("return correct psi for 22mm tire") {
val psiTable = table(headers("loadWeight", " tireWidth", "psi"),
row(0.0, "22", -6),
row(5.0, "22", 0),
row(50.0, "22", 52),
row(100.0, "22", 111),
row(63.9, "22", 68),
row(77.4, "22", 84),
row(84.15, "22", 92),
row(85.2, "22", 93),
row(91.8, "22", 101),
row(102.6, "22", 114),
row(103.2, "22", 114),
row(105.3, "22", 117),
row(112.2, "22", 125),
row(122.4, "22", 137),
row(136.9, "22", 154),
row(140.4, "22", 158))
forAll(psiTable) { loadWeight, tireWidth, psi ->
calculator.psi(loadWeight,
tireWidth) shouldBe (psi.toDouble().roundToLong().toDouble() plusOrMinus 0.5)
}
}
should("return correct psi for 23mm tire") {
val psiTable = table(headers("loadWeight", " tireWidth", "psi"),
row(0.0, "23", -9),
row(8.0, "23", 0),
row(50.0, "23", 47),
row(100.0, "23", 104),
row(63.9, "23", 63),
row(77.4, "23", 78),
row(84.15, "23", 86),
row(85.2, "23", 87),
row(91.8, "23", 95),
row(102.6, "23", 107),
row(103.2, "23", 108),
row(105.3, "23", 110),
row(112.2, "23", 118),
row(122.4, "23", 130),
row(136.9, "23", 146),
row(140.4, "23", 150))
forAll(psiTable) { loadWeight, tireWidth, psi ->
calculator.psi(loadWeight,
tireWidth) shouldBe (psi.toDouble().roundToLong().toDouble() plusOrMinus 0.5)
}
}
should("return correct psi for 24mm tire") {
val psiTable = table(headers("loadWeight", " tireWidth", "psi"),
row(0.0, "24", -10),
row(10.0, "24", 0),
row(50.0, "24", 42),
row(100.0, "24", 95),
row(63.9, "24", 57),
row(77.4, "24", 71),
row(84.15, "24", 78),
row(85.2, "24", 79),
row(91.8, "24", 86),
row(102.6, "24", 98),
row(103.2, "24", 98),
row(105.3, "24", 101),
row(112.2, "24", 108),
row(122.4, "24", 119),
row(136.9, "24", 134),
row(140.4, "24", 138))
forAll(psiTable) { loadWeight, tireWidth, psi ->
calculator.psi(loadWeight,
tireWidth) shouldBe (psi.toDouble().roundToLong().toDouble() plusOrMinus 0.5)
}
}
should("return correct psi for 25mm tire") {
val psiTable = table(headers("loadWeight", " tireWidth", "psi"),
row(0.0, "25", -13),
row(13.0, "25", 0),
row(50.0, "25", 37),
row(100.0, "25", 87),
row(63.9, "25", 51),
row(77.4, "25", 64),
row(84.15, "25", 71),
row(85.2, "25", 72),
row(91.8, "25", 79),
row(102.6, "25", 90),
row(103.2, "25", 90),
row(105.3, "25", 92),
row(112.2, "25", 99),
row(122.4, "25", 109),
row(136.9, "25", 124),
row(140.4, "25", 127))
forAll(psiTable) { loadWeight, tireWidth, psi ->
calculator.psi(loadWeight,
tireWidth) shouldBe (psi.toDouble().roundToLong().toDouble() plusOrMinus 0.5)
}
}
should("return correct psi for 26mm tire") {
val psiTable = table(headers("loadWeight", " tireWidth", "psi"),
row(0.0, "26", -13),
row(13.0, "26", 0),
row(50.0, "26", 35),
row(100.0, "26", 83),
row(63.9, "26", 48),
row(77.4, "26", 61),
row(84.15, "26", 68),
row(85.2, "26", 69),
row(91.8, "26", 75),
row(102.6, "26", 85),
row(103.2, "26", 86),
row(105.3, "26", 88),
row(112.2, "26", 94),
row(122.4, "26", 104),
row(136.9, "26", 118),
row(140.4, "26", 121))
forAll(psiTable) { loadWeight, tireWidth, psi ->
calculator.psi(loadWeight,
tireWidth) shouldBe (psi.toDouble().roundToLong().toDouble() plusOrMinus 0.5)
}
}
should("return correct psi for 27mm tire") {
val psiTable = table(headers("loadWeight", " tireWidth", "psi"),
row(0.0, "27", -8),
row(10.0, "27", 0),
row(50.0, "27", 36),
row(100.0, "27", 80),
row(63.9, "27", 48),
row(77.4, "27", 60),
row(84.15, "27", 66),
row(85.2, "27", 67),
row(91.8, "27", 73),
row(102.6, "27", 82),
row(103.2, "27", 83),
row(105.3, "27", 85),
row(112.2, "27", 91),
row(122.4, "27", 100),
row(136.9, "27", 113),
row(140.4, "27", 116))
forAll(psiTable) { loadWeight, tireWidth, psi ->
calculator.psi(loadWeight,
tireWidth) shouldBe (psi.toDouble().roundToLong().toDouble() plusOrMinus 0.5)
}
}
should("return correct psi for 28mm tire") {
val psiTable = table(headers("loadWeight", " tireWidth", "psi"),
row(0.0, "28", -6),
row(8.0, "28", 0),
row(50.0, "28", 34),
row(100.0, "28", 74),
row(63.9, "28", 45),
row(77.4, "28", 56),
row(84.15, "28", 61),
row(85.2, "28", 62),
row(91.8, "28", 67),
row(102.6, "28", 76),
row(103.2, "28", 76),
row(105.3, "28", 78),
row(112.2, "28", 84),
row(122.4, "28", 92),
row(136.9, "28", 103),
row(140.4, "28", 106))
forAll(psiTable) { loadWeight, tireWidth, psi ->
calculator.psi(loadWeight,
tireWidth) shouldBe (psi.toDouble().roundToLong().toDouble() plusOrMinus 0.5)
}
}
}
"unsupported tire widths" {
should("return 0 psi") {
val psiTable = table(headers("loadWeight", " tireWidth", "psi"),
row(0.0, "", 0),
row(50.0, "", 0),
row(100.0, "", 0),
row(0.0, "29", 0),
row(50.0, "29", 0),
row(100.0, "29", 0))
forAll(psiTable) { loadWeight, tireWidth, psi ->
calculator.psi(loadWeight,
tireWidth) shouldBe (psi.toDouble().roundToLong().toDouble() plusOrMinus 0.5)
}
}
}
}
}
| apache-2.0 | 9d777407c197ec27eefe5e2a57b42f5c | 29.761134 | 84 | 0.518952 | 2.558249 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/base/scripting/src/org/jetbrains/kotlin/idea/highlighter/ScriptExternalHighlightingPass.kt | 1 | 5630 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.highlighter
import com.intellij.codeHighlighting.*
import com.intellij.codeInsight.daemon.impl.HighlightInfo
import com.intellij.codeInsight.daemon.impl.UpdateHighlightersUtil
import com.intellij.lang.annotation.Annotation
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.lang.annotation.HighlightSeverity.*
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.MessageType
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.wm.WindowManager
import com.intellij.openapi.wm.ex.StatusBarEx
import com.intellij.psi.PsiFile
import com.intellij.util.ui.UIUtil
import org.jetbrains.kotlin.idea.core.script.IdeScriptReportSink
import org.jetbrains.kotlin.idea.script.ScriptDiagnosticFixProvider
import org.jetbrains.kotlin.idea.util.application.isApplicationInternalMode
import org.jetbrains.kotlin.psi.KtFile
import kotlin.script.experimental.api.ScriptDiagnostic
import kotlin.script.experimental.api.SourceCode
class ScriptExternalHighlightingPass(
private val file: KtFile,
document: Document
) : TextEditorHighlightingPass(file.project, document), DumbAware {
override fun doCollectInformation(progress: ProgressIndicator) = Unit
override fun doApplyInformationToEditor() {
val document = document
if (!file.isScript()) return
val reports = IdeScriptReportSink.getReports(file)
val annotations = reports.mapNotNull { scriptDiagnostic ->
val (startOffset, endOffset) = scriptDiagnostic.location?.let { computeOffsets(document, it) } ?: (0 to 0)
val exception = scriptDiagnostic.exception
val exceptionMessage = if (exception != null) " ($exception)" else ""
@Suppress("HardCodedStringLiteral")
val message = scriptDiagnostic.message + exceptionMessage
val annotation = Annotation(
startOffset,
endOffset,
scriptDiagnostic.severity.convertSeverity() ?: return@mapNotNull null,
message,
message
)
// if range is empty, show notification panel in editor
annotation.isFileLevelAnnotation = startOffset == endOffset
for (provider in ScriptDiagnosticFixProvider.EP_NAME.extensions) {
provider.provideFixes(scriptDiagnostic).forEach {
annotation.registerFix(it)
}
}
annotation
}
val infos = annotations.map { HighlightInfo.fromAnnotation(it) }
UpdateHighlightersUtil.setHighlightersToEditor(myProject, myDocument, 0, file.textLength, infos, colorsScheme, id)
}
private fun computeOffsets(document: Document, position: SourceCode.Location): Pair<Int, Int> {
val startLine = position.start.line.coerceLineIn(document)
val startOffset = document.offsetBy(startLine, position.start.col)
val endLine = position.end?.line?.coerceAtLeast(startLine)?.coerceLineIn(document) ?: startLine
val endOffset = document.offsetBy(
endLine,
position.end?.col ?: document.getLineEndOffset(endLine)
).coerceAtLeast(startOffset)
return startOffset to endOffset
}
private fun Int.coerceLineIn(document: Document) = coerceIn(0, document.lineCount - 1)
private fun Document.offsetBy(line: Int, col: Int): Int {
return (getLineStartOffset(line) + col).coerceIn(getLineStartOffset(line), getLineEndOffset(line))
}
private fun ScriptDiagnostic.Severity.convertSeverity(): HighlightSeverity? {
return when (this) {
ScriptDiagnostic.Severity.FATAL -> ERROR
ScriptDiagnostic.Severity.ERROR -> ERROR
ScriptDiagnostic.Severity.WARNING -> WARNING
ScriptDiagnostic.Severity.INFO -> INFORMATION
ScriptDiagnostic.Severity.DEBUG -> if (isApplicationInternalMode()) INFORMATION else null
}
}
private fun showNotification(file: KtFile, @NlsContexts.PopupContent message: String) {
UIUtil.invokeLaterIfNeeded {
val ideFrame = WindowManager.getInstance().getIdeFrame(file.project)
if (ideFrame != null) {
val statusBar = ideFrame.statusBar as StatusBarEx
statusBar.notifyProgressByBalloon(
MessageType.WARNING,
message,
null,
null
)
}
}
}
class Registrar : TextEditorHighlightingPassFactoryRegistrar {
override fun registerHighlightingPassFactory(registrar: TextEditorHighlightingPassRegistrar, project: Project) {
registrar.registerTextEditorHighlightingPass(
Factory(),
TextEditorHighlightingPassRegistrar.Anchor.BEFORE,
Pass.UPDATE_FOLDING,
false,
false
)
}
}
class Factory : TextEditorHighlightingPassFactory {
override fun createHighlightingPass(file: PsiFile, editor: Editor): TextEditorHighlightingPass? {
if (file !is KtFile) return null
return ScriptExternalHighlightingPass(file, editor.document)
}
}
}
| apache-2.0 | 842a31bca37b2466ac717578243a6372 | 41.014925 | 158 | 0.690586 | 5.242086 | false | false | false | false |
NativeScript/android-runtime | test-app/build-tools/android-metadata-generator/src/src/com/telerik/metadata/parsing/NativeClassDescriptor.kt | 1 | 1511 | package com.telerik.metadata.parsing
/**
* Describes the properties of a native class
*/
interface NativeClassDescriptor : AccessModifiable, NativeDescriptor {
val isClass: Boolean
val isInterface: Boolean
val isEnum: Boolean
val isStatic: Boolean
val methods: Array<out NativeMethodDescriptor>
val properties: Array<out NativePropertyDescriptor>
val fields: Array<out NativeFieldDescriptor>
val metadataInfoAnnotation: MetadataInfoAnnotationDescriptor?
val interfaceNames: Array<String>
val packageName: String
val className: String
val superclassName: String
companion object Missing : NativeClassDescriptor {
override val isClass = false
override val isInterface = false
override val isEnum = false
override val isStatic = false
override val methods = emptyArray<NativeMethodDescriptor>()
override val properties = emptyArray<NativePropertyDescriptor>()
override val fields = emptyArray<NativeFieldDescriptor>()
override val metadataInfoAnnotation: MetadataInfoAnnotationDescriptor? = null
override val interfaceNames = emptyArray<String>()
override val packageName = ""
override val className = ""
override val superclassName = ""
override val isPublic = false
override val isInternal = false
override val isProtected = false
override val isPackagePrivate = false
override val isPrivate = false
}
}
| apache-2.0 | ad20e7bbb16eb4706c770f8fa9c1a7dc | 28.627451 | 85 | 0.710788 | 5.902344 | false | false | false | false |
JetBrains/kotlin-native | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/lower/PostInlineLowering.kt | 1 | 5866 | /*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package org.jetbrains.kotlin.backend.konan.lower
import org.jetbrains.kotlin.backend.common.BodyLoweringPass
import org.jetbrains.kotlin.backend.common.ir.Symbols
import org.jetbrains.kotlin.backend.common.lower.at
import org.jetbrains.kotlin.backend.common.lower.createIrBuilder
import org.jetbrains.kotlin.backend.konan.Context
import org.jetbrains.kotlin.backend.konan.renderCompilerError
import org.jetbrains.kotlin.ir.builders.IrBuilderWithScope
import org.jetbrains.kotlin.ir.declarations.IrDeclaration
import org.jetbrains.kotlin.ir.declarations.IrDeclarationBase
import org.jetbrains.kotlin.ir.declarations.IrSimpleFunction
import org.jetbrains.kotlin.ir.declarations.IrSymbolOwner
import org.jetbrains.kotlin.ir.expressions.*
import org.jetbrains.kotlin.ir.expressions.impl.IrConstImpl
import org.jetbrains.kotlin.ir.symbols.IrClassSymbol
import org.jetbrains.kotlin.ir.util.file
import org.jetbrains.kotlin.ir.util.irCall
import org.jetbrains.kotlin.ir.visitors.IrElementTransformer
/**
* This pass runs after inlining and performs the following additional transformations over some operations:
* - Convert immutableBlobOf() arguments to special IrConst.
* - Convert `obj::class` and `Class::class` to calls.
*/
internal class PostInlineLowering(val context: Context) : BodyLoweringPass {
private val symbols get() = context.ir.symbols
override fun lower(irBody: IrBody, container: IrDeclaration) {
val irFile = container.file
irBody.transformChildren(object : IrElementTransformer<IrBuilderWithScope> {
override fun visitDeclaration(declaration: IrDeclarationBase, data: IrBuilderWithScope) =
super.visitDeclaration(declaration,
data = (declaration as? IrSymbolOwner)?.let { context.createIrBuilder(it.symbol, it.startOffset, it.endOffset) }
?: data
)
override fun visitClassReference(expression: IrClassReference, data: IrBuilderWithScope): IrExpression {
expression.transformChildren(this, data)
return data.at(expression).run {
(expression.symbol as? IrClassSymbol)?.let { irKClass([email protected], it) }
?:
// E.g. for `T::class` in a body of an inline function itself.
irCall(symbols.throwNullPointerException.owner)
}
}
override fun visitGetClass(expression: IrGetClass, data: IrBuilderWithScope): IrExpression {
expression.transformChildren(this, data)
return data.at(expression).run {
irCall(symbols.kClassImplConstructor, listOf(expression.argument.type)).apply {
val typeInfo = irCall(symbols.getObjectTypeInfo).apply {
putValueArgument(0, expression.argument)
}
putValueArgument(0, typeInfo)
}
}
}
override fun visitCall(expression: IrCall, data: IrBuilderWithScope): IrExpression {
expression.transformChildren(this, data)
// Function inlining is changing function symbol at callsite
// and unbound symbol replacement is happening later.
// So we compare descriptors for now.
if (expression.symbol == symbols.immutableBlobOf) {
// Convert arguments of the binary blob to special IrConst<String> structure, so that
// vararg lowering will not affect it.
val args = expression.getValueArgument(0) as? IrVararg
?: error("varargs shall not be lowered yet")
val builder = StringBuilder()
args.elements.forEach {
require(it is IrConst<*>) { renderCompilerError(irFile, it, "expected const") }
val value = (it as? IrConst<*>)?.value
require(value is Short && value >= 0 && value <= 0xff) {
renderCompilerError(irFile, it, "incorrect value for binary data: $value")
}
// Luckily, all values in range 0x00 .. 0xff represent valid UTF-16 symbols,
// block 0 (Basic Latin) and block 1 (Latin-1 Supplement) in
// Basic Multilingual Plane, so we could just append data "as is".
builder.append(value.toChar())
}
expression.putValueArgument(0, IrConstImpl(
expression.startOffset, expression.endOffset,
context.irBuiltIns.stringType,
IrConstKind.String, builder.toString()))
} else if (Symbols.isTypeOfIntrinsic(expression.symbol)) {
// Inline functions themselves are not called (they have been inlined at all call sites),
// so it is ok not to build exact type parameters for them.
val needExactTypeParameters = (container as? IrSimpleFunction)?.isInline != true
return with (KTypeGenerator(context, irFile, expression, needExactTypeParameters)) {
data.at(expression).irKType(expression.getTypeArgument(0)!!, leaveReifiedForLater = false)
}
}
return expression
}
}, data = context.createIrBuilder((container as IrSymbolOwner).symbol, irBody.startOffset, irBody.endOffset))
}
} | apache-2.0 | 63072db6e8227e35b4f028c9f667d4ee | 52.825688 | 140 | 0.620525 | 5.200355 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/gradle/gradle-tooling/src/org/jetbrains/kotlin/idea/gradleTooling/reflect/KotlinCompilationReflection.kt | 1 | 2344 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.gradleTooling.reflect
import org.gradle.api.Named
import org.jetbrains.kotlin.idea.gradleTooling.getMethodOrNull
fun KotlinCompilationReflection(kotlinCompilation: Any): KotlinCompilationReflection =
KotlinCompilationReflectionImpl(kotlinCompilation)
interface KotlinCompilationReflection {
val compilationName: String
val gradleCompilation: Named
val sourceSets: Collection<Named>? // Source Sets that directly added to compilation
val allSourceSets: Collection<Named>? // this.sourceSets + their transitive closure through dependsOn relation
val compilationOutput: KotlinCompilationOutputReflection?
val konanTargetName: String?
val compileKotlinTaskName: String?
}
private class KotlinCompilationReflectionImpl(private val instance: Any) : KotlinCompilationReflection {
override val gradleCompilation: Named
get() = instance as Named
override val compilationName: String by lazy {
gradleCompilation.name
}
override val sourceSets: Collection<Named>? by lazy {
instance.callReflectiveGetter("getKotlinSourceSets", logger)
}
override val allSourceSets: Collection<Named>? by lazy {
instance.callReflectiveGetter("getAllKotlinSourceSets", logger)
}
override val compilationOutput: KotlinCompilationOutputReflection? by lazy {
instance.callReflectiveAnyGetter("getOutput", logger)?.let { gradleOutput -> KotlinCompilationOutputReflection(gradleOutput) }
}
// Get konanTarget (for native compilations only).
override val konanTargetName: String? by lazy {
if (instance.javaClass.getMethodOrNull("getKonanTarget") == null) null
else instance.callReflectiveAnyGetter("getKonanTarget", logger)
?.callReflectiveGetter("getName", logger)
}
override val compileKotlinTaskName: String? by lazy {
instance.callReflectiveGetter("getCompileKotlinTaskName", logger)
}
companion object {
private val logger: ReflectionLogger = ReflectionLogger(KotlinCompilationReflection::class.java)
private const val NATIVE_COMPILATION_CLASS = "org.jetbrains.kotlin.gradle.plugin.mpp.AbstractKotlinNativeCompilation"
}
} | apache-2.0 | c5b5d94eaae594ef95b73354582208d5 | 43.245283 | 134 | 0.763652 | 5.363844 | false | false | false | false |
SimpleMobileTools/Simple-Calendar | app/src/main/kotlin/com/simplemobiletools/calendar/pro/models/EventType.kt | 1 | 940 | package com.simplemobiletools.calendar.pro.models
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
import com.simplemobiletools.calendar.pro.helpers.OTHER_EVENT
@Entity(tableName = "event_types", indices = [(Index(value = ["id"], unique = true))])
data class EventType(
@PrimaryKey(autoGenerate = true) var id: Long?,
@ColumnInfo(name = "title") var title: String,
@ColumnInfo(name = "color") var color: Int,
@ColumnInfo(name = "caldav_calendar_id") var caldavCalendarId: Int = 0,
@ColumnInfo(name = "caldav_display_name") var caldavDisplayName: String = "",
@ColumnInfo(name = "caldav_email") var caldavEmail: String = "",
@ColumnInfo(name = "type") var type: Int = OTHER_EVENT
) {
fun getDisplayTitle() = if (caldavCalendarId == 0) title else "$caldavDisplayName ($caldavEmail)"
fun isSyncedEventType() = caldavCalendarId != 0
}
| gpl-3.0 | 68c15df0a530f444b02b3c4abe74b29f | 41.727273 | 101 | 0.718085 | 3.868313 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/CallFromPublicInlineFactory.kt | 4 | 3502 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.psi.util.parentOfTypes
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.lexer.KtModifierKeywordToken
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.visibilityModifierType
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
object CallFromPublicInlineFactory : KotlinIntentionActionsFactory() {
override fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction> {
val fixes = mutableListOf<IntentionAction>()
val element = diagnostic.psiElement.safeAs<KtExpression>() ?: return fixes
val (containingDeclaration, containingDeclarationName) = element.containingDeclaration() ?: return fixes
when (diagnostic.factory) {
Errors.NON_PUBLIC_CALL_FROM_PUBLIC_INLINE,
Errors.PROTECTED_CALL_FROM_PUBLIC_INLINE.warningFactory,
Errors.PROTECTED_CALL_FROM_PUBLIC_INLINE.errorFactory -> {
val (declaration, declarationName, declarationVisibility) = element.referenceDeclaration() ?: return fixes
fixes.add(ChangeVisibilityFix(containingDeclaration, containingDeclarationName, declarationVisibility))
fixes.add(ChangeVisibilityFix(declaration, declarationName, KtTokens.PUBLIC_KEYWORD))
if (!containingDeclaration.hasReifiedTypeParameter()) {
fixes.add(RemoveModifierFix(containingDeclaration, KtTokens.INLINE_KEYWORD, isRedundant = false))
}
}
Errors.SUPER_CALL_FROM_PUBLIC_INLINE.warningFactory, Errors.SUPER_CALL_FROM_PUBLIC_INLINE.errorFactory -> {
fixes.add(ChangeVisibilityFix(containingDeclaration, containingDeclarationName, KtTokens.INTERNAL_KEYWORD))
fixes.add(ChangeVisibilityFix(containingDeclaration, containingDeclarationName, KtTokens.PRIVATE_KEYWORD))
if (!containingDeclaration.hasReifiedTypeParameter()) {
fixes.add(RemoveModifierFix(containingDeclaration, KtTokens.INLINE_KEYWORD, isRedundant = false))
}
}
}
return fixes
}
private fun KtExpression.containingDeclaration(): Pair<KtCallableDeclaration, String>? {
val declaration = parentOfTypes(KtNamedFunction::class, KtProperty::class)
?.safeAs<KtCallableDeclaration>()
?.takeIf { it.hasModifier(KtTokens.INLINE_KEYWORD) }
?: return null
val name = declaration.name ?: return null
return declaration to name
}
private fun KtExpression.referenceDeclaration(): Triple<KtDeclaration, String, KtModifierKeywordToken>? {
val declaration = safeAs<KtNameReferenceExpression>()?.mainReference?.resolve().safeAs<KtDeclaration>() ?: return null
val name = declaration.name ?: return null
val visibility = declaration.visibilityModifierType() ?: return null
return Triple(declaration, name, visibility)
}
private fun KtCallableDeclaration.hasReifiedTypeParameter() = typeParameters.any { it.hasModifier(KtTokens.REIFIED_KEYWORD) }
}
| apache-2.0 | 4e0e53e6fd7018db091b075b33199d37 | 58.355932 | 158 | 0.728441 | 5.379416 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantCompanionReferenceInspection.kt | 1 | 9930 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.CleanupLocalInspectionTool
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.analyzeAsReplacement
import org.jetbrains.kotlin.idea.intentions.isReferenceToBuiltInEnumFunction
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.references.resolveToDescriptors
import org.jetbrains.kotlin.idea.util.getResolutionScope
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.load.java.descriptors.JavaMethodDescriptor
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClass
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedElementSelector
import org.jetbrains.kotlin.psi.psiUtil.getReceiverExpression
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.FakeCallableDescriptorForObject
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperClassNotAny
import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperInterfaces
import org.jetbrains.kotlin.resolve.descriptorUtil.overriddenTreeAsSequence
import org.jetbrains.kotlin.resolve.scopes.utils.findFunction
import org.jetbrains.kotlin.resolve.scopes.utils.findVariable
import org.jetbrains.kotlin.resolve.scopes.utils.getImplicitReceiversHierarchy
import org.jetbrains.kotlin.types.typeUtil.isTypeParameter
import org.jetbrains.kotlin.types.typeUtil.makeNotNullable
import org.jetbrains.kotlin.types.typeUtil.supertypes
class RedundantCompanionReferenceInspection : AbstractKotlinInspection(), CleanupLocalInspectionTool {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return referenceExpressionVisitor(fun(expression) {
if (isRedundantCompanionReference(expression)) {
holder.registerProblem(
expression,
KotlinBundle.message("redundant.companion.reference"),
RemoveRedundantCompanionReferenceFix()
)
}
})
}
private fun isRedundantCompanionReference(reference: KtReferenceExpression): Boolean {
val parent = reference.parent as? KtDotQualifiedExpression ?: return false
val grandParent = parent.parent as? KtElement
val selectorExpression = parent.selectorExpression
if (reference == selectorExpression && grandParent !is KtDotQualifiedExpression) return false
if (parent.getStrictParentOfType<KtImportDirective>() != null) return false
val objectDeclaration = reference.mainReference.resolve() as? KtObjectDeclaration ?: return false
if (!objectDeclaration.isCompanion()) return false
val referenceText = reference.text
if (referenceText != objectDeclaration.name) return false
if (reference != selectorExpression && referenceText == (selectorExpression as? KtNameReferenceExpression)?.text) return false
val containingClass = objectDeclaration.containingClass() ?: return false
if (reference.containingClass() != containingClass && reference == parent.receiverExpression) return false
if (parent.isReferenceToBuildInEnumFunctionInEnumClass(containingClass)) return false
val context = reference.analyze()
if (grandParent.isReferenceToClassOrObject(context)) return false
val containingClassDescriptor =
context[BindingContext.DECLARATION_TO_DESCRIPTOR, containingClass] as? ClassDescriptor ?: return false
if (containingClassDescriptor.hasSameNameMemberAs(selectorExpression, context)) return false
val implicitReceiverClassDescriptor = reference.getResolutionScope(context)?.getImplicitReceiversHierarchy().orEmpty()
.flatMap {
val type = it.value.type
if (type.isTypeParameter()) type.supertypes() else listOf(type)
}
.mapNotNull { it.constructor.declarationDescriptor as? ClassDescriptor }
.filterNot { it.isCompanionObject }
if (implicitReceiverClassDescriptor.any { it.hasSameNameMemberAs(selectorExpression, context) }) return false
(reference as? KtSimpleNameExpression)?.getReceiverExpression()?.getQualifiedElementSelector()
?.mainReference?.resolveToDescriptors(context)?.firstOrNull()
?.let { if (it != containingClassDescriptor) return false }
if (selectorExpression is KtCallExpression && referenceText == selectorExpression.calleeExpression?.text) {
val newExpression = KtPsiFactory(reference).createExpressionByPattern("$0", selectorExpression)
val newContext = newExpression.analyzeAsReplacement(parent, context)
val descriptor = newExpression.getResolvedCall(newContext)?.resultingDescriptor as? FunctionDescriptor
if (descriptor?.isOperator == true) return false
}
return true
}
private fun KtDotQualifiedExpression.isReferenceToBuildInEnumFunctionInEnumClass(containingClass: KtClass): Boolean {
return containingClass.isEnum()
&& (isReferenceToBuiltInEnumFunction() || (parent as? KtElement)?.isReferenceToBuiltInEnumFunction() == true)
}
private fun KtElement?.isReferenceToClassOrObject(context: BindingContext): Boolean {
if (this !is KtQualifiedExpression) return false
val descriptor = getResolvedCall(context)?.resultingDescriptor
return descriptor == null || descriptor is ConstructorDescriptor || descriptor is FakeCallableDescriptorForObject
}
private fun ClassDescriptor?.hasSameNameMemberAs(expression: KtExpression?, context: BindingContext): Boolean {
if (this == null) return false
when (val descriptor = expression?.getResolvedCall(context)?.resultingDescriptor) {
is PropertyDescriptor -> {
val name = descriptor.name
if (findMemberVariable(name) != null) return true
val type = descriptor.type
val javaGetter = findMemberFunction(Name.identifier(JvmAbi.getterName(name.asString())))
?.takeIf { f -> f is JavaMethodDescriptor || f.overriddenTreeAsSequence(true).any { it is JavaMethodDescriptor } }
if (javaGetter?.valueParameters?.isEmpty() == true && javaGetter.returnType?.makeNotNullable() == type) return true
val variable = expression.getResolutionScope().findVariable(name, NoLookupLocation.FROM_IDE)
if (variable != null && variable.isLocalOrExtension(this)) return true
}
is FunctionDescriptor -> {
val name = descriptor.name
if (findMemberFunction(name) != null) return true
val function = expression.getResolutionScope().findFunction(name, NoLookupLocation.FROM_IDE)
if (function != null && function.isLocalOrExtension(this)) return true
}
}
return false
}
private fun <D : MemberDescriptor> ClassDescriptor.findMemberByName(name: Name, find: ClassDescriptor.(Name) -> D?): D? {
val member = find(name)
if (member != null) return member
val memberInSuperClass = getSuperClassNotAny()?.findMemberByName(name, find)
if (memberInSuperClass != null) return memberInSuperClass
getSuperInterfaces().forEach {
val memberInInterface = it.findMemberByName(name, find)
if (memberInInterface != null) return memberInInterface
}
return null
}
private fun ClassDescriptor.findMemberVariable(name: Name): PropertyDescriptor? = findMemberByName(name) {
unsubstitutedMemberScope.getContributedVariables(it, NoLookupLocation.FROM_IDE).firstOrNull()
}
private fun ClassDescriptor.findMemberFunction(name: Name): FunctionDescriptor? = findMemberByName(name) {
unsubstitutedMemberScope.getContributedFunctions(it, NoLookupLocation.FROM_IDE).firstOrNull()
}
private fun CallableDescriptor.isLocalOrExtension(extensionClassDescriptor: ClassDescriptor): Boolean {
return visibility == DescriptorVisibilities.LOCAL ||
extensionReceiverParameter?.type?.constructor?.declarationDescriptor == extensionClassDescriptor
}
private class RemoveRedundantCompanionReferenceFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("remove.redundant.companion.reference.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val expression = descriptor.psiElement as? KtReferenceExpression ?: return
removeRedundantCompanionReference(expression)
}
companion object {
fun removeRedundantCompanionReference(expression: KtReferenceExpression) {
val parent = expression.parent as? KtDotQualifiedExpression ?: return
val selector = parent.selectorExpression ?: return
val receiver = parent.receiverExpression
if (expression == receiver) parent.replace(selector) else parent.replace(receiver)
}
}
}
}
| apache-2.0 | e57256d6233298f67abbb64f50aaba42 | 52.967391 | 134 | 0.734542 | 5.700344 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameKotlinParameterProcessor.kt | 1 | 2897 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.rename
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import com.intellij.psi.search.SearchScope
import com.intellij.refactoring.listeners.RefactoringElementListener
import com.intellij.usageView.UsageInfo
import org.jetbrains.kotlin.asJava.namedUnwrappedElement
import org.jetbrains.kotlin.idea.base.util.or
import org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringSettings
import org.jetbrains.kotlin.psi.KtFunction
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.utils.SmartList
class RenameKotlinParameterProcessor : RenameKotlinPsiProcessor() {
override fun canProcessElement(element: PsiElement) = element is KtParameter && element.ownerFunction is KtFunction
override fun isToSearchInComments(psiElement: PsiElement) = KotlinRefactoringSettings.instance.RENAME_SEARCH_IN_COMMENTS_FOR_VARIABLE
override fun setToSearchInComments(element: PsiElement, enabled: Boolean) {
KotlinRefactoringSettings.instance.RENAME_SEARCH_IN_COMMENTS_FOR_VARIABLE = enabled
}
override fun findCollisions(
element: PsiElement,
newName: String,
allRenames: MutableMap<out PsiElement, String>,
result: MutableList<UsageInfo>
) {
val declaration = element.namedUnwrappedElement as? KtNamedDeclaration ?: return
val collisions = SmartList<UsageInfo>()
checkRedeclarations(declaration, newName, collisions)
checkOriginalUsagesRetargeting(declaration, newName, result, collisions)
checkNewNameUsagesRetargeting(declaration, newName, collisions)
result += collisions
}
override fun findReferences(
element: PsiElement,
searchScope: SearchScope,
searchInCommentsAndStrings: Boolean
): Collection<PsiReference> {
val correctScope = if (element is KtParameter) {
searchScope or element.useScopeForRename
} else {
searchScope
}
return super.findReferences(element, correctScope, searchInCommentsAndStrings)
}
override fun renameElement(element: PsiElement, newName: String, usages: Array<UsageInfo>, listener: RefactoringElementListener?) {
super.renameElement(element, newName, usages, listener)
usages.forEach { (it as? KtResolvableCollisionUsageInfo)?.apply() }
}
override fun prepareRenaming(element: PsiElement, newName: String, allRenames: MutableMap<PsiElement, String>, scope: SearchScope) {
super.prepareRenaming(element, newName, allRenames, scope)
ForeignUsagesRenameProcessor.prepareRenaming(element, newName, allRenames, scope)
}
}
| apache-2.0 | a38314de3e1915f48eaab2011fcaf64c | 42.893939 | 158 | 0.760097 | 5.109347 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/idea/util/psi/patternMatching/KotlinPsiUnifier.kt | 1 | 46893 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.util.psi.patternMatching
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.impl.source.tree.LeafPsiElement
import com.intellij.util.containers.MultiMap
import org.jetbrains.kotlin.builtins.isExtensionFunctionType
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.base.psi.unifier.KotlinPsiRange
import org.jetbrains.kotlin.idea.base.psi.unifier.KotlinPsiRange.Empty
import org.jetbrains.kotlin.idea.base.psi.unifier.KotlinPsiUnificationResult
import org.jetbrains.kotlin.idea.base.psi.unifier.KotlinPsiUnificationResult.*
import org.jetbrains.kotlin.idea.base.psi.unifier.toRange
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.refactoring.introduce.ExtractableSubstringInfo
import org.jetbrains.kotlin.idea.refactoring.introduce.extractableSubstringInfo
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.lexer.KtToken
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorEquivalenceForOverrides
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.VariableAsFunctionResolvedCall
import org.jetbrains.kotlin.resolve.calls.tasks.ExplicitReceiverKind
import org.jetbrains.kotlin.resolve.calls.util.getCall
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.util.isSafeCall
import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver
import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver
import org.jetbrains.kotlin.resolve.scopes.receivers.Receiver
import org.jetbrains.kotlin.resolve.source.getPsi
import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.types.error.ErrorUtils
import org.jetbrains.kotlin.types.checker.KotlinTypeChecker
import org.jetbrains.kotlin.types.expressions.DoubleColonLHS
import org.jetbrains.kotlin.types.expressions.OperatorConventions
import java.util.*
class UnifierParameter(
val descriptor: DeclarationDescriptor,
val expectedType: KotlinType?
)
class KotlinPsiUnifier(
parameters: Collection<UnifierParameter> = Collections.emptySet(),
val allowWeakMatches: Boolean = false
) {
companion object {
val DEFAULT = KotlinPsiUnifier()
}
private inner class Context(val originalTarget: KotlinPsiRange, val originalPattern: KotlinPsiRange) {
val patternContext: BindingContext = originalPattern.getBindingContext()
val targetContext: BindingContext = originalTarget.getBindingContext()
val substitution = HashMap<UnifierParameter, KtElement>()
val declarationPatternsToTargets = MultiMap<DeclarationDescriptor, DeclarationDescriptor>()
val weakMatches = HashMap<KtElement, KtElement>()
var checkEquivalence: Boolean = false
var targetSubstringInfo: ExtractableSubstringInfo? = null
private fun KotlinPsiRange.getBindingContext(): BindingContext {
val element = elements.firstOrNull() as? KtElement
if ((element?.containingFile as? KtFile)?.doNotAnalyze != null) return BindingContext.EMPTY
return element?.analyze() ?: BindingContext.EMPTY
}
private fun matchDescriptors(first: DeclarationDescriptor?, second: DeclarationDescriptor?): Boolean {
if (DescriptorEquivalenceForOverrides.areEquivalent(first, second, allowCopiesFromTheSameDeclaration = true)) return true
if (second in declarationPatternsToTargets[first] || first in declarationPatternsToTargets[second]) return true
if (first == null || second == null) return false
val firstPsi = DescriptorToSourceUtils.descriptorToDeclaration(first) as? KtDeclaration
val secondPsi = DescriptorToSourceUtils.descriptorToDeclaration(second) as? KtDeclaration
if (firstPsi == null || secondPsi == null) return false
if (firstPsi == secondPsi) return true
if ((firstPsi in originalTarget && secondPsi in originalPattern) || (secondPsi in originalTarget && firstPsi in originalPattern)) {
return matchDeclarations(firstPsi, secondPsi, first, second) == true
}
return false
}
private fun matchReceivers(first: Receiver?, second: Receiver?): Boolean {
return when {
first is ExpressionReceiver && second is ExpressionReceiver ->
doUnify(first.expression, second.expression)
first is ImplicitReceiver && second is ImplicitReceiver ->
matchDescriptors(first.declarationDescriptor, second.declarationDescriptor)
else ->
first == second
}
}
private fun matchCalls(first: Call, second: Call): Boolean {
return matchReceivers(first.explicitReceiver, second.explicitReceiver)
&& matchReceivers(first.dispatchReceiver, second.dispatchReceiver)
}
private fun matchArguments(first: ValueArgument, second: ValueArgument): Boolean {
return when {
first.isExternal() != second.isExternal() -> false
(first.getSpreadElement() == null) != (second.getSpreadElement() == null) -> false
else -> doUnify(first.getArgumentExpression(), second.getArgumentExpression())
}
}
private fun matchResolvedCalls(first: ResolvedCall<*>, second: ResolvedCall<*>): Boolean? {
fun checkSpecialOperations(): Boolean {
val op1 = (first.call.calleeExpression as? KtSimpleNameExpression)?.getReferencedNameElementType()
val op2 = (second.call.calleeExpression as? KtSimpleNameExpression)?.getReferencedNameElementType()
return when {
op1 == op2 -> true
op1 == KtTokens.NOT_IN || op2 == KtTokens.NOT_IN -> false
op1 == KtTokens.EXCLEQ || op2 == KtTokens.EXCLEQ -> false
op1 in OperatorConventions.COMPARISON_OPERATIONS || op2 in OperatorConventions.COMPARISON_OPERATIONS -> false
else -> true
}
}
fun checkArguments(): Boolean? {
val firstArguments = first.resultingDescriptor?.valueParameters?.map { first.valueArguments[it] } ?: emptyList()
val secondArguments = second.resultingDescriptor?.valueParameters?.map { second.valueArguments[it] } ?: emptyList()
if (firstArguments.size != secondArguments.size) return false
if (first.call.valueArguments.size != firstArguments.size || second.call.valueArguments.size != secondArguments.size) return null
val mappedArguments = firstArguments.asSequence().zip(secondArguments.asSequence())
return mappedArguments.fold(true) { status, (firstArgument, secondArgument) ->
status && when {
firstArgument == secondArgument -> true
firstArgument == null || secondArgument == null -> false
else -> {
val mappedInnerArguments = firstArgument.arguments.asSequence().zip(secondArgument.arguments.asSequence())
mappedInnerArguments.fold(true) { statusForArgument, pair ->
statusForArgument && matchArguments(pair.first, pair.second)
}
}
}
}
}
fun checkImplicitReceiver(implicitCall: ResolvedCall<*>, explicitCall: ResolvedCall<*>): Boolean {
val (implicitReceiver, explicitReceiver) =
when (explicitCall.explicitReceiverKind) {
ExplicitReceiverKind.EXTENSION_RECEIVER ->
(implicitCall.extensionReceiver as? ImplicitReceiver) to (explicitCall.extensionReceiver as? ExpressionReceiver)
ExplicitReceiverKind.DISPATCH_RECEIVER ->
(implicitCall.dispatchReceiver as? ImplicitReceiver) to (explicitCall.dispatchReceiver as? ExpressionReceiver)
else ->
null to null
}
val thisExpression = explicitReceiver?.expression as? KtThisExpression
if (implicitReceiver == null || thisExpression == null) return false
return matchDescriptors(
implicitReceiver.declarationDescriptor,
thisExpression.getAdjustedResolvedCall()?.candidateDescriptor?.containingDeclaration
)
}
fun checkReceivers(): Boolean {
return when {
first.explicitReceiverKind == second.explicitReceiverKind -> {
if (!matchReceivers(first.extensionReceiver, second.extensionReceiver)) {
false
} else {
first.explicitReceiverKind == ExplicitReceiverKind.BOTH_RECEIVERS
|| matchReceivers(first.dispatchReceiver, second.dispatchReceiver)
}
}
first.explicitReceiverKind == ExplicitReceiverKind.NO_EXPLICIT_RECEIVER -> checkImplicitReceiver(first, second)
second.explicitReceiverKind == ExplicitReceiverKind.NO_EXPLICIT_RECEIVER -> checkImplicitReceiver(second, first)
else -> false
}
}
fun checkTypeArguments(): Boolean? {
val firstTypeArguments = first.typeArguments.toList()
val secondTypeArguments = second.typeArguments.toList()
if (firstTypeArguments.size != secondTypeArguments.size) return false
for ((firstTypeArgument, secondTypeArgument) in (firstTypeArguments.zip(secondTypeArguments))) {
if (!matchDescriptors(firstTypeArgument.first, secondTypeArgument.first)) return false
val status = matchTypes(firstTypeArgument.second, secondTypeArgument.second)
if (status != true) return status
}
return true
}
return when {
!checkSpecialOperations() -> false
!matchDescriptors(first.candidateDescriptor, second.candidateDescriptor) -> false
!checkReceivers() -> false
first.call.isSafeCall() != second.call.isSafeCall() -> false
else -> {
val status = checkTypeArguments()
if (status != true) status else checkArguments()
}
}
}
private val KtElement.bindingContext: BindingContext
get() = if (this in originalPattern) patternContext else targetContext
private fun KtElement.getAdjustedResolvedCall(): ResolvedCall<*>? {
val rc = if (this is KtArrayAccessExpression) {
bindingContext[BindingContext.INDEXED_LVALUE_GET, this]
} else {
getResolvedCall(bindingContext)?.let {
when {
it !is VariableAsFunctionResolvedCall -> it
this is KtSimpleNameExpression -> it.variableCall
else -> it.functionCall
}
}
}
return when {
rc == null || ErrorUtils.isError(rc.candidateDescriptor) -> null
else -> rc
}
}
private fun matchCalls(first: KtElement, second: KtElement): Boolean? {
if (first.shouldIgnoreResolvedCall() || second.shouldIgnoreResolvedCall()) return null
val firstResolvedCall = first.getAdjustedResolvedCall()
val secondResolvedCall = second.getAdjustedResolvedCall()
return when {
firstResolvedCall != null && secondResolvedCall != null ->
matchResolvedCalls(firstResolvedCall, secondResolvedCall)
firstResolvedCall == null && secondResolvedCall == null -> {
val firstCall = first.getCall(first.bindingContext)
val secondCall = second.getCall(second.bindingContext)
when {
firstCall != null && secondCall != null ->
if (matchCalls(firstCall, secondCall)) null else false
else ->
if (firstCall == null && secondCall == null) null else false
}
}
else -> false
}
}
private fun matchTypes(
firstType: KotlinType?,
secondType: KotlinType?,
firstTypeReference: KtTypeReference? = null,
secondTypeReference: KtTypeReference? = null
): Boolean? {
if (firstType != null && secondType != null) {
val firstUnwrappedType = firstType.unwrap()
val secondUnwrappedType = secondType.unwrap()
if (firstUnwrappedType !== firstType || secondUnwrappedType !== secondType) return matchTypes(
firstUnwrappedType,
secondUnwrappedType,
firstTypeReference,
secondTypeReference
)
if (firstType.isError || secondType.isError) return null
if (firstType is AbbreviatedType != secondType is AbbreviatedType) return false
if (firstType.isExtensionFunctionType != secondType.isExtensionFunctionType) return false
if (TypeUtils.equalTypes(firstType, secondType)) return true
if (firstType.isMarkedNullable != secondType.isMarkedNullable) return false
if (!matchDescriptors(
firstType.constructor.declarationDescriptor,
secondType.constructor.declarationDescriptor
)
) return false
val firstTypeArguments = firstType.arguments
val secondTypeArguments = secondType.arguments
if (firstTypeArguments.size != secondTypeArguments.size) return false
for ((index, firstTypeArgument) in firstTypeArguments.withIndex()) {
val secondTypeArgument = secondTypeArguments[index]
if (!matchTypeArguments(index, firstTypeArgument, secondTypeArgument, firstTypeReference, secondTypeReference)) {
return false
}
}
return true
}
return if (firstType == null && secondType == null) null else false
}
private fun matchTypeArguments(
argIndex: Int,
firstArgument: TypeProjection,
secondArgument: TypeProjection,
firstTypeReference: KtTypeReference?,
secondTypeReference: KtTypeReference?
): Boolean {
val firstArgumentReference = firstTypeReference?.typeElement?.typeArgumentsAsTypes?.getOrNull(argIndex)
val secondArgumentReference = secondTypeReference?.typeElement?.typeArgumentsAsTypes?.getOrNull(argIndex)
if (firstArgument.projectionKind != secondArgument.projectionKind) return false
val firstArgumentType = firstArgument.type
val secondArgumentType = secondArgument.type
// Substitution attempt using either arg1, or arg2 as a pattern type. Falls back to exact matching if substitution is not possible
val status = if (!checkEquivalence && firstTypeReference != null && secondTypeReference != null) {
val firstTypeDeclaration = firstArgumentType.constructor.declarationDescriptor?.source?.getPsi()
val secondTypeDeclaration = secondArgumentType.constructor.declarationDescriptor?.source?.getPsi()
descriptorToParameter[firstTypeDeclaration]?.let { substitute(it, secondArgumentReference) }
?: descriptorToParameter[secondTypeDeclaration]?.let { substitute(it, firstArgumentReference) }
?: matchTypes(firstArgumentType, secondArgumentType, firstArgumentReference, secondArgumentReference)
} else matchTypes(firstArgumentType, secondArgumentType, firstArgumentReference, secondArgumentReference)
return status == true
}
private fun matchTypes(firstTypes: Collection<KotlinType>, secondTypes: Collection<KotlinType>): Boolean {
fun sortTypes(types: Collection<KotlinType>) = types.sortedBy { DescriptorRenderer.FQ_NAMES_IN_TYPES.renderType(it) }
if (firstTypes.size != secondTypes.size) return false
return (sortTypes(firstTypes).zip(sortTypes(secondTypes)))
.all { (first, second) -> matchTypes(first, second) == true }
}
private fun KtElement.shouldIgnoreResolvedCall(): Boolean {
return when (this) {
is KtConstantExpression -> true
is KtOperationReferenceExpression -> getReferencedNameElementType() == KtTokens.EXCLEXCL
is KtIfExpression -> true
is KtWhenExpression -> true
is KtUnaryExpression -> when (operationReference.getReferencedNameElementType()) {
KtTokens.EXCLEXCL, KtTokens.PLUSPLUS, KtTokens.MINUSMINUS -> true
else -> false
}
is KtBinaryExpression -> operationReference.getReferencedNameElementType() == KtTokens.ELVIS
is KtThisExpression -> true
is KtSimpleNameExpression -> getStrictParentOfType<KtTypeElement>() != null
else -> false
}
}
private fun KtBinaryExpression.matchComplexAssignmentWithSimple(expression: KtBinaryExpression): Boolean {
return when (doUnify(left, expression.left)) {
false -> false
else -> expression.right?.let { matchCalls(this, it) } ?: false
}
}
private fun KtBinaryExpression.matchAssignment(element: KtElement): Boolean? {
val operationType = operationReference.getReferencedNameElementType() as KtToken
if (operationType == KtTokens.EQ) {
if (element.shouldIgnoreResolvedCall()) return false
if (KtPsiUtil.isAssignment(element) && !KtPsiUtil.isOrdinaryAssignment(element)) {
return (element as KtBinaryExpression).matchComplexAssignmentWithSimple(this)
}
val lhs = left?.unwrap()
if (lhs !is KtArrayAccessExpression) return null
val setResolvedCall = bindingContext[BindingContext.INDEXED_LVALUE_SET, lhs]
val resolvedCallToMatch = element.getAdjustedResolvedCall()
return when {
setResolvedCall == null || resolvedCallToMatch == null -> null
else -> matchResolvedCalls(setResolvedCall, resolvedCallToMatch)
}
}
val assignResolvedCall = getAdjustedResolvedCall() ?: return false
val operationName = OperatorConventions.getNameForOperationSymbol(operationType)
if (assignResolvedCall.resultingDescriptor?.name == operationName) return matchCalls(this, element)
return if (KtPsiUtil.isAssignment(element)) null else false
}
private fun matchLabelTargets(first: KtLabelReferenceExpression, second: KtLabelReferenceExpression): Boolean {
val firstTarget = first.bindingContext[BindingContext.LABEL_TARGET, first]
val secondTarget = second.bindingContext[BindingContext.LABEL_TARGET, second]
return firstTarget == secondTarget
}
private fun PsiElement.isIncrement(): Boolean {
val parent = this.parent
return parent is KtUnaryExpression
&& this == parent.operationReference
&& ((parent.operationToken as KtToken) in OperatorConventions.INCREMENT_OPERATIONS)
}
private fun KtCallableReferenceExpression.hasExpressionReceiver(): Boolean {
return bindingContext[BindingContext.DOUBLE_COLON_LHS, receiverExpression] is DoubleColonLHS.Expression
}
private fun matchCallableReferences(first: KtCallableReferenceExpression, second: KtCallableReferenceExpression): Boolean? {
if (first.hasExpressionReceiver() || second.hasExpressionReceiver()) return null
val firstDescriptor = first.bindingContext[BindingContext.REFERENCE_TARGET, first.callableReference]
val secondDescriptor = second.bindingContext[BindingContext.REFERENCE_TARGET, second.callableReference]
return matchDescriptors(firstDescriptor, secondDescriptor)
}
private fun matchThisExpressions(e1: KtThisExpression, e2: KtThisExpression): Boolean {
val d1 = e1.bindingContext[BindingContext.REFERENCE_TARGET, e1.instanceReference]
val d2 = e2.bindingContext[BindingContext.REFERENCE_TARGET, e2.instanceReference]
return matchDescriptors(d1, d2)
}
private fun matchDestructuringDeclarations(e1: KtDestructuringDeclaration, e2: KtDestructuringDeclaration): Boolean {
val entries1 = e1.entries
val entries2 = e2.entries
if (entries1.size != entries2.size) return false
return entries1.zip(entries2).all { p ->
val (entry1, entry2) = p
val rc1 = entry1.bindingContext[BindingContext.COMPONENT_RESOLVED_CALL, entry1]
val rc2 = entry2.bindingContext[BindingContext.COMPONENT_RESOLVED_CALL, entry2]
when {
rc1 == null && rc2 == null -> true
rc1 != null && rc2 != null -> matchResolvedCalls(rc1, rc2) == true
else -> false
}
}
}
fun matchReceiverParameters(firstReceiver: ReceiverParameterDescriptor?, secondReceiver: ReceiverParameterDescriptor?): Boolean {
val matchedReceivers = when {
firstReceiver == null && secondReceiver == null -> true
matchDescriptors(firstReceiver, secondReceiver) -> true
firstReceiver != null && secondReceiver != null -> matchTypes(firstReceiver.type, secondReceiver.type) == true
else -> false
}
if (matchedReceivers && firstReceiver != null) {
declarationPatternsToTargets.putValue(firstReceiver, secondReceiver)
}
return matchedReceivers
}
private fun matchCallables(
first: KtDeclaration,
second: KtDeclaration,
firstDescriptor: CallableDescriptor,
secondDescriptor: CallableDescriptor
): Boolean {
if (firstDescriptor is VariableDescriptor && firstDescriptor.isVar != (secondDescriptor as VariableDescriptor).isVar) {
return false
}
if (!matchNames(first, second, firstDescriptor, secondDescriptor)) {
return false
}
fun needToCompareReturnTypes(): Boolean {
if (first !is KtCallableDeclaration) return true
return first.typeReference != null || (second as KtCallableDeclaration).typeReference != null
}
if (needToCompareReturnTypes()) {
val type1 = firstDescriptor.returnType
val type2 = secondDescriptor.returnType
if (type1 != type2 && (type1 == null || type2 == null || type1.isError || type2.isError || matchTypes(
type1,
type2
) != true)
) {
return false
}
}
if (!matchReceiverParameters(firstDescriptor.extensionReceiverParameter, secondDescriptor.extensionReceiverParameter)) {
return false
}
if (!matchReceiverParameters(firstDescriptor.dispatchReceiverParameter, secondDescriptor.dispatchReceiverParameter)) {
return false
}
val params1 = firstDescriptor.valueParameters
val params2 = secondDescriptor.valueParameters
val zippedParams = params1.zip(params2)
val parametersMatch =
(params1.size == params2.size) && zippedParams.all { matchTypes(it.first.type, it.second.type) == true }
if (!parametersMatch) return false
zippedParams.forEach { declarationPatternsToTargets.putValue(it.first, it.second) }
return doUnify(
(first as? KtTypeParameterListOwner)?.typeParameters?.toRange() ?: Empty,
(second as? KtTypeParameterListOwner)?.typeParameters?.toRange() ?: Empty
) && when (first) {
is KtDeclarationWithBody -> doUnify(first.bodyExpression, (second as KtDeclarationWithBody).bodyExpression)
is KtDeclarationWithInitializer -> doUnify(first.initializer, (second as KtDeclarationWithInitializer).initializer)
is KtParameter -> doUnify(first.defaultValue, (second as KtParameter).defaultValue)
else -> false
}
}
private fun KtDeclaration.isNameRelevant(): Boolean {
if (this is KtParameter && hasValOrVar()) return true
val parent = parent
return parent is KtClassBody || parent is KtFile
}
private fun matchNames(
first: KtDeclaration,
second: KtDeclaration,
firstDescriptor: DeclarationDescriptor,
secondDescriptor: DeclarationDescriptor
): Boolean {
return (!first.isNameRelevant() && !second.isNameRelevant())
|| firstDescriptor.name == secondDescriptor.name
}
private fun matchClasses(
first: KtClassOrObject,
second: KtClassOrObject,
firstDescriptor: ClassDescriptor,
secondDescriptor: ClassDescriptor
): Boolean {
class OrderInfo<out T>(
val orderSensitive: List<T>,
val orderInsensitive: List<T>
)
fun getMemberOrderInfo(cls: KtClassOrObject): OrderInfo<KtDeclaration> {
val (orderInsensitive, orderSensitive) = (cls.body?.declarations ?: Collections.emptyList()).partition {
it is KtClassOrObject || it is KtFunction
}
return OrderInfo(orderSensitive, orderInsensitive)
}
fun getDelegationOrderInfo(cls: KtClassOrObject): OrderInfo<KtSuperTypeListEntry> {
val (orderInsensitive, orderSensitive) = cls.superTypeListEntries.partition { it is KtSuperTypeEntry }
return OrderInfo(orderSensitive, orderInsensitive)
}
fun resolveAndSortDeclarationsByDescriptor(declarations: List<KtDeclaration>): List<Pair<KtDeclaration, DeclarationDescriptor?>> {
return declarations.map { it to it.bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, it] }
.sortedBy { it.second?.let { descriptor -> IdeDescriptorRenderers.SOURCE_CODE.render(descriptor) } ?: "" }
}
fun sortDeclarationsByElementType(declarations: List<KtDeclaration>): List<KtDeclaration> {
return declarations.sortedBy { it.node?.elementType?.index ?: -1 }
}
if (firstDescriptor.kind != secondDescriptor.kind) return false
if (!matchNames(first, second, firstDescriptor, secondDescriptor)) return false
declarationPatternsToTargets.putValue(firstDescriptor.thisAsReceiverParameter, secondDescriptor.thisAsReceiverParameter)
val firstConstructor = firstDescriptor.unsubstitutedPrimaryConstructor
val secondConstructor = secondDescriptor.unsubstitutedPrimaryConstructor
if (firstConstructor != null && secondConstructor != null) {
declarationPatternsToTargets.putValue(firstConstructor, secondConstructor)
}
val firstOrderInfo = getDelegationOrderInfo(first)
val secondOrderInfo = getDelegationOrderInfo(second)
if (firstOrderInfo.orderInsensitive.size != secondOrderInfo.orderInsensitive.size) return false
outer@ for (firstSpecifier in firstOrderInfo.orderInsensitive) {
for (secondSpecifier in secondOrderInfo.orderInsensitive) {
if (doUnify(firstSpecifier, secondSpecifier)) continue@outer
}
return false
}
val firstParameters = (first as? KtClass)?.getPrimaryConstructorParameterList()
val secondParameters = (second as? KtClass)?.getPrimaryConstructorParameterList()
val status = doUnify(firstParameters, secondParameters)
&& doUnify((first as? KtClass)?.typeParameterList, (second as? KtClass)?.typeParameterList)
&& doUnify(firstOrderInfo.orderSensitive.toRange(), secondOrderInfo.orderSensitive.toRange())
if (!status) return false
val firstMemberInfo = getMemberOrderInfo(first)
val secondMemberInfo = getMemberOrderInfo(second)
val firstSortedMembers = resolveAndSortDeclarationsByDescriptor(firstMemberInfo.orderInsensitive)
val secondSortedMembers = resolveAndSortDeclarationsByDescriptor(secondMemberInfo.orderInsensitive)
if ((firstSortedMembers.size != secondSortedMembers.size)) return false
for ((index, firstSortedMember) in firstSortedMembers.withIndex()) {
val (firstMember, firstMemberDescriptor) = firstSortedMember
val (secondMember, secondMemberDescriptor) = secondSortedMembers[index]
val memberResult = matchDeclarations(firstMember, secondMember, firstMemberDescriptor, secondMemberDescriptor)
?: doUnify(firstMember, secondMember)
if (!memberResult) {
return false
}
}
return doUnify(
sortDeclarationsByElementType(firstMemberInfo.orderSensitive).toRange(),
sortDeclarationsByElementType(secondMemberInfo.orderSensitive).toRange()
)
}
private fun matchTypeParameters(first: TypeParameterDescriptor, second: TypeParameterDescriptor): Boolean {
if (first.variance != second.variance) return false
if (!matchTypes(first.upperBounds, second.upperBounds)) return false
return true
}
private fun KtDeclaration.matchDeclarations(element: PsiElement): Boolean? {
if (element !is KtDeclaration) return false
val firstDescriptor = bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, this]
val secondDescriptor = element.bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, element]
return matchDeclarations(this, element, firstDescriptor, secondDescriptor)
}
private fun matchDeclarations(
decl1: KtDeclaration,
decl2: KtDeclaration,
desc1: DeclarationDescriptor?,
desc2: DeclarationDescriptor?
): Boolean? {
if (decl1::class.java != decl2::class.java) return false
if (desc1 == null || desc2 == null) {
return if (decl1 is KtParameter
&& decl2 is KtParameter
&& decl1.getStrictParentOfType<KtTypeElement>() != null
&& decl2.getStrictParentOfType<KtTypeElement>() != null
)
null
else
false
}
if (ErrorUtils.isError(desc1) || ErrorUtils.isError(desc2)) return false
if (desc1::class.java != desc2::class.java) return false
declarationPatternsToTargets.putValue(desc1, desc2)
val status = when (decl1) {
is KtDeclarationWithBody, is KtDeclarationWithInitializer, is KtParameter ->
matchCallables(decl1, decl2, desc1 as CallableDescriptor, desc2 as CallableDescriptor)
is KtClassOrObject ->
matchClasses(decl1, decl2 as KtClassOrObject, desc1 as ClassDescriptor, desc2 as ClassDescriptor)
is KtTypeParameter ->
matchTypeParameters(desc1 as TypeParameterDescriptor, desc2 as TypeParameterDescriptor)
else ->
null
}
if (status == false) {
declarationPatternsToTargets.remove(desc1, desc2)
}
return status
}
private fun matchResolvedInfo(first: PsiElement, second: PsiElement): Boolean? {
fun KtTypeReference.getType(): KotlinType? {
return (bindingContext[BindingContext.ABBREVIATED_TYPE, this] ?: bindingContext[BindingContext.TYPE, this])
?.takeUnless { it.isError }
}
return when {
first !is KtElement || second !is KtElement ->
null
first is KtDestructuringDeclaration && second is KtDestructuringDeclaration ->
if (matchDestructuringDeclarations(first, second)) null else false
first is KtAnonymousInitializer && second is KtAnonymousInitializer ->
null
first is KtDeclaration ->
first.matchDeclarations(second)
second is KtDeclaration ->
second.matchDeclarations(first)
first is KtTypeElement && second is KtTypeElement && first.parent is KtTypeReference && second.parent is KtTypeReference ->
matchResolvedInfo(first.parent, second.parent)
first is KtTypeReference && second is KtTypeReference ->
matchTypes(first.getType(), second.getType(), first, second)
KtPsiUtil.isAssignment(first) ->
(first as KtBinaryExpression).matchAssignment(second)
KtPsiUtil.isAssignment(second) ->
(second as KtBinaryExpression).matchAssignment(first)
first is KtLabelReferenceExpression && second is KtLabelReferenceExpression ->
matchLabelTargets(first, second)
first.isIncrement() != second.isIncrement() ->
false
first is KtCallableReferenceExpression && second is KtCallableReferenceExpression ->
matchCallableReferences(first, second)
first is KtThisExpression && second is KtThisExpression -> matchThisExpressions(first, second)
else ->
matchCalls(first, second)
}
}
private fun PsiElement.checkType(parameter: UnifierParameter): Boolean {
val expectedType = parameter.expectedType ?: return true
val targetElementType = (this as? KtExpression)?.let { it.bindingContext.getType(it) }
return targetElementType != null && KotlinTypeChecker.DEFAULT.isSubtypeOf(targetElementType, expectedType)
}
private fun doUnifyStringTemplateFragments(target: KtStringTemplateExpression, pattern: ExtractableSubstringInfo): Boolean {
val prefixLength = pattern.prefix.length
val suffixLength = pattern.suffix.length
val targetEntries = target.entries
val patternEntries = pattern.entries.toList()
for ((index, targetEntry) in targetEntries.withIndex()) {
if (index + patternEntries.size > targetEntries.size) return false
val targetEntryText = targetEntry.text
if (pattern.startEntry == pattern.endEntry && (prefixLength > 0 || suffixLength > 0)) {
if (targetEntry !is KtLiteralStringTemplateEntry) continue
val patternText = with(pattern.startEntry.text) { substring(prefixLength, length - suffixLength) }
val i = targetEntryText.indexOf(patternText)
if (i < 0) continue
val targetPrefix = targetEntryText.substring(0, i)
val targetSuffix = targetEntryText.substring(i + patternText.length)
targetSubstringInfo = ExtractableSubstringInfo(targetEntry, targetEntry, targetPrefix, targetSuffix, pattern.type)
return true
}
val matchStartByText = pattern.startEntry is KtLiteralStringTemplateEntry
val matchEndByText = pattern.endEntry is KtLiteralStringTemplateEntry
val targetPrefix = if (matchStartByText) {
if (targetEntry !is KtLiteralStringTemplateEntry) continue
val patternText = pattern.startEntry.text.substring(prefixLength)
if (!targetEntryText.endsWith(patternText)) continue
targetEntryText.substring(0, targetEntryText.length - patternText.length)
} else ""
val lastTargetEntry = targetEntries[index + patternEntries.lastIndex]
val targetSuffix = if (matchEndByText) {
if (lastTargetEntry !is KtLiteralStringTemplateEntry) continue
val patternText = with(pattern.endEntry.text) { substring(0, length - suffixLength) }
val lastTargetEntryText = lastTargetEntry.text
if (!lastTargetEntryText.startsWith(patternText)) continue
lastTargetEntryText.substring(patternText.length)
} else ""
val fromIndex = if (matchStartByText) 1 else 0
val toIndex = if (matchEndByText) patternEntries.lastIndex - 1 else patternEntries.lastIndex
val status = (fromIndex..toIndex).fold(true) { status, patternEntryIndex ->
val targetEntryToUnify = targetEntries[index + patternEntryIndex]
val patternEntryToUnify = patternEntries[patternEntryIndex]
status && doUnify(targetEntryToUnify, patternEntryToUnify)
}
if (!status) continue
targetSubstringInfo = ExtractableSubstringInfo(targetEntry, lastTargetEntry, targetPrefix, targetSuffix, pattern.type)
return true
}
return false
}
fun doUnify(target: KotlinPsiRange, pattern: KotlinPsiRange): Boolean {
(pattern.elements.singleOrNull() as? KtExpression)?.extractableSubstringInfo?.let {
val targetTemplate = target.elements.singleOrNull() as? KtStringTemplateExpression ?: return false
return doUnifyStringTemplateFragments(targetTemplate, it)
}
val targetElements = target.elements
val patternElements = pattern.elements
if (targetElements.size != patternElements.size) return false
return (targetElements.asSequence().zip(patternElements.asSequence())).fold(true) { status, (first, second) ->
status && doUnify(first, second)
}
}
private fun ASTNode.getChildrenRange(): KotlinPsiRange = getChildren(null).mapNotNull { it.psi }.toRange()
private fun PsiElement.unwrapWeakly(): KtElement? {
return when {
this is KtReturnExpression -> returnedExpression
this is KtProperty -> initializer
KtPsiUtil.isOrdinaryAssignment(this) -> (this as KtBinaryExpression).right
this is KtExpression && this !is KtDeclaration -> this
else -> null
}
}
private fun doUnifyWeakly(targetElement: KtElement, patternElement: KtElement): Boolean {
if (!allowWeakMatches) return false
val targetElementUnwrapped = targetElement.unwrapWeakly()
val patternElementUnwrapped = patternElement.unwrapWeakly()
if (targetElementUnwrapped == null || patternElementUnwrapped == null) return false
if (targetElementUnwrapped == targetElement && patternElementUnwrapped == patternElement) return false
val status = doUnify(targetElementUnwrapped, patternElementUnwrapped)
if (status) {
weakMatches[patternElement] = targetElement
}
return status
}
private fun substitute(parameter: UnifierParameter, targetElement: PsiElement?): Boolean {
return when (val existingArgument = substitution[parameter]) {
null -> {
substitution[parameter] = targetElement as KtElement
true
}
else -> {
checkEquivalence = true
val status = doUnify(existingArgument, targetElement)
checkEquivalence = false
status
}
}
}
fun doUnify(
targetElement: PsiElement?,
patternElement: PsiElement?
): Boolean {
val targetElementUnwrapped = targetElement?.unwrap()
val patternElementUnwrapped = patternElement?.unwrap()
if (targetElementUnwrapped == patternElementUnwrapped) return true
if (targetElementUnwrapped == null || patternElementUnwrapped == null) return false
if (!checkEquivalence && targetElementUnwrapped !is KtBlockExpression) {
val referencedPatternDescriptor = when (patternElementUnwrapped) {
is KtReferenceExpression -> {
if (targetElementUnwrapped !is KtExpression) return false
patternElementUnwrapped.bindingContext[BindingContext.REFERENCE_TARGET, patternElementUnwrapped]
}
is KtUserType -> {
if (targetElementUnwrapped !is KtUserType) return false
patternElementUnwrapped.bindingContext[BindingContext.REFERENCE_TARGET, patternElementUnwrapped.referenceExpression]
}
else -> null
}
val referencedPatternDeclaration = (referencedPatternDescriptor as? DeclarationDescriptorWithSource)?.source?.getPsi()
val parameter = descriptorToParameter[referencedPatternDeclaration]
if (referencedPatternDeclaration != null && parameter != null) {
if (targetElementUnwrapped is KtExpression) {
if (!targetElementUnwrapped.checkType(parameter)) return false
}
return substitute(parameter, targetElementUnwrapped)
}
}
val targetNode = targetElementUnwrapped.node
val patternNode = patternElementUnwrapped.node
if (targetNode == null || patternNode == null) return false
val resolvedStatus = matchResolvedInfo(targetElementUnwrapped, patternElementUnwrapped)
if (resolvedStatus == true) return resolvedStatus
if (targetElementUnwrapped is KtElement && patternElementUnwrapped is KtElement) {
val weakStatus = doUnifyWeakly(targetElementUnwrapped, patternElementUnwrapped)
if (weakStatus) return true
}
if (targetNode.elementType != patternNode.elementType) return false
if (resolvedStatus != null) return resolvedStatus
val targetChildren = targetNode.getChildrenRange()
val patternChildren = patternNode.getChildrenRange()
if (patternChildren.isEmpty && targetChildren.isEmpty) {
return targetElementUnwrapped.unquotedText() == patternElementUnwrapped.unquotedText()
}
return doUnify(targetChildren, patternChildren)
}
}
private val descriptorToParameter = parameters.associateBy { (it.descriptor as? DeclarationDescriptorWithSource)?.source?.getPsi() }
private fun PsiElement.unwrap(): PsiElement? = when (this) {
is KtExpression -> KtPsiUtil.deparenthesize(this)
is KtStringTemplateEntryWithExpression -> KtPsiUtil.deparenthesize(expression)
else -> this
}
private fun PsiElement.unquotedText(): String {
val text = text ?: ""
return if (this is LeafPsiElement) KtPsiUtil.unquoteIdentifier(text) else text
}
fun unify(target: KotlinPsiRange, pattern: KotlinPsiRange): KotlinPsiUnificationResult {
return with(Context(target, pattern)) {
val status = doUnify(target, pattern)
when {
substitution.size != descriptorToParameter.size -> Failure
status -> {
val targetRange = targetSubstringInfo?.createExpression()?.toRange() ?: target
if (weakMatches.isEmpty()) {
StrictSuccess(targetRange, substitution)
} else {
WeakSuccess(targetRange, substitution, weakMatches)
}
}
else -> Failure
}
}
}
fun unify(targetElement: PsiElement?, patternElement: PsiElement?): KotlinPsiUnificationResult =
unify(targetElement.toRange(), patternElement.toRange())
}
fun PsiElement?.matches(e: PsiElement?): Boolean = KotlinPsiUnifier.DEFAULT.unify(this, e).isMatched
fun KotlinPsiRange.matches(r: KotlinPsiRange): Boolean = KotlinPsiUnifier.DEFAULT.unify(this, r).isMatched
fun KotlinPsiRange.match(scope: PsiElement, unifier: KotlinPsiUnifier): List<Success<UnifierParameter>> {
return match(scope) { target, pattern ->
@Suppress("UNCHECKED_CAST")
unifier.unify(target, pattern) as? Success<UnifierParameter>
}
} | apache-2.0 | b586a9610ab0a929f6eff3aca87258d4 | 47.949896 | 158 | 0.626959 | 5.946361 | false | false | false | false |
androidx/androidx | compose/ui/ui-geometry/src/commonMain/kotlin/androidx/compose/ui/geometry/CornerRadius.kt | 3 | 5647 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.geometry
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.Stable
import androidx.compose.ui.util.lerp
import androidx.compose.ui.util.packFloats
import androidx.compose.ui.util.unpackFloat1
import androidx.compose.ui.util.unpackFloat2
/**
* Constructs a Radius with the given [x] and [y] parameters for the
* size of the radius along the x and y axis respectively. By default
* the radius along the Y axis matches that of the given x-axis
* unless otherwise specified. Negative radii values are clamped to 0.
*/
@Stable
fun CornerRadius(x: Float, y: Float = x) = CornerRadius(packFloats(x, y))
/**
* A radius for either circular or elliptical (oval) shapes.
*
* Note consumers should create an instance of this class through the corresponding
* function constructor as it is represented as an inline class with 2 float
* parameters packed into a single long to reduce allocation overhead
**/
@Immutable
@kotlin.jvm.JvmInline
value class CornerRadius internal constructor(@PublishedApi internal val packedValue: Long) {
/** The radius value on the horizontal axis. */
@Stable
val x: Float
get() = unpackFloat1(packedValue)
/** The radius value on the vertical axis. */
@Stable
val y: Float
get() = unpackFloat2(packedValue)
@Suppress("NOTHING_TO_INLINE")
@Stable
inline operator fun component1(): Float = x
@Suppress("NOTHING_TO_INLINE")
@Stable
inline operator fun component2(): Float = y
/**
* Returns a copy of this Radius instance optionally overriding the
* radius parameter for the x or y axis
*/
fun copy(x: Float = this.x, y: Float = this.y) = CornerRadius(x, y)
companion object {
/**
* A radius with [x] and [y] values set to zero.
*
* You can use [CornerRadius.Zero] with [RoundRect] to have right-angle corners.
*/
@Stable
val Zero: CornerRadius = CornerRadius(0.0f)
}
/**
* Unary negation operator.
*
* Returns a Radius with the distances negated.
*
* Radiuses with negative values aren't geometrically meaningful, but could
* occur as part of expressions. For example, negating a radius of one pixel
* and then adding the result to another radius is equivalent to subtracting
* a radius of one pixel from the other.
*/
@Stable
operator fun unaryMinus() = CornerRadius(-x, -y)
/**
* Binary subtraction operator.
*
* Returns a radius whose [x] value is the left-hand-side operand's [x]
* minus the right-hand-side operand's [x] and whose [y] value is the
* left-hand-side operand's [y] minus the right-hand-side operand's [y].
*/
@Stable
operator fun minus(other: CornerRadius) = CornerRadius(x - other.x, y - other.y)
/**
* Binary addition operator.
*
* Returns a radius whose [x] value is the sum of the [x] values of the
* two operands, and whose [y] value is the sum of the [y] values of the
* two operands.
*/
@Stable
operator fun plus(other: CornerRadius) = CornerRadius(x + other.x, y + other.y)
/**
* Multiplication operator.
*
* Returns a radius whose coordinates are the coordinates of the
* left-hand-side operand (a radius) multiplied by the scalar
* right-hand-side operand (a Float).
*/
@Stable
operator fun times(operand: Float) = CornerRadius(x * operand, y * operand)
/**
* Division operator.
*
* Returns a radius whose coordinates are the coordinates of the
* left-hand-side operand (a radius) divided by the scalar right-hand-side
* operand (a Float).
*/
@Stable
operator fun div(operand: Float) = CornerRadius(x / operand, y / operand)
override fun toString(): String {
return if (x == y) {
"CornerRadius.circular(${x.toStringAsFixed(1)})"
} else {
"CornerRadius.elliptical(${x.toStringAsFixed(1)}, ${y.toStringAsFixed(1)})"
}
}
}
/**
* Linearly interpolate between two radii.
*
* The [fraction] argument represents position on the timeline, with 0.0 meaning
* that the interpolation has not started, returning [start] (or something
* equivalent to [start]), 1.0 meaning that the interpolation has finished,
* returning [stop] (or something equivalent to [stop]), and values in between
* meaning that the interpolation is at the relevant point on the timeline
* between [start] and [stop]. The interpolation can be extrapolated beyond 0.0 and
* 1.0, so negative values and values greater than 1.0 are valid (and can
* easily be generated by curves).
*
* Values for [fraction] are usually obtained from an [Animation<Float>], such as
* an `AnimationController`.
*/
@Stable
fun lerp(start: CornerRadius, stop: CornerRadius, fraction: Float): CornerRadius {
return CornerRadius(
lerp(start.x, stop.x, fraction),
lerp(start.y, stop.y, fraction)
)
}
| apache-2.0 | 80f17b94ceca6b8ada264a06d79d4f4a | 33.644172 | 93 | 0.678236 | 4.103924 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/JavaModifiersConversion.kt | 2 | 2575 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.nj2k.conversions
import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext
import org.jetbrains.kotlin.nj2k.RecursiveApplicableConversionBase
import org.jetbrains.kotlin.nj2k.annotationByFqName
import org.jetbrains.kotlin.nj2k.jvmAnnotation
import org.jetbrains.kotlin.nj2k.tree.*
class JavaModifiersConversion(context: NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) {
override fun applyToElement(element: JKTreeElement): JKTreeElement {
if (element is JKModalityOwner && element is JKAnnotationListOwner) {
val overrideAnnotation = element.annotationList.annotationByFqName("java.lang.Override")
if (overrideAnnotation != null) {
element.annotationList.annotations -= overrideAnnotation
}
}
if (element is JKOtherModifiersOwner && element is JKAnnotationListOwner) {
element.elementByModifier(OtherModifier.VOLATILE)?.also { modifierElement ->
element.otherModifierElements -= modifierElement
element.annotationList.annotations +=
jvmAnnotation("Volatile", symbolProvider).withFormattingFrom(modifierElement)
}
element.elementByModifier(OtherModifier.TRANSIENT)?.also { modifierElement ->
element.otherModifierElements -= modifierElement
element.annotationList.annotations +=
jvmAnnotation("Transient", symbolProvider).withFormattingFrom(modifierElement)
}
element.elementByModifier(OtherModifier.STRICTFP)?.also { modifierElement ->
element.otherModifierElements -= modifierElement
element.annotationList.annotations +=
jvmAnnotation("Strictfp", symbolProvider).withFormattingFrom(modifierElement)
}
element.elementByModifier(OtherModifier.SYNCHRONIZED)?.also { modifierElement ->
element.otherModifierElements -= modifierElement
element.annotationList.annotations +=
jvmAnnotation("Synchronized", symbolProvider).withFormattingFrom(modifierElement)
}
element.elementByModifier(OtherModifier.NATIVE)?.also { modifierElement ->
modifierElement.otherModifier = OtherModifier.EXTERNAL
}
}
return recurse(element)
}
} | apache-2.0 | e682dfd4b0522ae5f879a36f7bdb4ce5 | 49.509804 | 158 | 0.693204 | 5.79955 | false | false | false | false |
OnyxDevTools/onyx-database-parent | onyx-remote-driver/src/main/kotlin/com/onyx/network/ssl/SSLPeer.kt | 1 | 3545 | package com.onyx.network.ssl
import com.onyx.network.auth.impl.NetworkPeer
import java.io.File
import java.security.KeyStore
import javax.net.ssl.KeyManager
import javax.net.ssl.KeyManagerFactory
import javax.net.ssl.TrustManager
import javax.net.ssl.TrustManagerFactory
/**
* Created by Tim Osborn on 2/13/17.
*
* Contract for SSL Peer communication
*/
interface SSLPeer {
/**
* SSL Protocol defaults to "TLSv1.2"
* @since 2.0.0 Added to SSL Peer
*/
var protocol:String
/**
* Set for SSL Store Password. Note, this is different than Keystore Password
* @since 1.2.0
*/
var sslStorePassword:String?
/**
* Set Keystore file path. This should contain the location of the JKS Keystore file
* @since 1.2.0
*/
var sslKeystoreFilePath: String?
/**
* Set for SSL KeysStore Password.
* @since 1.2.0
*/
var sslKeystorePassword: String?
/**
* Set Trust store file path. Location of the trust store JKS File. This should contain
* a file of the trusted sites that can access your secure endpoint
* @since 1.2.0
*/
var sslTrustStoreFilePath: String?
/**
* Trust store password
* @since 1.2.0
*/
var sslTrustStorePassword: String?
/**
* Default implementation of the copy. Helper method used to copy the SSLPeer properties
*
* @since 2.0.0
*/
fun copySSLPeerTo(peer: SSLPeer) {
peer.protocol = protocol
peer.sslStorePassword = sslStorePassword
peer.sslKeystoreFilePath = sslKeystoreFilePath
peer.sslKeystorePassword = sslKeystorePassword
peer.sslTrustStoreFilePath = sslTrustStoreFilePath
peer.sslTrustStorePassword = sslTrustStorePassword
}
/**
* Create Key Managers
*
* @param filepath File path of JKS file
* @param keystorePassword JSK file password
* @param keyPassword Store password
* @return Array of Key managers
* @since 1.2.0
* @throws Exception Invalid SSL Settings and or JKS files
*/
@Throws(Exception::class)
fun createKeyManagers(filepath: String, keystorePassword: String, keyPassword: String): Array<KeyManager> {
val keyStore = KeyStore.getInstance("JKS")
val keyStoreIS = NetworkPeer::class.java.classLoader.getResourceAsStream(filepath) ?: File(filepath).inputStream()
keyStoreIS.use {
keyStore.load(it, keystorePassword.toCharArray())
}
val kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())
kmf.init(keyStore, keyPassword.toCharArray())
return kmf.keyManagers
}
/**
* Create Trust managers
* @param filepath Trust store JKS file path
* @param trustStorePassword Password for the JKS File
* @return Array of trust managers
* @throws Exception Invalid SSK Settings or JKS file
*
* @since 1.2.0
*/
@Throws(Exception::class)
fun createTrustManagers(filepath: String, trustStorePassword: String): Array<TrustManager> {
val trustStore = KeyStore.getInstance("JKS")
val trustStoreIS = NetworkPeer::class.java.classLoader.getResourceAsStream(filepath) ?: File(filepath).inputStream()
trustStoreIS.use {
trustStore.load(it, trustStorePassword.toCharArray())
}
val trustFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
trustFactory.init(trustStore)
return trustFactory.trustManagers
}
}
| agpl-3.0 | 7496de293e468bc0ef68da8e198cf5d9 | 30.936937 | 124 | 0.673907 | 4.344363 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/internal/statistic/collectors/fus/project/IndexableFilesCollector.kt | 4 | 2535 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.internal.statistic.collectors.fus.project
import com.intellij.internal.statistic.beans.MetricEvent
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.service.fus.collectors.ProjectUsagesCollector
import com.intellij.internal.statistic.utils.StatisticsUtil.roundToPowerOfTwo
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ContentIterator
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.util.concurrency.NonUrgentExecutor
import com.intellij.util.indexing.FileBasedIndex
import org.jetbrains.concurrency.CancellablePromise
import java.util.concurrent.Callable
private class IndexableFilesCollector : ProjectUsagesCollector() {
override fun getGroup(): EventLogGroup = GROUP
override fun getMetrics(project: Project, indicator: ProgressIndicator?): CancellablePromise<out Set<MetricEvent>> {
var action = ReadAction.nonBlocking(
Callable<Set<MetricEvent>> {
var allIndexableFiles = 0
var inContentIndexableFiles = 0
val fileIndex = ProjectRootManager.getInstance(project).fileIndex
FileBasedIndex.getInstance().iterateIndexableFiles(ContentIterator { fileOrDir ->
indicator?.checkCanceled()
if (!fileOrDir.isDirectory && !fileIndex.isExcluded(fileOrDir)) {
if (fileIndex.isInContent(fileOrDir)) {
inContentIndexableFiles++
}
allIndexableFiles++
}
true
}, project, indicator)
hashSetOf(
ALL_INDEXABLE_FILES.metric(roundToPowerOfTwo(allIndexableFiles)),
CONTENT_INDEXABLE_FILES.metric(roundToPowerOfTwo(inContentIndexableFiles))
)
})
.inSmartMode(project)
if (indicator != null) {
action = action.wrapProgress(indicator)
}
return action
.submit(NonUrgentExecutor.getInstance())
}
companion object {
private val GROUP = EventLogGroup("project.indexable.files", 3)
private val ALL_INDEXABLE_FILES = GROUP.registerEvent("all.indexable.files", EventFields.Int("count"))
private val CONTENT_INDEXABLE_FILES = GROUP.registerEvent("content.indexable.files", EventFields.Int("count"))
}
}
| apache-2.0 | 3e2453e1e24b81dc5089804dea3aa95c | 44.267857 | 120 | 0.754241 | 4.92233 | false | false | false | false |
pablow91/KotlinFXML | src/main/kotlin/eu/stosdev/Binders.kt | 1 | 619 | package eu.stosdev
import javafx.scene.Node
import kotlin.properties.ReadOnlyProperty
public class bindFXML<T : Node> : ReadOnlyProperty<Any?, T> {
private var value: T? = null
public override fun get(thisRef: Any?, desc: PropertyMetadata): T {
val v = value
if (v == null) {
throw IllegalStateException("Node was not properly injected")
}
return v
}
}
public class bindOptionalFXML<T : Node> : ReadOnlyProperty<Any?, T?> {
private var value: T? = null
public override fun get(thisRef: Any?, desc: PropertyMetadata): T? {
return value
}
} | apache-2.0 | fcb5fe59f5960529bc798ffa9cec5bff | 24.833333 | 73 | 0.644588 | 4.099338 | false | false | false | false |
idea4bsd/idea4bsd | platform/projectModel-api/src/com/intellij/configurationStore/StreamProvider.kt | 3 | 1993 | /*
* 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.configurationStore
import com.intellij.openapi.components.RoamingType
import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream
import org.jetbrains.annotations.TestOnly
import java.io.InputStream
interface StreamProvider {
val enabled: Boolean
get() = true
fun isApplicable(fileSpec: String, roamingType: RoamingType = RoamingType.DEFAULT) = true
/**
* @param fileSpec
* @param content bytes of content, size of array is not actual size of data, you must use `size`
* @param size actual size of data
*/
fun write(fileSpec: String, content: ByteArray, size: Int = content.size, roamingType: RoamingType = RoamingType.DEFAULT)
fun read(fileSpec: String, roamingType: RoamingType = RoamingType.DEFAULT): InputStream?
fun processChildren(path: String, roamingType: RoamingType, filter: (name: String) -> Boolean, processor: (name: String, input: InputStream, readOnly: Boolean) -> Boolean)
/**
* Delete file or directory
*/
fun delete(fileSpec: String, roamingType: RoamingType = RoamingType.DEFAULT)
}
@TestOnly
fun StreamProvider.write(path: String, content: String) {
write(path, content.toByteArray())
}
fun StreamProvider.write(path: String, content: BufferExposingByteArrayOutputStream, roamingType: RoamingType = RoamingType.DEFAULT) {
write(path, content.internalBuffer, content.size(), roamingType)
} | apache-2.0 | 5aa564118e5d6ba953757bf02ebbd5d4 | 36.622642 | 173 | 0.75715 | 4.38022 | false | false | false | false |
JetBrains/kotlin-native | tools/performance-server/shared/src/main/kotlin/org/jetbrains/elastic/ElasticSearchIndex.kt | 2 | 8195 | /*
* Copyright 2010-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.elastic
import org.jetbrains.report.*
import org.jetbrains.report.json.*
import org.jetbrains.report.MeanVarianceBenchmark
import org.jetbrains.network.*
import kotlin.js.Promise // TODO - migrate to multiplatform.
data class Commit(val revision: String, val developer: String) : JsonSerializable {
override fun toString() = "$revision by $developer"
override fun serializeFields() = """
"revision": "$revision",
"developer": "$developer"
"""
companion object : EntityFromJsonFactory<Commit> {
fun parse(description: String) = if (description != "...") {
description.split(" by ").let {
val (currentRevision, currentDeveloper) = it
Commit(currentRevision, currentDeveloper)
}
} else {
Commit("unknown", "unknown")
}
override fun create(data: JsonElement): Commit {
if (data is JsonObject) {
val revision = elementToString(data.getRequiredField("revision"), "revision")
val developer = elementToString(data.getRequiredField("developer"), "developer")
return Commit(revision, developer)
} else {
error("Top level entity is expected to be an object. Please, check origin files.")
}
}
}
}
// List of commits.
class CommitsList : ConvertedFromJson, JsonSerializable {
val commits: List<Commit>
constructor(data: JsonElement) {
if (data !is JsonObject) {
error("Commits description is expected to be a JSON object!")
}
val changesElement = data.getOptionalField("change")
commits = changesElement?.let {
if (changesElement !is JsonArray) {
error("Change field is expected to be an array. Please, check source.")
}
changesElement.jsonArray.map {
with(it as JsonObject) {
Commit(elementToString(getRequiredField("version"), "version"),
elementToString(getRequiredField("username"), "username")
)
}
}
} ?: listOf<Commit>()
}
constructor(_commits: List<Commit>) {
commits = _commits
}
override fun toString(): String =
commits.toString()
companion object {
fun parse(description: String) = CommitsList(description.split(";").filter { it.isNotEmpty() }.map {
Commit.parse(it)
})
}
override fun serializeFields() = """
"commits": ${arrayToJson(commits)}
"""
}
data class BuildInfo(val buildNumber: String, val startTime: String, val endTime: String, val commitsList: CommitsList,
val branch: String,
val agentInfo: String /* Important agent information often used in requests.*/) : JsonSerializable {
override fun serializeFields() = """
"buildNumber": "$buildNumber",
"startTime": "$startTime",
"endTime": "$endTime",
${commitsList.serializeFields()},
"branch": "$branch",
"agentInfo": "$agentInfo"
"""
companion object : EntityFromJsonFactory<BuildInfo> {
override fun create(data: JsonElement): BuildInfo {
if (data is JsonObject) {
val buildNumber = elementToString(data.getRequiredField("buildNumber"), "buildNumber")
val startTime = elementToString(data.getRequiredField("startTime"), "startTime")
val endTime = elementToString(data.getRequiredField("endTime"), "endTime")
val branch = elementToString(data.getRequiredField("branch"), "branch")
val commitsList = data.getRequiredField("commits")
val commits = if (commitsList is JsonArray) {
commitsList.jsonArray.map { Commit.create(it as JsonObject) }
} else {
error("benchmarksSets field is expected to be an array. Please, check origin files.")
}
val agentInfoElement = data.getOptionalField("agentInfo")
val agentInfo = agentInfoElement?.let {
elementToString(agentInfoElement, "agentInfo")
} ?: ""
return BuildInfo(buildNumber, startTime, endTime, CommitsList(commits), branch, agentInfo)
} else {
error("Top level entity is expected to be an object. Please, check origin files.")
}
}
}
}
enum class ElasticSearchType {
TEXT, KEYWORD, DATE, LONG, DOUBLE, BOOLEAN, OBJECT, NESTED
}
abstract class ElasticSearchIndex(val indexName: String, val connector: ElasticSearchConnector) {
// Insert data.
fun insert(data: JsonSerializable): Promise<String> {
val description = data.toJson()
val writePath = "$indexName/_doc/"
return connector.request(RequestMethod.POST, writePath, body = description)
}
// Delete data.
fun delete(data: String): Promise<String> {
val writePath = "$indexName/_delete_by_query"
return connector.request(RequestMethod.POST, writePath, body = data)
}
// Make search request.
fun search(requestJson: String, filterPathes: List<String> = emptyList()): Promise<String> {
val path = "$indexName/_search?pretty${if (filterPathes.isNotEmpty())
"&filter_path=" + filterPathes.joinToString(",") else ""}"
return connector.request(RequestMethod.POST, path, body = requestJson)
}
abstract val mapping: Map<String, ElasticSearchType>
val mappingDescription: String
get() = """
{
"mappings": {
"properties": {
${mapping.map { (property, type) ->
"\"${property}\": { \"type\": \"${type.name.toLowerCase()}\"${if (type == ElasticSearchType.DATE) "," +
"\"format\": \"basic_date_time_no_millis\"" else ""} }"
}.joinToString()}}
}
}
""".trimIndent()
fun createMapping() =
connector.request(RequestMethod.PUT, indexName, body = mappingDescription)
}
class BenchmarksIndex(name: String, connector: ElasticSearchConnector) : ElasticSearchIndex(name, connector) {
override val mapping: Map<String, ElasticSearchType>
get() = mapOf("buildNumber" to ElasticSearchType.KEYWORD,
"benchmarks" to ElasticSearchType.NESTED,
"env" to ElasticSearchType.NESTED,
"kotlin" to ElasticSearchType.NESTED)
}
class GoldenResultsIndex(connector: ElasticSearchConnector) : ElasticSearchIndex("golden", connector) {
override val mapping: Map<String, ElasticSearchType>
get() = mapOf("buildNumber" to ElasticSearchType.KEYWORD,
"benchmarks" to ElasticSearchType.NESTED,
"env" to ElasticSearchType.NESTED,
"kotlin" to ElasticSearchType.NESTED)
}
class BuildInfoIndex(connector: ElasticSearchConnector) : ElasticSearchIndex("builds", connector) {
override val mapping: Map<String, ElasticSearchType>
get() = mapOf("buildNumber" to ElasticSearchType.KEYWORD,
"startTime" to ElasticSearchType.DATE,
"endTime" to ElasticSearchType.DATE,
"commits" to ElasticSearchType.NESTED)
}
// Processed benchmark result with calculated mean, variance and normalized reult.
class NormalizedMeanVarianceBenchmark(name: String, status: BenchmarkResult.Status, score: Double, metric: BenchmarkResult.Metric,
runtimeInUs: Double, repeat: Int, warmup: Int, variance: Double, val normalizedScore: Double) :
MeanVarianceBenchmark(name, status, score, metric, runtimeInUs, repeat, warmup, variance) {
override fun serializeFields(): String {
return """
${super.serializeFields()},
"normalizedScore": $normalizedScore
"""
}
} | apache-2.0 | cc7b54504d76481dd1763d74132475cb | 39.574257 | 133 | 0.610372 | 4.89546 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/compiler/IDELanguageSettingsProvider.kt | 1 | 8154 | // 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.compiler
import com.intellij.openapi.components.service
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.roots.ProjectRootModificationTracker
import com.intellij.openapi.util.Key
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.util.CachedValue
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import org.jetbrains.kotlin.analyzer.LanguageSettingsProvider
import org.jetbrains.kotlin.analyzer.ModuleInfo
import org.jetbrains.kotlin.caches.project.cacheInvalidatingOnRootModifications
import org.jetbrains.kotlin.cli.common.arguments.JavaTypeEnhancementStateParser
import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments
import org.jetbrains.kotlin.cli.common.arguments.parseCommandLineArguments
import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.config.*
import org.jetbrains.kotlin.idea.caches.project.*
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinPluginLayout
import org.jetbrains.kotlin.idea.core.script.ScriptRelatedModuleNameFile
import org.jetbrains.kotlin.idea.project.*
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.platform.TargetPlatformVersion
import org.jetbrains.kotlin.platform.jvm.JdkPlatform
import org.jetbrains.kotlin.platform.subplatformsOfType
import org.jetbrains.kotlin.scripting.definitions.ScriptDefinition
import org.jetbrains.kotlin.load.java.JavaTypeEnhancementState
class IDELanguageSettingsProviderHelper(private val project: Project) {
internal val languageVersionSettings: LanguageVersionSettings
get() = project.cacheInvalidatingOnRootModifications {
project.getLanguageVersionSettings()
}
internal val languageVersionSettingsWithJavaTypeEnhancementState: LanguageVersionSettings
get() = project.cacheInvalidatingOnRootModifications {
project.getLanguageVersionSettings(
javaTypeEnhancementState = computeJavaTypeEnhancementState(project)
)
}
private fun computeJavaTypeEnhancementState(project: Project): JavaTypeEnhancementState? {
var result: JavaTypeEnhancementState? = null
for (module in ModuleManager.getInstance(project).modules) {
val settings = KotlinFacetSettingsProvider.getInstance(project)?.getSettings(module) ?: continue
val compilerArguments = settings.mergedCompilerArguments as? K2JVMCompilerArguments ?: continue
val kotlinVersion = LanguageVersion.fromVersionString(compilerArguments.languageVersion)?.toKotlinVersion()
?: KotlinPluginLayout.instance.standaloneCompilerVersion.kotlinVersion
result = JavaTypeEnhancementStateParser(MessageCollector.NONE, kotlinVersion).parse(
compilerArguments.jsr305,
compilerArguments.supportCompatqualCheckerFrameworkAnnotations,
compilerArguments.jspecifyAnnotations,
compilerArguments.nullabilityAnnotations
)
}
return result
}
companion object {
fun getInstance(project: Project): IDELanguageSettingsProviderHelper = project.service()
}
}
object IDELanguageSettingsProvider : LanguageSettingsProvider {
override fun getLanguageVersionSettings(
moduleInfo: ModuleInfo,
project: Project
): LanguageVersionSettings =
when (moduleInfo) {
is ModuleSourceInfo -> moduleInfo.module.languageVersionSettings
is LibraryInfo -> IDELanguageSettingsProviderHelper.getInstance(project).languageVersionSettingsWithJavaTypeEnhancementState
is ScriptModuleInfo -> {
getLanguageSettingsForScripts(
project,
moduleInfo.scriptFile,
moduleInfo.scriptDefinition
).languageVersionSettings
}
is ScriptDependenciesInfo.ForFile ->
getLanguageSettingsForScripts(
project,
moduleInfo.scriptFile,
moduleInfo.scriptDefinition
).languageVersionSettings
is PlatformModuleInfo -> moduleInfo.platformModule.module.languageVersionSettings
else -> IDELanguageSettingsProviderHelper.getInstance(project).languageVersionSettings
}
// TODO(dsavvinov): get rid of this method; instead store proper instance of TargetPlatformVersion in platform-instance
override fun getTargetPlatform(moduleInfo: ModuleInfo, project: Project): TargetPlatformVersion =
when (moduleInfo) {
is ModuleSourceInfo ->
moduleInfo.module.platform?.subplatformsOfType<JdkPlatform>()?.firstOrNull()?.targetVersion
?: TargetPlatformVersion.NoVersion
is ScriptModuleInfo,
is ScriptDependenciesInfo.ForFile -> detectDefaultTargetPlatformVersion(moduleInfo.platform)
else -> TargetPlatformVersion.NoVersion
}
}
private data class ScriptLanguageSettings(
val languageVersionSettings: LanguageVersionSettings,
val targetPlatformVersion: TargetPlatformVersion
)
private val SCRIPT_LANGUAGE_SETTINGS = Key.create<CachedValue<ScriptLanguageSettings>>("SCRIPT_LANGUAGE_SETTINGS")
fun getTargetPlatformVersionForScript(project: Project, file: VirtualFile, scriptDefinition: ScriptDefinition): TargetPlatformVersion {
return getLanguageSettingsForScripts(project, file, scriptDefinition).targetPlatformVersion
}
private fun detectDefaultTargetPlatformVersion(platform: TargetPlatform?): TargetPlatformVersion {
return platform?.subplatformsOfType<JdkPlatform>()?.firstOrNull()?.targetVersion ?: TargetPlatformVersion.NoVersion
}
private fun getLanguageSettingsForScripts(project: Project, file: VirtualFile, scriptDefinition: ScriptDefinition): ScriptLanguageSettings {
val scriptModule = file.let {
ScriptRelatedModuleNameFile[project, it]?.let { module -> ModuleManager.getInstance(project).findModuleByName(module) }
?: ProjectFileIndex.SERVICE.getInstance(project).getModuleForFile(it)
}
val environmentCompilerOptions = scriptDefinition.defaultCompilerOptions
val args = scriptDefinition.compilerOptions
return if (environmentCompilerOptions.none() && args.none()) {
ScriptLanguageSettings(
project.getLanguageVersionSettings(contextModule = scriptModule),
detectDefaultTargetPlatformVersion(scriptModule?.platform)
)
} else {
val settings = scriptDefinition.getUserData(SCRIPT_LANGUAGE_SETTINGS) ?: createCachedValue(project) {
val compilerArguments = K2JVMCompilerArguments()
parseCommandLineArguments(environmentCompilerOptions.toList(), compilerArguments)
parseCommandLineArguments(args.toList(), compilerArguments)
// TODO: reporting
val versionSettings = compilerArguments.toLanguageVersionSettings(MessageCollector.NONE)
val jvmTarget =
compilerArguments.jvmTarget?.let { JvmTarget.fromString(it) } ?: detectDefaultTargetPlatformVersion(scriptModule?.platform)
ScriptLanguageSettings(versionSettings, jvmTarget)
}.also { scriptDefinition.putUserData(SCRIPT_LANGUAGE_SETTINGS, it) }
settings.value
}
}
private inline fun createCachedValue(
project: Project,
crossinline body: () -> ScriptLanguageSettings
): CachedValue<ScriptLanguageSettings> {
return CachedValuesManager
.getManager(project)
.createCachedValue(
{
CachedValueProvider.Result(
body(),
ProjectRootModificationTracker.getInstance(project), ModuleManager.getInstance(project)
)
}, false
)
}
| apache-2.0 | 651be55eec0c818401a07c68c43da7ab | 48.120482 | 158 | 0.744665 | 5.883117 | false | false | false | false |
GunoH/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/data/provider/GHPRDetailsDataProviderImpl.kt | 2 | 3897 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest.data.provider
import com.intellij.collaboration.async.CompletableFutureUtil.completionOnEdt
import com.intellij.collaboration.async.CompletableFutureUtil.successOnEdt
import com.intellij.collaboration.ui.SimpleEventListener
import com.intellij.collaboration.util.CollectionDelta
import com.intellij.openapi.Disposable
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.util.EventDispatcher
import com.intellij.util.messages.MessageBus
import org.jetbrains.plugins.github.api.data.GHLabel
import org.jetbrains.plugins.github.api.data.GHUser
import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequest
import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestRequestedReviewer
import org.jetbrains.plugins.github.pullrequest.data.GHPRIdentifier
import org.jetbrains.plugins.github.pullrequest.data.service.GHPRDetailsService
import org.jetbrains.plugins.github.util.LazyCancellableBackgroundProcessValue
import java.util.concurrent.CompletableFuture
class GHPRDetailsDataProviderImpl(private val detailsService: GHPRDetailsService,
private val pullRequestId: GHPRIdentifier,
private val messageBus: MessageBus)
: GHPRDetailsDataProvider, Disposable {
private val detailsLoadedEventDispatcher = EventDispatcher.create(SimpleEventListener::class.java)
@Volatile
override var loadedDetails: GHPullRequest? = null
private set
private val detailsRequestValue = LazyCancellableBackgroundProcessValue.create { indicator ->
detailsService.loadDetails(indicator, pullRequestId).successOnEdt {
loadedDetails = it
detailsLoadedEventDispatcher.multicaster.eventOccurred()
it
}
}
override fun loadDetails(): CompletableFuture<GHPullRequest> = detailsRequestValue.value
override fun reloadDetails() = detailsRequestValue.drop()
override fun updateDetails(indicator: ProgressIndicator, title: String?, description: String?): CompletableFuture<GHPullRequest> {
val future = detailsService.updateDetails(indicator, pullRequestId, title, description).completionOnEdt {
messageBus.syncPublisher(GHPRDataOperationsListener.TOPIC).onMetadataChanged()
}
detailsRequestValue.overrideProcess(future.successOnEdt {
loadedDetails = it
detailsLoadedEventDispatcher.multicaster.eventOccurred()
it
})
return future
}
override fun adjustReviewers(indicator: ProgressIndicator,
delta: CollectionDelta<GHPullRequestRequestedReviewer>): CompletableFuture<Unit> {
return detailsService.adjustReviewers(indicator, pullRequestId, delta).notify()
}
override fun adjustAssignees(indicator: ProgressIndicator, delta: CollectionDelta<GHUser>): CompletableFuture<Unit> {
return detailsService.adjustAssignees(indicator, pullRequestId, delta).notify()
}
override fun adjustLabels(indicator: ProgressIndicator, delta: CollectionDelta<GHLabel>): CompletableFuture<Unit> {
return detailsService.adjustLabels(indicator, pullRequestId, delta).notify()
}
override fun addDetailsReloadListener(disposable: Disposable, listener: () -> Unit) =
detailsRequestValue.addDropEventListener(disposable, listener)
override fun addDetailsLoadedListener(disposable: Disposable, listener: () -> Unit) =
SimpleEventListener.addDisposableListener(detailsLoadedEventDispatcher, disposable, listener)
private fun <T> CompletableFuture<T>.notify(): CompletableFuture<T> =
completionOnEdt {
detailsRequestValue.drop()
messageBus.syncPublisher(GHPRDataOperationsListener.TOPIC).onMetadataChanged()
}
override fun dispose() {
detailsRequestValue.drop()
}
} | apache-2.0 | 45293344659271b61c35f6a39745d966 | 45.404762 | 140 | 0.792148 | 5.196 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/KotlinPullUpHelperFactory.kt | 4 | 4411 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.pullUp
import com.intellij.ide.highlighter.JavaFileType
import com.intellij.lang.java.JavaLanguage
import com.intellij.psi.*
import com.intellij.refactoring.memberPullUp.JavaPullUpHelper
import com.intellij.refactoring.memberPullUp.PullUpData
import com.intellij.refactoring.memberPullUp.PullUpHelper
import com.intellij.refactoring.memberPullUp.PullUpHelperFactory
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.idea.refactoring.createJavaClass
import org.jetbrains.kotlin.idea.refactoring.memberInfo.toKtDeclarationWrapperAware
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.parents
import org.jetbrains.kotlin.psi.psiUtil.startOffset
class KotlinPullUpHelperFactory : PullUpHelperFactory {
private fun PullUpData.toKotlinPullUpData(): KotlinPullUpData? {
val sourceClass = sourceClass.unwrapped as? KtClassOrObject ?: return null
val targetClass = targetClass.unwrapped as? PsiNamedElement ?: return null
val membersToMove = membersToMove
.mapNotNull { it.toKtDeclarationWrapperAware() }
.sortedBy { it.startOffset }
return KotlinPullUpData(sourceClass, targetClass, membersToMove)
}
override fun createPullUpHelper(data: PullUpData): PullUpHelper<*> {
if (!data.sourceClass.isInheritor(data.targetClass, true)) return EmptyPullUpHelper
data.toKotlinPullUpData()?.let { return KotlinPullUpHelper(data, it) }
if (data.targetClass.language == KotlinLanguage.INSTANCE && data.sourceClass.language == JavaLanguage.INSTANCE) {
return JavaToKotlinPostconversionPullUpHelper(data)
}
return EmptyPullUpHelper
}
}
class JavaToKotlinPullUpHelperFactory : PullUpHelperFactory {
private fun createJavaToKotlinPullUpHelper(data: PullUpData): PullUpHelper<*>? {
if (!data.sourceClass.isInheritor(data.targetClass, true)) return null
val dummyTargetClass = createDummyTargetClass(data) ?: return null
val dataForDelegate = object : PullUpData by data {
override fun getTargetClass() = dummyTargetClass
}
return JavaToKotlinPreconversionPullUpHelper(data, dummyTargetClass, JavaPullUpHelper(dataForDelegate))
}
private fun createDummyTargetClass(data: PullUpData): PsiClass? {
val targetClass = data.targetClass.unwrapped as? KtClass ?: return null
val project = targetClass.project
val targetPackage = targetClass.containingKtFile.packageFqName.asString()
val dummyFile = PsiFileFactory.getInstance(project).createFileFromText(
"dummy.java",
JavaFileType.INSTANCE,
if (targetPackage.isNotEmpty()) "package $targetPackage;\n" else ""
)
val elementFactory = PsiElementFactory.getInstance(project)
val dummyTargetClass = createJavaClass(targetClass, null, forcePlainClass = true)
val outerClasses = targetClass.parents.filterIsInstance<KtClassOrObject>().toList().asReversed()
if (outerClasses.isEmpty()) return dummyFile.add(dummyTargetClass) as PsiClass
val outerPsiClasses = outerClasses.map {
val psiClass = elementFactory.createClass(it.name!!)
if (!(it is KtClass && it.isInner())) {
psiClass.modifierList!!.setModifierProperty(PsiModifier.STATIC, true)
}
psiClass
}
return outerPsiClasses.asSequence().drop(1).plus(dummyTargetClass)
.fold(dummyFile.add(outerPsiClasses.first()), PsiElement::add) as PsiClass
}
override fun createPullUpHelper(data: PullUpData): PullUpHelper<*> {
if (data.sourceClass is KtLightClass) return KotlinPullUpHelperFactory().createPullUpHelper(data)
createJavaToKotlinPullUpHelper(data)?.let { return it }
return PullUpHelper.INSTANCE
.allForLanguage(JavaLanguage.INSTANCE)
.firstOrNull { it !is JavaToKotlinPullUpHelperFactory }
?.createPullUpHelper(data)
?: EmptyPullUpHelper
}
} | apache-2.0 | 6590ba27e420c7991cad3287a09ee9c7 | 46.44086 | 158 | 0.735888 | 5.201651 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/AddReturnToUnusedLastExpressionInFunctionFix.kt | 2 | 2731 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.calls.callUtil.getType
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.isError
import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf
class AddReturnToUnusedLastExpressionInFunctionFix(element: KtElement) : KotlinQuickFixAction<KtElement>(element) {
private val available: Boolean
init {
val expression = element as? KtExpression
available = expression?.analyze(BodyResolveMode.PARTIAL)?.let { context ->
if (expression.isLastStatementInFunctionBody()) {
expression.getType(context)?.takeIf { !it.isError }
} else null
}?.let { expressionType ->
val function = expression.parent?.parent as? KtNamedFunction
val functionReturnType = function?.resolveToDescriptorIfAny()?.returnType?.takeIf { !it.isError } ?: return@let false
expressionType.isSubtypeOf(functionReturnType)
} ?: false
}
override fun getText() = KotlinBundle.message("fix.add.return.before.expression")
override fun getFamilyName() = text
override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean =
element != null && available
private fun KtExpression.isLastStatementInFunctionBody(): Boolean {
val body = this.parent as? KtBlockExpression ?: return false
val last = body.statements.lastOrNull() ?: return false
return last === this
}
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
element.replace(KtPsiFactory(project).createExpression("return ${element.text}"))
}
companion object Factory : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val casted = Errors.UNUSED_EXPRESSION.cast(diagnostic)
return AddReturnToUnusedLastExpressionInFunctionFix(casted.psiElement).takeIf(AddReturnToUnusedLastExpressionInFunctionFix::available)
}
}
}
| apache-2.0 | 8aa1638bf50198f1c1a33920055345e9 | 44.516667 | 158 | 0.739656 | 5.06679 | false | false | false | false |
medavox/MuTime | library/src/main/java/com/medavox/library/mutime/RebootWatcher.kt | 1 | 2235 | package com.medavox.library.mutime
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.SystemClock
import android.util.Log
import com.medavox.library.mutime.DiskCache.Companion.SHARED_PREFS_KEY
/**
* A {@link BroadcastReceiver} which listens for device reboots and clock changes by the user.
* Register this class as a broadcast receiver for {@link Intent#ACTION_BOOT_COMPLETED BOOT_COMPLETED}
* and {@link Intent#ACTION_TIME_CHANGED TIME_CHANGED},
* to allow MuTime to correct its offsets against these events.
*/
class RebootWatcher : BroadcastReceiver() {
private val TAG:String = "TimeDataPreserver"
/**Detects when one of the stored time stamps have been invalidated by user actions,
* and repairs it using the intact timestamp
*
* <p>
*
* For instance, if the user changes the system clock manually,
* then the uptime timestamp is used to calculate a new value for the system clock time stamp.
* */
override fun onReceive(context:Context, intent:Intent) {
val diskCache = DiskCache(context.getSharedPreferences(SHARED_PREFS_KEY, Context.MODE_PRIVATE))
val old = diskCache.getTimeData()
Log.i(TAG, "action \""+intent.action+"\" detected. Repairing TimeData...")
val clockNow = System.currentTimeMillis()
val uptimeNow = SystemClock.elapsedRealtime()
val trueTime:Long
when(intent.action) {
Intent.ACTION_BOOT_COMPLETED -> {
//uptime clock can no longer be trusted
trueTime = clockNow + old.systemClockOffset
val newUptimeOffset = trueTime -uptimeNow
val fixedUptime = old.copy(uptimeOffset=newUptimeOffset)
diskCache.onSntpTimeData(fixedUptime)
}
Intent.ACTION_TIME_CHANGED -> {
//system clock can no longer be trusted
trueTime = uptimeNow + old.uptimeOffset
val newClockOffset = trueTime -clockNow
val fixedSystemClockTime = old.copy(systemClockOffset = newClockOffset)
diskCache.onSntpTimeData(fixedSystemClockTime)
}
}
}
}
| apache-2.0 | e2dc5c7730db706c966f663ea29df5b7 | 39.636364 | 103 | 0.67472 | 4.461078 | false | false | false | false |
sksamuel/ktest | kotest-assertions/kotest-assertions-core/src/jvmTest/kotlin/com/sksamuel/kotest/matchers/comparables/ComparableMatchersTest.kt | 1 | 5770 | package com.sksamuel.kotest.matchers.comparables
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.style.FreeSpec
import io.kotest.inspectors.forAll
import io.kotest.matchers.comparables.beGreaterThan
import io.kotest.matchers.comparables.beGreaterThanOrEqualTo
import io.kotest.matchers.comparables.beLessThan
import io.kotest.matchers.comparables.beLessThanOrEqualTo
import io.kotest.matchers.comparables.compareTo
import io.kotest.matchers.comparables.gt
import io.kotest.matchers.comparables.gte
import io.kotest.matchers.comparables.lt
import io.kotest.matchers.comparables.lte
import io.kotest.matchers.comparables.shouldBeEqualComparingTo
import io.kotest.matchers.comparables.shouldBeGreaterThan
import io.kotest.matchers.comparables.shouldBeGreaterThanOrEqualTo
import io.kotest.matchers.comparables.shouldBeLessThan
import io.kotest.matchers.comparables.shouldBeLessThanOrEqualTo
import io.kotest.matchers.comparables.shouldNotBeEqualComparingTo
import io.kotest.matchers.should
import io.kotest.matchers.shouldBe
import io.kotest.matchers.shouldNot
import io.kotest.property.checkAll
class ComparableMatchersTest : FreeSpec() {
class ComparableExample(
private val underlying: Int
) : Comparable<ComparableExample> {
override fun compareTo(other: ComparableExample): Int {
return when {
underlying == other.underlying -> 0
underlying > other.underlying -> 1
else -> -1
}
}
}
init {
val cn = ComparableExample(-100)
val cz = ComparableExample(0)
val cp = ComparableExample(100)
"Comparable matchers" - {
"beLessThan (`<`) comparison" - {
"should pass test for lesser values" {
arrayOf(cn to cz, cz to cp).forAll {
it.first shouldBe lt(it.second)
it.first should beLessThan(it.second)
it.first shouldBeLessThan it.second
}
}
"should throw exception for equal values" {
arrayOf(cn, cz, cp).forAll {
shouldThrow<AssertionError> { it shouldBe lt(it) }
shouldThrow<AssertionError> { it should beLessThan(it) }
shouldThrow<AssertionError> { it shouldBeLessThan it }
}
}
"should throw exception for greater values" {
arrayOf(cp to cz, cz to cn).forAll {
shouldThrow<AssertionError> { it.first shouldBe lt(it.second) }
shouldThrow<AssertionError> { it.first should beLessThan(it.second) }
shouldThrow<AssertionError> { it.first shouldBeLessThan it.second }
}
}
}
"beLessThanOrEqualTo (`<=`) comparison" - {
"should pass for lesser or equal values" {
arrayOf(cn to cn, cn to cz, cz to cz, cz to cp, cp to cp).forAll {
it.first shouldBe lte(it.second)
it.first should beLessThanOrEqualTo(it.second)
it.first shouldBeLessThanOrEqualTo it.second
}
}
"should throw exception for greater values" {
arrayOf(cp to cz, cz to cn).forAll {
shouldThrow<AssertionError> { it.first shouldBe lte(it.second) }
shouldThrow<AssertionError> { it.first should beLessThanOrEqualTo(it.second) }
shouldThrow<AssertionError> { it.first shouldBeLessThanOrEqualTo it.second }
}
}
}
"beGreaterThan (`>`) comparison" - {
"should pass for greater values" {
arrayOf(cp to cz, cz to cn).forAll {
it.first shouldBe gt(it.second)
it.first should beGreaterThan(it.second)
it.first shouldBeGreaterThan it.second
}
}
"should throw exception for equal values" {
arrayOf(cn, cz, cp).forAll {
shouldThrow<AssertionError> { it shouldBe gt(it) }
shouldThrow<AssertionError> { it should beGreaterThan(it) }
shouldThrow<AssertionError> { it shouldBeGreaterThan it }
}
}
"should throw exception for lesser values" {
arrayOf(cn to cz, cz to cp).forAll {
shouldThrow<AssertionError> { it.first shouldBe gt(it.second) }
shouldThrow<AssertionError> { it.first should beGreaterThan(it.second) }
shouldThrow<AssertionError> { it.first shouldBeGreaterThan it.second }
}
}
}
"beGreaterThanOrEqualTo (`>=`) comparison" - {
"should pass for greater than or equal values" {
arrayOf(cp to cp, cp to cz, cz to cz, cz to cn, cn to cn).forAll {
it.first shouldBe gte(it.second)
it.first should beGreaterThanOrEqualTo(it.second)
it.first shouldBeGreaterThanOrEqualTo it.second
}
}
"should throw exception for lesser values" {
arrayOf(cn to cz, cz to cp).forAll {
shouldThrow<AssertionError> { it.first shouldBe gte(it.second) }
shouldThrow<AssertionError> { it.first should beGreaterThanOrEqualTo(it.second) }
shouldThrow<AssertionError> { it.first shouldBeGreaterThanOrEqualTo it.second }
}
}
}
"compareTo" - {
"should pass for equal values" {
checkAll { a: Int, b: Int ->
if (a == b) {
a should compareTo(b, Comparator { o1, o2 -> o1 - o2 })
a.shouldBeEqualComparingTo(b, Comparator { o1, o2 -> o1 - o2 } )
a shouldBeEqualComparingTo b
}
else {
a shouldNot compareTo(b, Comparator { o1, o2 -> o1 - o2 })
a.shouldNotBeEqualComparingTo(b, Comparator { o1, o2 -> o1 - o2 } )
a shouldNotBeEqualComparingTo b
}
}
}
}
}
}
}
| mit | 28ba8bacef3d8c53ad2810fca604e4bc | 34.182927 | 93 | 0.632756 | 4.583002 | false | true | false | false |
JetBrains/teamcity-azure-plugin | plugin-azure-server/src/main/kotlin/jetbrains/buildServer/clouds/azure/arm/connector/tasks/AzureThrottlerReadTasks.kt | 1 | 2221 | /*
* Copyright 2000-2021 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 jetbrains.buildServer.clouds.azure.arm.connector.tasks
class AzureThrottlerReadTasks {
enum class Values {
FetchResourceGroups,
FetchVirtualMachines,
FetchInstances,
FetchCustomImages,
FetchStorageAccounts,
FetchVirtualMachineSizes,
FetchSubscriptions,
FetchLocations,
FetchNetworks,
FetchServices,
}
companion object {
val FetchResourceGroups = AzureTaskDescriptorImpl(Values.FetchResourceGroups, { FetchResourceGroupsMapTaskImpl() })
val FetchVirtualMachines = AzureTaskDescriptorImpl(Values.FetchVirtualMachines, { FetchVirtualMachinesTaskImpl() })
val FetchInstances = AzureTaskDescriptorImpl(Values.FetchInstances, { notifications -> FetchInstancesTaskImpl(notifications) })
val FetchCustomImages = AzureTaskDescriptorImpl(Values.FetchCustomImages, { FetchCustomImagesTaskImpl() })
val FetchStorageAccounts = AzureTaskDescriptorImpl(Values.FetchStorageAccounts, { FetchStorageAccountsTaskImpl() })
val FetchVirtualMachineSizes = AzureTaskDescriptorImpl(Values.FetchVirtualMachineSizes, { FetchVirtualMachineSizesTaskImpl() })
val FetchSubscriptions = AzureTaskDescriptorImpl(Values.FetchSubscriptions, { FetchSubscriptionsTaskImpl() })
val FetchLocations = AzureTaskDescriptorImpl(Values.FetchLocations, { FetchLocationsTaskImpl() })
val FetchNetworks = AzureTaskDescriptorImpl(Values.FetchNetworks, { FetchNetworksTaskImpl() })
val FetchServices = AzureTaskDescriptorImpl(Values.FetchServices, { FetchServicesTaskImpl() })
}
}
| apache-2.0 | d4b69ec6b1529799d7f7d7beadf2e860 | 48.355556 | 135 | 0.754165 | 4.83878 | false | false | false | false |
RSDT/Japp | app/src/main/java/nl/rsdt/japp/application/activities/SplashActivity.kt | 1 | 8753 | package nl.rsdt.japp.application.activities
import android.Manifest
import android.app.Activity
import android.app.AlertDialog
import android.content.Intent
import android.media.MediaPlayer
import android.os.Bundle
import android.util.Log
import com.google.firebase.iid.FirebaseInstanceId
import com.google.firebase.messaging.FirebaseMessaging
import nl.rsdt.japp.R
import nl.rsdt.japp.application.Japp
import nl.rsdt.japp.application.JappPreferences
import nl.rsdt.japp.jotial.data.structures.area348.MetaColorInfo
import nl.rsdt.japp.jotial.io.AppData
import nl.rsdt.japp.jotial.maps.MapManager
import nl.rsdt.japp.jotial.maps.MapStorage
import nl.rsdt.japp.jotial.maps.deelgebied.Deelgebied
import nl.rsdt.japp.jotial.net.apis.MetaApi
import nl.rsdt.japp.service.cloud.data.NoticeInfo
import pub.devrel.easypermissions.AppSettingsDialog
import pub.devrel.easypermissions.EasyPermissions
import pub.devrel.easypermissions.PermissionRequest
import retrofit2.Call
import retrofit2.Callback
import java.io.IOException
/**
* @author Dingenis Sieger Sinke
* @version 1.0
* @since 8-7-2016
* Description...
*/
class SplashActivity : Activity(), MapStorage.OnMapDataLoadedCallback, EasyPermissions.PermissionCallbacks {
private var started: Boolean = false
private var locationGranted = false
private var storageGranted = false
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
/*
* Checks if the Fresh-Start feature is enabled if so the data of the app is cleared.
* */
if (JappPreferences.isFreshStart) {
/*
* Clear preferences.
* */
JappPreferences.clear()
/*
* Clear all the data files
* */
AppData.clear()
val thread = Thread(Runnable {
try {
/*
* Resets Instance ID and revokes all tokens.
* */
FirebaseInstanceId.getInstance().deleteInstanceId()
} catch (e: IOException) {
Log.e(TAG, e.toString(), e)
}
/*
* Get a new token.
* */
FirebaseInstanceId.getInstance().token
})
thread.run()
}
/**
* Subscribe to the updates topic.
*/
FirebaseMessaging.getInstance().subscribeToTopic("updates")
if (JappPreferences.shacoEnabled() && (JappPreferences.accountUsername == "David" || JappPreferences.accountUsername == "test")) {
val player = MediaPlayer.create(this, R.raw.shaco_tank_engine)
player.start()
}
val metaApi = Japp.getApi(MetaApi::class.java)
metaApi.getMetaColor(JappPreferences.accountKey).enqueue(object : Callback<MetaColorInfo> {
override fun onResponse(call: Call<MetaColorInfo>, response: retrofit2.Response<MetaColorInfo>) {
val colorInfo = response.body()
JappPreferences.setColorHex("a", colorInfo?.ColorCode?.a?: "#FFFFFFFF")
JappPreferences.setColorHex("b", colorInfo?.ColorCode?.b?: "#FFFFFFFF")
JappPreferences.setColorHex("c", colorInfo?.ColorCode?.c?: "#FFFFFFFF")
JappPreferences.setColorHex("d", colorInfo?.ColorCode?.d?: "#FFFFFFFF")
JappPreferences.setColorHex("e", colorInfo?.ColorCode?.e?: "#FFFFFFFF")
JappPreferences.setColorHex("f", colorInfo?.ColorCode?.f?: "#FFFFFFFF")
JappPreferences.setColorHex("x", colorInfo?.ColorCode?.x?: "#FFFFFFFF")
JappPreferences.setColorName("a", colorInfo?.ColorName?.a?: "#FFFFFFFF")
JappPreferences.setColorName("b", colorInfo?.ColorName?.b?: "#FFFFFFFF")
JappPreferences.setColorName("c", colorInfo?.ColorName?.c?: "#FFFFFFFF")
JappPreferences.setColorName("d", colorInfo?.ColorName?.d?: "#FFFFFFFF")
JappPreferences.setColorName("e", colorInfo?.ColorName?.e?: "#FFFFFFFF")
JappPreferences.setColorName("f", colorInfo?.ColorName?.f?: "#FFFFFFFF")
JappPreferences.setColorName("x", colorInfo?.ColorName?.x?: "#FFFFFFFF")
}
override fun onFailure(call: Call<MetaColorInfo>, t: Throwable) {
Log.e(TAG, t.toString())
}
})
val intent = intent
val extras = intent.extras
if (extras != null) {
if (extras.containsKey("title") && extras.containsKey("body")) {
val dialog = AlertDialog.Builder(this)
.setTitle(extras.getString("title"))
.setMessage(extras.getString("body"))
.setIcon(NoticeInfo.parseDrawable(extras.getString("icon")))
.setPositiveButton(R.string.continue_to_app) { _,_-> start() }
.create()
dialog.setOnShowListener { dialog -> (dialog as AlertDialog).getButton(AlertDialog.BUTTON_NEGATIVE).isEnabled = false }
dialog.show()
} else {
requestPermissions()
}
} else {
requestPermissions()
}
}
private fun requestPermissions() {
EasyPermissions.requestPermissions(
PermissionRequest.Builder(this, RC_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION)
.setRationale(R.string.location_rationale)
.setPositiveButtonText(R.string.rationale_ask_ok)
.setNegativeButtonText(R.string.rationale_ask_cancel)
.build())
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
// Forward results to EasyPermissions
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}
override fun onPermissionsDenied(requestCode: Int, perms: MutableList<String>) {
if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
AppSettingsDialog.Builder(this).build().show()
}
val dialog = AlertDialog.Builder(this).apply {
title = "Permission Denied!"
setMessage(R.string.location_storage_rationale)
setPositiveButton(R.string.oke) { _,_ -> finishAffinity()}
}.create()
dialog.show()
}
override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>) {
if (requestCode == RC_LOCATION){
locationGranted = true
EasyPermissions.requestPermissions(
PermissionRequest.Builder(this, RC_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
.setRationale(R.string.storage_rationale)
.setPositiveButtonText(R.string.storage_ask_ok)
.setNegativeButtonText(R.string.storage_ask_cancel)
.build())
}
if (requestCode == RC_STORAGE){
storageGranted = true
}
if (!started && storageGranted && locationGranted){
started = true
start()
}
}
private fun start() {
val storage = MapStorage.instance
val mapManager = MapManager.instance
Deelgebied.initialize(this.resources)
storage.add(this)
storage.load(mapManager)
}
override fun onMapDataLoaded() {
val storage = MapStorage.instance
storage.remove(this)
continueToNext()
}
fun continueToNext() {
determineAndStartNewActivity()
}
private fun determineAndStartNewActivity() {
val key = JappPreferences.accountKey
if (key?.isEmpty() != false) {
val intent = Intent(this, LoginActivity::class.java)
startActivity(intent)
finish()
} else {
if (JappPreferences.isFirstRun) {
val intent = Intent(this, IntroActivity::class.java)
startActivity(intent)
finish()
} else {
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
finish()
}
}
}
companion object {
val TAG = "SplashActivity"
val LOAD_ID = "LOAD_RESULTS"
private const val RC_LOCATION: Int = 1
private const val RC_STORAGE: Int = 2
private const val RC_LOCATION_STORAGE = RC_STORAGE or RC_LOCATION
}
}
| apache-2.0 | fecc236351a89444aa9d9647db8b0a8d | 36.728448 | 150 | 0.602194 | 4.939616 | false | false | false | false |
kpspemu/kpspemu | src/jvmTest/kotlin/com/soywiz/kpspemu/cpu/dynarec/DynarekMethodBuilderTestJvm.kt | 1 | 1875 | package com.soywiz.kpspemu.cpu.dynarec
import com.soywiz.dynarek2.*
import com.soywiz.dynarek2.target.js.*
import com.soywiz.kmem.*
import com.soywiz.korio.stream.*
import com.soywiz.kpspemu.cpu.*
import com.soywiz.kpspemu.cpu.assembler.*
import com.soywiz.kpspemu.cpu.dis.*
import com.soywiz.kpspemu.mem.*
import com.soywiz.krypto.encoding.*
import org.junit.Test
import java.io.*
import kotlin.test.*
class DynarekMethodBuilderTestJvm {
@Test
fun name() {
val mb = DynarekMethodBuilder()
val bytes = Assembler.assemble(
"li a1, 10",
"li a2, 0",
"sll r0, r0, 0",
"li a0, 0x0890_0004",
"",
"label1: addi a2, a2, 2",
//"beq a1, zero, label1",
"j label1",
"addi a1, a1, -1",
"bitrev a0, a0",
"lui s0, 0x890",
//"addiu a0, s0, 4",
""
)
for (pc in 0 until bytes.size step 4) {
println("%08X: %s".format(pc, Disassembler.disasm(pc, bytes.readS32_le(pc))))
mb.dispatch(pc, bytes.readS32_le(pc))
if (mb.reachedFlow) {
break
}
}
val func = mb.generateFunction()
val ctx = D2ContextPspEmu()
println("----")
println(func.generateJsBody(ctx, strict = false))
try {
val state = CpuState("DynarekMethodBuilderTest", GlobalCpuState(Memory()))
val ff = func.generateCpuStateFunction(ctx)
ff(state)
assertEquals(0x08900004.hex, state.A0.hex)
assertEquals(9.hex, state.A1.hex)
assertEquals(2.hex, state.A2.hex)
assertEquals(0x00000014.hex, state.PC.hex)
} catch (e: InvalidCodeGenerated) {
File("generated.class").writeBytes(e.data)
throw e
}
}
}
| mit | 0156fd7f393bf614da21f9b518de9b59 | 27.409091 | 89 | 0.552533 | 3.517824 | false | true | false | false |
feer921/BaseProject | src/main/java/common/base/mvx/vm/BaseNetReqWithOkgoViewModel.kt | 1 | 9965 | package common.base.mvx.vm
import androidx.annotation.CallSuper
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.OkgoNetCallback
import common.base.netAbout.INetEvent
import common.base.netAbout.NetRequestLifeMarker
import common.base.netAbout.WrapperRespData
import common.base.utils.GenericsParamUtil
/**
* ******************(^_^)***********************<br>
* User: fee(QQ/WeiXin:1176610771)<br>
* <P>DESC:
* [ViewModel] 的基础封装,
* 可进行 基于[OkGo]的网络数据请求
* 注:此基类把 业务数据层(网络请求数据) 耦合到了 [ViewModel]层
* </p>
* ******************(^_^)***********************
*/
@Deprecated("此基类把 业务数据层(网络请求数据) 耦合到了")
abstract class BaseNetReqWithOkgoViewModel<R> : BaseViewModel(), INetEvent<R> {
/**
* 是否启用 网络请求错误回调时的 Log 输出
* def: true
*/
protected var enableDebugOnErrorResp = true
/**
* 是否启用 网络请求 正常回调里的 Log 输出
*/
protected var enableDebugOnNormalResp = true
protected var aOkGoCallback: OkgoNetCallback<R>? = null
/**
* 通用的 网络请求 响应 的[LiveData],子类可以不用
*/
private var commonNetRespLiveData: MutableLiveData<WrapperRespData<R?>> ? = null
/**
* 如果该方法调用了,即表明 某处是希望来 观察 该 LiveData 的
*/
fun getCommonNetRespLiveData(): MutableLiveData<WrapperRespData<R?>>? {
if (commonNetRespLiveData == null) {
commonNetRespLiveData = MutableLiveData()
}
return commonNetRespLiveData
}
/**
* 是否启用 本基类 通用的网络请求 结果数据的 LiveData
* def: true
*/
protected var enableCommonNetRespLivedata = true
/**
* 当本[ViewModel] 销毁时,是否自动标记当前进行的网络请求(如果有的话) 为取消状态
* def: true
*/
protected var enableAutoCancelNetReq = true
/**
* 网络请求 状态 标记者
* 用于标记一个网络请求的:开始、结束
*/
protected val netRequestStateMarker = NetRequestLifeMarker()
protected fun initOkgoNetDataListener() {
if (aOkGoCallback == null) {
aOkGoCallback = createOkgoNetListener()
}
}
protected fun createOkgoNetListener(): OkgoNetCallback<R> {
return OkgoNetCallback(getSubClasGenericsParamClass(), this)
}
/**
* 获取本基类的子类所指定的泛型T的具体的对象类型的Class对象
* 即:最多有效到第一个非泛型参数的本基类的子类
* changed by fee 2017-04-29:如果本基类的子类已经是一个实体类[非泛型参数类]的子类时,需要自己指定泛型的class类型了
* eg.: FirstSubClasss extends BaseNetCallFragment<ServerResut>{} 在FirstSubClass是可以自动获取到泛型参数为ServerResult的
* 但是如果 FirstSubClass 再有子类,则自动获取不到了,需要重写本方法,直接指定ServerResut.class
* @return Class<T> T指代本类所声明的泛型T eg.: xxSubClass extends BaseNetCallFragment<String>,
</String></T></ServerResut> */
protected open fun getSubClasGenericsParamClass(): Class<R> {
return GenericsParamUtil.getGenericsParamCalss(javaClass.genericSuperclass, 0)
}
/**
* 按tag 取消 Okgo 的网络请求
* @param toCancelTag
*/
protected fun cancelOkGoNetWork(toCancelTag: Any) {
OkGo.getInstance().cancelTag(toCancelTag)
}
/**
* 网络请求失败
*
* @param requestDataType 当前请求类型
* @param errorInfo 错误信息
*/
final override fun onErrorResponse(requestDataType: Int, errorInfo: String?) {
if (isEnableLogDebug && enableDebugOnErrorResp) {
e(null, " --> onErrorResponse() requestDataType = $requestDataType, errorInfo = $errorInfo")
}
//如果用户主动取消了当前网络请求如【Loading dialog】被取消了(实际上该请求已到达服务端,因而会响应回调)
//则不让各子类处理已被用户取消了的请求
if (curRequestCanceled(requestDataType)) {
return
}
addRequestStateMark(requestDataType, NetRequestLifeMarker.REQUEST_STATE_FINISHED)
dealWithErrorResponse(requestDataType, errorInfo)
}
/**
* 网络请求的【错误/异常】 响应回调
* @param requestDataType 当前网络请求类型
* @param errorInfo 错误/异常 信息
*/
protected open fun dealWithErrorResponse(requestDataType: Int, errorInfo: String?){
//如果子类重写,并不调用 supper本方法,则[netRespLiveData] 无效
if (enableCommonNetRespLivedata) {
// if (commonNetRespLiveData == null) {
// commonNetRespLiveData = MutableLiveData()
// }
commonNetRespLiveData?.value = WrapperRespData(null, requestDataType, errorInfo)
}
}
/**
* 网络请求的响应
*
* @param requestDataType 当前网络请求数据类型
* @param result 响应实体:即表示将网络响应的结果转化成指定的数据实体bean
*/
final override fun onResponse(requestDataType: Int, result: R?) {
if (isEnableLogDebug && enableDebugOnNormalResp) {
v(null, "--> onResponse() requestDataType = $requestDataType, result = $result")
}
if (curRequestCanceled(requestDataType)) {
return
}
addRequestStateMark(requestDataType, NetRequestLifeMarker.REQUEST_STATE_FINISHED)
dealWithResponse(requestDataType, result)
}
/**
* 网络请求的 正常响应回调
* @param requestDataType 当前网络请求类型
* @param result 序列化后[如JSON序列化后] 的结果对象
*/
protected open fun dealWithResponse(requestDataType: Int, result: R?){
//如果子类重写,并不调用 supper本方法,则[netRespLiveData] 无效
if (enableCommonNetRespLivedata) {
// if (commonNetRespLiveData == null) {
// commonNetRespLiveData = MutableLiveData()
// }
commonNetRespLiveData?.value = WrapperRespData(result, requestDataType, null)
}
}
/**
* 错误回调,在还没有开始请求之前,比如:一些参数错误
*
* @param curRequestDataType 当前网络请求类型
* @param errorType 错误类型
*/
override fun onErrorBeforeRequest(curRequestDataType: Int, errorType: Int) {
}
/**
* 当前的请求是否取消了
* @param dataType
* @return
*/
protected fun curRequestCanceled(dataType: Int): Boolean {
return netRequestStateMarker.curRequestCanceled(dataType)
}
/**
* 查询当前网络请求的状态
* @param curRequestType
* @return
*/
protected fun curNetRequestState(curRequestType: Int): Byte {
return netRequestStateMarker.curRequestLifeState(curRequestType)
}
/**
* 标记当前网络请求的状态 : 正在请求、已完成、已取消等
* @see {@link NetRequestLifeMarker.REQUEST_STATE_ING}
*
* @param requestDataType
* @param targetState
*/
protected fun addRequestStateMark(requestDataType: Int, targetState: Byte) {
netRequestStateMarker.addRequestToMark(requestDataType, targetState)
}
/**
* 开始追踪、标记一个对应的网络请求类型的请求状态
* @param curRequestDataType
*/
protected fun trackARequestState(curRequestDataType: Int) {
netRequestStateMarker.addRequestToMark(curRequestDataType, NetRequestLifeMarker.REQUEST_STATE_ING)
}
protected fun isCurRequestWorking(reqDataType: Int): Boolean {
return curNetRequestState(reqDataType) == NetRequestLifeMarker.REQUEST_STATE_ING
}
/**
* 某个请求类型的网络请求是否已经完成
* @param requestDataType
* @return
*/
protected fun curRequestFinished(requestDataType: Int): Boolean {
return NetRequestLifeMarker.REQUEST_STATE_FINISHED == curNetRequestState(requestDataType)
}
/***
* 取消网络请求(注:该方法只适合本框架的Retrofit请求模块才会真正取消网络请求,
* 如果使用的是本框架的OkGo请求模块,还请各APP的基类再进行处理一下,或本框架再优化来统一处理)
* @param curRequestType 要取消的网络请求类型
*/
protected fun cancelNetRequest(curRequestType: Int) {
netRequestStateMarker.cancelCallRequest(curRequestType)
}
/**
* 判断是否某些网络请求全部完成了
* @param theRequestTypes 对应要加入判断的网络请求类型
* @return true:所有参与判断的网络请求都完成了;false:只要有任何一个请求未完成即未完成。
*/
protected fun isAllRequestFinished(vararg theRequestTypes: Int): Boolean {
if (theRequestTypes.isEmpty()) {
return false
}
for (oneRequestType in theRequestTypes) {
if (!curRequestFinished(oneRequestType)) {
return false //只要有一个请求没有完成,就是未全部完成
}
}
return true
}
/**
* This method will be called when this ViewModel is no longer used and will be destroyed.
* <p>
* It is useful when ViewModel observes some data and you need to clear this subscription to
* prevent a leak of this ViewModel.
*/
@CallSuper
override fun onCleared() {
super.onCleared()
if (enableAutoCancelNetReq) {
aOkGoCallback?.canceled = true
}
e(null, " --> onCleared()")
}
} | apache-2.0 | 375fb4df93e034e33c50da2fe938d174 | 29.338235 | 110 | 0.649739 | 3.879173 | false | false | false | false |
Esri/arcgis-runtime-samples-android | kotlin/render-multilayer-symbols/src/main/java/com/esri/arcgisruntime/sample/rendermultilayersymbols/MainActivity.kt | 1 | 25236 | /* Copyright 2022 Esri
*
* 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.esri.arcgisruntime.sample.rendermultilayersymbols
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.esri.arcgisruntime.ArcGISRuntimeEnvironment
import com.esri.arcgisruntime.geometry.Geometry
import com.esri.arcgisruntime.symbology.TextSymbol
import com.esri.arcgisruntime.symbology.PictureMarkerSymbolLayer
import com.esri.arcgisruntime.symbology.MultilayerPolylineSymbol
import com.esri.arcgisruntime.symbology.MultilayerPointSymbol
import com.esri.arcgisruntime.symbology.MultilayerSymbol
import com.esri.arcgisruntime.symbology.VectorMarkerSymbolElement
import com.esri.arcgisruntime.symbology.StrokeSymbolLayer
import com.esri.arcgisruntime.symbology.VectorMarkerSymbolLayer
import com.esri.arcgisruntime.symbology.SymbolAnchor
import com.esri.arcgisruntime.symbology.HatchFillSymbolLayer
import com.esri.arcgisruntime.symbology.SymbolLayer
import com.esri.arcgisruntime.geometry.Point
import com.esri.arcgisruntime.geometry.PolylineBuilder
import com.esri.arcgisruntime.geometry.SpatialReferences
import com.esri.arcgisruntime.geometry.PolygonBuilder
import com.esri.arcgisruntime.geometry.Envelope
import com.esri.arcgisruntime.loadable.LoadStatus
import com.esri.arcgisruntime.mapping.ArcGISMap
import com.esri.arcgisruntime.mapping.BasemapStyle
import com.esri.arcgisruntime.mapping.view.Graphic
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay
import com.esri.arcgisruntime.mapping.view.MapView
import com.esri.arcgisruntime.sample.rendermultilayersymbols.databinding.ActivityMainBinding
import com.esri.arcgisruntime.symbology.DashGeometricEffect
import com.esri.arcgisruntime.symbology.MultilayerPolygonSymbol
import com.esri.arcgisruntime.symbology.SolidFillSymbolLayer
import com.esri.arcgisruntime.symbology.SolidStrokeSymbolLayer
import java.io.File
import java.io.FileOutputStream
import java.io.OutputStream
class MainActivity : AppCompatActivity() {
private var graphicsOverlay: GraphicsOverlay? = null
private val TAG = MainActivity::class.java.simpleName
// define offset used to keep a consistent distance between symbols in the same column
private val offset = 20.0
private val activityMainBinding by lazy {
ActivityMainBinding.inflate(layoutInflater)
}
private val mapView: MapView by lazy {
activityMainBinding.mapView
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(activityMainBinding.root)
// authentication with an API key or named user is required
// to access basemaps and other location services
ArcGISRuntimeEnvironment.setApiKey(BuildConfig.API_KEY)
// create a map with the BasemapType
val map = ArcGISMap(BasemapStyle.ARCGIS_LIGHT_GRAY)
// create a graphics overlay
graphicsOverlay = GraphicsOverlay()
mapView.apply {
// set the map to be displayed in the layout's map view
mapView.map = map
// add the graphic overlay to the map view
graphicsOverlays.add(graphicsOverlay)
}
// create labels to go above each category of graphic
addTextGraphics()
// create picture marker symbols, from URI or local cache
addImageGraphics()
// add graphics with simple vector marker symbol elements (MultilayerPoint Simple Markers on app UI)
val solidFillSymbolLayer = SolidFillSymbolLayer(Color.RED)
val multilayerPolygonSymbol =
MultilayerPolygonSymbol(listOf(solidFillSymbolLayer))
val solidStrokeSymbolLayer =
SolidStrokeSymbolLayer(1.0, Color.RED, listOf(DashGeometricEffect()))
val multilayerPolylineSymbol =
MultilayerPolylineSymbol(listOf(solidStrokeSymbolLayer))
// define vector element for a diamond, triangle and cross
val diamondGeometry =
Geometry.fromJson("{\"rings\":[[[0.0,2.5],[2.5,0.0],[0.0,-2.5],[-2.5,0.0],[0.0,2.5]]]}")
val triangleGeometry =
Geometry.fromJson("{\"rings\":[[[0.0,5.0],[5,-5.0],[-5,-5.0],[0.0,5.0]]]}")
val crossGeometry =
Geometry.fromJson("{\"paths\":[[[-1,1],[0,0],[1,-1]],[[1,1],[0,0],[-1,-1]]]}")
// add red diamond graphic
addGraphicsWithVectorMarkerSymbolElements(
multilayerPolygonSymbol,
diamondGeometry,
0.0
)
// add red triangle graphic
addGraphicsWithVectorMarkerSymbolElements(
multilayerPolygonSymbol,
triangleGeometry,
offset
)
// add red cross graphic
addGraphicsWithVectorMarkerSymbolElements(
multilayerPolylineSymbol,
crossGeometry,
2 * offset
)
// create line marker symbols
// similar to SimpleLineSymbolStyle.SHORTDASHDOTDOT
addLineGraphicsWithMarkerSymbols(
listOf(4.0, 6.0, 0.5, 6.0, 0.5, 6.0),
0.0
)
// similar to SimpleLineSymbolStyle.SHORTDASH
addLineGraphicsWithMarkerSymbols(
listOf(4.0, 6.0),
offset
)
// similar to SimpleLineSymbolStyle.DASHDOTDOT
addLineGraphicsWithMarkerSymbols(
listOf(7.0, 9.0, 0.5, 9.0),
2 * offset
)
// create polygon marker symbols
// cross-hatched diagonal lines
addPolygonGraphicsWithMarkerSymbols(
listOf(-45.0, 45.0),
0.0
)
// hatched diagonal lines
addPolygonGraphicsWithMarkerSymbols(
listOf(-45.0),
offset
)
// hatched vertical lines
addPolygonGraphicsWithMarkerSymbols(
listOf(90.0),
2 * offset
)
// define vector element for a hexagon which will be used as the basis of a complex point
val complexPointGeometry =
Geometry.fromJson("{\"rings\":[[[-2.89,5.0],[2.89,5.0],[5.77,0.0],[2.89,-5.0],[-2.89,-5.0],[-5.77,0.0],[-2.89,5.0]]]}")
// create the more complex multilayer graphics: a point, polygon, and polyline
addComplexPoint(complexPointGeometry)
addComplexPolygon()
addComplexPolyline()
}
/**
* Creates the label graphics to be displayed above each category of symbol,
* and adds them to the graphics overlay.
*/
private fun addTextGraphics() {
graphicsOverlay?.graphics?.addAll(
listOf(
Graphic(
Point(-150.0, 50.0, SpatialReferences.getWgs84()),
getTextSymbol("MultilayerPoint\nSimple Markers")
),
Graphic(
Point(-80.0, 50.0, SpatialReferences.getWgs84()),
getTextSymbol("MultilayerPoint\nPicture Markers")
),
Graphic(
Point(0.0, 50.0, SpatialReferences.getWgs84()),
getTextSymbol("Multilayer\nPolyline")
),
Graphic(
Point(65.0, 50.0, SpatialReferences.getWgs84()),
getTextSymbol("Multilayer\nPolygon")
),
Graphic(
Point(130.0, 50.0, SpatialReferences.getWgs84()),
getTextSymbol("Multilayer\nComplex Symbols")
)
)
)
}
/**
* @return the TextSymbol with the [text] to be displayed on the map.
*/
private fun getTextSymbol(text: String): TextSymbol {
val textSymbol = TextSymbol(
10F,
text,
Color.BLACK,
TextSymbol.HorizontalAlignment.CENTER,
TextSymbol.VerticalAlignment.MIDDLE
)
// give the text symbol a white background
textSymbol.backgroundColor = Color.WHITE
return textSymbol
}
/**
* Create picture marker symbols from online URI or local cache.
*/
private fun addImageGraphics() {
// URI of image to display
val bluePinImageURI =
"https://sampleserver6.arcgisonline.com/arcgis/rest/services/Recreation/FeatureServer/0/images/e82f744ebb069bb35b234b3fea46deae/blue_pin.png"
// load the PictureMarkerSymbolLayer using the image URI
val pictureMarkerFromUri = PictureMarkerSymbolLayer(bluePinImageURI)
pictureMarkerFromUri.addDoneLoadingListener {
if (pictureMarkerFromUri.loadStatus == LoadStatus.LOADED) {
// add loaded layer to the map
addGraphicFromPictureMarkerSymbolLayer(pictureMarkerFromUri, 0.0)
} else {
showError("Picture marker symbol layer failed to load from URI: ${pictureMarkerFromUri.loadError.message}")
}
}
pictureMarkerFromUri.loadAsync()
val localCachePath = cacheDir.toString() + File.separator + getString(R.string.blue_pin)
// load blue pin from assets into cache directory
copyFileFromAssetsToCache(localCachePath)
// load the PictureMarkerSymbolLayer using the image using local cache
val pictureMarkerFromCache = PictureMarkerSymbolLayer(localCachePath)
pictureMarkerFromCache.addDoneLoadingListener {
if (pictureMarkerFromCache.loadStatus == LoadStatus.LOADED) {
// add loaded layer to the map
addGraphicFromPictureMarkerSymbolLayer(pictureMarkerFromCache, 20.0)
} else {
showError("Picture marker symbol layer failed to load from cache: ${pictureMarkerFromCache.loadError.message}")
}
}
pictureMarkerFromCache.loadAsync()
}
/**
* Copy the given file from the app's assets folder to the app's cache directory.
* @param localCachePath as String.
*/
private fun copyFileFromAssetsToCache(localCachePath: String) {
val assetManager = applicationContext.assets
val file = File(localCachePath)
if (!file.exists()) {
try {
val fileIn = assetManager.open(getString(R.string.blue_pin))
val fileOut: OutputStream =
FileOutputStream(localCachePath)
val buffer = ByteArray(1024)
var read = fileIn.read(buffer)
while (read != -1) {
fileOut.write(buffer, 0, read)
read = fileIn.read(buffer)
}
} catch (e: Exception) {
Log.e(TAG, "Error writing to cache. " + e.message)
}
} else {
Log.i(TAG, "File already in cache.")
}
}
/**
* Loads a picture marker symbol layer and after it has loaded, creates a new multilayer point symbol from it.
* A graphic is created from the multilayer point symbol and added to the graphics overlay.
*
* The [pictureMarkerSymbolLayer] to be loaded.
* The [offset] value used to keep a consistent distance between symbols in the same column.
*
*/
private fun addGraphicFromPictureMarkerSymbolLayer(
pictureMarkerSymbolLayer: PictureMarkerSymbolLayer,
offset: Double
) {
// wait for the picture marker symbol layer to load and check it has loaded
pictureMarkerSymbolLayer.addDoneLoadingListener {
if (pictureMarkerSymbolLayer.loadStatus === LoadStatus.LOADED) {
// set the size of the layer and create a new multilayer point symbol from it
pictureMarkerSymbolLayer.size = 40.0
val multilayerPointSymbol =
MultilayerPointSymbol(listOf(pictureMarkerSymbolLayer))
// create location for the symbol
val point = Point(-80.0, 20.0 - offset, SpatialReferences.getWgs84())
// create graphic with the location and symbol and add it to the graphics overlay
val graphic = Graphic(point, multilayerPointSymbol)
graphicsOverlay?.graphics?.add(graphic)
} else if (pictureMarkerSymbolLayer.loadStatus === LoadStatus.FAILED_TO_LOAD) {
showError("Picture marker symbol layer failed to load: ${pictureMarkerSymbolLayer.loadError.message}")
}
}
// load the picture marker symbol layer
pictureMarkerSymbolLayer.loadAsync()
}
/**
* Adds new graphics constructed from multilayer point symbols.
*
* The [multilayerSymbol] to construct the vector marker symbol element with.
* The input [geometry] for the vector marker symbol element.
* [offset] the value used to keep a consistent distance between symbols in the same column.
*/
private fun addGraphicsWithVectorMarkerSymbolElements(
multilayerSymbol: MultilayerSymbol,
geometry: Geometry,
offset: Double
) {
// define a vector element and create a new multilayer point symbol from it
val vectorMarkerSymbolElement = VectorMarkerSymbolElement(geometry, multilayerSymbol)
val vectorMarkerSymbolLayer = VectorMarkerSymbolLayer(listOf(vectorMarkerSymbolElement))
val multilayerPointSymbol = MultilayerPointSymbol(listOf(vectorMarkerSymbolLayer))
// create point graphic using the symbol and add it to the graphics overlay
val graphic =
Graphic(Point(-150.0, 20 - offset, SpatialReferences.getWgs84()), multilayerPointSymbol)
graphicsOverlay?.graphics?.add(graphic)
}
/**
* Adds new graphics constructed from multilayer polyline symbols.
*
* The pattern of [dashSpacing] dots/dashes used by the line and
* [offset] the value used to keep a consistent distance between symbols in the same column.
*/
private fun addLineGraphicsWithMarkerSymbols(dashSpacing: List<Double>, offset: Double) {
// create a dash effect from the provided values
val dashGeometricEffect = DashGeometricEffect(dashSpacing)
// create stroke used by line symbols
val solidStrokeSymbolLayer = SolidStrokeSymbolLayer(
3.0,
Color.RED,
listOf(dashGeometricEffect)
).apply {
capStyle = StrokeSymbolLayer.CapStyle.ROUND
}
// create a polyline for the multilayer polyline symbol
val polylineBuilder = PolylineBuilder(SpatialReferences.getWgs84()).apply {
addPoint(Point(-30.0, 20 - offset))
addPoint(Point(30.0, 20 - offset))
}
// create a multilayer polyline symbol from the solidStrokeSymbolLayer
val multilayerPolylineSymbol = MultilayerPolylineSymbol(listOf(solidStrokeSymbolLayer))
// create a polyline graphic with geometry using the symbol created above, and add it to the graphics overlay
graphicsOverlay?.graphics?.add(
Graphic(
polylineBuilder.toGeometry(),
multilayerPolylineSymbol
)
)
}
/**
* Adds new graphics constructed from multilayer polygon symbols.
*
* A list containing the [angles] at which to draw fill lines within the polygon and
* [offset] the value used to keep a consistent distance between symbols in the same column.
*/
private fun addPolygonGraphicsWithMarkerSymbols(angles: List<Double>, offset: Double) {
val polygonBuilder = PolygonBuilder(SpatialReferences.getWgs84()).apply {
addPoint(Point(60.0, 25 - offset))
addPoint(Point(70.0, 25 - offset))
addPoint(Point(70.0, 20 - offset))
addPoint(Point(60.0, 20 - offset))
}
// create a stroke symbol layer to be used by patterns
val strokeForHatches =
SolidStrokeSymbolLayer(2.0, Color.RED, listOf(DashGeometricEffect()))
// create a stroke symbol layer to be used as an outline for aforementioned patterns
val strokeForOutline =
SolidStrokeSymbolLayer(1.0, Color.BLACK, listOf(DashGeometricEffect()))
// create an array to hold all necessary symbol layers - at least one for patterns and one for an outline at the end
val symbolLayerArray = arrayOfNulls<SymbolLayer>(angles.size + 1)
// for each angle, create a symbol layer using the pattern stroke, with hatched lines at the given angle
for (i in angles.indices) {
val hatchFillSymbolLayer = HatchFillSymbolLayer(
MultilayerPolylineSymbol(listOf(strokeForHatches)),
angles[i]
)
// define separation distance for lines and add them to the symbol layer array
hatchFillSymbolLayer.separation = 9.0
symbolLayerArray[i] = hatchFillSymbolLayer
}
// assign the outline layer to the last element of the symbol layer array
symbolLayerArray[symbolLayerArray.size - 1] = strokeForOutline
// create a multilayer polygon symbol from the symbol layer array
val multilayerPolygonSymbol = MultilayerPolygonSymbol(listOf(*symbolLayerArray))
// create a polygon graphic with geometry using the symbol created above, and add it to the graphics overlay
val graphic = Graphic(polygonBuilder.toGeometry(), multilayerPolygonSymbol)
graphicsOverlay?.graphics?.add(graphic)
}
/**
* Creates a complex point from multiple symbol layers and a provided geometry.
* @param complexPointGeometry a base geometry upon which other symbol layers are drawn.
*/
private fun addComplexPoint(complexPointGeometry: Geometry) {
// create marker layers for complex point
val orangeSquareVectorMarkerLayer: VectorMarkerSymbolLayer =
getLayerForComplexPoint(Color.CYAN, Color.BLUE, 11.0)
val blackSquareVectorMarkerLayer: VectorMarkerSymbolLayer =
getLayerForComplexPoint(Color.BLACK, Color.CYAN, 6.0)
val purpleSquareVectorMarkerLayer: VectorMarkerSymbolLayer =
getLayerForComplexPoint(Color.TRANSPARENT, Color.MAGENTA, 14.0)
// set anchors for marker layers
orangeSquareVectorMarkerLayer.anchor =
SymbolAnchor(-4.0, -6.0, SymbolAnchor.PlacementMode.ABSOLUTE)
blackSquareVectorMarkerLayer.anchor =
SymbolAnchor(2.0, 1.0, SymbolAnchor.PlacementMode.ABSOLUTE)
purpleSquareVectorMarkerLayer.anchor =
SymbolAnchor(4.0, 2.0, SymbolAnchor.PlacementMode.ABSOLUTE)
// create a yellow hexagon with a black outline
val yellowFillLayer = SolidFillSymbolLayer(Color.YELLOW)
val blackOutline =
SolidStrokeSymbolLayer(2.0, Color.BLACK, listOf(DashGeometricEffect()))
val hexagonVectorElement = VectorMarkerSymbolElement(
complexPointGeometry,
MultilayerPolylineSymbol(listOf(yellowFillLayer, blackOutline))
)
val hexagonVectorMarkerLayer = VectorMarkerSymbolLayer(listOf(hexagonVectorElement)).apply {
size = 35.0
}
// create the multilayer point symbol
val multilayerPointSymbol = MultilayerPointSymbol(
listOf(
hexagonVectorMarkerLayer,
orangeSquareVectorMarkerLayer,
blackSquareVectorMarkerLayer,
purpleSquareVectorMarkerLayer
)
)
// create the multilayer point graphic using the symbols created above
val complexPointGraphic =
Graphic(Point(130.0, 20.0, SpatialReferences.getWgs84()), multilayerPointSymbol)
graphicsOverlay?.graphics?.add(complexPointGraphic)
}
/**
* Creates a symbol layer for use in the composition of a complex point.
* [fillColor] of the symbol
* [outlineColor] of the symbol
* [size] of the symbol
* @return the vector marker symbol layer.
*/
private fun getLayerForComplexPoint(
fillColor: Int,
outlineColor: Int,
size: Double
): VectorMarkerSymbolLayer {
// create the fill layer and outline
val fillLayer = SolidFillSymbolLayer(fillColor)
val outline = SolidStrokeSymbolLayer(
2.0,
outlineColor,
listOf(DashGeometricEffect())
)
// create a geometry from an envelope
val geometry = Envelope(
Point(-0.5, -0.5, SpatialReferences.getWgs84()),
Point(0.5, 0.5, SpatialReferences.getWgs84())
)
//create a symbol element using the geometry, fill layer, and outline
val vectorMarkerSymbolElement = VectorMarkerSymbolElement(
geometry,
MultilayerPolygonSymbol(listOf(fillLayer, outline))
)
// create a symbol layer containing just the above symbol element, set its size, and return it
val vectorMarkerSymbolLayer =
VectorMarkerSymbolLayer(listOf(vectorMarkerSymbolElement)).apply {
this.size = size
}
return vectorMarkerSymbolLayer
}
/**
* Adds a complex polygon generated with multiple symbol layers.
*/
private fun addComplexPolygon() {
// create the multilayer polygon symbol
val multilayerPolygonSymbol = MultilayerPolygonSymbol(getLayersForComplexPolys(true))
// create the polygon
val polygonBuilder = PolygonBuilder(SpatialReferences.getWgs84()).apply {
addPoint(Point(120.0, 0.0))
addPoint(Point(140.0, 0.0))
addPoint(Point(140.0, -10.0))
addPoint(Point(120.0, -10.0))
}
// create a multilayer polygon graphic with geometry using the symbols
// created above and add it to the graphics overlay
graphicsOverlay?.graphics?.add(
Graphic(
polygonBuilder.toGeometry(),
multilayerPolygonSymbol
)
)
}
/**
* Adds a complex polyline generated with multiple symbol layers.
*/
private fun addComplexPolyline() {
// create the multilayer polyline symbol
val multilayerPolylineSymbol = MultilayerPolylineSymbol(getLayersForComplexPolys(false))
val polylineBuilder = PolylineBuilder(SpatialReferences.getWgs84()).apply {
addPoint(Point(120.0, -25.0))
addPoint(Point(140.0, -25.0))
}
// create the multilayer polyline graphic with geometry using the symbols created above and add it to the graphics overlay
graphicsOverlay?.graphics?.add(
Graphic(
polylineBuilder.toGeometry(),
multilayerPolylineSymbol
)
)
}
/**
* Generates and returns the symbol layers used by the addComplexPolygon and addComplexPolyline methods.
* [includeRedFill] indicates whether to include the red fill needed by the complex polygon.
* @return a list of symbol layers including the necessary effects.
*/
private fun getLayersForComplexPolys(includeRedFill: Boolean): List<SymbolLayer> {
// create a black dash effect
val blackDashes = SolidStrokeSymbolLayer(
1.0,
Color.BLACK,
listOf(DashGeometricEffect(listOf(5.0, 3.0)))
).apply {
capStyle = StrokeSymbolLayer.CapStyle.SQUARE
}
// create a black outline
val blackOutline =
SolidStrokeSymbolLayer(
7.0,
Color.BLACK,
listOf(DashGeometricEffect())
).apply {
capStyle = StrokeSymbolLayer.CapStyle.ROUND
}
// create a yellow stroke inside
val yellowStroke = SolidStrokeSymbolLayer(
5.0,
Color.YELLOW,
listOf(DashGeometricEffect())
).apply {
capStyle = StrokeSymbolLayer.CapStyle.ROUND
}
return if (includeRedFill) {
// create a red filling for the polygon
val redFillLayer = SolidFillSymbolLayer(Color.RED)
listOf(redFillLayer, blackOutline, yellowStroke, blackDashes)
} else {
listOf(blackOutline, yellowStroke, blackDashes)
}
}
private fun showError(message: String) {
Toast.makeText(this@MainActivity, message, Toast.LENGTH_SHORT).show()
Log.e(TAG, message)
}
override fun onPause() {
mapView.pause()
super.onPause()
}
override fun onResume() {
super.onResume()
mapView.resume()
}
override fun onDestroy() {
mapView.dispose()
super.onDestroy()
}
}
| apache-2.0 | bcf59a66b96dba452f68b648b476ecd8 | 40.168026 | 153 | 0.651252 | 4.744501 | false | false | false | false |
gradle/gradle | subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/ProjectExtensions.kt | 2 | 8639 | /*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.kotlin.dsl
import org.gradle.api.NamedDomainObjectContainer
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.artifacts.Dependency
import org.gradle.api.artifacts.dsl.RepositoryHandler
import org.gradle.api.initialization.dsl.ScriptHandler
import org.gradle.api.internal.artifacts.dependencies.DefaultSelfResolvingDependency
import org.gradle.api.internal.artifacts.dsl.dependencies.DependencyFactoryInternal
import org.gradle.api.internal.file.FileCollectionInternal
import org.gradle.api.plugins.Convention
import org.gradle.api.plugins.PluginAware
import org.gradle.api.tasks.TaskContainer
import org.gradle.internal.component.local.model.OpaqueComponentIdentifier
import org.gradle.kotlin.dsl.provider.fileCollectionOf
import org.gradle.kotlin.dsl.provider.gradleKotlinDslOf
import org.gradle.kotlin.dsl.support.configureWith
import org.gradle.kotlin.dsl.support.invalidPluginsCall
import org.gradle.plugin.use.PluginDependenciesSpec
import kotlin.reflect.KClass
import kotlin.reflect.KProperty
/**
* Configures the build script classpath for this project.
*/
fun Project.buildscript(action: ScriptHandlerScope.() -> Unit): Unit =
project.buildscript.configureWith(action)
/**
* Sets the default tasks of this project. These are used when no tasks names are provided when
* starting the build.
*/
@Suppress("nothing_to_inline")
inline fun Project.defaultTasks(vararg tasks: Task) {
defaultTasks(*tasks.map { it.name }.toTypedArray())
}
/**
* Applies the plugin of the given type [T]. Does nothing if the plugin has already been applied.
*
* The given class should implement the [Plugin] interface, and be parameterized for a
* compatible type of `this`.
*
* @param T the plugin type.
* @see [PluginAware.apply]
*/
inline fun <reified T : Plugin<Project>> Project.apply() =
(this as PluginAware).apply<T>()
/**
* Executes the given configuration block against the [plugin convention]
* [Convention.getPlugin] or extension of the specified type.
*
* Note, that the concept of conventions is deprecated and scheduled for
* removal in Gradle 8.
*
* @param T the plugin convention type.
* @param configuration the configuration block.
* @see [Convention.getPlugin]
*/
inline fun <reified T : Any> Project.configure(noinline configuration: T.() -> Unit): Unit =
@Suppress("deprecation")
typeOf<T>().let { type ->
convention.findByType(type)?.let(configuration)
?: convention.findPlugin<T>()?.let(configuration)
?: convention.configure(type, configuration)
}
/**
* Returns the plugin convention or extension of the specified type.
*
* Note, that the concept of conventions is deprecated and scheduled for
* removal in Gradle 8.
*/
inline fun <reified T : Any> Project.the(): T =
@Suppress("deprecation")
typeOf<T>().let { type ->
convention.findByType(type)
?: convention.findPlugin(T::class.java)
?: convention.getByType(type)
}
/**
* Returns the plugin convention or extension of the specified type.
*
* Note, that the concept of conventions is deprecated and scheduled for
* removal in Gradle 8.
*/
fun <T : Any> Project.the(extensionType: KClass<T>): T =
@Suppress("deprecation") convention.findByType(extensionType.java)
?: @Suppress("deprecation") convention.findPlugin(extensionType.java)
?: @Suppress("deprecation") convention.getByType(extensionType.java)
/**
* Creates a [Task] with the given [name] and [type], configures it with the given [configuration] action,
* and adds it to this project tasks container.
*/
inline fun <reified type : Task> Project.task(name: String, noinline configuration: type.() -> Unit) =
task(name, type::class, configuration)
/**
* Creates a [Task] with the given [name] and [type], and adds it to this project tasks container.
*
* @see [Project.getTasks]
* @see [TaskContainer.create]
*/
@Suppress("extension_shadowed_by_member")
inline fun <reified type : Task> Project.task(name: String) =
tasks.create(name, type::class.java)
fun <T : Task> Project.task(name: String, type: KClass<T>, configuration: T.() -> Unit) =
tasks.create(name, type.java, configuration)
/**
* Configures the repositories for this project.
*
* Executes the given configuration block against the [RepositoryHandler] for this
* project.
*
* @param configuration the configuration block.
*/
fun Project.repositories(configuration: RepositoryHandler.() -> Unit) =
repositories.configuration()
/**
* Configures the repositories for the script dependencies.
*/
fun ScriptHandler.repositories(configuration: RepositoryHandler.() -> Unit) =
repositories.configuration()
/**
* Configures the dependencies for this project.
*
* Executes the given configuration block against the [DependencyHandlerScope] for this
* project.
*
* @param configuration the configuration block.
*/
fun Project.dependencies(configuration: DependencyHandlerScope.() -> Unit) =
DependencyHandlerScope.of(dependencies).configuration()
/**
* Configures the artifacts for this project.
*
* Executes the given configuration block against the [ArtifactHandlerScope] for this
* project.
*
* @param configuration the configuration block.
*/
fun Project.artifacts(configuration: ArtifactHandlerScope.() -> Unit) =
ArtifactHandlerScope.of(artifacts).configuration()
/**
* Locates a property on [Project].
*/
operator fun Project.provideDelegate(any: Any?, property: KProperty<*>): PropertyDelegate =
propertyDelegateFor(this, property)
/**
* Creates a container for managing named objects of the specified type.
*
* The specified type must have a public constructor which takes the name as a [String] parameter.
*
* All objects **MUST** expose their name as a bean property named `name`.
* The name must be constant for the life of the object.
*
* @param T The type of objects for the container to contain.
* @return The container.
*
* @see [Project.container]
*/
inline fun <reified T> Project.container(): NamedDomainObjectContainer<T> =
container(T::class.java)
/**
* Creates a container for managing named objects of the specified type.
*
* The given factory is used to create object instances.
*
* All objects **MUST** expose their name as a bean property named `name`.
* The name must be constant for the life of the object.
*
* @param T The type of objects for the container to contain.
* @param factory The factory to use to create object instances.
* @return The container.
*
* @see [Project.container]
*/
inline fun <reified T : Any> Project.container(noinline factory: (String) -> T): NamedDomainObjectContainer<T> =
container(T::class.java, factory)
/**
* Creates a dependency on the API of the current version of the Gradle Kotlin DSL.
*
* Includes the Kotlin and Gradle APIs.
*
* @return The dependency.
*/
fun Project.gradleKotlinDsl(): Dependency =
DefaultSelfResolvingDependency(
OpaqueComponentIdentifier(DependencyFactoryInternal.ClassPathNotation.GRADLE_KOTLIN_DSL),
project.fileCollectionOf(
gradleKotlinDslOf(project),
"gradleKotlinDsl"
) as FileCollectionInternal
)
/**
* Nested `plugins` blocks are **NOT** allowed, for example:
* ```
* project(":core") {
* plugins { java }
* }
* ```
* If you need to apply a plugin imperatively, please use apply<PluginType>() or apply(plugin = "id") instead.
* ```
* project(":core") {
* apply(plugin = "java")
* }
* ```
* @since 6.0
*/
@Suppress("unused", "DeprecatedCallableAddReplaceWith")
@Deprecated(
"The plugins {} block must not be used here. " + "If you need to apply a plugin imperatively, please use apply<PluginType>() or apply(plugin = \"id\") instead.",
level = DeprecationLevel.ERROR
)
fun Project.plugins(@Suppress("unused_parameter") block: PluginDependenciesSpec.() -> Unit): Nothing =
invalidPluginsCall()
| apache-2.0 | 0fc2764aebb2285911dd2df4d2c0cf7e | 30.644689 | 165 | 0.726473 | 4.143405 | false | true | false | false |
gradle/gradle | build-logic/binary-compatibility/src/test/kotlin/gradlebuild/binarycompatibility/SortAcceptedApiChangesTaskIntegrationTest.kt | 2 | 7629 | /*
* Copyright 2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package gradlebuild.binarycompatibility
import com.google.gson.Gson
import org.gradle.testkit.runner.TaskOutcome
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
class SortAcceptedApiChangesTaskIntegrationTest : AbstractAcceptedApiChangesMaintenanceTaskIntegrationTest() {
@Test
fun `verify misordered changes can be sorted`() {
//language=JSON
acceptedApiChangesFile.writeText(
"""
{
"acceptedApiChanges": [
{
"type": "org.gradle.api.file.SourceDirectorySet",
"member": "Method org.gradle.api.file.SourceDirectorySet.getOutputDir()",
"acceptation": "Deprecated method removed",
"changes": [
"Method has been removed"
]
},
{
"type": "org.gradle.api.tasks.AbstractExecTask",
"member": "Method org.gradle.api.tasks.AbstractExecTask.getExecResult()",
"acceptation": "Removed for Gradle 8.0",
"changes": [
"Method has been removed"
]
},
{
"type": "org.gradle.api.tasks.testing.AbstractTestTask",
"member": "Method org.gradle.api.tasks.testing.AbstractTestTask.getBinResultsDir()",
"acceptation": "Deprecated method removed",
"changes": [
"Method has been removed"
]
},
{
"type": "org.gradle.api.AntBuilder",
"member": "Class org.gradle.api.AntBuilder",
"acceptation": "org.gradle.api.AntBuilder now extends groovy.ant.AntBuilder",
"changes": [
"Abstract method has been added in implemented interface"
]
},
{
"type": "org.gradle.api.file.SourceDirectorySet",
"member": "Method org.gradle.api.file.SourceDirectorySet.setOutputDir(org.gradle.api.provider.Provider)",
"acceptation": "Deprecated method removed",
"changes": [
"Method has been removed"
]
},
{
"type": "org.gradle.api.file.SourceDirectorySet",
"member": "Method org.gradle.api.file.SourceDirectorySet.setOutputDir(java.io.File)",
"acceptation": "Deprecated method removed",
"changes": [
"Method has been removed"
]
}
]
}
""".trimIndent()
)
val initialVerifyResult = run(":verifyAcceptedApiChangesOrdering").buildAndFail()
Assertions.assertEquals(TaskOutcome.FAILED, initialVerifyResult.task(":verifyAcceptedApiChangesOrdering")!!.outcome)
val sortingResult = run(":sortAcceptedApiChanges").build()
Assertions.assertEquals(TaskOutcome.SUCCESS, sortingResult.task(":sortAcceptedApiChanges")!!.outcome)
val finalVerifyResult = run(":verifyAcceptedApiChangesOrdering").build()
Assertions.assertEquals(TaskOutcome.SUCCESS, finalVerifyResult.task(":verifyAcceptedApiChangesOrdering")!!.outcome)
val expectedJson = loadChangesJson(
"""
{
"acceptedApiChanges": [
{
"type": "org.gradle.api.AntBuilder",
"member": "Class org.gradle.api.AntBuilder",
"acceptation": "org.gradle.api.AntBuilder now extends groovy.ant.AntBuilder",
"changes": [
"Abstract method has been added in implemented interface"
]
},
{
"type": "org.gradle.api.file.SourceDirectorySet",
"member": "Method org.gradle.api.file.SourceDirectorySet.getOutputDir()",
"acceptation": "Deprecated method removed",
"changes": [
"Method has been removed"
]
},
{
"type": "org.gradle.api.file.SourceDirectorySet",
"member": "Method org.gradle.api.file.SourceDirectorySet.setOutputDir(java.io.File)",
"acceptation": "Deprecated method removed",
"changes": [
"Method has been removed"
]
},
{
"type": "org.gradle.api.file.SourceDirectorySet",
"member": "Method org.gradle.api.file.SourceDirectorySet.setOutputDir(org.gradle.api.provider.Provider)",
"acceptation": "Deprecated method removed",
"changes": [
"Method has been removed"
]
},
{
"type": "org.gradle.api.tasks.AbstractExecTask",
"member": "Method org.gradle.api.tasks.AbstractExecTask.getExecResult()",
"acceptation": "Removed for Gradle 8.0",
"changes": [
"Method has been removed"
]
},
{
"type": "org.gradle.api.tasks.testing.AbstractTestTask",
"member": "Method org.gradle.api.tasks.testing.AbstractTestTask.getBinResultsDir()",
"acceptation": "Deprecated method removed",
"changes": [
"Method has been removed"
]
}
]
}
""")
val actualJson = loadChangesJson(acceptedApiChangesFile.readText())
Assertions.assertEquals(expectedJson, actualJson)
}
private
fun loadChangesJson(rawText: String) = Gson().fromJson(rawText, AbstractAcceptedApiChangesMaintenanceTask.AcceptedApiChanges::class.java)
}
| apache-2.0 | 007b947a73c22f96cd45b739cadcb29c | 47.592357 | 141 | 0.469917 | 5.955504 | false | true | false | false |
xwiki-contrib/android-authenticator | app/src/main/java/org/xwiki/android/sync/activities/SettingServerIpViewFlipper.kt | 1 | 2805 | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.android.sync.activities
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.EditText
import org.xwiki.android.sync.R
import org.xwiki.android.sync.auth.AuthenticatorActivity
import java.net.MalformedURLException
import java.net.URL
/**
* Flipper for setting XWiki server address.
*
* @version $Id: 1764429bc21ab6d1aaa331ae01d81ac5b9afd1f2 $
*/
/**
* Standard constructor.
*
* @param activity Actual [AuthenticatorActivity]
* @param contentRootView Root [View] of that flipper (not activity)
*/
class SettingServerIpViewFlipper(activity: AuthenticatorActivity, contentRootView: View)
: BaseViewFlipper(activity, contentRootView) {
/**
* Check typed server address and call sign in if all is ok.
*/
override fun doNext() = checkInput() ?.also {
mActivity.serverUrl = it
} != null
/**
* Do nothing (Setting server IP is first operation of adding account.
*/
override fun doPrevious() {}
/**
* @return Valid server address or null
*/
private fun checkInput(): String? {
val serverEditText = findViewById<EditText>(R.id.accountServer)
serverEditText.error = null
val serverAddress = serverEditText.text.toString()
return if (TextUtils.isEmpty(serverAddress)) {
serverEditText.error = mContext.getString(R.string.error_field_required)
serverEditText.requestFocus()
null
} else {
try {
URL(serverAddress)
serverAddress
} catch (e: MalformedURLException) {
Log.e(SettingServerIpViewFlipper::class.java.simpleName, "Wrong url", e)
serverEditText.error = mContext.getString(R.string.error_invalid_server)
serverEditText.requestFocus()
null
}
}
}
}
| lgpl-2.1 | fd343319a621238708226d7fd8306779 | 33.207317 | 88 | 0.687701 | 4.375975 | false | false | false | false |
hwki/SimpleBitcoinWidget | bitcoin/src/main/java/com/brentpanther/bitcoinwidget/ui/theme/Theme.kt | 1 | 1316 | package com.brentpanther.bitcoinwidget.ui.theme
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material.MaterialTheme
import androidx.compose.material.darkColors
import androidx.compose.material.lightColors
import androidx.compose.material.ripple.RippleAlpha
import androidx.compose.material.ripple.RippleTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
private val DarkColorPalette = darkColors(
primary = Color(0xff3a554e),
secondary = Color(0xff843d19),
secondaryVariant = Color(0xffba5624),
primaryVariant = Color(0xff253638)
)
private val LightColorPalette = lightColors(
primary = Color(0xff52796f),
secondary = Color(0xffba5624),
secondaryVariant = Color(0xffba5624),
primaryVariant = Color(0xff354f52),
)
class HighlightRippleTheme : RippleTheme {
@Composable
override fun defaultColor() = Highlight
@Composable
override fun rippleAlpha() = RippleAlpha(0.8f,0.8f,0.8f,0.8f)
}
@Composable
fun SimpleBitcoinWidgetTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit) {
val colors = if (darkTheme) {
DarkColorPalette
} else {
LightColorPalette
}
MaterialTheme(
colors = colors,
content = content
)
} | mit | 4534454e90facafce8270b384505e26e | 26.4375 | 107 | 0.75 | 4.099688 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.