repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ingokegel/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/OoChildWithPidEntityImpl.kt | 1 | 9505 | package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.PersistentEntityId
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToOneParent
import com.intellij.workspaceModel.storage.impl.updateOneToOneParentOfChild
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class OoChildWithPidEntityImpl : OoChildWithPidEntity, WorkspaceEntityBase() {
companion object {
internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(OoParentWithoutPidEntity::class.java,
OoChildWithPidEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_ONE, false)
val connections = listOf<ConnectionId>(
PARENTENTITY_CONNECTION_ID,
)
}
@JvmField
var _childProperty: String? = null
override val childProperty: String
get() = _childProperty!!
override val parentEntity: OoParentWithoutPidEntity
get() = snapshot.extractOneToOneParent(PARENTENTITY_CONNECTION_ID, this)!!
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: OoChildWithPidEntityData?) : ModifiableWorkspaceEntityBase<OoChildWithPidEntity>(), OoChildWithPidEntity.Builder {
constructor() : this(OoChildWithPidEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity OoChildWithPidEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isChildPropertyInitialized()) {
error("Field OoChildWithPidEntity#childProperty should be initialized")
}
if (_diff != null) {
if (_diff.extractOneToOneParent<WorkspaceEntityBase>(PARENTENTITY_CONNECTION_ID, this) == null) {
error("Field OoChildWithPidEntity#parentEntity should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] == null) {
error("Field OoChildWithPidEntity#parentEntity should be initialized")
}
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as OoChildWithPidEntity
this.entitySource = dataSource.entitySource
this.childProperty = dataSource.childProperty
if (parents != null) {
this.parentEntity = parents.filterIsInstance<OoParentWithoutPidEntity>().single()
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var childProperty: String
get() = getEntityData().childProperty
set(value) {
checkModificationAllowed()
getEntityData().childProperty = value
changedProperty.add("childProperty")
}
override var parentEntity: OoParentWithoutPidEntity
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToOneParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false,
PARENTENTITY_CONNECTION_ID)]!! as OoParentWithoutPidEntity
}
else {
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as OoParentWithoutPidEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToOneParentOfChild(PARENTENTITY_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value
}
changedProperty.add("parentEntity")
}
override fun getEntityData(): OoChildWithPidEntityData = result ?: super.getEntityData() as OoChildWithPidEntityData
override fun getEntityClass(): Class<OoChildWithPidEntity> = OoChildWithPidEntity::class.java
}
}
class OoChildWithPidEntityData : WorkspaceEntityData.WithCalculablePersistentId<OoChildWithPidEntity>() {
lateinit var childProperty: String
fun isChildPropertyInitialized(): Boolean = ::childProperty.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<OoChildWithPidEntity> {
val modifiable = OoChildWithPidEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): OoChildWithPidEntity {
val entity = OoChildWithPidEntityImpl()
entity._childProperty = childProperty
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun persistentId(): PersistentEntityId<*> {
return OoChildEntityId(childProperty)
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return OoChildWithPidEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return OoChildWithPidEntity(childProperty, entitySource) {
this.parentEntity = parents.filterIsInstance<OoParentWithoutPidEntity>().single()
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
res.add(OoParentWithoutPidEntity::class.java)
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as OoChildWithPidEntityData
if (this.entitySource != other.entitySource) return false
if (this.childProperty != other.childProperty) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as OoChildWithPidEntityData
if (this.childProperty != other.childProperty) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + childProperty.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + childProperty.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| apache-2.0 | f42e2bafa2047829b99573273edf9fed | 36.128906 | 161 | 0.70626 | 5.425228 | false | false | false | false |
ingokegel/intellij-community | python/python-psi-impl/src/com/jetbrains/python/codeInsight/typing/PyTypingInspectionExtension.kt | 7 | 3061 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.codeInsight.typing
import com.intellij.psi.PsiReference
import com.jetbrains.python.PyNames
import com.jetbrains.python.inspections.PyInspectionExtension
import com.jetbrains.python.psi.PyElement
import com.jetbrains.python.psi.PyReferenceExpression
import com.jetbrains.python.psi.PySubscriptionExpression
import com.jetbrains.python.psi.PyTargetExpression
import com.jetbrains.python.psi.impl.PyBuiltinCache
import com.jetbrains.python.psi.impl.references.PyOperatorReference
import com.jetbrains.python.psi.resolve.PyResolveContext
import com.jetbrains.python.psi.types.PyClassLikeType
import com.jetbrains.python.psi.types.PyClassType
import com.jetbrains.python.psi.types.TypeEvalContext
class PyTypingInspectionExtension : PyInspectionExtension() {
override fun ignoreUnresolvedReference(node: PyElement, reference: PsiReference, context: TypeEvalContext): Boolean {
if (node is PySubscriptionExpression && reference is PyOperatorReference && node.referencedName == PyNames.GETITEM) {
val operand = node.operand
val type = context.getType(operand)
if (type is PyClassLikeType && type.isDefinition && isGenericItselfOrDescendant(type, context)) {
// `true` is not returned for the cases like `typing.List[int]`
// because these types contain builtins as a class
if (!isBuiltin(type)) return true
// here is the check that current element is like `typing.List[int]`
// but be careful: builtin collections inherit `typing.Generic` in typeshed
if (operand is PyReferenceExpression) {
val resolveContext = PyResolveContext.defaultContext(context)
val resolveResults = operand.getReference(resolveContext).multiResolve(false)
if (resolveResults
.asSequence()
.map { it.element }
.any { it is PyTargetExpression && PyTypingTypeProvider.BUILTIN_COLLECTION_CLASSES.containsKey(it.qualifiedName) }) {
return true
}
}
}
}
return false
}
private fun isGenericItselfOrDescendant(type: PyClassLikeType, context: TypeEvalContext): Boolean {
return PyTypingTypeProvider.GENERIC_CLASSES.contains(type.classQName) || PyTypingTypeProvider.isGeneric(type, context)
}
private fun isBuiltin(type: PyClassLikeType): Boolean {
return if (type is PyClassType) PyBuiltinCache.getInstance(type.pyClass).isBuiltin(type.pyClass) else false
}
}
| apache-2.0 | 9449e12bf8331b2843cfa9f777068ee5 | 42.112676 | 129 | 0.751388 | 4.673282 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/jvm-debugger/evaluation/src/org/jetbrains/kotlin/idea/debugger/evaluate/variables/VariableFinder.kt | 1 | 21349 | // 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.evaluate.variables
import com.intellij.debugger.engine.JavaValue
import com.intellij.debugger.engine.evaluation.EvaluationContextImpl
import com.intellij.debugger.jdi.LocalVariableProxyImpl
import com.intellij.debugger.jdi.StackFrameProxyImpl
import com.sun.jdi.*
import org.jetbrains.kotlin.codegen.AsmUtil
import org.jetbrains.kotlin.codegen.AsmUtil.getCapturedFieldName
import org.jetbrains.kotlin.codegen.AsmUtil.getLabeledThisName
import org.jetbrains.kotlin.codegen.coroutines.CONTINUATION_VARIABLE_NAME
import org.jetbrains.kotlin.codegen.coroutines.SUSPEND_FUNCTION_COMPLETION_PARAMETER_NAME
import org.jetbrains.kotlin.codegen.inline.INLINE_FUN_VAR_SUFFIX
import org.jetbrains.kotlin.codegen.inline.INLINE_TRANSFORMATION_SUFFIX
import org.jetbrains.kotlin.idea.debugger.*
import org.jetbrains.kotlin.idea.debugger.base.util.*
import org.jetbrains.kotlin.idea.debugger.coroutine.proxy.CoroutineStackFrameProxyImpl
import org.jetbrains.kotlin.idea.debugger.evaluate.ExecutionContext
import org.jetbrains.kotlin.idea.debugger.evaluate.compilation.CodeFragmentParameter
import org.jetbrains.kotlin.idea.debugger.evaluate.compilation.CodeFragmentParameter.Kind
import org.jetbrains.kotlin.idea.debugger.evaluate.compilation.DebugLabelPropertyDescriptorProvider
import org.jetbrains.kotlin.idea.debugger.stackFrame.InlineStackFrameProxyImpl
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import kotlin.coroutines.Continuation
import com.sun.jdi.Type as JdiType
import org.jetbrains.org.objectweb.asm.Type as AsmType
class VariableFinder(val context: ExecutionContext) {
private val frameProxy = context.frameProxy
companion object {
private val USE_UNSAFE_FALLBACK: Boolean
get() = true
private fun getCapturedVariableNameRegex(capturedName: String): Regex {
val escapedName = Regex.escape(capturedName)
val escapedSuffix = Regex.escape(INLINE_TRANSFORMATION_SUFFIX)
return Regex("^$escapedName(?:$escapedSuffix)?$")
}
}
val evaluatorValueConverter = EvaluatorValueConverter(context)
val refWrappers: List<RefWrapper>
get() = mutableRefWrappers
private val mutableRefWrappers = mutableListOf<RefWrapper>()
class RefWrapper(val localVariableName: String, val wrapper: Value?)
sealed class VariableKind(val asmType: AsmType) {
abstract fun capturedNameMatches(name: String): Boolean
class Ordinary(val name: String, asmType: AsmType, val isDelegated: Boolean) : VariableKind(asmType) {
private val capturedNameRegex = getCapturedVariableNameRegex(getCapturedFieldName(this.name))
override fun capturedNameMatches(name: String) = capturedNameRegex.matches(name)
}
// TODO Support overloaded local functions
class LocalFunction(val name: String, asmType: AsmType) : VariableKind(asmType) {
@Suppress("ConvertToStringTemplate")
override fun capturedNameMatches(name: String) = name == "$" + name
}
class UnlabeledThis(asmType: AsmType) : VariableKind(asmType) {
override fun capturedNameMatches(name: String) =
(name == AsmUtil.CAPTURED_RECEIVER_FIELD || name.startsWith(getCapturedFieldName(AsmUtil.LABELED_THIS_FIELD)))
}
class OuterClassThis(asmType: AsmType) : VariableKind(asmType) {
override fun capturedNameMatches(name: String) = false
}
class FieldVar(val fieldName: String, asmType: AsmType) : VariableKind(asmType) {
// Captured 'field' are not supported yet
override fun capturedNameMatches(name: String) = false
}
class ExtensionThis(val label: String, asmType: AsmType) : VariableKind(asmType) {
val parameterName = getLabeledThisName(label, AsmUtil.LABELED_THIS_PARAMETER, AsmUtil.RECEIVER_PARAMETER_NAME)
val fieldName = getLabeledThisName(label, getCapturedFieldName(AsmUtil.LABELED_THIS_FIELD), AsmUtil.CAPTURED_RECEIVER_FIELD)
private val capturedNameRegex = getCapturedVariableNameRegex(fieldName)
override fun capturedNameMatches(name: String) = capturedNameRegex.matches(name)
}
}
class Result(val value: Value?)
private class NamedEntity(val name: String, val lazyType: Lazy<JdiType?>, val lazyValue: Lazy<Value?>) {
val type: JdiType?
get() = lazyType.value
val value: Value?
get() = lazyValue.value
companion object {
fun of(field: Field, owner: ObjectReference): NamedEntity {
val type = lazy(LazyThreadSafetyMode.PUBLICATION) { field.safeType() }
val value = lazy(LazyThreadSafetyMode.PUBLICATION) { owner.getValue(field) }
return NamedEntity(field.name(), type, value)
}
fun of(variable: LocalVariableProxyImpl, frameProxy: StackFrameProxyImpl): NamedEntity {
val type = lazy(LazyThreadSafetyMode.PUBLICATION) { variable.safeType() }
val value = lazy(LazyThreadSafetyMode.PUBLICATION) { frameProxy.getValue(variable) }
return NamedEntity(variable.name(), type, value)
}
fun of(variable: JavaValue, context: EvaluationContextImpl): NamedEntity {
val type = lazy(LazyThreadSafetyMode.PUBLICATION) { variable.descriptor.type }
val value = lazy(LazyThreadSafetyMode.PUBLICATION) { variable.descriptor.safeCalcValue(context) }
return NamedEntity(variable.name, type, value)
}
}
}
fun find(parameter: CodeFragmentParameter, asmType: AsmType): Result? {
return when (parameter.kind) {
Kind.ORDINARY -> findOrdinary(VariableKind.Ordinary(parameter.name, asmType, isDelegated = false))
Kind.DELEGATED -> findOrdinary(VariableKind.Ordinary(parameter.name, asmType, isDelegated = true))
Kind.FAKE_JAVA_OUTER_CLASS -> thisObject()?.let { Result(it) }
Kind.EXTENSION_RECEIVER -> findExtensionThis(VariableKind.ExtensionThis(parameter.name, asmType))
Kind.LOCAL_FUNCTION -> findLocalFunction(VariableKind.LocalFunction(parameter.name, asmType))
Kind.DISPATCH_RECEIVER -> findDispatchThis(VariableKind.OuterClassThis(asmType))
Kind.COROUTINE_CONTEXT -> findCoroutineContext()
Kind.FIELD_VAR -> findFieldVariable(VariableKind.FieldVar(parameter.name, asmType))
Kind.DEBUG_LABEL -> findDebugLabel(parameter.name)
}
}
private fun findOrdinary(kind: VariableKind.Ordinary): Result? {
val variables = frameProxy.safeVisibleVariables()
// Local variables – direct search
findLocalVariable(variables, kind, kind.name)?.let { return it }
// Recursive search in local receiver variables
findCapturedVariableInReceiver(variables, kind)?.let { return it }
// Recursive search in captured this
return findCapturedVariableInContainingThis(kind)
}
private fun findFieldVariable(kind: VariableKind.FieldVar): Result? {
val thisObject = thisObject()
if (thisObject != null) {
val field = thisObject.referenceType().fieldByName(kind.fieldName) ?: return null
return Result(thisObject.getValue(field))
} else {
val containingType = frameProxy.safeLocation()?.declaringType() ?: return null
val field = containingType.fieldByName(kind.fieldName) ?: return null
return Result(containingType.getValue(field))
}
}
private fun findLocalFunction(kind: VariableKind.LocalFunction): Result? {
val variables = frameProxy.safeVisibleVariables()
// Local variables – direct search, new convention
val newConventionName = AsmUtil.LOCAL_FUNCTION_VARIABLE_PREFIX + kind.name
findLocalVariable(variables, kind, newConventionName)?.let { return it }
// Local variables – direct search, old convention (before 1.3.30)
findLocalVariable(variables, kind, kind.name + "$")?.let { return it }
// Recursive search in local receiver variables
findCapturedVariableInReceiver(variables, kind)?.let { return it }
// Recursive search in captured this
return findCapturedVariableInContainingThis(kind)
}
private fun findCapturedVariableInContainingThis(kind: VariableKind): Result? {
if (frameProxy is CoroutineStackFrameProxyImpl && frameProxy.isCoroutineScopeAvailable()) {
findCapturedVariable(kind, frameProxy.thisObject())?.let { return it }
return findCapturedVariable(kind, frameProxy.continuation)
}
val containingThis = thisObject() ?: return null
return findCapturedVariable(kind, containingThis)
}
private fun findExtensionThis(kind: VariableKind.ExtensionThis): Result? {
val variables = frameProxy.safeVisibleVariables()
// Local variables – direct search
val namePredicate = fun(name: String) = name == kind.parameterName || name.startsWith(kind.parameterName + '$')
findLocalVariable(variables, kind, namePredicate)?.let { return it }
// Recursive search in local receiver variables
findCapturedVariableInReceiver(variables, kind)?.let { return it }
// Recursive search in captured this
findCapturedVariableInContainingThis(kind)?.let { return it }
if (USE_UNSAFE_FALLBACK) {
// Find an unlabeled this with the compatible type
findUnlabeledThis(VariableKind.UnlabeledThis(kind.asmType))?.let { return it }
}
return null
}
private fun findDispatchThis(kind: VariableKind.OuterClassThis): Result? {
findCapturedVariableInContainingThis(kind)?.let { return it }
if (isInsideDefaultImpls()) {
val variables = frameProxy.safeVisibleVariables()
findLocalVariable(variables, kind, AsmUtil.THIS_IN_DEFAULT_IMPLS)?.let { return it }
}
val variables = frameProxy.safeVisibleVariables()
val inlineDepth = getInlineDepth(variables)
if (inlineDepth > 0) {
variables.namedEntitySequence()
.filter { it.name.matches(INLINED_THIS_REGEX) && getInlineDepth(it.name) == inlineDepth && kind.typeMatches(it.type) }
.mapNotNull { it.unwrapAndCheck(kind) }
.firstOrNull()
?.let { return it }
}
if (USE_UNSAFE_FALLBACK) {
// Find an unlabeled this with the compatible type
findUnlabeledThis(VariableKind.UnlabeledThis(kind.asmType))?.let { return it }
}
return null
}
private fun findDebugLabel(name: String): Result? {
val markupMap = DebugLabelPropertyDescriptorProvider.getMarkupMap(context.debugProcess)
for ((value, markup) in markupMap) {
if (markup.text == name) {
return Result(value)
}
}
return null
}
private fun findUnlabeledThis(kind: VariableKind.UnlabeledThis): Result? {
val variables = frameProxy.safeVisibleVariables()
// Recursive search in local receiver variables
findCapturedVariableInReceiver(variables, kind)?.let { return it }
return findCapturedVariableInContainingThis(kind)
}
private fun findLocalVariable(variables: List<LocalVariableProxyImpl>, kind: VariableKind, name: String): Result? {
return findLocalVariable(variables, kind) { it == name }
}
private fun findLocalVariable(
variables: List<LocalVariableProxyImpl>,
kind: VariableKind,
namePredicate: (String) -> Boolean
): Result? {
val inlineDepth =
frameProxy.safeAs<InlineStackFrameProxyImpl>()?.inlineDepth
?: getInlineDepth(variables)
findLocalVariable(variables, kind, inlineDepth, namePredicate)?.let { return it }
// Try to find variables outside of inline functions as well
if (inlineDepth > 0 && USE_UNSAFE_FALLBACK) {
findLocalVariable(variables, kind, 0, namePredicate)?.let { return it }
}
return null
}
private fun findLocalVariable(
variables: List<LocalVariableProxyImpl>,
kind: VariableKind,
inlineDepth: Int,
namePredicate: (String) -> Boolean
): Result? {
val actualPredicate: (String) -> Boolean
if (inlineDepth > 0) {
actualPredicate = fun(name: String): Boolean {
var endIndex = name.length
var depth = 0
val suffixLen = INLINE_FUN_VAR_SUFFIX.length
while (endIndex >= suffixLen) {
if (name.substring(endIndex - suffixLen, endIndex) != INLINE_FUN_VAR_SUFFIX) {
break
}
depth++
endIndex -= suffixLen
}
return namePredicate(name.take(endIndex)) && getInlineDepth(name) == inlineDepth
}
} else {
actualPredicate = namePredicate
}
val namedEntities = variables.namedEntitySequence() + getCoroutineStackFrameNamedEntities()
for (item in namedEntities) {
if (!actualPredicate(item.name) || !kind.typeMatches(item.type)) {
continue
}
val rawValue = item.value
val result = evaluatorValueConverter.coerce(getUnwrapDelegate(kind, rawValue), kind.asmType) ?: continue
if (!rawValue.isRefType && result.value.isRefType) {
// Local variable was wrapped into a Ref instance
mutableRefWrappers += RefWrapper(item.name, result.value)
}
return result
}
return null
}
private fun getCoroutineStackFrameNamedEntities() =
if (frameProxy is CoroutineStackFrameProxyImpl) {
frameProxy.spilledVariables.namedEntitySequence(context.evaluationContext)
} else {
emptySequence()
}
private fun isInsideDefaultImpls(): Boolean {
val declaringType = frameProxy.safeLocation()?.declaringType() ?: return false
return declaringType.name().endsWith(JvmAbi.DEFAULT_IMPLS_SUFFIX)
}
private fun findCoroutineContext(): Result? {
val method = frameProxy.safeLocation()?.safeMethod() ?: return null
val result = findCoroutineContextForLambda(method) ?: findCoroutineContextForMethod(method) ?: return null
return Result(result)
}
private fun findCoroutineContextForLambda(method: Method): ObjectReference? {
if (method.name() != "invokeSuspend" || method.signature() != "(Ljava/lang/Object;)Ljava/lang/Object;" ||
frameProxy !is CoroutineStackFrameProxyImpl) {
return null
}
val continuation = frameProxy.continuation ?: return null
val continuationType = continuation.referenceType()
if (SUSPEND_LAMBDA_CLASSES.none { continuationType.isSubtype(it) }) {
return null
}
return findCoroutineContextForContinuation(continuation)
}
private fun findCoroutineContextForMethod(method: Method): ObjectReference? {
if (CONTINUATION_TYPE.descriptor + ")" !in method.signature()) {
return null
}
val continuationVariable = frameProxy.safeVisibleVariableByName(CONTINUATION_VARIABLE_NAME)
?: frameProxy.safeVisibleVariableByName(SUSPEND_FUNCTION_COMPLETION_PARAMETER_NAME)
?: return null
val continuation = frameProxy.getValue(continuationVariable) as? ObjectReference ?: return null
return findCoroutineContextForContinuation(continuation)
}
private fun findCoroutineContextForContinuation(continuation: ObjectReference): ObjectReference? {
val continuationType = (continuation.referenceType() as? ClassType)
?.allInterfaces()?.firstOrNull { it.name() == Continuation::class.java.name }
?: return null
val getContextMethod = continuationType
.methodsByName("getContext", "()Lkotlin/coroutines/CoroutineContext;").firstOrNull()
?: return null
return context.invokeMethod(continuation, getContextMethod, emptyList()) as? ObjectReference
}
private fun findCapturedVariableInReceiver(variables: List<LocalVariableProxyImpl>, kind: VariableKind): Result? {
fun isReceiverOrPassedThis(name: String) =
name.startsWith(AsmUtil.LABELED_THIS_PARAMETER)
|| name == AsmUtil.RECEIVER_PARAMETER_NAME
|| name == AsmUtil.THIS_IN_DEFAULT_IMPLS
|| INLINED_THIS_REGEX.matches(name)
if (kind is VariableKind.ExtensionThis) {
variables.namedEntitySequence()
.filter { kind.capturedNameMatches(it.name) && kind.typeMatches(it.type) }
.mapNotNull { it.unwrapAndCheck(kind) }
.firstOrNull()
?.let { return it }
}
return variables.namedEntitySequence()
.filter { isReceiverOrPassedThis(it.name) }
.mapNotNull { findCapturedVariable(kind, it.value) }
.firstOrNull()
}
private fun findCapturedVariable(kind: VariableKind, parentFactory: () -> Value?): Result? {
val parent = getUnwrapDelegate(kind, parentFactory())
return findCapturedVariable(kind, parent)
}
private fun findCapturedVariable(kind: VariableKind, parent: Value?): Result? {
val acceptsParentValue = kind is VariableKind.UnlabeledThis || kind is VariableKind.OuterClassThis
if (parent != null && acceptsParentValue && kind.typeMatches(parent.type())) {
return Result(parent)
}
val fields = (parent as? ObjectReference)?.referenceType()?.fields() ?: return null
if (kind !is VariableKind.OuterClassThis) {
// Captured variables - direct search
fields.namedEntitySequence(parent)
.filter { kind.capturedNameMatches(it.name) && kind.typeMatches(it.type) }
.mapNotNull { it.unwrapAndCheck(kind) }
.firstOrNull()
?.let { return it }
// Recursive search in captured receivers
fields.namedEntitySequence(parent)
.filter { isCapturedReceiverFieldName(it.name) }
.mapNotNull { findCapturedVariable(kind, it.value) }
.firstOrNull()
?.let { return it }
}
// Recursive search in outer and captured this
fields.namedEntitySequence(parent)
.filter { it.name == AsmUtil.THIS_IN_DEFAULT_IMPLS || it.name == AsmUtil.CAPTURED_THIS_FIELD }
.mapNotNull { findCapturedVariable(kind, it.value) }
.firstOrNull()
?.let { return it }
return null
}
private fun getUnwrapDelegate(kind: VariableKind, rawValue: Value?): Value? {
if (kind !is VariableKind.Ordinary || !kind.isDelegated) {
return rawValue
}
val delegateValue = rawValue as? ObjectReference ?: return rawValue
val getValueMethod = delegateValue.referenceType()
.methodsByName("getValue", "()Ljava/lang/Object;").firstOrNull()
?: return rawValue
return context.invokeMethod(delegateValue, getValueMethod, emptyList())
}
private fun isCapturedReceiverFieldName(name: String): Boolean {
return name.startsWith(getCapturedFieldName(AsmUtil.LABELED_THIS_FIELD))
|| name == AsmUtil.CAPTURED_RECEIVER_FIELD
}
private fun VariableKind.typeMatches(actualType: JdiType?): Boolean {
if (this is VariableKind.Ordinary && isDelegated) {
// We can't figure out the actual type of the value yet.
// No worries: it will be checked again (and more carefully) in `unwrapAndCheck()`.
return true
}
return evaluatorValueConverter.typeMatches(asmType, actualType)
}
private fun NamedEntity.unwrapAndCheck(kind: VariableKind): Result? {
return evaluatorValueConverter.coerce(getUnwrapDelegate(kind, value), kind.asmType)
}
private fun List<Field>.namedEntitySequence(owner: ObjectReference): Sequence<NamedEntity> {
return asSequence().map { NamedEntity.of(it, owner) }
}
private fun List<LocalVariableProxyImpl>.namedEntitySequence(): Sequence<NamedEntity> {
return asSequence().map { NamedEntity.of(it, frameProxy) }
}
private fun List<JavaValue>.namedEntitySequence(context: EvaluationContextImpl): Sequence<NamedEntity> {
return asSequence().map { NamedEntity.of(it, context) }
}
private fun thisObject(): ObjectReference? {
val thisObjectFromEvaluation = context.evaluationContext.computeThisObject() as? ObjectReference
if (thisObjectFromEvaluation != null) {
return thisObjectFromEvaluation
}
return frameProxy.thisObject()
}
}
| apache-2.0 | b405cc19c377bfafd48fe6f2f2697cd1 | 41.853414 | 136 | 0.666838 | 5.398685 | false | false | false | false |
FlexSeries/FlexLib | src/main/kotlin/me/st28/flexseries/flexlib/permission/PermissionNode.kt | 1 | 1917 | /**
* Copyright 2016 Stealth2800 <http://stealthyone.com/>
* Copyright 2016 Contributors <https://github.com/FlexSeries>
*
* 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 me.st28.flexseries.flexlib.permission
import org.bukkit.permissions.Permissible
interface PermissionNode {
companion object {
// I'm not sure if it's really worth caching variable nodes?
//private val variableNodes: MutableMap<String, PermissionNode> = HashMap()
fun buildVariableNode(mainPerm: PermissionNode, vararg variables: String): PermissionNode {
val node = "${mainPerm.node}.${variables.joinToString(separator = ".")}".toLowerCase()
/*if (variableNodes.containsKey(node)) {
return variableNodes[node]!!
}*/
val newNode = object: PermissionNode {
override val node: String
get() = node
}
//variableNodes.put(node, newNode)
return newNode
}
}
fun isAllowed(permissible: Permissible): Boolean {
return permissible.hasPermission(node)
}
val node: String
}
fun PermissionNode.withVariables(vararg variables: String): PermissionNode {
return PermissionNode.buildVariableNode(this, *variables)
}
// Extension method
fun Permissible.hasPermission(perm: PermissionNode): Boolean = this.hasPermission(perm.node)
| apache-2.0 | 0423882754ad97797deced98b61251df | 31.491525 | 99 | 0.683359 | 4.564286 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/findUsages/kotlin/conventions/compareTo.0.kt | 5 | 457 | // PSI_ELEMENT: org.jetbrains.kotlin.psi.KtNamedFunction
// OPTIONS: usages
class A(val n: Int) {
infix operator fun <caret>compareTo(other: A): Int = compareTo(other.n)
infix operator fun compareTo(m: Int): Int = n.compareTo(m)
}
fun test() {
A(0) compareTo A(1)
A(0) < A(1)
A(0) <= A(1)
A(0) > A(1)
A(0) >= A(1)
A(0) compareTo 1
A(0) < 1
A(0) <= 1
A(0) > 1
A(0) >= 1
}
// FIR_COMPARISON
// IGNORE_FIR_LOG | apache-2.0 | b605a99ce72ec87845873265939ecd8d | 18.913043 | 75 | 0.555799 | 2.581921 | false | false | false | false |
GunoH/intellij-community | platform/build-scripts/src/org/jetbrains/intellij/build/impl/ModuleStructureValidator.kt | 2 | 12414 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.intellij.build.impl
import com.intellij.util.containers.MultiMap
import com.intellij.util.xml.dom.XmlElement
import com.intellij.util.xml.dom.readXmlAsModel
import org.jetbrains.intellij.build.BuildContext
import org.jetbrains.jps.model.java.JpsJavaExtensionService
import org.jetbrains.jps.model.java.impl.JpsJavaDependencyExtensionRole
import org.jetbrains.jps.model.library.JpsLibrary
import org.jetbrains.jps.model.library.JpsOrderRootType
import org.jetbrains.jps.model.module.JpsLibraryDependency
import org.jetbrains.jps.model.module.JpsModule
import org.jetbrains.jps.model.module.JpsModuleDependency
import org.jetbrains.jps.util.JpsPathUtil
import java.io.FileInputStream
import java.nio.file.Files
import java.nio.file.Path
import java.util.function.BiPredicate
import java.util.jar.JarInputStream
import kotlin.io.path.name
private const val includeName = "include"
private const val fallbackName = "fallback"
private val pathAttributes = hashSetOf(
"interface", "implementation", "class", "topic", "instance", "provider",
"implements", "headlessImplementation", "serviceInterface", "serviceImplementation",
"interfaceClass", "implementationClass", "beanClass", "schemeClass", "factoryClass", "handlerClass", "hostElementClass", "targetClass",
"forClass", "className", "predicateClassName", "displayNameSupplierClassName", "preloaderClassName",
"treeRenderer"
)
private val nonPathAttributes = hashSetOf(
"id", "value", "key", "testServiceImplementation", "defaultExtensionNs", "qualifiedName", "childrenEPName"
)
private val pathElements = hashSetOf("interface-class", "implementation-class")
private val predefinedTypes = hashSetOf("java.lang.Object")
private val ignoreModules = hashSetOf("intellij.java.testFramework", "intellij.platform.uast.tests")
class ModuleStructureValidator(
private val context: BuildContext,
moduleJars: Map<String, List<String>>,
) {
private val moduleJars = MultiMap<String, String>()
private val moduleNames = HashSet<String>()
private val errors = ArrayList<AssertionError>()
private val libraryFiles = HashMap<JpsLibrary, Set<String>>()
init {
for ((jar, modules) in moduleJars) {
// filter out jars with relative paths in name
if (jar.contains("\\") || jar.contains('/')) {
continue
}
this.moduleJars.put(jar, modules)
this.moduleNames.addAll(modules)
}
}
private fun getLibraryFiles(library: JpsLibrary): Set<String> {
@Suppress("NAME_SHADOWING")
return libraryFiles.computeIfAbsent(library) { library ->
val result = HashSet<String>()
for (libraryRootUrl in library.getRootUrls(JpsOrderRootType.COMPILED)) {
val path = Path.of(JpsPathUtil.urlToPath(libraryRootUrl))
JarInputStream(FileInputStream(path.toFile())).use { jarStream ->
while (true) {
result.add((jarStream.nextJarEntry ?: break).name)
}
}
}
result
}
}
fun validate(): List<AssertionError> {
errors.clear()
context.messages.info("Validating jars...")
validateJarModules()
context.messages.info("Validating modules...")
val visitedModules = HashSet<JpsModule>()
for (moduleName in moduleNames) {
if (ignoreModules.contains(moduleName)) {
continue
}
validateModuleDependencies(visitedModules, context.findRequiredModule(moduleName))
}
context.messages.info("Validating xml descriptors...")
validateXmlDescriptors()
if (errors.isEmpty()) {
context.messages.info("Validation finished successfully")
}
return errors
}
private fun validateJarModules() {
val modulesInJars = MultiMap<String, String>()
for (jar in moduleJars.keySet()) {
for (module in moduleJars.get(jar)) {
modulesInJars.putValue(module, jar)
}
}
for (module in modulesInJars.keySet()) {
val jars = modulesInJars.get(module)
if (jars.size > 1) {
context.messages.warning("Module '$module' contains in several JARs: ${jars.joinToString(separator = "; ")}")
}
}
}
private fun validateModuleDependencies(visitedModules: MutableSet<JpsModule>, module: JpsModule) {
if (visitedModules.contains(module)) {
return
}
visitedModules.add(module)
for (dependency in module.dependenciesList.dependencies) {
if (dependency is JpsModuleDependency) {
// skip test dependencies
val role = dependency.container.getChild(JpsJavaDependencyExtensionRole.INSTANCE)
if (role != null && role.scope.name == "TEST") {
continue
}
if (role != null && role.scope.name == "RUNTIME") {
continue
}
// skip localization modules
val dependantModule = dependency.module!!
if (dependantModule.name.endsWith("resources.en")) {
continue
}
if (!moduleNames.contains(dependantModule.name)) {
errors.add(AssertionError("Missing dependency found: ${module.name} -> ${dependantModule.name} [${role.scope.name}]", null))
continue
}
validateModuleDependencies(visitedModules, dependantModule)
}
}
}
private fun validateXmlDescriptors() {
val roots = ArrayList<Path>()
val libraries = HashSet<JpsLibrary>()
for (moduleName in moduleNames) {
val module = context.findRequiredModule(moduleName)
for (root in module.sourceRoots) {
roots.add(root.path)
}
for (dependencyElement in module.dependenciesList.dependencies) {
if (dependencyElement is JpsLibraryDependency) {
libraries.add(dependencyElement.library!!)
}
}
}
// start validating from product xml descriptor
val productDescriptorName = "META-INF/${context.productProperties.platformPrefix}Plugin.xml"
val productDescriptorFile = findDescriptorFile(productDescriptorName, roots)
if (productDescriptorFile == null) {
errors.add(AssertionError("Can not find product descriptor $productDescriptorName"))
return
}
val allDescriptors = HashSet<Path>()
validateXmlDescriptorsRec(productDescriptorFile, roots, libraries, allDescriptors)
validateXmlRegistrations(allDescriptors)
}
private fun findLibraryWithFile(name: String, libraries: Set<JpsLibrary>): JpsLibrary? {
return libraries.firstOrNull { getLibraryFiles(it).contains(name) }
}
private fun validateXmlDescriptorsRec(descriptor: Path, roots: List<Path>, libraries: Set<JpsLibrary>, allDescriptors: MutableSet<Path>) {
allDescriptors.add(descriptor)
val descriptorFiles = ArrayList<Path>()
val xml = Files.newInputStream(descriptor).use(::readXmlAsModel)
for (includeNode in xml.children(includeName)) {
val ref = includeNode.getAttributeValue("href") ?: continue
val descriptorFile = findDescriptorFile(ref, roots + listOf(descriptor.parent))
if (descriptorFile == null) {
val library1 = findLibraryWithFile(ref.removePrefix("/"), libraries)
if (library1 != null) {
context.messages.warning("Descriptor '$ref' came from library '${library1.name}', referenced in '${descriptor.name}'")
}
else {
val isOptional = includeNode.children.any { it.name == fallbackName }
if (isOptional) {
context.messages.info("Ignore optional missing xml descriptor '$ref' referenced in '${descriptor.name}'")
}
else {
errors.add(AssertionError("Can not find xml descriptor '$ref' referenced in '${descriptor.name}'"))
}
}
}
else {
descriptorFiles.add(descriptorFile)
}
}
for (descriptorFile in descriptorFiles) {
validateXmlDescriptorsRec(descriptorFile, roots, libraries, allDescriptors)
}
}
private fun validateXmlRegistrations(descriptors: HashSet<Path>) {
val classes = HashSet<String>(predefinedTypes)
val visitedLibraries = HashSet<String>()
for (moduleName in moduleNames) {
val jpsModule = context.findRequiredModule(moduleName)
val outputDirectory = JpsJavaExtensionService.getInstance().getOutputDirectory(jpsModule, false)!!.toPath()
val outputDirectoryPrefix = outputDirectory.toString().replace('\\', '/') + "/"
if (!Files.isDirectory(outputDirectory)) {
if (jpsModule.contentRootsList.urls.isEmpty()) {
// no content roots -> no classes
continue
}
throw IllegalStateException("Module output directory '$outputDirectory' is missing")
}
Files.find(outputDirectory, Int.MAX_VALUE, BiPredicate { path, attributes ->
if (attributes.isRegularFile) {
val fileName = path.fileName.toString()
fileName.endsWith(".class") && !fileName.endsWith("Kt.class")
}
else {
false
}
}).use { stream ->
stream.forEach {
val normalizedPath = it.toString().replace('\\', '/')
val className = removeSuffixStrict(removePrefixStrict(normalizedPath, outputDirectoryPrefix), ".class").replace('/', '.')
classes.add(className)
}
}
for (dependencyElement in jpsModule.dependenciesList.dependencies) {
if (dependencyElement is JpsLibraryDependency) {
val jpsLibrary = dependencyElement.library
val library = jpsLibrary ?: continue
if (!visitedLibraries.add(library.name)) {
continue
}
val libraryFiles = getLibraryFiles(jpsLibrary)
for (fileName in libraryFiles) {
if (!fileName.endsWith(".class") || fileName.endsWith("Kt.class")) {
return
}
classes.add(removeSuffixStrict(fileName, ".class").replace("/", "."))
}
}
}
}
context.messages.info("Found ${classes.size} classes in ${moduleNames.size} modules and ${visitedLibraries.size} libraries")
for (descriptor in descriptors) {
val xml = Files.newInputStream(descriptor).use(::readXmlAsModel)
validateXmlRegistrationsRec(descriptor.name, xml, classes)
}
}
private fun validateXmlRegistrationsRec(source: String, xml: XmlElement, classes: HashSet<String>) {
for ((name, value) in xml.attributes) {
if (pathAttributes.contains(name)) {
checkRegistration(source, value, classes)
continue
}
if (nonPathAttributes.contains(name)) {
continue
}
if (value.startsWith("com.") || value.startsWith("org.")) {
context.messages.warning(
"Attribute '$name' contains qualified path '$value'. " +
"Add attribute into 'ModuleStructureValidator.pathAttributes' or 'ModuleStructureValidator.nonPathAttributes' collection."
)
}
}
for (child in xml.children) {
for (pathElement in pathElements) {
if (child.name == pathElement) {
checkRegistration(source, child.content, classes)
}
}
validateXmlRegistrationsRec(source, child, classes)
}
}
private fun checkRegistration(source: String, value: String?, classes: Set<String>) {
if (value.isNullOrEmpty() || classes.contains(value)) {
return
}
errors.add(AssertionError("Unresolved registration '$value' in $source"))
}
}
private fun removeSuffixStrict(string: String, @Suppress("SameParameterValue") suffix: String?): String {
if (suffix.isNullOrEmpty()) {
throw IllegalArgumentException("'suffix' is null or empty")
}
if (!string.endsWith(suffix)) {
throw IllegalStateException("String must end with '$suffix': $string")
}
return string.substring(0, string.length - suffix.length)
}
private fun findDescriptorFile(name: String, roots: List<Path>): Path? {
for (root in roots) {
val descriptorFile = root.resolve(name.removePrefix("/"))
if (Files.isRegularFile(descriptorFile)) {
return descriptorFile
}
}
return null
}
private fun removePrefixStrict(string: String, prefix: String?): String {
if (prefix.isNullOrEmpty()) {
throw IllegalArgumentException("'prefix' is null or empty")
}
if (!string.startsWith(prefix)) {
throw IllegalStateException("String must start with '$prefix': $string")
}
return string.substring(prefix.length)
} | apache-2.0 | a0470834da89d10cdae9d1f6521ebb7a | 34.471429 | 140 | 0.679555 | 4.592675 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/migration/WarningOnMainUnusedParameterMigrationInspection.kt | 2 | 2310 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.inspections.migration
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInspection.CleanupLocalInspectionTool
import org.jetbrains.kotlin.config.LanguageVersion
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.DiagnosticFactoryWithPsiElement
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.MainFunctionDetector
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.migration.MigrationInfo
import org.jetbrains.kotlin.idea.migration.isLanguageVersionUpdate
import org.jetbrains.kotlin.idea.quickfix.RemoveUnusedFunctionParameterFix
import org.jetbrains.kotlin.idea.quickfix.migration.MigrationFix
import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtParameter
class WarningOnMainUnusedParameterMigrationInspection :
AbstractDiagnosticBasedMigrationInspection<KtParameter>(KtParameter::class.java),
MigrationFix,
CleanupLocalInspectionTool {
override fun isApplicable(migrationInfo: MigrationInfo): Boolean {
return migrationInfo.isLanguageVersionUpdate(LanguageVersion.KOTLIN_1_3, LanguageVersion.KOTLIN_1_4)
}
override fun getDiagnosticFactory(languageVersionSettings: LanguageVersionSettings): DiagnosticFactoryWithPsiElement<KtParameter, *> =
Errors.UNUSED_PARAMETER
override fun customIntentionFactory(): (Diagnostic) -> IntentionAction? = fun(diagnostic: Diagnostic): IntentionAction? {
val parameter = diagnostic.psiElement as? KtParameter ?: return null
val ownerFunction = parameter.ownerFunction as? KtNamedFunction ?: return null
val mainFunctionDetector = MainFunctionDetector(parameter.languageVersionSettings) { it.descriptor as? FunctionDescriptor }
if (!mainFunctionDetector.isMain(ownerFunction)) return null
return RemoveUnusedFunctionParameterFix(parameter, false)
}
}
| apache-2.0 | 739812d6a8dacc2be78138200fafeaf7 | 54 | 138 | 0.82987 | 5.347222 | false | false | false | false |
ftomassetti/kolasu | core/src/main/kotlin/com/strumenta/kolasu/model/Processing.kt | 1 | 17116 | @file:JvmName("Processing")
package com.strumenta.kolasu.model
import com.strumenta.kolasu.traversing.children
import com.strumenta.kolasu.traversing.searchByType
import com.strumenta.kolasu.traversing.walk
import com.strumenta.kolasu.traversing.walkChildren
import java.util.*
import kotlin.reflect.*
import kotlin.reflect.full.memberProperties
import kotlin.reflect.full.primaryConstructor
/**
* Sets or corrects the parent of all AST nodes.
* Kolasu does not see set/add/delete operations on the AST nodes,
* so this function should be called manually after modifying the AST.
*/
fun Node.assignParents() {
this.walkChildren().forEach {
if (it == this) {
throw java.lang.IllegalStateException("A node cannot be parent of itself: $this")
}
it.parent = this
it.assignParents()
}
}
/**
* Recursively execute [operation] on [this] node, and all nodes below this node.
* @param walker the function that generates the nodes to operate on in the desired sequence.
*/
fun Node.processNodes(operation: (Node) -> Unit, walker: KFunction1<Node, Sequence<Node>> = Node::walk) {
walker.invoke(this).forEach(operation)
}
fun Node.invalidPositions(): Sequence<Node> = this.walk().filter {
it.position == null || run {
val parentPos = it.parent?.position
// If the parent position is null, we can't say anything about this node's position
(parentPos != null && !(parentPos.contains(it.position!!.start) && parentPos.contains(it.position!!.end)))
}
}
fun Node.findInvalidPosition(): Node? = this.invalidPositions().firstOrNull()
fun Node.hasValidParents(parent: Node? = this.parent): Boolean {
return this.parent == parent && this.children.all { it.hasValidParents(this) }
}
fun <T : Node> T.withParent(parent: Node?): T {
this.parent = parent
return this
}
/**
* Executes an operation on the properties of a node.
* @param propertiesToIgnore which properties to ignore
* @param propertyOperation the operation to perform on each property.
*/
@JvmOverloads
fun Node.processProperties(
propertiesToIgnore: Set<String> = emptySet(),
propertyOperation: (PropertyDescription) -> Unit
) {
this.properties.filter { it.name !in propertiesToIgnore }.forEach {
try {
propertyOperation(it)
} catch (t: Throwable) {
throw java.lang.RuntimeException("Issue processing property $it in $this", t)
}
}
}
/**
* Executes an operation on the properties definitions of a node class.
* @param propertiesToIgnore which properties to ignore
* @param propertyTypeOperation the operation to perform on each property.
*/
fun <T : Any> Class<T>.processProperties(
propertiesToIgnore: Set<String> = emptySet(),
propertyTypeOperation: (PropertyTypeDescription) -> Unit
) = kotlin.processProperties(propertiesToIgnore, propertyTypeOperation)
/**
* @param walker the function that generates the nodes to operate on in the desired sequence.
* @return the first node in the AST for which the [predicate] is true. Null if none are found.
*/
fun Node.find(predicate: (Node) -> Boolean, walker: KFunction1<Node, Sequence<Node>> = Node::walk): Node? {
return walker.invoke(this).find(predicate)
}
/**
* Recursively execute [operation] on this node, and all nodes below this node that extend [klass].
*
* T is not forced to be a subtype of Node to support using interfaces.
*
* @param walker the function that generates the nodes to operate on in the desired sequence.
*/
fun <T> Node.processNodesOfType(
klass: Class<T>,
operation: (T) -> Unit,
walker: KFunction1<Node, Sequence<Node>> = Node::walk
) {
searchByType(klass, walker).forEach(operation)
}
/**
* Recursively execute [operation] on this node, and all nodes below this node.
* Every node is informed about its [parent] node. (But not about the parent's parent!)
*/
fun Node.processConsideringDirectParent(operation: (Node, Node?) -> Unit, parent: Node? = null) {
operation(this, parent)
this.properties.forEach { p ->
when (val v = p.value) {
is Node -> v.processConsideringDirectParent(operation, this)
is Collection<*> -> v.forEach { (it as? Node)?.processConsideringDirectParent(operation, this) }
}
}
}
/**
* @return all direct children of this node.
*/
val Node.children: List<Node>
get() {
val children = mutableListOf<Node>()
this.properties.forEach { p ->
val v = p.value
when (v) {
is Node -> children.add(v)
is Collection<*> -> v.forEach { if (it is Node) children.add(it) }
}
}
return children
}
/**
* @return the next sibling node. Notice that children of a sibling collection are considered siblings
* and not the collection itself.
*/
val Node.nextSibling: Node?
get() {
if (this.parent != null) {
val siblings = this.parent!!.children
val index = siblings.indexOf(this)
return if (index == children.size - 1) null else siblings[index + 1]
}
return null
}
/**
* @return the previous sibling. Notice that children of a sibling collection are considered siblings
* and not the collection itself.
*/
val Node.previousSibling: Node?
get() {
if (this.parent != null) {
val siblings = this.parent!!.children
val index = siblings.indexOf(this)
return if (index == 0) null else siblings[index - 1]
}
return null
}
/**
* @return the next sibling node in the same property.
*/
val Node.nextSamePropertySibling: Node?
get() {
if (this.parent != null) {
val siblings = this.parent!!.properties.find { p ->
val v = p.value
when (v) {
is Collection<*> -> v.contains(this)
else -> false
}
}?.value as? Collection<*> ?: emptyList<Node>()
val index = siblings.indexOf(this)
return if (index == siblings.size - 1 || index == -1) null else siblings.elementAt(index + 1) as Node
}
return null
}
/**
* @return the previous sibling in the same property.
*/
val Node.previousSamePropertySibling: Node?
get() {
if (this.parent != null) {
val siblings = this.parent!!.properties.find { p ->
val v = p.value
when (v) {
is Collection<*> -> v.contains(this)
else -> false
}
}?.value as? Collection<*> ?: emptyList<Node>()
val index = siblings.indexOf(this)
return if (index == 0 || index == -1) null else siblings.elementAt(index - 1) as Node
}
return null
}
/**
* @return the next sibling of the specified type. Notice that children of a sibling collection are considered siblings
* and not the collection itself.
*/
inline fun <reified T : Node> Node.nextSibling(): Node? {
if (this.parent != null) {
val siblings = this.parent!!.children
return siblings.takeLast(siblings.size - 1 - siblings.indexOf(this)).firstOrNull { it is T }
}
return null
}
/**
* @return the previous sibling of the specified type. Notice that children of a sibling collection are considered siblings
* and not the collection itself.
*/
inline fun <reified T : Node> Node.previousSibling(): Node? {
if (this.parent != null) {
val siblings = this.parent!!.children
return siblings.take(siblings.indexOf(this)).lastOrNull { it is T }
}
return null
}
// TODO reimplement using transformChildren
fun Node.transformTree(
operation: (Node) -> Node,
inPlace: Boolean = false,
mutationsCache: IdentityHashMap<Node, Node> = IdentityHashMap<Node, Node>()
): Node {
if (inPlace) TODO()
mutationsCache.computeIfAbsent(this) { operation(this) }
val changes = mutableMapOf<String, Any>()
relevantMemberProperties().forEach { p ->
when (val v = p.get(this)) {
is Node -> {
val newValue = v.transformTree(operation, inPlace, mutationsCache)
if (newValue != v) changes[p.name] = newValue
}
is Collection<*> -> {
val newValue = v.map { if (it is Node) it.transformTree(operation, inPlace, mutationsCache) else it }
if (newValue != v) changes[p.name] = newValue
}
}
}
var instanceToTransform = this
if (changes.isNotEmpty()) {
val constructor = this.javaClass.kotlin.primaryConstructor!!
val params = mutableMapOf<KParameter, Any?>()
constructor.parameters.forEach { param ->
if (changes.containsKey(param.name)) {
params[param] = changes[param.name]
} else {
params[param] = this.javaClass.kotlin.memberProperties.find { param.name == it.name }!!.get(this)
}
}
instanceToTransform = constructor.callBy(params)
}
return mutationsCache.computeIfAbsent(instanceToTransform) { operation(instanceToTransform) }
}
class ImmutablePropertyException(property: KProperty<*>, node: Node) :
RuntimeException("Cannot mutate property '${property.name}' of node $node (class: ${node.javaClass.canonicalName})")
// assumption: every MutableList in the AST contains Nodes.
@Suppress("UNCHECKED_CAST")
fun Node.transformChildren(operation: (Node) -> Node) {
nodeProperties.forEach { property ->
when (val value = property.get(this)) {
is Node -> {
val newValue = operation(value)
if (newValue != value) {
if (property is KMutableProperty<*>) {
property.setter.call(this, newValue)
newValue.parent = this
} else {
throw ImmutablePropertyException(property, value)
}
}
}
is Collection<*> -> {
if (value is List<*>) {
for (i in 0 until value.size) {
val element = value[i]
if (element is Node) {
val newValue = operation(element)
if (newValue != element) {
if (value is MutableList<*>) {
(value as MutableList<Node>)[i] = newValue
newValue.parent = this
} else {
throw ImmutablePropertyException(property, element)
}
}
}
}
} else {
throw UnsupportedOperationException(
"Only modifications in a List and MutableList are supported, not ${value::class}"
)
}
}
}
}
}
fun Node.mapChildren(operation: (Node) -> Node): Node {
val changes = mutableMapOf<String, Any>()
relevantMemberProperties().forEach { property ->
val value = property.get(this)
when (value) {
is Node -> {
val newValue = operation(value)
if (newValue != value) {
changes[property.name] = newValue
}
}
is Collection<*> -> {
val newValue = value.map { if (it is Node) operation(it) else it }
if (newValue != value) {
changes[property.name] = newValue
}
}
}
}
var instanceToTransform = this
if (changes.isNotEmpty()) {
val constructor = this.javaClass.kotlin.primaryConstructor!!
val params = mutableMapOf<KParameter, Any?>()
constructor.parameters.forEach { param ->
if (changes.containsKey(param.name)) {
params[param] = changes[param.name]
} else {
params[param] = this.javaClass.kotlin.memberProperties.find { param.name == it.name }!!.get(this)
}
}
instanceToTransform = constructor.callBy(params)
}
return instanceToTransform
}
/**
* Replace [this] node with [other] (by modifying the children of the parent node.)
* For this to work, [Node.assignParents] must have been called.
*/
fun Node.replaceWith(other: Node) {
if (this.parent == null) {
throw IllegalStateException("Parent not set")
}
this.parent!!.transformChildren { if (it == this) other else it }
}
/**
* Looks for [oldNode] in the lists of nodes in this node.
* When found, it is removed, and in its place the [newNodes] are inserted.
* When not found, an [IllegalStateException] is thrown.
*/
fun Node.replaceWithSeveral(oldNode: Node, newNodes: List<Node>) {
findMutableListContainingChild(oldNode) { nodeList, index ->
nodeList.replaceWithSeveral(index, newNodes)
oldNode.parent = null
newNodes.forEach { node -> node.parent = this }
}
}
/**
* Looks for [targetNode] in the lists of nodes in this node.
* When found, it is removed.
* When not found, an [IllegalStateException] is thrown.
*/
fun Node.removeFromList(targetNode: Node) {
findMutableListContainingChild(targetNode) { nodeList, index ->
nodeList.removeAt(index)
targetNode.parent = null
}
}
/**
* Looks for [targetNode] in the lists of nodes in this node.
* When found, [newNodes] are inserted before it.
* When not found, an [IllegalStateException] is thrown.
*/
fun Node.addSeveralBefore(targetNode: Node, newNodes: List<Node>) {
findMutableListContainingChild(targetNode) { nodeList, index ->
nodeList.addSeveralBefore(index, newNodes)
newNodes.forEach { node -> node.parent = this }
}
}
/**
* Looks for [targetNode] in the lists of nodes in this node.
* When found, [newNodes] are inserted after it.
* When not found, an [IllegalStateException] is thrown.
*/
fun Node.addSeveralAfter(targetNode: Node, newNodes: List<Node>) {
findMutableListContainingChild(targetNode) { nodeList, index ->
nodeList.addSeveralAfter(index, newNodes)
newNodes.forEach { node -> node.parent = this }
}
}
/**
* Supports functions that manipulate a list of child nodes by finding [targetNode] in the [MutableList]s of nodes contained in [this] node.
*/
@Suppress("UNCHECKED_CAST") // assumption: a MutableList with a Node in it is a MutableList<Node>
private fun Node.findMutableListContainingChild(
targetNode: Node,
whenFoundDo: (nodeList: MutableList<Node>, index: Int) -> Unit
) {
relevantMemberProperties().forEach { property ->
when (val value = property.get(this)) {
is MutableList<*> -> {
for (i in 0 until value.size) {
if (value[i] == targetNode) {
whenFoundDo(value as MutableList<Node>, i)
return
}
}
}
}
}
throw IllegalStateException("Did not find $targetNode in any MutableList in $this.")
}
/**
* Replaces [this] node with any amount of other nodes if it is in a [MutableList].
* <p/>Looks for [this] in the lists of nodes in the parent node.
* When found, [this] is removed, and in its place [newNodes] are inserted.
* For this to work, [Node.assignParents] must have been called.
*/
fun Node.replaceWithSeveral(newNodes: List<Node>) {
parent?.replaceWithSeveral(this, newNodes) ?: throw IllegalStateException("Parent not set")
}
/**
* Inserts the [newNodes] before [this] node if it is in a [MutableList].
* For this to work, [Node.assignParents] must have been called.
*/
fun Node.addSeveralBefore(newNodes: List<Node>) {
parent?.addSeveralBefore(this, newNodes) ?: throw IllegalStateException("Parent not set")
}
/**
* Inserts the [newNodes] after [this] node if it is in a [MutableList].
* For this to work, [Node.assignParents] must have been called.
*/
fun Node.addSeveralAfter(newNodes: List<Node>) {
parent?.addSeveralAfter(this, newNodes) ?: throw IllegalStateException("Parent not set")
}
/**
* Removes [this] node from the parent if it is in a [MutableList].
* For this to work, [Node.assignParents] must have been called.
*/
fun Node.removeFromList() {
parent?.removeFromList(this) ?: throw IllegalStateException("Parent not set")
}
/**
* Replaces the element at [index] with [replacements].
*/
fun <T> MutableList<T>.replaceWithSeveral(index: Int, replacements: List<T>) {
removeAt(index)
addAll(index, replacements)
}
/**
* Replaces the element at [index] with [additions].
*/
fun <T> MutableList<T>.addSeveralBefore(index: Int, additions: List<T>) {
addAll(index, additions)
}
/**
* Replaces the element at [index] with [additions].
*/
fun <T> MutableList<T>.addSeveralAfter(index: Int, additions: List<T>) {
addAll(index + 1, additions)
}
| apache-2.0 | 7ca20347a7e20be7235a004a80c87319 | 34.436853 | 140 | 0.616324 | 4.267265 | false | false | false | false |
jk1/intellij-community | plugins/stats-collector/features/src/com/jetbrains/completion/feature/impl/FeatureTransformer.kt | 3 | 1600 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.completion.feature.impl
import com.jetbrains.completion.feature.Feature
import com.jetbrains.completion.feature.Transformer
/**
* @author Vitaliy.Bibaev
*/
class FeatureTransformer(val features: Map<String, Feature>,
private val ignoredFeatures: Set<String>,
arraySize: Int)
: Transformer {
private val array = DoubleArray(arraySize)
override fun featureArray(relevanceMap: Map<String, Any>, userFactors: Map<String, Any?>): DoubleArray {
for ((name, feature) in features) {
val value = relevanceMap[name]
if (value == null || isFeatureIgnored(name)) {
feature.setDefaults(array)
} else {
feature.process(value, array)
}
}
return array
}
private fun isFeatureIgnored(name: String): Boolean {
val normalized = name.substringBefore('@')
return normalized in ignoredFeatures
}
} | apache-2.0 | adc177415a41c640976ab6d0fd617f20 | 32.354167 | 108 | 0.665 | 4.532578 | false | false | false | false |
jk1/intellij-community | plugins/stats-collector/src/com/intellij/stats/personalization/impl/DayImpl.kt | 3 | 2796 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.stats.personalization.impl
import com.intellij.openapi.diagnostic.Logger
import com.intellij.stats.personalization.Day
import java.text.ParsePosition
import java.text.SimpleDateFormat
import java.util.*
/**
* @author Vitaliy.Bibaev
*/
class DayImpl(date: Date) : Day {
override val dayOfMonth: Int
override val month: Int
override val year: Int
companion object {
private val LOG = Logger.getInstance(DayImpl::class.java)
private val DATE_FORMAT = SimpleDateFormat("dd-MM-yyyy")
fun fromString(str: String): Day? {
val position = ParsePosition(0)
val date: Date
try {
date = DATE_FORMAT.parse(str, position)
}
catch (e: NumberFormatException) {
LOG.error("Could not parse a date from string: $str. Collected data for the day will be skipped.", e)
return null
}
if (position.index == 0) return null
return DayImpl(date)
}
}
init {
val calendar = Calendar.getInstance()
calendar.time = date
dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH)
// a month is a zero-based property for some reason
// see details: https://stackoverflow.com/questions/344380/why-is-january-month-0-in-java-calendar
month = calendar.get(Calendar.MONTH) + 1
year = calendar.get(Calendar.YEAR)
}
override fun compareTo(other: Day): Int {
if (year == other.year) {
if (month == other.month) {
return dayOfMonth.compareTo(other.dayOfMonth)
}
return month.compareTo(other.month)
}
return year.compareTo(other.year)
}
override fun hashCode(): Int {
return Objects.hash(year, month, dayOfMonth)
}
override fun equals(other: Any?): Boolean {
if (other != null && other is Day) return compareTo(other) == 0
return false
}
override fun toString(): String {
val calendar = Calendar.getInstance()
calendar.set(year, month - 1, dayOfMonth)
return DATE_FORMAT.format(calendar.time)
}
}
| apache-2.0 | 81dbe610ce20167e3d9c53b6e08f3b3c | 31.137931 | 117 | 0.637339 | 4.268702 | false | false | false | false |
code-disaster/lwjgl3 | modules/lwjgl/odbc/src/templates/kotlin/odbc/ODBCTypes.kt | 4 | 5170 | /*
* Copyright LWJGL. All rights reserved.
* License terms: http://lwjgl.org/license.php
*/
package odbc
import org.lwjgl.generator.*
import core.windows.*
val ODBC_BINDING = simpleBinding(Module.ODBC, libraryExpression = "Configuration.ODBC_LIBRARY_NAME, \"odbc32\", \"odbc\"")
val SQLCHAR = typedef(unsigned_char, "SQLCHAR")
val SQLSCHAR = IntegerType("SQLSCHAR", PrimitiveMapping.BYTE, unsigned = true)
val SQLWCHAR = typedef(unsigned_short, "SQLWCHAR")
val SQLTCHAR = typedef(SQLWCHAR, "SQLTCHAR")
val SQLCHARASCII = CharType("SQLCHAR", CharMapping.ASCII)
val SQLCHARUTF16 = CharType("SQLWCHAR", CharMapping.UTF16)
val SQLSMALLINT = typedef(short, "SQLSMALLINT")
val SQLUSMALLINT = typedef(unsigned_short, "SQLUSMALLINT")
val SQLINTEGER = typedef(int32_t, "SQLINTEGER")
val SQLUINTEGER = typedef(uint32_t, "SQLUINTEGER")
val SQLRETURN = typedef(SQLSMALLINT, "SQLRETURN")
val SQLPOINTER = typedef(PrimitiveType("void", PrimitiveMapping.BYTE).p, "SQLPOINTER")
val SQLLEN = IntegerType("SQLLEN", PrimitiveMapping.POINTER)
val SQLULEN = IntegerType("SQLULEN", PrimitiveMapping.POINTER, unsigned = true)
val SQLSETPOSIROW = IntegerType("SQLSETPOSIROW", PrimitiveMapping.LONG, unsigned = true)
val SQLHANDLE = "SQLHANDLE".handle
val SQLHENV = typedef(SQLHANDLE, "SQLHENV")
val SQLHDBC = typedef(SQLHANDLE, "SQLHDBC")
val SQLHSTMT = typedef(SQLHANDLE, "SQLHSTMT")
val SQLHDESC = typedef(SQLHANDLE, "SQLHDESC")
val SQLHWND = typedef(HWND, "SQLHWND")
val RETCODE = IntegerType("RETCODE", PrimitiveMapping.SHORT)
// sqltypes.h structs
val SQL_DATE_STRUCT = struct(Module.ODBC, "SQL_DATE_STRUCT") {
SQLSMALLINT("year", "")
SQLUSMALLINT("month", "")
SQLUSMALLINT("day", "")
}
val SQL_TIME_STRUCT = struct(Module.ODBC, "SQL_TIME_STRUCT") {
SQLUSMALLINT("hour", "")
SQLUSMALLINT("minute", "")
SQLUSMALLINT("second", "")
}
val SQL_TIMESTAMP_STRUCT = struct(Module.ODBC, "SQL_TIMESTAMP_STRUCT") {
SQLSMALLINT("year", "")
SQLUSMALLINT("month", "")
SQLUSMALLINT("day", "")
SQLUSMALLINT("hour", "")
SQLUSMALLINT("minute", "")
SQLUSMALLINT("second", "")
SQLUINTEGER("fraction", "")
}
val SQL_YEAR_MONTH_STRUCT = struct(Module.ODBC, "SQL_YEAR_MONTH_STRUCT") {
SQLUINTEGER("year", "")
SQLUINTEGER("month", "")
}
val SQL_DAY_SECOND_STRUCT = struct(Module.ODBC, "SQL_DAY_SECOND_STRUCT") {
SQLUINTEGER("day", "")
SQLUINTEGER("hour", "")
SQLUINTEGER("minute", "")
SQLUINTEGER("second", "")
SQLUINTEGER("fraction", "")
}
val SQLINTERVAL = typedef(int, "SQLINTERVAL")
val SQL_INTERVAL_STRUCT = struct(Module.ODBC, "SQL_INTERVAL_STRUCT") {
SQLINTERVAL("interval_type", "")
SQLSMALLINT("interval_sign", "")
struct {
SQL_YEAR_MONTH_STRUCT("year_month", "")
SQL_DAY_SECOND_STRUCT("day_second", "")
}("intval", "")
}
val SQL_NUMERIC_STRUCT = struct(Module.ODBC, "SQL_NUMERIC_STRUCT") {
javaImport("static org.lwjgl.odbc.SQL.*")
SQLCHAR("precision", "")
SQLSCHAR("scale", "")
SQLCHAR("sign", "")
SQLCHAR("val", "")["SQL_MAX_NUMERIC_LEN"]
}
// sqlncli.h structs
val DBMONEY = struct(Module.ODBC, "DBMONEY") {
LONG("mnyhigh", "")
ULONG("mnylow", "")
}
val DBDATETIME = struct(Module.ODBC, "DBDATETIME") {
LONG("dtdays", "")
ULONG("dttime", "")
}
val DBDATETIM4 = struct(Module.ODBC, "DBDATETIM4") {
USHORT("numdays", "")
USHORT("nummins", "")
}
val SQL_SS_TIME2_STRUCT = struct(Module.ODBC, "SQL_SS_TIME2_STRUCT") {
SQLUSMALLINT("hour", "")
SQLUSMALLINT("minute", "")
SQLUSMALLINT("second", "")
SQLUINTEGER("fraction", "")
}
val SQL_SS_TIMESTAMPOFFSET_STRUCT = struct(Module.ODBC, "SQL_SS_TIMESTAMPOFFSET_STRUCT") {
SQLSMALLINT("year", "")
SQLUSMALLINT("month", "")
SQLUSMALLINT("day", "")
SQLUSMALLINT("hour", "")
SQLUSMALLINT("minute", "")
SQLUSMALLINT("second", "")
SQLUINTEGER("fraction", "")
SQLSMALLINT("timezone_hour", "")
SQLSMALLINT("timezone_minute", "")
}
val SQLPERF = struct(Module.ODBC, "SQLPERF") {
// Application Profile Statistics
DWORD("TimerResolution", "")
DWORD("SQLidu", "")
DWORD("SQLiduRows", "")
DWORD("SQLSelects", "")
DWORD("SQLSelectRows", "")
DWORD("Transactions", "")
DWORD("SQLPrepares", "")
DWORD("ExecDirects", "")
DWORD("SQLExecutes", "")
DWORD("CursorOpens", "")
DWORD("CursorSize", "")
DWORD("CursorUsed", "")
LDOUBLE("PercentCursorUsed", "")
LDOUBLE("AvgFetchTime", "")
LDOUBLE("AvgCursorSize", "")
LDOUBLE("AvgCursorUsed", "")
DWORD("SQLFetchTime", "")
DWORD("SQLFetchCount", "")
DWORD("CurrentStmtCount", "")
DWORD("MaxOpenStmt", "")
DWORD("SumOpenStmt", "")
// Connection Statistics
DWORD("CurrentConnectionCount", "")
DWORD("MaxConnectionsOpened", "")
DWORD("SumConnectionsOpened", "")
DWORD("SumConnectiontime", "")
LDOUBLE("AvgTimeOpened", "")
// Network Statistics
DWORD("ServerRndTrips", "")
DWORD("BuffersSent", "")
DWORD("BuffersRec", "")
DWORD("BytesSent", "")
DWORD("BytesRec", "")
// Time Statistics
DWORD("msExecutionTime", "")
DWORD("msNetWorkServerTime", "")
} | bsd-3-clause | e24036b812debb08a9392d2f094689ba | 28.380682 | 122 | 0.653385 | 3.225203 | false | false | false | false |
taskworld/KxAndroid | kxandroid/src/main/kotlin/com/taskworld/kxandroid/Strings.kt | 1 | 1094 | package com.taskworld.kxandroid
import java.text.SimpleDateFormat
val EMAIL_REGEX_PATTERN = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
fun String.toStartingLetterUppercase(): String {
if (isEmpty()) return this
var firstChar = this[0]
val valueOfFirstChar = firstChar.toInt()
if (valueOfFirstChar in 97..122) {
firstChar = (valueOfFirstChar - 32).toChar()
}
val builder = StringBuilder()
var i = 0
for (ch in this) {
if (i == 0) {
builder.append(firstChar)
} else {
builder.append(ch)
}
i++
}
return builder.toString()
}
fun String.fromSnakeToCamel(): String {
if (this.isEmpty()) return this
val builder = StringBuilder()
for (token in split("_".toRegex()).toTypedArray()) {
builder.append(token.toStartingLetterUppercase())
}
return builder.toString()
}
fun String.convertTimeString(oldFormat: SimpleDateFormat, newFormat: SimpleDateFormat): String {
if (this.isEmpty()) return this
return newFormat.format(oldFormat.parse(this))
}
| mit | a17393fcbe255bda9a976c9085da5ce1 | 22.276596 | 96 | 0.627971 | 3.798611 | false | false | false | false |
mdanielwork/intellij-community | java/java-tests/testSrc/com/intellij/util/io/java/ClassFileBuilderTest.kt | 11 | 3037 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.util.io.java
import com.intellij.testFramework.UsefulTestCase.assertEmpty
import com.intellij.testFramework.UsefulTestCase.assertOneElement
import com.intellij.util.io.directoryContent
import junit.framework.TestCase.assertSame
import org.junit.Test
import java.io.File
import java.io.Serializable
import java.lang.reflect.Modifier
import java.util.*
import kotlin.test.assertEquals
import kotlin.test.assertTrue
/**
* @author nik
*/
class ClassFileBuilderTest {
@Test
fun `empty class`() {
val dir = directoryContent {
classFile("A") {}
}.generateInTempDir()
val aClass = loadClass("A", File(dir, "A.class"))
assertSame(Object::class.java, aClass.superclass)
assertEmpty(aClass.interfaces)
assertEmpty(aClass.declaredFields)
}
@Test
fun `class with extends and implements`() {
val dir = directoryContent {
classFile("A") {
superclass = ArrayList::class.java.name
interfaces = listOf(Serializable::class.java.name)
}
}.generateInTempDir()
val aClass = loadClass("A", File(dir, "A.class"))
assertSame(ArrayList::class.java, aClass.superclass)
assertSame(Serializable::class.java, assertOneElement(aClass.interfaces))
assertEmpty(aClass.declaredFields)
}
@Test
fun `class with fields`() {
val dir = directoryContent {
classFile("A") {
field("foo", Int::class, AccessModifier.PUBLIC)
field("bar", Object::class.java.name)
}
}.generateInTempDir()
val aClass = loadClass("A", File(dir, "A.class"))
val foo = aClass.getDeclaredField("foo")
assertSame(Int::class.java, foo.type)
assertTrue(Modifier.isPublic(foo.modifiers))
val bar = aClass.getDeclaredField("bar")
assertSame(Object::class.java, bar.type)
assertTrue(Modifier.isPrivate(bar.modifiers))
}
@Test
fun `class in non-default package`() {
val dir = directoryContent {
classFile("p.A") {}
}.generateInTempDir()
val aClass = loadClass("p.A", File(dir, "p/A.class"))
assertEquals("p.A", aClass.name)
}
}
private fun loadClass(name: String, file: File): Class<*> {
return MyClassLoader(ClassFileBuilderTest::class.java.classLoader).doDefineClass(name, file.readBytes())
}
private class MyClassLoader(parent: ClassLoader) : ClassLoader(parent) {
fun doDefineClass(name: String, data: ByteArray): Class<*> {
return defineClass(name, data, 0, data.size)
}
}
| apache-2.0 | cb0f42e41d6de6227fd80ed4f1d70c1b | 31.308511 | 106 | 0.708594 | 4.038564 | false | true | false | false |
mdanielwork/intellij-community | platform/configuration-store-impl/src/ChooseComponentsToExportDialog.kt | 4 | 8357 | // 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.configurationStore
import com.intellij.ide.IdeBundle
import com.intellij.ide.util.ElementsChooser
import com.intellij.ide.util.MultiStateElementsChooser
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.application.ConfigImportHelper
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.fileChooser.FileChooser
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.VerticalFlowLayout
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.FieldPanel
import com.intellij.util.ArrayUtil
import gnu.trove.THashSet
import org.jetbrains.concurrency.AsyncPromise
import org.jetbrains.concurrency.Promise
import java.awt.Component
import java.awt.event.ActionEvent
import java.io.File
import java.nio.file.Path
import java.nio.file.Paths
import java.util.*
import javax.swing.*
private const val DEFAULT_FILE_NAME = "settings.zip"
private val DEFAULT_PATH = FileUtil.toSystemDependentName(PathManager.getConfigPath() + "/") + DEFAULT_FILE_NAME
private const val KEY_MARKED_NAMES = "export.settings.marked"
private val markedElementNames: Set<String>
get() {
val value = PropertiesComponent.getInstance().getValue(KEY_MARKED_NAMES)
return if (value.isNullOrEmpty()) {
emptySet()
}
else THashSet(StringUtil.split(value!!.trim { it <= ' ' }, "|"))
}
private fun addToExistingListElement(item: ExportableItem,
itemToContainingListElement: MutableMap<ExportableItem, ComponentElementProperties>,
fileToItem: Map<Path, List<ExportableItem>>): Boolean {
val list = fileToItem.get(item.file)
if (list == null || list.isEmpty()) {
return false
}
var file: Path? = null
for (tiedItem in list) {
if (tiedItem === item) {
continue
}
val elementProperties = itemToContainingListElement.get(tiedItem)
if (elementProperties != null && item.file !== file) {
LOG.assertTrue(file == null, "Component $item serialize itself into $file and ${item.file}")
// found
elementProperties.items.add(item)
itemToContainingListElement.set(item, elementProperties)
file = item.file
}
}
return file != null
}
fun chooseSettingsFile(oldPath: String?, parent: Component?, title: String, description: String): Promise<String> {
val chooserDescriptor = FileChooserDescriptorFactory.createSingleLocalFileDescriptor()
chooserDescriptor.description = description
chooserDescriptor.isHideIgnored = false
chooserDescriptor.title = title
chooserDescriptor.withFileFilter { ConfigImportHelper.isSettingsFile(it) }
var initialDir: VirtualFile?
if (oldPath != null) {
val oldFile = File(oldPath)
initialDir = LocalFileSystem.getInstance().findFileByIoFile(oldFile)
if (initialDir == null && oldFile.parentFile != null) {
initialDir = LocalFileSystem.getInstance().findFileByIoFile(oldFile.parentFile)
}
}
else {
initialDir = null
}
val result = AsyncPromise<String>()
FileChooser.chooseFiles(chooserDescriptor, null, parent, initialDir, object : FileChooser.FileChooserConsumer {
override fun consume(files: List<VirtualFile>) {
val file = files[0]
if (file.isDirectory) {
result.setResult("${file.path}/$DEFAULT_FILE_NAME")
}
else {
result.setResult(file.path)
}
}
override fun cancelled() {
result.setError("")
}
})
return result
}
internal class ChooseComponentsToExportDialog(fileToComponents: Map<Path, List<ExportableItem>>, private val isShowFilePath: Boolean, title: String, private val description: String) : DialogWrapper(false) {
private val chooser: ElementsChooser<ComponentElementProperties>
private val pathPanel = FieldPanel(IdeBundle.message("editbox.export.settings.to"), null, null, null)
internal val exportableComponents: Set<ExportableItem>
get() {
val components = THashSet<ExportableItem>()
for (elementProperties in chooser.markedElements) {
components.addAll(elementProperties.items)
}
return components
}
internal val exportFile: Path
get() = Paths.get(pathPanel.text)
init {
pathPanel.setBrowseButtonActionListener {
chooseSettingsFile(pathPanel.text, window, IdeBundle.message("title.export.file.location"), IdeBundle.message("prompt.choose.export.settings.file.path"))
.onSuccess { path -> pathPanel.text = FileUtil.toSystemDependentName(path) }
}
val componentToContainingListElement = LinkedHashMap<ExportableItem, ComponentElementProperties>()
for (list in fileToComponents.values) {
for (item in list) {
if (!addToExistingListElement(item, componentToContainingListElement, fileToComponents)) {
val componentElementProperties = ComponentElementProperties()
componentElementProperties.items.add(item)
componentToContainingListElement.set(item, componentElementProperties)
}
}
}
chooser = ElementsChooser(true)
chooser.setColorUnmarkedElements(false)
val markedElementNames = markedElementNames
for (componentElementProperty in LinkedHashSet(componentToContainingListElement.values)) {
chooser.addElement(componentElementProperty, markedElementNames.isEmpty() || markedElementNames.contains(componentElementProperty.fileName), componentElementProperty)
}
chooser.sort(Comparator.comparing<ComponentElementProperties, String> { it.toString() })
val exportPath = PropertiesComponent.getInstance().getValue("export.settings.path", DEFAULT_PATH)
pathPanel.text = exportPath
pathPanel.changeListener = Runnable { this.updateControls() }
updateControls()
setTitle(title)
init()
}
private fun updateControls() {
isOKActionEnabled = !StringUtil.isEmptyOrSpaces(pathPanel.text)
}
override fun createLeftSideActions(): Array<Action> {
val selectAll = object : AbstractAction("Select &All") {
override fun actionPerformed(e: ActionEvent) {
chooser.setAllElementsMarked(true)
}
}
val selectNone = object : AbstractAction("Select &None") {
override fun actionPerformed(e: ActionEvent) {
chooser.setAllElementsMarked(false)
}
}
val invert = object : AbstractAction("&Invert") {
override fun actionPerformed(e: ActionEvent) {
chooser.invertSelection()
}
}
return arrayOf(selectAll, selectNone, invert)
}
override fun doOKAction() {
PropertiesComponent.getInstance().setValue("export.settings.path", pathPanel.text, DEFAULT_PATH)
val builder = StringBuilder()
if (chooser.hasUnmarkedElements()) {
val marked = chooser.getElements(true)
for (element in marked) {
builder.append(element.fileName)
builder.append("|")
}
}
PropertiesComponent.getInstance().setValue(KEY_MARKED_NAMES, if (builder.isEmpty()) null else builder.toString())
super.doOKAction()
}
override fun getPreferredFocusedComponent(): JTextField? = pathPanel.textField
override fun createNorthPanel() = JLabel(description)
override fun createCenterPanel(): JComponent = chooser
override fun createSouthPanel(): JComponent {
val buttons = super.createSouthPanel()
if (!isShowFilePath) {
return buttons
}
val panel = JPanel(VerticalFlowLayout())
panel.add(pathPanel)
panel.add(buttons)
return panel
}
override fun getDimensionServiceKey() = "#com.intellij.ide.actions.ChooseComponentsToExportDialog"
}
private class ComponentElementProperties : MultiStateElementsChooser.ElementProperties {
val items = THashSet<ExportableItem>()
val fileName: String
get() = items.first().file.fileName.toString()
override fun toString(): String {
val names = LinkedHashSet<String>()
for ((_, presentableName) in items) {
names.add(presentableName)
}
return StringUtil.join(ArrayUtil.toStringArray(names), ", ")
}
} | apache-2.0 | 4ad71b7698d8b3d0c49fd45a81ed3a71 | 35.497817 | 206 | 0.730286 | 4.72681 | false | false | false | false |
Tickaroo/tikxml | annotationprocessortesting-kt/src/main/java/com/tickaroo/tikxml/regressiontests/TeamDataClass.kt | 1 | 884 | package com.tickaroo.tikxml.regressiontests
import com.tickaroo.tikxml.annotation.Attribute
import com.tickaroo.tikxml.annotation.Xml
/**
* A Element that skips some inner elements
*
* @author Hannes Dorfmann
*/
@Xml(name = "team")
data class TeamDataClass(
@field:Attribute
var id: Int = 0,
@field:Attribute
var countryId: String? = null,
@field:Attribute
var shortName: String? = null,
@field:Attribute
var longName: String? = null,
@field:Attribute
var token: String? = null,
@field:Attribute
var iconSmall: String? = null,
@field:Attribute
var iconBig: String? = null,
@field:Attribute
var defaultLeagueId: Int = 0,
@field:Attribute
var lat: Double = 0.toDouble(),
@field:Attribute
var lng: Double = 0.toDouble()
) | apache-2.0 | 956778eac384562d2831b5547f22d8e2 | 25.818182 | 47 | 0.613122 | 4.092593 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/AddConstModifierFix.kt | 1 | 5327 | // 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.ide.highlighter.JavaFileType
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElementFactory
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiMethodCallExpression
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import org.jetbrains.kotlin.asJava.LightClassUtil
import org.jetbrains.kotlin.descriptors.VariableDescriptor
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.base.util.allScope
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.intentions.SelfTargetingIntention
import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor
import org.jetbrains.kotlin.idea.util.application.runWriteActionIfPhysical
import org.jetbrains.kotlin.idea.util.findAnnotation
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtAnnotationEntry
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.KtReferenceExpression
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.hasActualModifier
import org.jetbrains.kotlin.resolve.checkers.ConstModifierChecker
import org.jetbrains.kotlin.resolve.source.PsiSourceElement
class AddConstModifierFix(property: KtProperty) : AddModifierFixFE10(property, KtTokens.CONST_KEYWORD), CleanupFix {
override fun invokeImpl(project: Project, editor: Editor?, file: PsiFile) {
val property = element as? KtProperty ?: return
addConstModifier(property)
}
companion object {
private val removeAnnotations = listOf(FqName("kotlin.jvm.JvmStatic"), FqName("kotlin.jvm.JvmField"))
fun addConstModifier(property: KtProperty) {
val annotationsToRemove = removeAnnotations.mapNotNull { property.findAnnotation(it) }
replaceReferencesToGetterByReferenceToField(property)
runWriteActionIfPhysical(property) {
property.addModifier(KtTokens.CONST_KEYWORD)
annotationsToRemove.forEach(KtAnnotationEntry::delete)
}
}
}
}
class AddConstModifierIntention : SelfTargetingIntention<KtProperty>(
KtProperty::class.java,
KotlinBundle.lazyMessage("fix.add.const.modifier"),
) {
override fun applyTo(element: KtProperty, editor: Editor?) = AddConstModifierFix.addConstModifier(element)
override fun isApplicableTo(element: KtProperty, caretOffset: Int): Boolean = isApplicableTo(element)
companion object {
fun isApplicableTo(element: KtProperty): Boolean {
with(element) {
if (isLocal || isVar || hasDelegate() || initializer == null
|| getter?.hasBody() == true || receiverTypeReference != null
|| hasModifier(KtTokens.CONST_KEYWORD) || hasModifier(KtTokens.OVERRIDE_KEYWORD) || hasActualModifier()
) {
return false
}
}
val propertyDescriptor = element.descriptor as? VariableDescriptor ?: return false
return ConstModifierChecker.canBeConst(element, element, propertyDescriptor)
}
}
}
object ConstFixFactory : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val expr = diagnostic.psiElement as? KtReferenceExpression ?: return null
val targetDescriptor = expr.resolveToCall()?.resultingDescriptor as? VariableDescriptor ?: return null
val declaration = (targetDescriptor.source as? PsiSourceElement)?.psi as? KtProperty ?: return null
if (ConstModifierChecker.canBeConst(declaration, declaration, targetDescriptor)) {
return AddConstModifierFix(declaration)
}
return null
}
}
fun replaceReferencesToGetterByReferenceToField(property: KtProperty) {
val project = property.project
val getter = LightClassUtil.getLightClassPropertyMethods(property).getter ?: return
val javaScope = GlobalSearchScope.getScopeRestrictedByFileTypes(project.allScope(), JavaFileType.INSTANCE)
val backingField = LightClassUtil.getLightClassPropertyMethods(property).backingField
if (backingField != null) {
val getterUsages = ReferencesSearch.search(getter, javaScope).findAll()
val factory = PsiElementFactory.getInstance(project)
val fieldFQName = backingField.containingClass!!.qualifiedName + "." + backingField.name
runWriteActionIfPhysical(property) {
getterUsages.forEach {
val call = it.element.getNonStrictParentOfType<PsiMethodCallExpression>()
if (call != null && it.element == call.methodExpression) {
val fieldRef = factory.createExpressionFromText(fieldFQName, it.element)
call.replace(fieldRef)
}
}
}
}
}
| apache-2.0 | 0a11628b989448f09ac4b5380ee85e50 | 45.321739 | 158 | 0.73869 | 5.181907 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/extractFunction/controlFlow/outputValues/tooManyOutputValuesAsList.kt | 9 | 752 | // WITH_STDLIB
// SUGGESTED_NAMES: ints, intList, list
// OPTIONS: true, true, false, false, false
// PARAM_TYPES: kotlin.Int
// PARAM_TYPES: kotlin.Int
// PARAM_TYPES: kotlin.Int
// PARAM_TYPES: kotlin.Int
// PARAM_TYPES: kotlin.Int
// PARAM_DESCRIPTOR: var b: kotlin.Int defined in foo
// PARAM_DESCRIPTOR: value-parameter a: kotlin.Int defined in foo
// PARAM_DESCRIPTOR: var c: kotlin.Int defined in foo
// PARAM_DESCRIPTOR: var d: kotlin.Int defined in foo
// PARAM_DESCRIPTOR: var e: kotlin.Int defined in foo
// SIBLING:
fun foo(a: Int): Int {
var b: Int = 1
var c: Int = 1
var d: Int = 1
var e: Int = 1
<selection>b += a
c -= a
d += c
e -= d
println(b)
println(c)</selection>
return b + c + d + e
} | apache-2.0 | f35c2c32eed1e6de75a484a37c23c2ce | 24.965517 | 65 | 0.636968 | 3.2 | false | false | false | false |
securityfirst/Umbrella_android | app/src/main/java/org/secfirst/umbrella/feature/reader/view/feed/FeedLocationDialog.kt | 1 | 2509 | package org.secfirst.umbrella.feature.reader.view.feed
import android.app.AlertDialog
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.ArrayAdapter
import kotlinx.android.synthetic.main.alert_control.view.*
import kotlinx.android.synthetic.main.feed_location_dialog.view.*
import org.secfirst.umbrella.data.database.reader.FeedLocation
import org.secfirst.umbrella.misc.countryList
import org.secfirst.umbrella.misc.countryNames
class FeedLocationDialog(private val feedLocationView: View,
private val feedLocationListener: FeedLocationListener) {
private val context = feedLocationView.context
private val feedLocationAlertDialog: AlertDialog = AlertDialog
.Builder(context)
.setView(feedLocationView)
.create()
init {
initComponent()
startAutocompleteLocation()
}
private fun initComponent() {
feedLocationView.alertControlCancel.setOnClickListener { feedLocationCancel() }
feedLocationView.alertControlOk.setOnClickListener { feedLocationOk() }
}
private fun startAutocompleteLocation() {
val adapter = ArrayAdapter<String>(context, android.R.layout.select_dialog_item, countryNames())
feedLocationView.location.threshold = 2
feedLocationView.location.setAdapter(adapter)
feedLocationView.location.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
})
}
fun show() {
feedLocationAlertDialog.show()
}
private fun feedLocationCancel() {
feedLocationAlertDialog.dismiss()
feedLocationListener.onLocationCancel()
}
private fun feedLocationOk() {
val newLocation = feedLocationView.location.text.toString()
val country = countryList().find { it.name == newLocation }
if (newLocation.isNotBlank() && country != null ) {
val feedLocation = FeedLocation(0, newLocation, country.codeAlpha2)
feedLocationListener.onLocationSuccess(feedLocation)
}
feedLocationAlertDialog.dismiss()
}
interface FeedLocationListener {
fun onLocationSuccess(feedLocation: FeedLocation)
fun onLocationCancel() {}
}
} | gpl-3.0 | 7fcb4254b71767a7ad3a36da98ed1d93 | 36.462687 | 104 | 0.707453 | 4.815739 | false | false | false | false |
devjn/Android-Map-KotlinSample | app/src/main/kotlin/com/github/devjn/kotlinmap/utils/PermissionUtils.kt | 1 | 7418 | package com.github.devjn.kotlinmap.utils
/**
* Created by Emper on 06-Nov-16.
*/
import android.Manifest
import android.app.AlertDialog
import android.app.Dialog
import android.content.DialogInterface
import android.content.pm.PackageManager
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v4.app.DialogFragment
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.widget.Toast
import com.github.devjn.kotlinmap.Common
import com.github.devjn.kotlinmap.R
/**
* Utility class for access to runtime permissions.
*/
object PermissionUtils {
/**
* Requests the fine location permission. If a rationale with an additional explanation should
* be shown to the user, displays a dialog that triggers the request.
*/
fun requestPermission(activity: AppCompatActivity, requestId: Int,
permission: String, finishActivity: Boolean) {
if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)) {
// Display a dialog with rationale.
PermissionUtils.RationaleDialog.newInstance(requestId, finishActivity)
.show(activity.supportFragmentManager, "dialog")
} else {
// Location permission has not been granted yet, request it.
ActivityCompat.requestPermissions(activity, arrayOf(permission), requestId)
}
}
fun requestPermission(activity: AppCompatActivity, requestId: Int, vararg permissions: String) {
ActivityCompat.requestPermissions(activity, permissions, requestId)
}
/**
* Checks if the result contains a [PackageManager.PERMISSION_GRANTED] result for a
* permission from a runtime permissions request.
* @see android.support.v4.app.ActivityCompat.OnRequestPermissionsResultCallback
*/
fun isPermissionGranted(grantPermissions: Array<String>, grantResults: IntArray,
permission: String): Boolean {
for (i in grantPermissions.indices) {
if (permission == grantPermissions[i]) {
return grantResults[i] == PackageManager.PERMISSION_GRANTED
}
}
return false
}
// && ContextCompat.checkSelfPermission(Common.applicationContext, Manifest.permission.ACCESS_COARSE_LOCATION)
// == PackageManager.PERMISSION_GRANTED;
val isLocationGranted: Boolean
get() = ContextCompat.checkSelfPermission(Common.applicationContext, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
val isStorageGranted: Boolean
get() = ContextCompat.checkSelfPermission(Common.applicationContext, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
/**
* A dialog that displays a permission denied message.
*/
class PermissionDeniedDialog : DialogFragment() {
private var mFinishActivity = false
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
mFinishActivity = arguments.getBoolean(ARGUMENT_FINISH_ACTIVITY)
return AlertDialog.Builder(activity)
.setMessage(R.string.location_permission_denied)
.setPositiveButton(android.R.string.ok, null)
.create()
}
override fun onDismiss(dialog: DialogInterface?) {
super.onDismiss(dialog)
if (mFinishActivity) {
Toast.makeText(activity, R.string.permission_required_toast,
Toast.LENGTH_SHORT).show()
activity.finish()
}
}
companion object {
private val ARGUMENT_FINISH_ACTIVITY = "finish"
/**
* Creates a new instance of this dialog and optionally finishes the calling Activity
* when the 'Ok' button is clicked.
*/
fun newInstance(finishActivity: Boolean): PermissionDeniedDialog {
val arguments = Bundle()
arguments.putBoolean(ARGUMENT_FINISH_ACTIVITY, finishActivity)
val dialog = PermissionDeniedDialog()
dialog.arguments = arguments
return dialog
}
}
}
/**
* A dialog that explains the use of the location permission and requests the necessary
* permission.
*
*
* The activity should implement
* [android.support.v4.app.ActivityCompat.OnRequestPermissionsResultCallback]
* to handle permit or denial of this permission request.
*/
class RationaleDialog : DialogFragment() {
private var mFinishActivity = false
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val arguments = arguments
val requestCode = arguments.getInt(ARGUMENT_PERMISSION_REQUEST_CODE)
mFinishActivity = arguments.getBoolean(ARGUMENT_FINISH_ACTIVITY)
return AlertDialog.Builder(activity)
.setMessage(R.string.permission_rationale_location)
.setPositiveButton(android.R.string.ok) { dialog, which ->
// After click on Ok, request the permission.
ActivityCompat.requestPermissions(activity,
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
requestCode)
// Do not finish the Activity while requesting permission.
mFinishActivity = false
}
.setNegativeButton(android.R.string.cancel, null)
.create()
}
override fun onDismiss(dialog: DialogInterface?) {
super.onDismiss(dialog)
if (mFinishActivity) {
Toast.makeText(activity,
R.string.permission_required_toast,
Toast.LENGTH_SHORT)
.show()
activity.finish()
}
}
companion object {
private val ARGUMENT_PERMISSION_REQUEST_CODE = "requestCode"
private val ARGUMENT_FINISH_ACTIVITY = "finish"
/**
* Creates a new instance of a dialog displaying the rationale for the use of the location
* permission.
*
*
* The permission is requested after clicking 'ok'.
* @param requestCode Id of the request that is used to request the permission. It is
* * returned to the
* * [android.support.v4.app.ActivityCompat.OnRequestPermissionsResultCallback].
* *
* @param finishActivity Whether the calling Activity should be finished if the dialog is
* * cancelled.
*/
fun newInstance(requestCode: Int, finishActivity: Boolean): RationaleDialog {
val arguments = Bundle()
arguments.putInt(ARGUMENT_PERMISSION_REQUEST_CODE, requestCode)
arguments.putBoolean(ARGUMENT_FINISH_ACTIVITY, finishActivity)
val dialog = RationaleDialog()
dialog.arguments = arguments
return dialog
}
}
}
}
| gpl-3.0 | 5b082fe6eeb755ad5649e686b3dae131 | 38.248677 | 157 | 0.618226 | 5.598491 | false | false | false | false |
paplorinc/intellij-community | plugins/groovy/src/org/jetbrains/plugins/groovy/console/GroovyConsoleEditorDecorator.kt | 1 | 1507 | // 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.groovy.console
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.openapi.editor.impl.EditorHeaderComponent
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.EditorNotifications.Provider
import org.jetbrains.plugins.groovy.console.GroovyConsoleRootType.EXECUTE_ACTION
import org.jetbrains.plugins.groovy.console.actions.GrSelectModuleAction
import javax.swing.JComponent
class GroovyConsoleEditorDecorator : Provider<JComponent>() {
companion object {
private val myKey = Key.create<JComponent>("groovy.console.toolbar")
}
override fun getKey(): Key<JComponent> = myKey
override fun createNotificationPanel(file: VirtualFile, fileEditor: FileEditor, project: Project): JComponent? {
val consoleService = GroovyConsoleStateService.getInstance(project)
if (!consoleService.isProjectConsole(file)) return null
val actionGroup = DefaultActionGroup(EXECUTE_ACTION, GrSelectModuleAction(project, file))
val menu = ActionManager.getInstance().createActionToolbar("GroovyConsole", actionGroup, true)
return EditorHeaderComponent().apply {
add(menu.component)
}
}
} | apache-2.0 | 91de184f2bc510c0fa3ce22ba0f03b63 | 46.125 | 140 | 0.810219 | 4.55287 | false | false | false | false |
vladmm/intellij-community | java/java-tests/testSrc/com/intellij/testIntergration/RecentTestsTest.kt | 1 | 2846 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testIntergration
import com.intellij.execution.TestStateStorage
import com.intellij.testFramework.UsefulTestCase.*
import com.intellij.testIntegration.RecentTestRunner
import com.intellij.testIntegration.SelectTestStep
import org.junit.Test
import org.mockito.Mockito.mock
import java.util.*
class RecentTestsStepTest {
val runner = mock(RecentTestRunner::class.java)
@Test
fun `suites comes before their children tests`() {
val map: MutableMap<String, TestStateStorage.Record> = hashMapOf()
val now = Date()
map.put("java:suite://JavaFormatterSuperDuperTest", TestStateStorage.Record(1, now))
map.put("java:test://Test.textXXX", TestStateStorage.Record(1, now))
map.put("java:suite://Test", TestStateStorage.Record(1, now))
map.put("java:test://Test.textYYY", TestStateStorage.Record(1, now))
map.put("java:test://Test.textZZZ", TestStateStorage.Record(1, now))
map.put("java:test://JavaFormatterSuperDuperTest.testItMakesMeSadToFixIt", TestStateStorage.Record(1, now))
map.put("java:test://Test.textQQQ", TestStateStorage.Record(1, now))
map.put("java:test://JavaFormatterSuperDuperTest.testUnconditionalAlignmentErrorneous", TestStateStorage.Record(1, now))
val step = SelectTestStep(map, runner)
val expected = listOf(
"java:suite://JavaFormatterSuperDuperTest",
"java:test://JavaFormatterSuperDuperTest.testItMakesMeSadToFixIt",
"java:test://JavaFormatterSuperDuperTest.testUnconditionalAlignmentErrorneous",
"java:suite://Test",
"java:test://Test.textQQQ",
"java:test://Test.textXXX",
"java:test://Test.textYYY",
"java:test://Test.textZZZ"
)
assertContainsOrdered(step.values, expected)
assertSize(8, step.values)
}
@Test
fun `shown value without protocol`() {
val step = SelectTestStep(emptyMap(), runner)
var shownValue = step.getTextFor("java:suite://JavaFormatterSuperDuperTest")
assertEquals(shownValue, "JavaFormatterSuperDuperTest")
shownValue = step.getTextFor("java:test://JavaFormatterSuperDuperTest.testItMakesMeSadToFixIt")
assertEquals(shownValue, "JavaFormatterSuperDuperTest.testItMakesMeSadToFixIt")
}
} | apache-2.0 | 5e98b859791f7a2230473b85ca09a412 | 40.26087 | 126 | 0.734013 | 3.789614 | false | true | false | false |
GreyTeardrop/jwt-tool | src/main/java/com/github/greyteardrop/jwt/ConsoleUI.kt | 1 | 2023 | package com.github.greyteardrop.jwt
import com.github.greyteardrop.jwt.CreateCommand.PayloadKeys.emailKey
import java.io.InputStream
import java.io.PrintStream
/**
* Manages console UI loop.
*/
class ConsoleUI(private val commandExecutor: CommandExecutor,
stdIn: InputStream = System.`in`,
private val stdOut: PrintStream = System.out) {
private val reader = stdIn.bufferedReader()
/**
* Start console UI loop, wait for user-entered parameters
*/
fun run() {
var command = CreateCommand(exportToClipboard = true)
var i = 0
stdOut.println("Starting with JWT token generation. Enter blank line to finish.")
stdOut.flush()
while (true) {
i++
stdOut.println("Enter key $i")
stdOut.print("$ ")
stdOut.flush()
val key = reader.readLine()
if (key.isNullOrEmpty()) {
executeCommand(command)
// TODO: option to execute multiple commands in a loop
return
}
do {
stdOut.println("Enter $key value")
stdOut.print("> $key = ")
stdOut.flush()
val value = reader.readLine()
if (isValidPayload(key, value)) {
command = command.withPayload(key, value)
break
}
else {
stdOut.print("Invalid $key entered! ")
}
}
while (true)
}
}
private fun executeCommand(command: CreateCommand) {
try {
commandExecutor.execute(command)
}
catch (e: UserException) {
// TODO: option to fix errors and continue
throw e
}
}
private fun isValidPayload(key: String, value: String?): Boolean = when (key) {
emailKey -> value != null && EmailValidator.isValidEmail(value)
else -> true
}
}
| mit | 073ab7b96624bfc343b186878b602ffd | 28.318841 | 89 | 0.529412 | 4.851319 | false | false | false | false |
google/intellij-community | platform/collaboration-tools/src/com/intellij/collaboration/api/graphql/GraphQLApiClient.kt | 5 | 2874 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.collaboration.api.graphql
import com.intellij.collaboration.api.HttpApiClient
import com.intellij.collaboration.api.dto.GraphQLRequestDTO
import com.intellij.collaboration.api.httpclient.ByteArrayProducingBodyPublisher
import com.intellij.collaboration.api.httpclient.HttpClientUtil
import com.intellij.collaboration.api.httpclient.StreamReadingBodyHandler
import java.io.InputStream
import java.net.URI
import java.net.http.HttpRequest
import java.net.http.HttpResponse
abstract class GraphQLApiClient : HttpApiClient() {
abstract val gqlQueryLoader: CachingGraphQLQueryLoader
abstract val gqlSerializer: GraphQLDataSerializer
fun gqlQuery(uri: URI, queryPath: String, variablesObject: Any? = null): HttpRequest {
val publisher = object : ByteArrayProducingBodyPublisher() {
override fun produceBytes(): ByteArray {
logger.debug("Request POST $uri")
val query = gqlQueryLoader.loadQuery(queryPath)
val request = GraphQLRequestDTO(query, variablesObject)
if (logger.isTraceEnabled) {
logger.trace("Request POST $uri : Request body: " + gqlSerializer.toJson(request))
}
return gqlSerializer.toJsonBytes(request)
}
}
return request(uri)
.POST(publisher)
.header(HttpClientUtil.CONTENT_TYPE_HEADER, HttpClientUtil.CONTENT_TYPE_JSON)
.build()
}
suspend fun <T> loadGQLResponse(request: HttpRequest, clazz: Class<T>, vararg pathFromData: String): HttpResponse<T?> {
return sendAndAwaitCancellable(request, gqlBodyHandler(request, pathFromData, clazz))
}
suspend inline fun <reified T> loadGQLResponse(request: HttpRequest, vararg pathFromData: String)
: HttpResponse<T?> = loadGQLResponse(request, T::class.java, *pathFromData)
fun <T> gqlBodyHandler(request: HttpRequest, pathFromData: Array<out String>, clazz: Class<T>): HttpResponse.BodyHandler<T?> =
object : StreamReadingBodyHandler<T?>(request) {
override fun read(bodyStream: InputStream): T? {
logger.debug("${request.logName()} : Success")
if (logger.isTraceEnabled) {
val body = bodyStream.reader().readText()
logger.trace("${request.logName()} : Response body: $body")
return gqlSerializer.readAndTraverseGQLResponse(body, pathFromData, clazz)
}
return gqlSerializer.readAndTraverseGQLResponse(bodyStream, pathFromData, clazz)
}
override fun handleError(statusCode: Int, errorBody: String): Nothing {
logger.debug("${request.logName()} : Error ${statusCode}")
if (logger.isTraceEnabled) {
logger.trace("${request.logName()} : Response body: $errorBody")
}
super.handleError(statusCode, errorBody)
}
}
}
| apache-2.0 | 66bbedc86335184724a9eea82423c6bb | 41.264706 | 128 | 0.724774 | 4.347958 | false | false | false | false |
JetBrains/intellij-community | platform/feedback/src/com/intellij/feedback/common/NewGeneralFeedbackSubmit.kt | 1 | 7068 | // 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.feedback
import com.intellij.feedback.common.FeedbackRequestType
import com.intellij.feedback.common.getProductTag
import com.intellij.feedback.common.notification.ThanksForFeedbackNotification
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.util.io.HttpRequests
import com.intellij.util.io.HttpRequests.JSON_CONTENT_TYPE
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
import java.io.IOException
import java.net.HttpURLConnection
import javax.net.ssl.HttpsURLConnection
private const val TEST_FEEDBACK_URL = "https://forms-stgn.w3jbcom-nonprod.aws.intellij.net/feedback"
private const val PRODUCTION_FEEDBACK_URL = "https://forms-service.jetbrains.com/feedback"
private const val FEEDBACK_FORM_ID_ONLY_DATA = "feedback/ide"
private const val FEEDBACK_FORM_ID_WITH_DETAILED_ANSWER = "feedback/ide_with_detailed_answer"
private const val FEEDBACK_FROM_ID_KEY = "formid"
private const val FEEDBACK_INTELLIJ_PRODUCT_KEY = "intellij_product"
private const val FEEDBACK_TYPE_KEY = "feedback_type"
private const val FEEDBACK_PRIVACY_CONSENT_KEY = "privacy_consent"
private const val FEEDBACK_PRIVACY_CONSENT_TYPE_KEY = "privacy_consent_type"
private const val FEEDBACK_COLLECTED_DATA_KEY = "collected_data"
private const val FEEDBACK_EMAIL_KEY = "email"
private const val FEEDBACK_SUBJECT_KEY = "subject"
private const val FEEDBACK_COMMENT_KEY = "comment"
private const val REQUEST_ID_KEY = "Request-Id"
private val LOG = Logger.getInstance(FeedbackRequestDataHolder::class.java)
sealed interface FeedbackRequestDataHolder {
val feedbackType: String
val collectedData: JsonObject
val privacyConsentType: String?
fun toJsonObject(): JsonObject
}
/**
* Feedback request data for answers that do not include a detailed answer and the user's email.
* Sent to WebTeam Backend and stored only on AWS S3.
*
* [privacyConsentType] is only required if the feedback contains personal data or system data. Otherwise, pass null.
*/
data class FeedbackRequestData(override val feedbackType: String,
override val collectedData: JsonObject,
override val privacyConsentType: String?) : FeedbackRequestDataHolder {
override fun toJsonObject(): JsonObject {
return buildJsonObject {
put(FEEDBACK_FROM_ID_KEY, FEEDBACK_FORM_ID_ONLY_DATA)
put(FEEDBACK_INTELLIJ_PRODUCT_KEY, getProductTag())
put(FEEDBACK_TYPE_KEY, feedbackType)
if (privacyConsentType != null) {
put(FEEDBACK_PRIVACY_CONSENT_KEY, true)
put(FEEDBACK_PRIVACY_CONSENT_TYPE_KEY, privacyConsentType)
}
else {
put(FEEDBACK_PRIVACY_CONSENT_KEY, false)
}
put(FEEDBACK_COLLECTED_DATA_KEY, collectedData)
}
}
}
/**
* Feedback request data for answers that include a detailed answer and the user's email.
* Sent to WebTeam Backend. Stored on the AWS S3 and also submit ticket to Zendesk.
* The created ticket will not be closed immediately, and it is assumed that a support specialist will look at it.
*/
data class FeedbackRequestDataWithDetailedAnswer(val email: String,
val title: String,
val description: String,
override val feedbackType: String,
override val collectedData: JsonObject,
override val privacyConsentType: String) : FeedbackRequestDataHolder {
override fun toJsonObject(): JsonObject {
return buildJsonObject {
put(FEEDBACK_FROM_ID_KEY, FEEDBACK_FORM_ID_WITH_DETAILED_ANSWER)
put(FEEDBACK_EMAIL_KEY, email)
put(FEEDBACK_SUBJECT_KEY, title)
put(FEEDBACK_COMMENT_KEY, description)
put(FEEDBACK_INTELLIJ_PRODUCT_KEY, getProductTag())
put(FEEDBACK_TYPE_KEY, feedbackType)
put(FEEDBACK_PRIVACY_CONSENT_KEY, true)
put(FEEDBACK_PRIVACY_CONSENT_TYPE_KEY, privacyConsentType)
put(FEEDBACK_COLLECTED_DATA_KEY, collectedData)
}
}
}
fun submitFeedback(project: Project?,
feedbackData: FeedbackRequestDataHolder,
onDone: () -> Unit,
onError: () -> Unit,
feedbackRequestType: FeedbackRequestType = FeedbackRequestType.TEST_REQUEST,
showNotification: Boolean = true) {
ApplicationManager.getApplication().executeOnPooledThread {
val feedbackUrl = when (feedbackRequestType) {
FeedbackRequestType.NO_REQUEST -> return@executeOnPooledThread
FeedbackRequestType.TEST_REQUEST -> TEST_FEEDBACK_URL
FeedbackRequestType.PRODUCTION_REQUEST -> PRODUCTION_FEEDBACK_URL
}
sendFeedback(feedbackUrl, feedbackData, onDone, onError)
}
if (showNotification) {
ApplicationManager.getApplication().invokeLater {
ThanksForFeedbackNotification().notify(project)
}
}
}
private fun sendFeedback(feedbackUrl: String,
feedbackData: FeedbackRequestDataHolder,
onDone: () -> Unit,
onError: () -> Unit) {
val requestData = feedbackData.toJsonObject().toString()
try {
HttpRequests
.post(feedbackUrl, JSON_CONTENT_TYPE)
.productNameAsUserAgent()
.accept("application/json")
.connect {
try {
it.write(requestData)
val connection = it.connection
if (connection is HttpsURLConnection && connection.responseCode != 200) {
val requestId = it.connection.getHeaderField(REQUEST_ID_KEY)
val errorResponse = it.readError()
LOG.info("Failed to submit feedback. Feedback data:\n$requestData\nStatus code:${connection.responseCode}\n" +
"Server response:${errorResponse}\nRequest ID:${requestId}")
onError()
return@connect
}
val bytes = it.inputStream.readAllBytes()
LOG.info(bytes.toString(Charsets.UTF_8))
val requestId = it.connection.getHeaderField(REQUEST_ID_KEY)
LOG.info("Feedback submitted successfully. Record ID is ${requestId}")
}
catch (e: IOException) {
val errorResponse = (it.connection as HttpURLConnection).errorStream.readAllBytes().toString(Charsets.UTF_8)
LOG.info("Failed to submit feedback. Feedback data:\n$requestData\nServer response:\n$errorResponse\n" +
"Exception message: ${e.message}")
onError()
return@connect
}
onDone()
}
}
catch (e: IOException) {
LOG.info("Failed to submit feedback. Feedback data:\n$requestData\nError message:\n${e.message}")
onError()
return
}
} | apache-2.0 | 2aa91cd3a15dd8892ec686b6a72b02e8 | 41.584337 | 122 | 0.685767 | 4.545338 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/base/analysis/src/org/jetbrains/kotlin/idea/search/usagesSearch/ExpressionsOfTypeProcessor.kt | 1 | 40791 | // 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.search.usagesSearch
import com.intellij.ide.highlighter.JavaFileType
import com.intellij.ide.highlighter.XmlFileType
import com.intellij.lang.java.JavaLanguage
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.psi.*
import com.intellij.psi.impl.source.resolve.reference.impl.PsiMultiReference
import com.intellij.psi.search.*
import com.intellij.psi.search.searches.ClassInheritorsSearch
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.util.Processor
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.KtNodeTypes
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.diagnostics.PsiDiagnosticUtils
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.idea.base.psi.kotlinFqName
import org.jetbrains.kotlin.idea.base.util.everythingScopeExcludeFileTypes
import org.jetbrains.kotlin.idea.base.util.excludeFileTypes
import org.jetbrains.kotlin.idea.base.util.restrictToKotlinSources
import org.jetbrains.kotlin.idea.references.KtDestructuringDeclarationReference
import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport.Companion.hasType
import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport.Companion.isInProjectSource
import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport.Companion.isSamInterface
import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchOptions
import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchParameters
import org.jetbrains.kotlin.idea.base.util.useScope
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import org.jetbrains.kotlin.idea.util.application.withPsiAttachment
import org.jetbrains.kotlin.kdoc.psi.impl.KDocName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments
import java.util.*
//TODO: check if smart search is too expensive
class ExpressionsOfTypeProcessor(
private val containsTypeOrDerivedInside: (KtDeclaration) -> Boolean,
private val classToSearch: PsiClass?,
private val searchScope: SearchScope,
private val project: Project,
private val possibleMatchHandler: (KtExpression) -> Unit,
private val possibleMatchesInScopeHandler: (SearchScope) -> Unit
) {
/** For tests only */
enum class Mode {
ALWAYS_SMART,
ALWAYS_PLAIN,
PLAIN_WHEN_NEEDED // use plain search for LocalSearchScope and when unknown type of reference encountered
}
companion object {
@get:TestOnly
var mode = Mode.ALWAYS_SMART
@TestOnly
fun prodMode() {
mode = Mode.PLAIN_WHEN_NEEDED
}
@TestOnly
fun resetMode() {
mode = if (isUnitTestMode()) Mode.ALWAYS_SMART else Mode.PLAIN_WHEN_NEEDED
}
@get:TestOnly
var testLog: MutableCollection<String>? = null
inline fun testLog(s: () -> String) {
testLog?.add(s())
}
val LOG = Logger.getInstance(ExpressionsOfTypeProcessor::class.java)
fun logPresentation(element: PsiElement): String? {
return runReadAction {
if (element !is KtDeclaration && element !is PsiMember) return@runReadAction element.text
val fqName = element.kotlinFqName?.asString()
?: (element as? KtNamedDeclaration)?.name
when (element) {
is PsiMethod -> fqName + element.parameterList.text
is KtFunction -> fqName + element.valueParameterList!!.text
is KtParameter -> {
val owner = element.ownerFunction?.let { logPresentation(it) } ?: element.parent.toString()
"parameter ${element.name} of $owner"
}
is KtDestructuringDeclaration -> element.entries.joinToString(", ", prefix = "(", postfix = ")") { it.text }
else -> fqName
}
}
}
private fun PsiModifierListOwner.isPrivate() = hasModifierProperty(PsiModifier.PRIVATE)
private fun PsiModifierListOwner.isLocal() = parents.any { it is PsiCodeBlock }
}
// note: a Task must define equals & hashCode!
private interface Task {
fun perform()
}
private val tasks = ArrayDeque<Task>()
private val taskSet = HashSet<Task>()
private val scopesToUsePlainSearch = LinkedHashMap<KtFile, ArrayList<PsiElement>>()
fun run() {
val usePlainSearch = when (mode) {
Mode.ALWAYS_SMART -> false
Mode.ALWAYS_PLAIN -> true
Mode.PLAIN_WHEN_NEEDED -> searchScope is LocalSearchScope // for local scope it's faster to use plain search
}
if (usePlainSearch || classToSearch == null) {
possibleMatchesInScopeHandler(searchScope)
return
}
// optimization
if (runReadAction {
searchScope is GlobalSearchScope && !FileTypeIndex.containsFileOfType(
KotlinFileType.INSTANCE,
searchScope
)
}) return
// for class from library always use plain search because we cannot search usages in compiled code (we could though)
if (!runReadAction { classToSearch.isValid && isInProjectSource(classToSearch) }) {
possibleMatchesInScopeHandler(searchScope)
return
}
addClassToProcess(classToSearch)
processTasks()
runReadAction {
val scopeElements = scopesToUsePlainSearch.values
.flatten()
.filter { it.isValid }
.toTypedArray()
if (scopeElements.isNotEmpty()) {
possibleMatchesInScopeHandler(LocalSearchScope(scopeElements))
}
}
}
private fun addTask(task: Task) {
if (taskSet.add(task)) {
tasks.push(task)
}
}
private fun processTasks() {
while (tasks.isNotEmpty()) {
tasks.pop().perform()
}
}
private fun downShiftToPlainSearch(reference: PsiReference) {
val message = getFallbackDiagnosticsMessage(reference)
LOG.info("ExpressionsOfTypeProcessor: $message")
testLog { "Downgrade to plain text search: $message" }
tasks.clear()
scopesToUsePlainSearch.clear()
possibleMatchesInScopeHandler(searchScope)
}
private fun checkPsiClass(psiClass: PsiClass): Boolean {
// we don't filter out private classes because we can inherit public class from private inside the same visibility scope
if (psiClass.isLocal()) {
return false
}
val qualifiedName = runReadAction { psiClass.qualifiedName }
if (qualifiedName.isNullOrEmpty()) {
return false
}
return true
}
private fun addNonKotlinClassToProcess(classToSearch: PsiClass) {
if (!checkPsiClass(classToSearch)) {
return
}
addClassToProcess(classToSearch)
}
private fun addClassToProcess(classToSearch: PsiClass) {
data class ProcessClassUsagesTask(val classToSearch: PsiClass) : Task {
override fun perform() {
val debugInfo: StringBuilder? = if (isUnitTestMode()) StringBuilder() else null
testLog { "Searched references to ${logPresentation(classToSearch)}" }
debugInfo?.apply { append("Searched references to ").append(logPresentation(classToSearch)) }
val scope = project.everythingScopeExcludeFileTypes(XmlFileType.INSTANCE) // ignore usages in XML - they don't affect us
searchReferences(classToSearch, scope) { reference ->
val element = reference.element
val language = element.language
debugInfo?.apply { append(", found reference element [$language]: $element") }
val wasProcessed = when (language) {
KotlinLanguage.INSTANCE -> processClassUsageInKotlin(element, debugInfo)
JavaLanguage.INSTANCE -> processClassUsageInJava(element)
else -> {
when (language.displayName) {
"Groovy" -> {
processClassUsageInLanguageWithPsiClass(element)
true
}
"Scala" -> false
"Clojure" -> false
else -> {
// If there's no PsiClass - consider processed
element.getParentOfType<PsiClass>(true) == null
}
}
}
}
if (wasProcessed) return@searchReferences true
if (mode != Mode.ALWAYS_SMART) {
downShiftToPlainSearch(reference)
return@searchReferences false
}
throw KotlinExceptionWithAttachments("Unsupported reference")
.withPsiAttachment("reference.txt", element)
.withAttachment("diagnostic_message.txt", getFallbackDiagnosticsMessage(reference, debugInfo))
}
// we must use plain search inside our class (and inheritors) because implicit 'this' can happen anywhere
(classToSearch as? KtLightClass)?.kotlinOrigin?.let { usePlainSearch(it) }
}
}
addTask(ProcessClassUsagesTask(classToSearch))
}
private fun getFallbackDiagnosticsMessage(reference: PsiReference, debugInfo: StringBuilder? = null): String {
val element = reference.element
val document = PsiDocumentManager.getInstance(project).getDocument(element.containingFile)
val lineAndCol = PsiDiagnosticUtils.offsetToLineAndColumn(document, element.startOffset)
return "Unsupported reference: '${element.text}' in ${element.containingFile.virtualFile} [${element.language}] " +
"line ${lineAndCol.line} column ${lineAndCol.column}${debugInfo?.let {" .$it"} ?: ""}"
}
private enum class ReferenceProcessor(val handler: (ExpressionsOfTypeProcessor, PsiReference) -> Boolean) {
CallableOfOurType(ExpressionsOfTypeProcessor::processReferenceToCallableOfOurType),
ProcessLambdasInCalls({ processor, reference ->
(reference.element as? KtReferenceExpression)?.let { processor.processLambdasForCallableReference(it) }
true
})
}
private class StaticMemberRequestResultProcessor(val psiMember: PsiMember, classes: List<PsiClass>) :
RequestResultProcessor(psiMember) {
val possibleClassesNames: Set<String> = runReadAction { classes.map { it.qualifiedName }.filterNotNullTo(HashSet()) }
override fun processTextOccurrence(element: PsiElement, offsetInElement: Int, consumer: Processor<in PsiReference>): Boolean {
when (element) {
is KtQualifiedExpression -> {
val selectorExpression = element.selectorExpression ?: return true
val selectorReference = element.findReferenceAt(selectorExpression.startOffsetInParent)
val references = when (selectorReference) {
is PsiMultiReference -> selectorReference.references.toList()
else -> listOf(selectorReference)
}.filterNotNull()
for (ref in references) {
ProgressManager.checkCanceled()
if (ref.isReferenceTo(psiMember)) {
consumer.process(ref)
}
}
}
is KtImportDirective -> {
if (element.isAllUnder) {
val fqName = element.importedFqName?.asString()
if (fqName != null && fqName in possibleClassesNames) {
val ref = element.importedReference
?.getQualifiedElementSelector()
?.references
?.firstOrNull()
if (ref != null) {
consumer.process(ref)
}
}
}
}
}
return true
}
}
private fun classUseScope(psiClass: PsiClass) = runReadAction {
if (!psiClass.isValid) {
throw ProcessCanceledException()
}
psiClass.containingFile?.useScope() ?: psiClass.useScope()
}
private fun addStaticMemberToProcess(psiMember: PsiMember, scope: SearchScope, processor: ReferenceProcessor) {
val declarationClass = runReadAction { psiMember.containingClass } ?: return
val declarationName = runReadAction { psiMember.name } ?: return
if (declarationName.isEmpty()) return
data class ProcessStaticCallableUsagesTask(
val member: PsiMember,
val memberScope: SearchScope,
val taskProcessor: ReferenceProcessor
) : Task {
override fun perform() {
// This class will look through the whole hierarchy anyway, so shouldn't be a big overhead here
val inheritanceClasses = ClassInheritorsSearch.search(
declarationClass,
classUseScope(declarationClass),
true, true, false
).findAll()
val classes = (inheritanceClasses + declarationClass).filter { it !is KtLightClass }
val searchRequestCollector = SearchRequestCollector(SearchSession())
val resultProcessor = StaticMemberRequestResultProcessor(member, classes)
val memberName = runReadAction { member.name }
for (klass in classes) {
val request = runReadAction { klass.name } + "." + declarationName
testLog { "Searched references to static $memberName in non-Java files by request $request" }
searchRequestCollector.searchWord(
request,
classUseScope(klass).intersectWith(memberScope), UsageSearchContext.IN_CODE, true, member, resultProcessor
)
val qualifiedName = runReadAction { klass.qualifiedName }
if (qualifiedName != null) {
val importAllUnderRequest = "$qualifiedName.*"
testLog { "Searched references to static $memberName in non-Java files by request $importAllUnderRequest" }
searchRequestCollector.searchWord(
importAllUnderRequest,
classUseScope(klass).intersectWith(memberScope), UsageSearchContext.IN_CODE, true, member, resultProcessor
)
}
}
PsiSearchHelper.getInstance(project).processRequests(searchRequestCollector) { reference ->
if (reference.element.parents.any { it is KtImportDirective }) {
// Found declaration in import - process all file with an ordinal reference search
val containingFile = reference.element.containingFile
addCallableDeclarationToProcess(member, LocalSearchScope(containingFile), taskProcessor)
true
} else {
val processed = taskProcessor.handler(this@ExpressionsOfTypeProcessor, reference)
if (!processed) { // we don't know how to handle this reference and down-shift to plain search
downShiftToPlainSearch(reference)
}
true
}
}
}
}
addTask(ProcessStaticCallableUsagesTask(psiMember, scope, processor))
return
}
private fun addCallableDeclarationToProcess(declaration: PsiElement, scope: SearchScope, processor: ReferenceProcessor) {
if (scope !is LocalSearchScope && declaration is PsiMember &&
(declaration.modifierList?.hasModifierProperty(PsiModifier.STATIC) == true)
) {
addStaticMemberToProcess(declaration, scope, processor)
return
}
data class ProcessCallableUsagesTask(
val declaration: PsiElement,
val processor: ReferenceProcessor,
val scope: SearchScope
) : Task {
override fun perform() {
if (scope is LocalSearchScope) {
testLog { runReadAction { "Searched imported static member $declaration in ${scope.scope.toList()}" } }
} else {
testLog { runReadAction { "Searched references to ${logPresentation(declaration)} in non-Java files" } }
}
val searchParameters = KotlinReferencesSearchParameters(
declaration, scope, kotlinOptions = KotlinReferencesSearchOptions(searchNamedArguments = false)
)
searchReferences(searchParameters) { reference ->
val processed = processor.handler(this@ExpressionsOfTypeProcessor, reference)
if (!processed) { // we don't know how to handle this reference and down-shift to plain search
downShiftToPlainSearch(reference)
}
processed
}
}
}
addTask(ProcessCallableUsagesTask(declaration, processor, scope))
}
private fun addPsiMemberTask(member: PsiMember) {
if (!member.isPrivate() && !member.isLocal()) {
addCallableDeclarationOfOurType(member)
}
}
private fun addCallableDeclarationOfOurType(declaration: PsiElement) {
addCallableDeclarationToProcess(declaration, searchScope.restrictToKotlinSources(), ReferenceProcessor.CallableOfOurType)
}
/**
* Process references to declaration which has parameter of functional type with our class used inside
*/
private fun addCallableDeclarationToProcessLambdasInCalls(declaration: PsiElement) {
// we don't need to search usages of declarations in Java because Java doesn't have implicitly typed declarations so such usages cannot affect Kotlin code
val scope = GlobalSearchScope.projectScope(project).excludeFileTypes(project, JavaFileType.INSTANCE, XmlFileType.INSTANCE)
addCallableDeclarationToProcess(declaration, scope, ReferenceProcessor.ProcessLambdasInCalls)
}
/**
* Process reference to declaration whose type is our class (or our class used anywhere inside that type)
*/
private fun processReferenceToCallableOfOurType(reference: PsiReference) = when (reference.element.language) {
KotlinLanguage.INSTANCE -> {
if (reference is KtDestructuringDeclarationReference) {
// declaration usage in form of destructuring declaration entry
addCallableDeclarationOfOurType(reference.element)
} else {
(reference.element as? KtReferenceExpression)?.let { processSuspiciousExpression(it) }
}
true
}
else -> false // reference in unknown language - we don't know how to handle it
}
private fun addSamInterfaceToProcess(psiClass: PsiClass) {
if (!checkPsiClass(psiClass)) {
return
}
data class ProcessSamInterfaceTask(val psiClass: PsiClass) : Task {
override fun perform() {
val scope = GlobalSearchScope.projectScope(project).excludeFileTypes(project, KotlinFileType.INSTANCE, XmlFileType.INSTANCE)
testLog { "Searched references to ${logPresentation(psiClass)} in non-Kotlin files" }
searchReferences(psiClass, scope) { reference ->
// reference in some JVM language can be method parameter (but we don't know)
if (reference.element.language != JavaLanguage.INSTANCE) {
downShiftToPlainSearch(reference)
return@searchReferences false
}
// check if the reference is method parameter type
val parameter = ((reference as? PsiJavaCodeReferenceElement)?.parent as? PsiTypeElement)?.parent as? PsiParameter
val method = parameter?.declarationScope as? PsiMethod
if (method != null) {
addCallableDeclarationToProcessLambdasInCalls(method)
}
true
}
}
}
addTask(ProcessSamInterfaceTask(psiClass))
}
private fun processClassUsageInKotlin(element: PsiElement, debugInfo: StringBuilder?): Boolean {
//TODO: type aliases
when (element) {
is KtReferenceExpression -> {
val elementParent = element.parent
debugInfo?.apply { append(", elementParent: $elementParent") }
when (elementParent) {
is KtUserType -> { // usage in type
val userTypeParent = elementParent.parent
if (userTypeParent is KtUserType && userTypeParent.qualifier == elementParent) {
return true // type qualifier
}
return processClassUsageInUserType(elementParent)
}
is KtCallExpression -> {
debugInfo?.apply { append(", KtCallExpression condition: ${element == elementParent.calleeExpression}") }
if (element == elementParent.calleeExpression) { // constructor or invoke operator invocation
processSuspiciousExpression(element)
return true
}
}
is KtContainerNode -> {
if (elementParent.node.elementType == KtNodeTypes.LABEL_QUALIFIER) {
return true // this@ClassName - it will be handled anyway because members and extensions are processed with plain search
}
}
is KtQualifiedExpression -> {
// <class name>.memberName or some.<class name>.memberName or some.<class name>::class
if (element == elementParent.receiverExpression ||
elementParent.parent is KtQualifiedExpression ||
elementParent.parent is KtClassLiteralExpression
) {
return true // companion object member or static member access - ignore it
}
}
is KtCallableReferenceExpression -> {
when (element) {
elementParent.receiverExpression -> { // usage in receiver of callable reference (before "::") - ignore it
return true
}
elementParent.callableReference -> { // usage after "::" in callable reference - should be reference to constructor of our class
processSuspiciousExpression(element)
return true
}
}
}
is KtClassLiteralExpression -> {
if (element == elementParent.receiverExpression) { // <class name>::class
processSuspiciousExpression(element)
return true
}
}
}
if (element.getStrictParentOfType<KtImportDirective>() != null) return true // ignore usage in import
if (element.hasType) { // access to object or companion object
processSuspiciousExpression(element)
return true
}
}
is KDocName -> return true // ignore usage in doc-comment
}
return false // unsupported type of reference
}
private fun processClassUsageInUserType(userType: KtUserType): Boolean {
val typeRef = userType.parents.lastOrNull { it is KtTypeReference }
when (val typeRefParent = typeRef?.parent) {
// TODO: type alias
//is KtTypeAlias -> {}
is KtCallableDeclaration -> {
when (typeRef) {
typeRefParent.typeReference -> { // usage in type of callable declaration
addCallableDeclarationOfOurType(typeRefParent)
if (typeRefParent is KtParameter) { //TODO: what if functional type is declared with "FunctionN<...>"?
val usedInsideFunctionalType = userType.parents.takeWhile { it != typeRef }.any { it is KtFunctionType }
if (usedInsideFunctionalType) {
val function = (typeRefParent.parent as? KtParameterList)?.parent as? KtFunction
if (function != null) {
addCallableDeclarationOfOurType(function)
}
}
}
return true
}
typeRefParent.receiverTypeReference -> { // usage in receiver type of callable declaration
// we must use plain search inside extensions because implicit 'this' can happen anywhere
usePlainSearch(typeRefParent)
return true
}
}
}
is KtTypeProjection -> { // usage in type arguments of a call
val callExpression = (typeRefParent.parent as? KtTypeArgumentList)?.parent as? KtCallExpression
if (callExpression != null) {
processSuspiciousExpression(callExpression)
return true
}
}
is KtConstructorCalleeExpression -> { // super-class name in the list of bases
val parent = typeRefParent.parent
if (parent is KtSuperTypeCallEntry) {
val classOrObject = (parent.parent as KtSuperTypeList).parent as KtClassOrObject
val psiClass = classOrObject.toLightClass()
psiClass?.let { addClassToProcess(it) }
return true
}
}
is KtSuperTypeListEntry -> { // super-interface name in the list of bases
if (typeRef == typeRefParent.typeReference) {
val classOrObject = (typeRefParent.parent as KtSuperTypeList).parent as KtClassOrObject
val psiClass = classOrObject.toLightClass()
psiClass?.let { addClassToProcess(it) }
return true
}
}
is KtIsExpression -> { // <expr> is <class name>
val scopeOfPossibleSmartCast = typeRefParent.getParentOfType<KtDeclarationWithBody>(true)
scopeOfPossibleSmartCast?.let { usePlainSearch(it) }
return true
}
is KtWhenConditionIsPattern -> { // "is <class name>" or "!is <class name>" in when
val whenEntry = typeRefParent.parent as KtWhenEntry
if (typeRefParent.isNegated) {
val whenExpression = whenEntry.parent as KtWhenExpression
val entriesAfter = whenExpression.entries.dropWhile { it != whenEntry }.drop(1)
entriesAfter.forEach { usePlainSearch(it) }
} else {
usePlainSearch(whenEntry)
}
return true
}
is KtBinaryExpressionWithTypeRHS -> { // <expr> as <class name>
processSuspiciousExpression(typeRefParent)
return true
}
is KtTypeParameter -> { // <expr> as `<reified T : ClassName>`
typeRefParent.extendsBound?.let {
addCallableDeclarationOfOurType(it)
return true
}
}
}
return false // unsupported case
}
private fun processClassUsageInJava(element: PsiElement): Boolean {
if (element !is PsiJavaCodeReferenceElement) return true // meaningless reference from Java
var prev = element
ParentsLoop@
for (parent in element.parents) {
when (parent) {
is PsiCodeBlock,
is PsiExpression ->
break@ParentsLoop // ignore local usages
is PsiMethod -> {
if (prev == parent.returnTypeElement) { // usage in return type of a method
addPsiMemberTask(parent)
}
break@ParentsLoop
}
is PsiField -> {
if (prev == parent.typeElement) { // usage in type of a field
addPsiMemberTask(parent)
}
break@ParentsLoop
}
is PsiReferenceList -> { // usage in extends/implements list
if (parent.role == PsiReferenceList.Role.EXTENDS_LIST || parent.role == PsiReferenceList.Role.IMPLEMENTS_LIST) {
val psiClass = parent.parent as PsiClass
addNonKotlinClassToProcess(psiClass)
}
break@ParentsLoop
}
//TODO: if Java parameter has Kotlin functional type then we should process method usages
is PsiParameter -> {
if (prev == parent.typeElement) { // usage in parameter type - check if the method is in SAM interface
processParameterInSamClass(parent)
}
break@ParentsLoop
}
}
prev = parent
}
return true
}
private fun processClassUsageInLanguageWithPsiClass(element: PsiElement) {
fun checkReferenceInTypeElement(typeElement: PsiTypeElement?, element: PsiElement): Boolean {
val typeTextRange = typeElement?.textRange
return (typeTextRange != null && element.textRange in typeTextRange)
}
fun processParameter(parameter: PsiParameter): Boolean {
if (checkReferenceInTypeElement(parameter.typeElement, element)) {
processParameterInSamClass(parameter)
return true
}
return false
}
fun processMethod(method: PsiMethod): Boolean {
if (checkReferenceInTypeElement(method.returnTypeElement, element)) {
addPsiMemberTask(method)
return true
}
val parameters = method.parameterList.parameters
for (parameter in parameters) {
if (processParameter(parameter)) {
return true
}
}
return false
}
fun processField(field: PsiField): Boolean {
if (checkReferenceInTypeElement(field.typeElement, element)) {
addPsiMemberTask(field)
return true
}
return false
}
fun processClass(psiClass: PsiClass) {
if (!checkPsiClass(psiClass)) {
return
}
val elementTextRange: TextRange? = element.textRange
if (elementTextRange != null) {
val superList = listOf(psiClass.extendsList, psiClass.implementsList)
for (psiReferenceList in superList) {
val superListRange: TextRange? = psiReferenceList?.textRange
if (superListRange != null && elementTextRange in superListRange) {
addNonKotlinClassToProcess(psiClass)
return
}
}
}
if (psiClass.fields.any { processField(it) }) {
return
}
if (psiClass.methods.any { processMethod(it) }) {
return
}
return
}
val psiClass = element.getParentOfType<PsiClass>(true)
if (psiClass != null) {
processClass(psiClass)
}
}
private fun processParameterInSamClass(psiParameter: PsiParameter): Boolean {
val method = psiParameter.declarationScope as? PsiMethod ?: return false
if (method.hasModifierProperty(PsiModifier.ABSTRACT)) {
val psiClass = method.containingClass
if (psiClass != null) {
testLog { "Resolved java class to descriptor: ${psiClass.qualifiedName}" }
if (psiClass.isSamInterface) {
addSamInterfaceToProcess(psiClass)
return true
}
}
}
return false
}
/**
* Process expression which may have type of our class (or our class used anywhere inside that type)
*/
private fun processSuspiciousExpression(expression: KtExpression) {
var inScope = expression in searchScope
var affectedScope: PsiElement = expression
ParentsLoop@
for (element in expression.parentsWithSelf) {
affectedScope = element
if (element !is KtExpression) continue
if (searchScope is LocalSearchScope) { // optimization to not check every expression
inScope = inScope && element in searchScope
}
if (inScope) {
possibleMatchHandler(element)
}
when (val parent = element.parent) {
is KtDestructuringDeclaration -> { // "val (x, y) = <expr>"
processSuspiciousDeclaration(parent)
break@ParentsLoop
}
is KtDeclarationWithInitializer -> { // "val x = <expr>" or "fun f() = <expr>"
if (element == parent.initializer) {
processSuspiciousDeclaration(parent)
}
break@ParentsLoop
}
is KtContainerNode -> {
if (parent.node.elementType == KtNodeTypes.LOOP_RANGE) { // "for (x in <expr>) ..."
val forExpression = parent.parent as KtForExpression
(forExpression.destructuringDeclaration ?: forExpression.loopParameter as KtDeclaration?)?.let {
processSuspiciousDeclaration(it)
}
break@ParentsLoop
}
}
}
if (!element.mayTypeAffectAncestors()) break
}
// use plain search in all lambdas and anonymous functions inside because they parameters or receiver can be implicitly typed with our class
usePlainSearchInLambdas(affectedScope)
}
private fun processLambdasForCallableReference(expression: KtReferenceExpression) {
//TODO: receiver?
usePlainSearchInLambdas(expression.parent)
}
/**
* Process declaration which may have implicit type of our class (or our class used anywhere inside that type)
*/
private fun processSuspiciousDeclaration(declaration: KtDeclaration) {
if (declaration is KtDestructuringDeclaration) {
declaration.entries.forEach { processSuspiciousDeclaration(it) }
} else {
if (!isImplicitlyTyped(declaration)) return
testLog { "Checked type of ${logPresentation(declaration)}" }
if (containsTypeOrDerivedInside(declaration)) {
addCallableDeclarationOfOurType(declaration)
}
}
}
private fun usePlainSearchInLambdas(scope: PsiElement) {
scope.forEachDescendantOfType<KtFunction> {
if (it.nameIdentifier == null) {
usePlainSearch(it)
}
}
}
private fun usePlainSearch(scope: KtElement) {
runReadAction {
if (!scope.isValid) return@runReadAction
val file = scope.containingKtFile
val restricted = LocalSearchScope(scope).intersectWith(searchScope)
if (restricted is LocalSearchScope) {
ScopeLoop@
for (element in restricted.scope) {
val prevElements = scopesToUsePlainSearch.getOrPut(file) { ArrayList() }
for ((index, prevElement) in prevElements.withIndex()) {
if (!prevElement.isValid) continue@ScopeLoop
if (prevElement.isAncestor(element, strict = false)) continue@ScopeLoop
if (element.isAncestor(prevElement)) {
prevElements[index] = element
continue@ScopeLoop
}
}
prevElements.add(element)
}
} else {
assert(SearchScope.isEmptyScope(restricted))
}
}
}
//TODO: code is quite similar to PartialBodyResolveFilter.isValueNeeded
private fun KtExpression.mayTypeAffectAncestors(): Boolean {
when (val parent = this.parent) {
is KtBlockExpression -> {
return this == parent.statements.last() && parent.mayTypeAffectAncestors()
}
is KtDeclarationWithBody -> {
if (this == parent.bodyExpression) {
return !parent.hasBlockBody() && !parent.hasDeclaredReturnType()
}
}
is KtContainerNode -> {
val grandParent = parent.parent
return when (parent.node.elementType) {
KtNodeTypes.CONDITION, KtNodeTypes.BODY -> false
KtNodeTypes.THEN, KtNodeTypes.ELSE -> (grandParent as KtExpression).mayTypeAffectAncestors()
KtNodeTypes.LOOP_RANGE, KtNodeTypes.INDICES -> true
else -> true // something else unknown
}
}
}
return true // we don't know
}
private fun isImplicitlyTyped(declaration: KtDeclaration): Boolean {
return when (declaration) {
is KtFunction -> !declaration.hasDeclaredReturnType()
is KtVariableDeclaration -> declaration.typeReference == null
is KtParameter -> declaration.typeReference == null
else -> false
}
}
private fun searchReferences(element: PsiElement, scope: SearchScope, processor: (PsiReference) -> Boolean) {
val parameters = ReferencesSearch.SearchParameters(element, scope, false)
searchReferences(parameters, processor)
}
private fun searchReferences(parameters: ReferencesSearch.SearchParameters, processor: (PsiReference) -> Boolean) {
ReferencesSearch.search(parameters).forEach(Processor { ref ->
ProgressManager.checkCanceled()
runReadAction {
if (ref.element.isValid) {
processor(ref)
} else {
true
}
}
})
}
}
| apache-2.0 | 38b229c1d0e63db292abefe1b7ab8ac5 | 41.66841 | 162 | 0.574293 | 6.051179 | false | false | false | false |
SimpleMobileTools/Simple-Gallery | app/src/main/kotlin/com/simplemobiletools/gallery/pro/dialogs/ManageBottomActionsDialog.kt | 1 | 4299 | package com.simplemobiletools.gallery.pro.dialogs
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.extensions.getAlertDialogBuilder
import com.simplemobiletools.commons.extensions.setupDialogStuff
import com.simplemobiletools.gallery.pro.R
import com.simplemobiletools.gallery.pro.extensions.config
import com.simplemobiletools.gallery.pro.helpers.*
import kotlinx.android.synthetic.main.dialog_manage_bottom_actions.view.*
class ManageBottomActionsDialog(val activity: BaseSimpleActivity, val callback: (result: Int) -> Unit) {
private var view = activity.layoutInflater.inflate(R.layout.dialog_manage_bottom_actions, null)
init {
val actions = activity.config.visibleBottomActions
view.apply {
manage_bottom_actions_toggle_favorite.isChecked = actions and BOTTOM_ACTION_TOGGLE_FAVORITE != 0
manage_bottom_actions_edit.isChecked = actions and BOTTOM_ACTION_EDIT != 0
manage_bottom_actions_share.isChecked = actions and BOTTOM_ACTION_SHARE != 0
manage_bottom_actions_delete.isChecked = actions and BOTTOM_ACTION_DELETE != 0
manage_bottom_actions_rotate.isChecked = actions and BOTTOM_ACTION_ROTATE != 0
manage_bottom_actions_properties.isChecked = actions and BOTTOM_ACTION_PROPERTIES != 0
manage_bottom_actions_change_orientation.isChecked = actions and BOTTOM_ACTION_CHANGE_ORIENTATION != 0
manage_bottom_actions_slideshow.isChecked = actions and BOTTOM_ACTION_SLIDESHOW != 0
manage_bottom_actions_show_on_map.isChecked = actions and BOTTOM_ACTION_SHOW_ON_MAP != 0
manage_bottom_actions_toggle_visibility.isChecked = actions and BOTTOM_ACTION_TOGGLE_VISIBILITY != 0
manage_bottom_actions_rename.isChecked = actions and BOTTOM_ACTION_RENAME != 0
manage_bottom_actions_set_as.isChecked = actions and BOTTOM_ACTION_SET_AS != 0
manage_bottom_actions_copy.isChecked = actions and BOTTOM_ACTION_COPY != 0
manage_bottom_actions_move.isChecked = actions and BOTTOM_ACTION_MOVE != 0
manage_bottom_actions_resize.isChecked = actions and BOTTOM_ACTION_RESIZE != 0
}
activity.getAlertDialogBuilder()
.setPositiveButton(R.string.ok) { dialog, which -> dialogConfirmed() }
.setNegativeButton(R.string.cancel, null)
.apply {
activity.setupDialogStuff(view, this)
}
}
private fun dialogConfirmed() {
var result = 0
view.apply {
if (manage_bottom_actions_toggle_favorite.isChecked)
result += BOTTOM_ACTION_TOGGLE_FAVORITE
if (manage_bottom_actions_edit.isChecked)
result += BOTTOM_ACTION_EDIT
if (manage_bottom_actions_share.isChecked)
result += BOTTOM_ACTION_SHARE
if (manage_bottom_actions_delete.isChecked)
result += BOTTOM_ACTION_DELETE
if (manage_bottom_actions_rotate.isChecked)
result += BOTTOM_ACTION_ROTATE
if (manage_bottom_actions_properties.isChecked)
result += BOTTOM_ACTION_PROPERTIES
if (manage_bottom_actions_change_orientation.isChecked)
result += BOTTOM_ACTION_CHANGE_ORIENTATION
if (manage_bottom_actions_slideshow.isChecked)
result += BOTTOM_ACTION_SLIDESHOW
if (manage_bottom_actions_show_on_map.isChecked)
result += BOTTOM_ACTION_SHOW_ON_MAP
if (manage_bottom_actions_toggle_visibility.isChecked)
result += BOTTOM_ACTION_TOGGLE_VISIBILITY
if (manage_bottom_actions_rename.isChecked)
result += BOTTOM_ACTION_RENAME
if (manage_bottom_actions_set_as.isChecked)
result += BOTTOM_ACTION_SET_AS
if (manage_bottom_actions_copy.isChecked)
result += BOTTOM_ACTION_COPY
if (manage_bottom_actions_move.isChecked)
result += BOTTOM_ACTION_MOVE
if (manage_bottom_actions_resize.isChecked)
result += BOTTOM_ACTION_RESIZE
}
activity.config.visibleBottomActions = result
callback(result)
}
}
| gpl-3.0 | 954872e2e9fa446a874e5c6b03218296 | 52.7375 | 114 | 0.665271 | 4.632543 | false | false | false | false |
lapis-mc/minecraft-versioning | src/main/kotlin/com/lapismc/minecraft/versioning/serialization/AssetCollectionJsonDeserializer.kt | 1 | 2478 | package com.lapismc.minecraft.versioning.serialization
import com.github.kittinunf.fuel.core.ResponseDeserializable
import com.github.salomonbrys.kotson.*
import com.google.gson.GsonBuilder
import com.google.gson.JsonElement
import com.lapismc.minecraft.versioning.Asset
import com.lapismc.minecraft.versioning.AssetCollection
import java.io.Reader
/**
* Pulls asset list information from a JSON document.
*/
class AssetCollectionJsonDeserializer : ResponseDeserializable<AssetCollection> {
/**
* Read asset list information.
* @param reader JSON reader used to get asset list data.
* @return Constructed asset list.
*/
override fun deserialize(reader: Reader): AssetCollection? {
val gson = GsonBuilder()
.registerTypeAdapter<AssetCollection> {
deserialize { readAssetList(it) }
serialize { jsonNull } // Empty, unused serializer to make Kotson happy.
}
.create()
return gson.fromJson<AssetCollection>(reader)
}
/**
* Parses an asset list from a JSON document.
* @param deserializer Deserialization information.
* @return Constructed asset list.
*/
private fun readAssetList(deserializer: DeserializerArg): AssetCollection {
val root = deserializer.json.asJsonObject
val legacy = root.has("legacy") && root["legacy"].bool
val builder = AssetCollection.Builder(legacy)
if(root.has("objects")) {
val objects = root["objects"].asJsonObject
objects.entrySet().forEach {
val asset = readAssetBlock(it.key, it.value)
builder.addAsset(asset)
}
}
return builder.build()
}
/**
* Reads asset information from a JSON asset block.
* @param path Path to where the asset should be stored locally.
* @param element Reference to the JSON block containing the asset information.
* @return Asset information read from the block.
*/
private fun readAssetBlock(path: String, element: JsonElement): Asset {
/**
* Asset blocks look like this:
* {
* "hash": "20abaa7d3b0baa105bc6023d5308f1e5d76acc41",
* "size": 11577
* }
*/
val assetObject = element.asJsonObject
val hash = assetObject["hash"].string
val size = assetObject["size"].int
return Asset(path, hash, size)
}
} | mit | c639ce6c8f9dd7c9e41917fa6eb774de | 35.455882 | 92 | 0.64205 | 4.623134 | false | false | false | false |
allotria/intellij-community | platform/lang-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/project/ProjectRootManagerBridge.kt | 1 | 13899 | // 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.workspaceModel.ide.impl.legacyBridge.project
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.ProjectJdkTable
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.RootProvider
import com.intellij.openapi.roots.RootProvider.RootSetChangedListener
import com.intellij.openapi.roots.impl.OrderRootsCache
import com.intellij.openapi.roots.impl.ProjectRootManagerComponent
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.roots.libraries.LibraryTable
import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar
import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar.APPLICATION_LEVEL
import com.intellij.openapi.util.EmptyRunnable
import com.intellij.util.containers.BidirectionalMultiMap
import com.intellij.util.containers.MultiMap
import com.intellij.workspaceModel.storage.EntityChange
import com.intellij.workspaceModel.storage.VersionedStorageChange
import com.intellij.workspaceModel.ide.WorkspaceModel
import com.intellij.workspaceModel.ide.WorkspaceModelChangeListener
import com.intellij.workspaceModel.ide.WorkspaceModelTopics
import com.intellij.workspaceModel.ide.impl.jps.serialization.levelToLibraryTableId
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.roots.OrderRootsCacheBridge
import com.intellij.workspaceModel.storage.bridgeEntities.*
@Suppress("ComponentNotRegistered")
class ProjectRootManagerBridge(project: Project) : ProjectRootManagerComponent(project) {
companion object {
private const val LIBRARY_NAME_DELIMITER = ":"
}
private val LOG = Logger.getInstance(javaClass)
private val globalLibraryTableListener = GlobalLibraryTableListener()
private val jdkChangeListener = JdkChangeListener()
init {
val bus = project.messageBus.connect(this)
WorkspaceModelTopics.getInstance(project).subscribeAfterModuleLoading(bus, object : WorkspaceModelChangeListener {
override fun changed(event: VersionedStorageChange) {
if (myProject.isDisposed) return
// Roots changed event should be fired for the global libraries linked with module
val moduleChanges = event.getChanges(ModuleEntity::class.java)
for (change in moduleChanges) {
when (change) {
is EntityChange.Added -> addTrackedLibraryAndJdkFromEntity(change.entity)
is EntityChange.Removed -> removeTrackedLibrariesAndJdkFromEntity(change.entity)
is EntityChange.Replaced -> {
removeTrackedLibrariesAndJdkFromEntity(change.oldEntity)
addTrackedLibraryAndJdkFromEntity(change.newEntity)
}
}
}
}
})
bus.subscribe(ProjectJdkTable.JDK_TABLE_TOPIC, jdkChangeListener)
}
override fun getActionToRunWhenProjectJdkChanges(): Runnable {
return Runnable {
super.getActionToRunWhenProjectJdkChanges().run()
if (jdkChangeListener.hasProjectSdkDependency()) fireRootsChanged()
}
}
override fun projectClosed() {
super.projectClosed()
unsubscribeListeners()
}
override fun dispose() {
super.dispose()
unsubscribeListeners()
}
override fun getOrderRootsCache(project: Project): OrderRootsCache {
return OrderRootsCacheBridge(project, project)
}
fun isFiringEvent(): Boolean = isFiringEvent
private fun unsubscribeListeners() {
val libraryTablesRegistrar = LibraryTablesRegistrar.getInstance()
val globalLibraryTable = libraryTablesRegistrar.libraryTable
globalLibraryTableListener.getLibraryLevels().forEach { libraryLevel ->
val libraryTable = when (libraryLevel) {
APPLICATION_LEVEL -> globalLibraryTable
else -> libraryTablesRegistrar.getLibraryTableByLevel(libraryLevel, project)
}
libraryTable?.libraryIterator?.forEach { (it as? RootProvider)?.removeRootSetChangedListener(globalLibraryTableListener) }
libraryTable?.removeListener(globalLibraryTableListener)
}
globalLibraryTableListener.clear()
jdkChangeListener.unsubscribeListeners()
}
fun setupTrackedLibrariesAndJdks() {
val currentStorage = WorkspaceModel.getInstance(project).entityStorage.current
for (moduleEntity in currentStorage.entities(ModuleEntity::class.java)) {
addTrackedLibraryAndJdkFromEntity(moduleEntity);
}
}
private fun addTrackedLibraryAndJdkFromEntity(moduleEntity: ModuleEntity) {
ApplicationManager.getApplication().assertWriteAccessAllowed()
LOG.debug { "Add tracked global libraries and JDK from ${moduleEntity.name}" }
val libraryTablesRegistrar = LibraryTablesRegistrar.getInstance()
moduleEntity.dependencies.forEach {
when {
it is ModuleDependencyItem.Exportable.LibraryDependency && it.library.tableId is LibraryTableId.GlobalLibraryTableId -> {
val libraryName = it.library.name
val libraryLevel = it.library.tableId.level
val libraryTable = libraryTablesRegistrar.getLibraryTableByLevel(libraryLevel, project) ?: return@forEach
if (globalLibraryTableListener.isEmpty(libraryLevel)) libraryTable.addListener(globalLibraryTableListener)
globalLibraryTableListener.addTrackedLibrary(moduleEntity, libraryTable, libraryName)
}
it is ModuleDependencyItem.SdkDependency || it is ModuleDependencyItem.InheritedSdkDependency -> {
jdkChangeListener.addTrackedJdk(it, moduleEntity)
}
}
}
}
private fun removeTrackedLibrariesAndJdkFromEntity(moduleEntity: ModuleEntity) {
LOG.debug { "Removed tracked global libraries and JDK from ${moduleEntity.name}" }
val libraryTablesRegistrar = LibraryTablesRegistrar.getInstance()
moduleEntity.dependencies.forEach {
when {
it is ModuleDependencyItem.Exportable.LibraryDependency && it.library.tableId is LibraryTableId.GlobalLibraryTableId -> {
val libraryName = it.library.name
val libraryLevel = it.library.tableId.level
val libraryTable = libraryTablesRegistrar.getLibraryTableByLevel(libraryLevel, project) ?: return@forEach
globalLibraryTableListener.unTrackLibrary(moduleEntity, libraryTable, libraryName)
if (globalLibraryTableListener.isEmpty(libraryLevel)) libraryTable.removeListener(globalLibraryTableListener)
}
it is ModuleDependencyItem.SdkDependency || it is ModuleDependencyItem.InheritedSdkDependency -> {
jdkChangeListener.removeTrackedJdk(it, moduleEntity)
}
}
}
}
private fun fireRootsChanged() {
if (myProject.isOpen) {
makeRootsChange(EmptyRunnable.INSTANCE, false, true)
}
}
// Listener for global libraries linked to module
private inner class GlobalLibraryTableListener : LibraryTable.Listener, RootSetChangedListener {
private val librariesPerModuleMap = BidirectionalMultiMap<ModuleId, String>()
private var insideRootsChange = false
fun addTrackedLibrary(moduleEntity: ModuleEntity, libraryTable: LibraryTable, libraryName: String) {
val library = libraryTable.getLibraryByName(libraryName)
val libraryIdentifier = getLibraryIdentifier(libraryTable, libraryName)
if (!librariesPerModuleMap.containsValue(libraryIdentifier)) {
(library as? RootProvider)?.addRootSetChangedListener(this)
}
librariesPerModuleMap.put(moduleEntity.persistentId(), libraryIdentifier)
}
fun unTrackLibrary(moduleEntity: ModuleEntity, libraryTable: LibraryTable, libraryName: String) {
val library = libraryTable.getLibraryByName(libraryName)
val libraryIdentifier = getLibraryIdentifier(libraryTable, libraryName)
librariesPerModuleMap.remove(moduleEntity.persistentId(), libraryIdentifier)
if (!librariesPerModuleMap.containsValue(libraryIdentifier)) {
(library as? RootProvider)?.removeRootSetChangedListener(this)
}
}
fun isEmpty(libraryLevel: String) = librariesPerModuleMap.values.none{ it.startsWith("$libraryLevel$LIBRARY_NAME_DELIMITER") }
fun getLibraryLevels() = librariesPerModuleMap.values.mapTo(HashSet()) { it.substringBefore(LIBRARY_NAME_DELIMITER) }
override fun afterLibraryAdded(newLibrary: Library) {
if (librariesPerModuleMap.containsValue(getLibraryIdentifier(newLibrary))) fireRootsChanged()
}
override fun afterLibraryRemoved(library: Library) {
if (librariesPerModuleMap.containsValue(getLibraryIdentifier(library))) fireRootsChanged()
}
override fun afterLibraryRenamed(library: Library, oldName: String?) {
val libraryTable = library.table
val newName = library.name
if (libraryTable != null && oldName != null && newName != null) {
val affectedModules = librariesPerModuleMap.getKeys(getLibraryIdentifier(libraryTable, oldName))
if (affectedModules.isNotEmpty()) {
val libraryTableId = levelToLibraryTableId(libraryTable.tableLevel)
WorkspaceModel.getInstance(myProject).updateProjectModel { builder ->
//maybe it makes sense to simplify this code by reusing code from PEntityStorageBuilder.updateSoftReferences
affectedModules.mapNotNull { builder.resolve(it) }.forEach { module ->
val updated = module.dependencies.map {
when {
it is ModuleDependencyItem.Exportable.LibraryDependency && it.library.tableId == libraryTableId && it.library.name == oldName ->
it.copy(library = LibraryId(newName, libraryTableId))
else -> it
}
}
builder.modifyEntity(ModifiableModuleEntity::class.java, module) {
dependencies = updated
}
}
}
}
}
}
override fun rootSetChanged(wrapper: RootProvider) {
if (insideRootsChange) return
insideRootsChange = true
try {
fireRootsChanged()
}
finally {
insideRootsChange = false
}
}
private fun getLibraryIdentifier(library: Library) = "${library.table.tableLevel}$LIBRARY_NAME_DELIMITER${library.name}"
private fun getLibraryIdentifier(libraryTable: LibraryTable,
libraryName: String) = "${libraryTable.tableLevel}$LIBRARY_NAME_DELIMITER$libraryName"
fun clear() = librariesPerModuleMap.clear()
}
private inner class JdkChangeListener : ProjectJdkTable.Listener, RootSetChangedListener {
private val sdkDependencies = MultiMap.createSet<ModuleDependencyItem, ModuleId>()
private val watchedSdks = HashSet<RootProvider>()
override fun jdkAdded(jdk: Sdk) {
if (hasDependencies(jdk)) {
if (watchedSdks.add(jdk.rootProvider)) {
jdk.rootProvider.addRootSetChangedListener(this)
}
fireRootsChanged()
}
}
override fun jdkNameChanged(jdk: Sdk, previousName: String) {
val sdkDependency = ModuleDependencyItem.SdkDependency(previousName, jdk.sdkType.name)
val affectedModules = sdkDependencies.get(sdkDependency)
if (affectedModules.isNotEmpty()) {
WorkspaceModel.getInstance(myProject).updateProjectModel { builder ->
for (moduleId in affectedModules) {
val module = moduleId.resolve(builder) ?: continue
val updated = module.dependencies.map {
when (it) {
is ModuleDependencyItem.SdkDependency -> ModuleDependencyItem.SdkDependency(jdk.name, jdk.sdkType.name)
else -> it
}
}
builder.modifyEntity(ModifiableModuleEntity::class.java, module) {
dependencies = updated
}
}
}
}
}
override fun jdkRemoved(jdk: Sdk) {
if (watchedSdks.remove(jdk.rootProvider)) {
jdk.rootProvider.removeRootSetChangedListener(this)
}
if (hasDependencies(jdk)) {
fireRootsChanged()
}
}
override fun rootSetChanged(wrapper: RootProvider) {
fireRootsChanged()
}
fun addTrackedJdk(sdkDependency: ModuleDependencyItem, moduleEntity: ModuleEntity) {
val sdk = findSdk(sdkDependency)
if (sdk != null && watchedSdks.add(sdk.rootProvider)) {
sdk.rootProvider.addRootSetChangedListener(this)
}
sdkDependencies.putValue(sdkDependency, moduleEntity.persistentId())
}
fun removeTrackedJdk(sdkDependency: ModuleDependencyItem, moduleEntity: ModuleEntity) {
sdkDependencies.remove(sdkDependency, moduleEntity.persistentId())
val sdk = findSdk(sdkDependency)
if (sdk != null && !hasDependencies(sdk) && watchedSdks.remove(sdk.rootProvider)) {
sdk.rootProvider.removeRootSetChangedListener(this)
}
}
fun hasProjectSdkDependency(): Boolean {
return sdkDependencies.get(ModuleDependencyItem.InheritedSdkDependency).isNotEmpty()
}
private fun findSdk(sdkDependency: ModuleDependencyItem): Sdk? = when (sdkDependency) {
is ModuleDependencyItem.InheritedSdkDependency -> projectSdk
is ModuleDependencyItem.SdkDependency -> ProjectJdkTable.getInstance().findJdk(sdkDependency.sdkName, sdkDependency.sdkType)
else -> null
}
private fun hasDependencies(jdk: Sdk): Boolean {
return sdkDependencies.get(ModuleDependencyItem.SdkDependency(jdk.name, jdk.sdkType.name)).isNotEmpty()
|| jdk.name == projectSdkName && jdk.sdkType.name == projectSdkTypeName && hasProjectSdkDependency()
}
fun unsubscribeListeners() {
watchedSdks.forEach {
it.removeRootSetChangedListener(this)
}
watchedSdks.clear()
}
}
} | apache-2.0 | cf90d0e81413587baeb1cae093454358 | 42.4375 | 146 | 0.730124 | 5.286801 | false | false | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit/src/main/kotlin/slatekit/docs/DocService.kt | 1 | 20000 | package slatekit.docs
import slatekit.common.*
import slatekit.utils.writer.ConsoleWriter
import slatekit.common.ext.toStringYYYYMMDD
import slatekit.common.utils.StringParser
import slatekit.results.Notice
import slatekit.results.Try
import slatekit.results.Success
import java.io.File
class DocService(val rootdir: String, val outputDir: String, val templatePathRaw: String) {
private val templatePath = File(rootdir, templatePathRaw).toString()
private var template = ""
private val writer = ConsoleWriter()
private val docFiles = DocFiles()
private val version = "0.9.35"
private val docs = listOf(
Doc("Args" , "slatekit-common" , "slatekit.common.args" ,"slatekit.common.args.Args" , version, "Example_Args" , true , false, false, "utils", "slatekit.common.jar" , "res" , "A lexical command line argument parser with optional support for allowing a route/method call in the beginning")
, Doc("Auth" , "slatekit-common" , "slatekit.common.auth" ,"slatekit.common.auth.Auth" , version, "Example_Auth" , true , false, false, "utils", "slatekit.common.jar" , "res" , "A simple authentication component to check current user role and permissions")
, Doc("Config" , "slatekit-common" , "slatekit.common.conf" ,"slatekit.common.conf.Config" , version, "Example_Config" , true , false, false, "utils", "slatekit.common.jar" , "res" , "Thin wrapper on java properties based config with decryption support, uri loading, and mapping of database connections and api keys")
, Doc("Console" , "slatekit-common" , "slatekit.common.console" ,"slatekit.common.console.Console" , version, "Example_Console" , true , false, false, "utils", "slatekit.common.jar" , "res" , "Enhanced printing to console with support for semantic writing like title, subtitle, url, error, etc with colors")
, Doc("DateTime" , "slatekit-common" , "slatekit.common" ,"slatekit.common.DateTime" , version, "Example_DateTime" , true , false, false, "utils", "slatekit.common.jar" , "res" , "DataTime wrapper around Java 8 LocalDateTime providing a simplified interface, some convenience, extra features.")
, Doc("Encrypt" , "slatekit-common" , "slatekit.common.encrypt" ,"slatekit.common.encrypt.Encryptor" , version, "Example_Encryptor" , true , false, false, "utils", "slatekit.common.jar" , "res" , "Encryption using AES")
, Doc("Env" , "slatekit-common" , "slatekit.common.envs" ,"slatekit.common.envs.Env" , version, "Example_Env" , true , false, false, "utils", "slatekit.common.jar" , "res" , "Environment selector and validator for environments such as (local, dev, qa, stg, prod) )")
, Doc("Folders" , "slatekit-common" , "slatekit.common.info" ,"slatekit.common.info.Folders" , version, "Example_Folders" , true , false, false, "utils", "slatekit.common.jar" , "res" , "Standardized application folder setup; includes conf, cache, inputs, logs, outputs")
, Doc("Info" , "slatekit-common" , "slatekit.common.info" ,"slatekit.common.info.About" , version, "Example_Info" , true , false, false, "utils", "slatekit.common.jar" , "res" , "Get/Set useful diagnostics about the system, language runtime, application and more")
, Doc("Lex" , "slatekit-common" , "slatekit.common.lex" ,"slatekit.common.lex.Lexer" , version, "Example_Lexer" , true , false, false, "utils", "slatekit.common.jar" , "res" , "Lexer for parsing text into tokens")
, Doc("Logger" , "slatekit-common" , "slatekit.common.log" ,"slatekit.common.log.Logger" , version, "Example_Logger" , true , false, false, "utils", "slatekit.common.jar" , "res" , "A simple logger with extensibility for using other 3rd party loggers")
, Doc("Random" , "slatekit-common" , "slatekit.common" ,"slatekit.common.utils.Random" , version, "Example_Random" , true , false, false, "utils", "slatekit.common.jar" , "res" , "A random generator for strings, guids, numbers, alpha-numeric, and alpha-numeric-symbols for various lengths" )
, Doc("Request" , "slatekit-common" , "slatekit.common.requests" ,"slatekit.common.requests.Request" , version, "Example_Request" , true , false, false, "utils", "slatekit.common.jar" , "res" , "Models and abstracts a send that can represent either an HTTP send or a send from the CLI ( Command line )." )
, Doc("SmartValues" , "slatekit-common" , "slatekit.common.smartvalues" ,"slatekit.common.smartvalues.Email" , version, "Example_SmartValues" , true , false, false, "utils", "slatekit.common.jar" , "res" , "A way to store, validate and describe strongly typed and formatted strings")
, Doc("Todo" , "slatekit-common" , "slatekit.common" ,"slatekit.common.Todo" , version, "Example_NOTE" , true , false, false, "utils", "slatekit.common.jar" , "res" , "A programmatic approach to marking and tagging code that is strongly typed and consistent")
, Doc("Serialization", "slatekit-common" , "slatekit.serialization" ,"slatekit.common.serialization.Serializer" , version, "Example_Serialization" , true , false, false, "utils", "slatekit.common.jar" , "res" , "Serializers for data classes to generate CSV, Props, HOCON, JSON files")
, Doc("Templates" , "slatekit-common" , "slatekit.common.templates" ,"slatekit.common.templates.Templates" , version, "Example_Templates" , true , false, false, "utils", "slatekit.common.jar" , "res" , "A micro template system for processing text with variables, useful for generating dynamic emails/messages.")
, Doc("Validations" , "slatekit-common" , "slatekit.common.validation" ,"slatekit.common.validation.ValidationFuncs" , version, "Example_Validation" , true , false, false, "utils", "slatekit.common.jar" , "res" , "A set of validation related components, simple validation checks, RegEx checks, error collection and custom validators")
, Doc("Utils" , "slatekit-common" , "slatekit.common.utils" ,"slatekit.common.console.ConsoleWriter" , version, "Example_Utils" , true , false, false, "utils", "slatekit.common.jar" , "res" , "Various utilities available in the Slate library")
, Doc("Query" , "slatekit-common" , "slatekit.query.Query" ,"slatekit.query.Query" , version, "Example_Query" , false , false, true , "utils", "slatekit.common.jar" , "" , "Query pattern used for specifying search and selection criteria" )
, Doc("Model" , "slatekit-meta" , "slatekit.common.Model" ,"slatekit.common.Model" , version, "Example_Model" , true , false, false, "utils", "slatekit.common.jar" , "" , "Allows construction of model schema with fields for code-generation. Also used in the ORM mapper" )
, Doc("Reflect" , "slatekit-meta" , "slatekit.common.Reflector" ,"slatekit.common.Reflector" , version, "Example_Reflect" , true , false, false, "utils", "slatekit.common.jar" , "" , "Reflection helper to create instances, get methods, fields, annotations and more" )
, Doc("ext-Users" , "slatekit-ext" , "slatekit.ext.users.User" ,"slatekit.ext.users.User" , version, "Example_Ext_Users" , false , true , false, "feat" , "slatekit.ext.jar" , "com,ent,core,cloud" , "Feature to create and manage users" )
, Doc("ext-Devices" , "slatekit-ext" , "slatekit.ext.devices.Device" ,"slatekit.ext.devices.Device" , version, "Example_Ext_Users" , false , true , false, "feat" , "slatekit.ext.jar" , "com,ent,core,cloud" , "Feature to create and manage users" )
, Doc("ext-Reg" , "slatekit-ext" , "slatekit.ext.reg.RegService" ,"slatekit.ext.reg.RegService" , version, "Example_Ext_Users" , false , true , false, "feat" , "slatekit.ext.jar" , "com,ent,core,cloud" , "Feature to create and manage users" )
, Doc("ext-Settings" , "slatekit-ext" , "slatekit.ext.settings.Settings" ,"slatekit.ext.settings.Settings" , version, "Example_Ext_Users" , false , true , false, "feat" , "slatekit.ext.jar" , "com,ent,core,cloud" , "Feature to create and manage users" )
, Doc("ext-Tasks" , "slatekit-ext" , "slatekit.ext.tasks.Tasks" ,"slatekit.ext.tasks.Tasks" , version, "Example_Ext_Users" , false , true , false, "feat" , "slatekit.ext.jar" , "com,ent,core,cloud" , "Feature to create and manage users" )
, Doc("ext-Invites" , "slatekit-ext" , "slatekit.ext.invites.Invite" ,"slatekit.ext.invites.Invite" , version, "Example_Ext_Users" , false , true , false, "feat" , "slatekit.ext.jar" , "com,ent,core,cloud" , "Feature to create and manage users" )
, Doc("ext-Logs" , "slatekit-ext" , "slatekit.ext.logs.Log" ,"slatekit.ext.logs.Log" , version, "Example_Ext_Users" , false , true , false, "feat" , "slatekit.ext.jar" , "com,ent,core,cloud" , "Feature to create and manage users" )
, Doc("ext-Status" , "slatekit-ext" , "slatekit.ext.status.Status" ,"slatekit.ext.status.Status" , version, "Example_Ext_Users" , false , true , false, "feat" , "slatekit.ext.jar" , "com,ent,core,cloud" , "Feature to create and manage users" )
, Doc("ext-Audits" , "slatekit-ext" , "slatekit.ext.audits.Audits" ,"slatekit.ext.audits.Audits" , version, "Example_Ext_Users" , false , true , false, "feat" , "slatekit.ext.jar" , "com,ent,core,cloud" , "Feature to create and manage users" )
)
fun process(): Try<String> {
val keys = docs.map { d -> d.name }.toList()
val maxLength = (keys.maxByOrNull { it.length }?.length ?: 0) + 3
var pos = 1
docs.forEach { doc ->
process(doc, pos, maxLength)
pos += 1
}
return Success(outputDir, msg = "generated docs to " + outputDir)
}
fun processItems(names:List<String>): Try<String> {
val docs = docs.filter{ names.contains(it.name) }
val keys = docs.map { d -> d.name }.toList()
val maxLength = (keys.maxByOrNull { it.length }?.length ?: 0) + 3
var pos = 1
docs.forEach { doc ->
process(doc, pos, maxLength)
pos += 1
}
return Success(outputDir, msg = "generated docs to " + outputDir)
}
fun processProject(project:String): Try<String> {
val docs = docs.filter{ it.proj == project }
val keys = docs.map { d -> d.name }.toList()
val maxLength = (keys.maxByOrNull { it.length }?.length ?: 0) + 3
var pos = 1
docs.forEach { doc ->
process(doc, pos, maxLength)
pos += 1
}
return Success(outputDir, msg = "generated docs to " + outputDir)
}
fun processComponent(name: String): Try<String> {
val doc = docs.first { it.name == name }
process(doc, 0, doc.name.length)
return Success(outputDir, msg = "generated docs to " + outputDir)
}
private fun process(doc: Doc, pos: Int, maxLength: Int) {
if (doc.available) {
val data = mutableMapOf<String, String>()
val number = pos.toString().padEnd(2)
val displayName = doc.name.padEnd(maxLength)
writer.highlight("$number. $displayName :", false)
init(doc, data)
val parseResult = if (doc.available) parse(doc, data) else fillComingSoon(doc, data)
val formatResult = fill(doc, data)
val filePath = generate(doc, data, formatResult)
if (doc.available && doc.readme) {
generateReadMe(doc, data, formatResult)
}
writer.url(filePath as String, true)
}
}
private fun fillComingSoon(doc: Doc, data: MutableMap<String, String>) {
data.put("import_required", newline + "coming soon")
data.put("import_examples", newline + "coming soon")
data.put("setup", "-")
data.put("examples", "coming soon")
data.put("output", "")
}
private fun fill(doc: Doc, data: Map<String, String>): Notice<String> {
var template = template
template = replace(template, "layout", data, "layout")
template = replace(template, "name", data, "name")
template = replace(template, "namelower", data, "namelower")
template = replace(template, "desc", data, "desc")
template = replace(template, "date", data, "date")
template = replace(template, "version", data, "version")
template = replace(template, "jar", data, "jar")
template = replace(template, "namespace", data, "namespace")
template = replace(template, "source", data, "source")
template = replace(template, "sourceFolder", data, "sourceFolder")
template = replace(template, "example", data, "example")
template = replace(template, "dependencies", data, "dependencies")
template = replace(template, "examplefile", data, "examplefile")
template = replace(template, "lang", data, "lang")
template = replace(template, "lang-ext", data, "lang-ext")
template = replace(template, "artifact", data, "artifact")
//https://github.com/kishorereddy/blend-server/blob/master/src/apps/kotlin/slate-examples/src/main/kotlin/slate/examples/Example_Args.kotlin
template = replace(template, DocConstants.header, data, "header")
template = replace(template, DocConstants.import_required, data, "import_required")
template = replace(template, DocConstants.import_optional, data, "import_optional")
template = replace(template, DocConstants.import_examples, data, "import_examples")
template = replace(template, DocConstants.depends, data, "depends")
template = replace(template, DocConstants.setup, data, "setup", true)
template = replace(template, DocConstants.examples, data, "examples")
template = replace(template, DocConstants.notes, data, "notes")
template = replaceWithSection("Output", template, DocConstants.output, data, "output")
return slatekit.results.Success(template)
}
private fun init(doc: Doc, data: MutableMap<String, String>) {
template = File(templatePath).readText()
data.put("output", "")
data.put("layout", doc.layout())
data.put("name", doc.name)
data.put("namelower", doc.name.toLowerCase())
data.put("desc", doc.desc)
data.put("date", DateTime.now().toStringYYYYMMDD())
data.put("version", doc.version)
data.put("jar", doc.jar)
data.put("dependencies", doc.dependsOn())
data.put("namespace", doc.namespace)
data.put("source", doc.source)
data.put("artifact", doc.artifact())
data.put("sourceFolder", doc.sourceFolder(docFiles))
data.put("example", doc.example)
data.put("setup", "")
data.put("lang", docFiles.lang)
data.put("lang-ext", docFiles.ext)
data.put("examplefile", docFiles.buildComponentExamplePathLink(doc))
}
private fun parse(doc: Doc, data: MutableMap<String, String>) {
val filePath = docFiles.buildComponentExamplePath(rootdir, doc)
val content = File(filePath).readText()
val parser = StringParser(content)
parser.moveTo("<doc:import_required>", ensure = true)
.saveUntil("//</doc:import_required>", name = "import_required", ensure = true)
.moveTo("<doc:import_examples>", ensure = true)
.saveUntil("//</doc:import_examples>", name = "import_examples", ensure = true)
.moveTo("<doc:setup>", ensure = false)
.saveUntil("//</doc:setup>", name = "setup", ensure = false)
.moveTo("<doc:examples>", ensure = true)
.saveUntil("//</doc:examples>", name = "examples", ensure = true)
.moveTo("<doc:output>", ensure = false)
.saveUntil("//</doc:output>", name = "output", ensure = false)
val extractedData = parser.extracts()
extractedData.forEach { entry ->
data.put(entry.key, entry.value)
}
}
private fun generate(doc: Doc, data: Any, result: Notice<String>): String {
val fileName = doc.name.toLowerCase() + ".md"
val outputPath = File(rootdir, outputDir)
val file = File(outputPath, fileName)
val content = result.map { content ->
file.writeText(content)
}
return content.toString()
}
private fun generateReadMe(doc: Doc, data: Any, result: Notice<String>): Unit {
val fileName = if (doc.multi) "Readme_" + doc.name + ".md" else "Readme.md"
val outputPath = docFiles.buildComponentFolder(rootdir, doc)
val file = File(outputPath, fileName)
result.map { content ->
file.writeText(content)
}
}
private fun replace(template: String, name: String, data: Map<String, String>, key: String,
enableNotApplicableIfEmptyData: Boolean = false): String {
if (!data.contains(key)) {
return template.replace("@{" + name + "}", "n/a")
}
val replacement = data[key]
if (replacement.isNullOrEmpty() && enableNotApplicableIfEmptyData) {
return template.replace("@{" + name + "}", "n/a")
}
val result = template.replace("@{" + name + "}", replacement ?: "")
return result
}
private fun replaceWithSection(sectionName: String, template: String,
name: String, data: Map<String, String>, key: String): String {
if (!data.contains(key)) return replaceItem(template, name)
val replacement = data[key]
if (replacement.isNullOrEmpty()) return replaceItem(template, name)
val section = "$newline## $sectionName$newline$replacement"
val result = template.replace("@{$name}", section)
return result
}
private fun replaceItem(template: String, name: String): String {
return template.replace("@{$name}", "")
}
}
| apache-2.0 | 94ba30007112a22a580c8363bd14678b | 73.626866 | 399 | 0.57335 | 4.069176 | false | false | false | false |
zdary/intellij-community | platform/vcs-impl/src/com/intellij/vcs/commit/NonModalCommitWorkflowHandler.kt | 1 | 9550 | // 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.actionSystem.ActionGroup
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.application.AppUIExecutor
import com.intellij.openapi.application.ApplicationListener
import com.intellij.openapi.application.ApplicationManager.getApplication
import com.intellij.openapi.application.impl.coroutineDispatchingContext
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.DumbService.isDumb
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.registry.RegistryValue
import com.intellij.openapi.util.registry.RegistryValueListener
import com.intellij.openapi.vcs.VcsBundle.message
import com.intellij.openapi.vcs.VcsException
import com.intellij.openapi.vcs.changes.CommitExecutor
import com.intellij.openapi.vcs.changes.CommitResultHandler
import com.intellij.openapi.vcs.changes.actions.DefaultCommitExecutorAction
import com.intellij.openapi.vcs.checkin.*
import com.intellij.openapi.vcs.checkin.CheckinHandler.ReturnResult
import com.intellij.vcs.commit.AbstractCommitWorkflow.Companion.getCommitExecutors
import kotlinx.coroutines.*
import java.lang.Runnable
import kotlin.properties.Delegates.observable
private val LOG = logger<NonModalCommitWorkflowHandler<*, *>>()
private val isBackgroundCommitChecksValue: RegistryValue get() = Registry.get("vcs.background.commit.checks")
fun isBackgroundCommitChecks(): Boolean = isBackgroundCommitChecksValue.asBoolean()
abstract class NonModalCommitWorkflowHandler<W : NonModalCommitWorkflow, U : NonModalCommitWorkflowUi> :
AbstractCommitWorkflowHandler<W, U>(),
DumbService.DumbModeListener {
abstract override val amendCommitHandler: NonModalAmendCommitHandler
private var areCommitOptionsCreated = false
private val uiDispatcher = AppUIExecutor.onUiThread().coroutineDispatchingContext()
private val exceptionHandler = CoroutineExceptionHandler { _, exception ->
if (exception !is ProcessCanceledException) LOG.error(exception)
}
private val coroutineScope =
CoroutineScope(CoroutineName("commit workflow") + uiDispatcher + SupervisorJob() + exceptionHandler)
private var isCommitChecksResultUpToDate: Boolean by observable(false) { _, oldValue, newValue ->
if (oldValue == newValue) return@observable
updateDefaultCommitActionName()
}
protected fun setupCommitHandlersTracking() {
isBackgroundCommitChecksValue.addListener(object : RegistryValueListener {
override fun afterValueChanged(value: RegistryValue) = commitHandlersChanged()
}, this)
CheckinHandlerFactory.EP_NAME.addChangeListener(Runnable { commitHandlersChanged() }, this)
VcsCheckinHandlerFactory.EP_NAME.addChangeListener(Runnable { commitHandlersChanged() }, this)
}
private fun commitHandlersChanged() {
if (workflow.isExecuting) return
saveCommitOptions(false)
disposeCommitOptions()
initCommitHandlers()
}
override fun vcsesChanged() {
initCommitHandlers()
workflow.initCommitExecutors(getCommitExecutors(project, workflow.vcses))
updateDefaultCommitActionEnabled()
updateDefaultCommitActionName()
ui.setCustomCommitActions(createCommitExecutorActions())
}
protected fun setupDumbModeTracking() {
if (isDumb(project)) enteredDumbMode()
project.messageBus.connect(this).subscribe(DumbService.DUMB_MODE, this)
}
override fun enteredDumbMode() {
ui.commitProgressUi.isDumbMode = true
}
override fun exitDumbMode() {
ui.commitProgressUi.isDumbMode = false
}
override fun executionStarted() = updateDefaultCommitActionEnabled()
override fun executionEnded() = updateDefaultCommitActionEnabled()
override fun updateDefaultCommitActionName() {
val commitText = getCommitActionName()
val isAmend = amendCommitHandler.isAmendCommitMode
val isSkipCommitChecks = isSkipCommitChecks()
ui.defaultCommitActionName = when {
isAmend && isSkipCommitChecks -> message("action.amend.commit.anyway.text", commitText)
isAmend && !isSkipCommitChecks -> message("amend.action.name", commitText)
!isAmend && isSkipCommitChecks -> message("action.commit.anyway.text", commitText)
else -> commitText
}
}
fun updateDefaultCommitActionEnabled() {
ui.isDefaultCommitActionEnabled = isReady()
}
protected open fun isReady() = workflow.vcses.isNotEmpty() && !workflow.isExecuting && !amendCommitHandler.isLoading
override fun isExecutorEnabled(executor: CommitExecutor): Boolean = super.isExecutorEnabled(executor) && isReady()
private fun createCommitExecutorActions(): List<AnAction> {
val executors = workflow.commitExecutors.ifEmpty { return emptyList() }
val group = ActionManager.getInstance().getAction("Vcs.CommitExecutor.Actions") as ActionGroup
return group.getChildren(null).toList() + executors.filter { it.useDefaultAction() }.map { DefaultCommitExecutorAction(it) }
}
override fun checkCommit(executor: CommitExecutor?): Boolean =
ui.commitProgressUi.run {
val executorWithoutChangesAllowed = executor?.areChangesRequired() == false
isEmptyChanges = !amendCommitHandler.isAmendWithoutChangesAllowed() && !executorWithoutChangesAllowed && isCommitEmpty()
isEmptyMessage = getCommitMessage().isBlank()
!isEmptyChanges && !isEmptyMessage
}
protected fun setupCommitChecksResultTracking() =
getApplication().addApplicationListener(object : ApplicationListener {
override fun writeActionStarted(action: Any) {
isCommitChecksResultUpToDate = false
}
}, this)
override fun beforeCommitChecksEnded(isDefaultCommit: Boolean, result: ReturnResult) {
super.beforeCommitChecksEnded(isDefaultCommit, result)
if (result == ReturnResult.COMMIT) {
ui.commitProgressUi.clearCommitCheckFailures()
}
}
fun isSkipCommitChecks(): Boolean = isBackgroundCommitChecks() && isCommitChecksResultUpToDate
override fun doExecuteDefault(executor: CommitExecutor?): Boolean {
if (!isBackgroundCommitChecks()) return super.doExecuteDefault(executor)
coroutineScope.launch {
workflow.executeDefault {
if (isSkipCommitChecks()) return@executeDefault ReturnResult.COMMIT
val indicator = ui.commitProgressUi.startProgress()
try {
runAllHandlers(executor, indicator)
}
finally {
indicator.stop()
}
}
}
return true
}
private suspend fun runAllHandlers(executor: CommitExecutor?, indicator: ProgressIndicator): ReturnResult {
workflow.runMetaHandlers(indicator)
FileDocumentManager.getInstance().saveAllDocuments()
val handlersResult = workflow.runHandlers(executor)
if (handlersResult != ReturnResult.COMMIT) return handlersResult
val checksResult = runCommitChecks(indicator)
if (checksResult != ReturnResult.COMMIT) isCommitChecksResultUpToDate = true
return checksResult
}
private suspend fun runCommitChecks(indicator: ProgressIndicator): ReturnResult {
var result = ReturnResult.COMMIT
for (commitCheck in commitHandlers.filterNot { it is CheckinMetaHandler }.filterIsInstance<CommitCheck<*>>()) {
val problem = runCommitCheck(commitCheck, indicator)
if (problem != null) result = ReturnResult.CANCEL
}
return result
}
private suspend fun <P : CommitProblem> runCommitCheck(commitCheck: CommitCheck<P>, indicator: ProgressIndicator): P? {
val problem = workflow.runCommitCheck(commitCheck, indicator)
problem?.let { ui.commitProgressUi.addCommitCheckFailure(it.text) { commitCheck.showDetails(it) } }
return problem
}
override fun dispose() {
coroutineScope.cancel()
super.dispose()
}
fun showCommitOptions(isFromToolbar: Boolean, dataContext: DataContext) =
ui.showCommitOptions(ensureCommitOptions(), getCommitActionName(), isFromToolbar, dataContext)
override fun saveCommitOptions(): Boolean = saveCommitOptions(true)
protected fun saveCommitOptions(isEnsureOptionsCreated: Boolean): Boolean {
if (isEnsureOptionsCreated) ensureCommitOptions()
return super.saveCommitOptions()
}
protected fun ensureCommitOptions(): CommitOptions {
if (!areCommitOptionsCreated) {
areCommitOptionsCreated = true
workflow.initCommitOptions(createCommitOptions())
commitOptions.restoreState()
commitOptionsCreated()
}
return commitOptions
}
protected open fun commitOptionsCreated() = Unit
protected fun disposeCommitOptions() {
workflow.disposeCommitOptions()
areCommitOptionsCreated = false
}
protected open inner class CommitStateCleaner : CommitResultHandler {
override fun onSuccess(commitMessage: String) = resetState()
override fun onCancel() = Unit
override fun onFailure(errors: List<VcsException>) = resetState()
protected open fun resetState() {
disposeCommitOptions()
workflow.clearCommitContext()
initCommitHandlers()
isCommitChecksResultUpToDate = false
updateDefaultCommitActionName()
}
}
} | apache-2.0 | af738d50557646e8dd44da7a06672d7f | 36.900794 | 140 | 0.77267 | 5.063627 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/coroutines/iterateOverArray.kt | 2 | 1080 | // WITH_RUNTIME
// WITH_COROUTINES
import helpers.*
import kotlin.coroutines.experimental.*
import kotlin.coroutines.experimental.intrinsics.*
class Controller {
suspend fun suspendHere(): String = suspendCoroutineOrReturn { x ->
x.resume("OK")
COROUTINE_SUSPENDED
}
}
fun builder(c: suspend Controller.() -> Unit) {
c.startCoroutine(Controller(), EmptyContinuation)
}
fun box(): String {
val a = arrayOfNulls<String>(2) as Array<String>
a[0] = "O"
a[1] = "K"
var result = ""
builder {
for (s in a) {
// 's' variable must be spilled before suspension point
// And it's important that it should be treated as a String instance because of 'result += s' after
// But BasicInterpreter just ignores type of argument array for AALOAD opcode (treating it's return type as plain Object),
// so we should refine the relevant part in our intepreter
if (suspendHere() != "OK") throw RuntimeException("fail 1")
result += s
}
}
return result
}
| apache-2.0 | 2da2686e792792fdea96ae8bf6b4dce4 | 29 | 134 | 0.631481 | 4.32 | false | false | false | false |
aconsuegra/algorithms-playground | src/main/kotlin/me/consuegra/algorithms/KPalindromePermutation.kt | 1 | 906 | package me.consuegra.algorithms
/**
* Given a string, write a function to check if it i a permutation of a palindrome. The palindrome does not need
* to be limited to just dictionary words.
* <p>
* Example:
* INPUT: "Tact Coa"
* OUTPUT: true ("taco cat", "atco cta", etc.)
*/
class KPalindromePermutation {
fun isPalindromePermutation(input: String): Boolean {
if (input.isEmpty()) {
return false
}
val map = HashMap<Char, Int>()
for (char in input.toLowerCase()) {
if (char != ' ') {
map.put(char, map.getOrDefault(char, 0) + 1)
}
}
var oddFound = false
for (count in map.values) {
if (count % 2 != 0) {
if (oddFound) {
return false
}
oddFound = true
}
}
return true
}
}
| mit | 56e52d96b711a9a464d9495c537a140e | 24.885714 | 112 | 0.506623 | 4.136986 | false | false | false | false |
exponent/exponent | android/expoview/src/main/java/host/exp/exponent/experience/ReactNativeActivity.kt | 2 | 23098 | // Copyright 2015-present 650 Industries. All rights reserved.
package host.exp.exponent.experience
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Process
import android.view.KeyEvent
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.annotation.UiThread
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.facebook.infer.annotation.Assertions
import com.facebook.internal.BundleJSONConverter
import com.facebook.react.devsupport.DoubleTapReloadRecognizer
import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler
import com.facebook.react.modules.core.PermissionAwareActivity
import com.facebook.react.modules.core.PermissionListener
import de.greenrobot.event.EventBus
import expo.modules.core.interfaces.Package
import expo.modules.manifests.core.Manifest
import host.exp.exponent.Constants
import host.exp.exponent.ExponentManifest
import host.exp.exponent.RNObject
import host.exp.exponent.analytics.Analytics
import host.exp.exponent.analytics.EXL
import host.exp.exponent.di.NativeModuleDepsProvider
import host.exp.exponent.experience.BaseExperienceActivity.ExperienceContentLoaded
import host.exp.exponent.experience.splashscreen.LoadingView
import host.exp.exponent.kernel.*
import host.exp.exponent.kernel.KernelConstants.AddedExperienceEventEvent
import host.exp.exponent.kernel.services.ErrorRecoveryManager
import host.exp.exponent.kernel.services.ExpoKernelServiceRegistry
import host.exp.exponent.notifications.ExponentNotification
import host.exp.exponent.storage.ExponentSharedPreferences
import host.exp.exponent.utils.ExperienceActivityUtils
import host.exp.exponent.utils.ScopedPermissionsRequester
import host.exp.expoview.Exponent
import host.exp.expoview.Exponent.InstanceManagerBuilderProperties
import host.exp.expoview.Exponent.StartReactInstanceDelegate
import host.exp.expoview.R
import org.json.JSONException
import org.json.JSONObject
import versioned.host.exp.exponent.ExponentPackage
import java.util.*
import javax.inject.Inject
abstract class ReactNativeActivity :
AppCompatActivity(),
DefaultHardwareBackBtnHandler,
PermissionAwareActivity {
class ExperienceDoneLoadingEvent internal constructor(val activity: Activity)
open fun initialProps(expBundle: Bundle?): Bundle? {
return expBundle
}
protected open fun onDoneLoading() {}
// Will be called after waitForDrawOverOtherAppPermission
protected open fun startReactInstance() {}
protected var reactInstanceManager: RNObject =
RNObject("com.facebook.react.ReactInstanceManager")
protected var isCrashed = false
protected var manifestUrl: String? = null
var experienceKey: ExperienceKey? = null
protected var sdkVersion: String? = null
protected var activityId = 0
// In detach we want UNVERSIONED most places. We still need the numbered sdk version
// when creating cache keys.
protected var detachSdkVersion: String? = null
protected lateinit var reactRootView: RNObject
private lateinit var doubleTapReloadRecognizer: DoubleTapReloadRecognizer
var isLoading = true
protected set
protected var jsBundlePath: String? = null
protected var manifest: Manifest? = null
var isInForeground = false
protected set
private var scopedPermissionsRequester: ScopedPermissionsRequester? = null
@Inject
protected lateinit var exponentSharedPreferences: ExponentSharedPreferences
@Inject
lateinit var expoKernelServiceRegistry: ExpoKernelServiceRegistry
private lateinit var containerView: FrameLayout
/**
* This view is optional and available only when the app runs in Expo Go.
*/
private var loadingView: LoadingView? = null
private lateinit var reactContainerView: FrameLayout
private val handler = Handler()
protected open fun shouldCreateLoadingView(): Boolean {
return !Constants.isStandaloneApp() || Constants.SHOW_LOADING_VIEW_IN_SHELL_APP
}
val rootView: View?
get() = reactRootView.get() as View?
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(null)
containerView = FrameLayout(this)
setContentView(containerView)
reactContainerView = FrameLayout(this)
containerView.addView(reactContainerView)
if (shouldCreateLoadingView()) {
containerView.setBackgroundColor(
ContextCompat.getColor(
this,
R.color.splashscreen_background
)
)
loadingView = LoadingView(this)
loadingView!!.show()
containerView.addView(loadingView)
}
doubleTapReloadRecognizer = DoubleTapReloadRecognizer()
Exponent.initialize(this, application)
NativeModuleDepsProvider.instance.inject(ReactNativeActivity::class.java, this)
// Can't call this here because subclasses need to do other initialization
// before their listener methods are called.
// EventBus.getDefault().registerSticky(this);
}
protected fun setReactRootView(reactRootView: View) {
reactContainerView.removeAllViews()
addReactViewToContentContainer(reactRootView)
}
fun addReactViewToContentContainer(reactView: View) {
if (reactView.parent != null) {
(reactView.parent as ViewGroup).removeView(reactView)
}
reactContainerView.addView(reactView)
}
fun hasReactView(reactView: View): Boolean {
return reactView.parent === reactContainerView
}
protected fun hideLoadingView() {
loadingView?.let {
val viewGroup = it.parent as ViewGroup?
viewGroup?.removeView(it)
it.hide()
}
loadingView = null
}
protected fun removeAllViewsFromContainer() {
containerView.removeAllViews()
}
// region Loading
/**
* Successfully finished loading
*/
@UiThread
protected fun finishLoading() {
waitForReactAndFinishLoading()
}
/**
* There was an error during loading phase
*/
protected fun interruptLoading() {
handler.removeCallbacksAndMessages(null)
}
// Loop until a view is added to the ReactRootView and once it happens run callback
private fun waitForReactRootViewToHaveChildrenAndRunCallback(callback: Runnable) {
if (reactRootView.isNull) {
return
}
if (reactRootView.call("getChildCount") as Int > 0) {
callback.run()
} else {
handler.postDelayed(
{ waitForReactRootViewToHaveChildrenAndRunCallback(callback) },
VIEW_TEST_INTERVAL_MS
)
}
}
/**
* Waits for JS side of React to be launched and then performs final launching actions.
*/
private fun waitForReactAndFinishLoading() {
if (Constants.isStandaloneApp() && Constants.SHOW_LOADING_VIEW_IN_SHELL_APP) {
val layoutParams = containerView.layoutParams
layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT
containerView.layoutParams = layoutParams
}
try {
// NOTE(evanbacon): Use the same view as the `expo-system-ui` module.
// Set before the application code runs to ensure immediate SystemUI calls overwrite the app.json value.
var rootView = this.window.decorView
ExperienceActivityUtils.setRootViewBackgroundColor(manifest!!, rootView)
} catch (e: Exception) {
EXL.e(TAG, e)
}
waitForReactRootViewToHaveChildrenAndRunCallback {
onDoneLoading()
try {
// NOTE(evanbacon): The hierarchy at this point looks like:
// window.decorView > [4 other views] > containerView > reactContainerView > rootView > [RN App]
// This can be inspected using Android Studio: View > Tool Windows > Layout Inspector.
// Container background color is set for "loading" view state, we need to set it to transparent to prevent obstructing the root view.
containerView!!.setBackgroundColor(Color.TRANSPARENT)
} catch (e: Exception) {
EXL.e(TAG, e)
}
ErrorRecoveryManager.getInstance(experienceKey!!).markExperienceLoaded()
pollForEventsToSendToRN()
EventBus.getDefault().post(ExperienceDoneLoadingEvent(this))
isLoading = false
}
}
// endregion
// region SplashScreen
/**
* Get what version (among versioned classes) of ReactRootView.class SplashScreen module should be looking for.
*/
protected fun getRootViewClass(manifest: Manifest): Class<out ViewGroup> {
val reactRootViewRNClass = reactRootView.rnClass()
if (reactRootViewRNClass != null) {
return reactRootViewRNClass as Class<out ViewGroup>
}
var sdkVersion = manifest.getSDKVersion()
if (Constants.TEMPORARY_ABI_VERSION != null && Constants.TEMPORARY_ABI_VERSION == this.sdkVersion) {
sdkVersion = RNObject.UNVERSIONED
}
sdkVersion = if (Constants.isStandaloneApp()) RNObject.UNVERSIONED else sdkVersion
return RNObject("com.facebook.react.ReactRootView").loadVersion(sdkVersion!!).rnClass() as Class<out ViewGroup>
}
// endregion
override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean {
devSupportManager?.let { devSupportManager ->
if (!isCrashed && devSupportManager.call("getDevSupportEnabled") as Boolean) {
val didDoubleTapR = Assertions.assertNotNull(doubleTapReloadRecognizer)
.didDoubleTapR(keyCode, currentFocus)
if (didDoubleTapR) {
devSupportManager.call("reloadExpoApp")
return true
}
}
}
return super.onKeyUp(keyCode, event)
}
override fun onBackPressed() {
if (reactInstanceManager.isNotNull && !isCrashed) {
reactInstanceManager.call("onBackPressed")
} else {
super.onBackPressed()
}
}
override fun invokeDefaultOnBackPressed() {
super.onBackPressed()
}
override fun onPause() {
super.onPause()
if (reactInstanceManager.isNotNull && !isCrashed) {
reactInstanceManager.onHostPause()
// TODO: use onHostPause(activity)
}
}
override fun onResume() {
super.onResume()
if (reactInstanceManager.isNotNull && !isCrashed) {
reactInstanceManager.onHostResume(this, this)
}
}
override fun onDestroy() {
super.onDestroy()
destroyReactInstanceManager()
handler.removeCallbacksAndMessages(null)
EventBus.getDefault().unregister(this)
}
public override fun onNewIntent(intent: Intent) {
if (reactInstanceManager.isNotNull && !isCrashed) {
try {
reactInstanceManager.call("onNewIntent", intent)
} catch (e: Throwable) {
EXL.e(TAG, e.toString())
super.onNewIntent(intent)
}
} else {
super.onNewIntent(intent)
}
}
open val isDebugModeEnabled: Boolean
get() = manifest?.isDevelopmentMode() ?: false
protected open fun destroyReactInstanceManager() {
if (reactInstanceManager.isNotNull && !isCrashed) {
reactInstanceManager.call("destroy")
}
}
public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
Exponent.instance.onActivityResult(requestCode, resultCode, data)
if (reactInstanceManager.isNotNull && !isCrashed) {
reactInstanceManager.call("onActivityResult", this, requestCode, resultCode, data)
}
// Have permission to draw over other apps. Resume loading.
if (requestCode == KernelConstants.OVERLAY_PERMISSION_REQUEST_CODE) {
// startReactInstance() checks isInForeground and onActivityResult is called before onResume,
// so manually set this here.
isInForeground = true
startReactInstance()
}
}
fun startReactInstance(
delegate: StartReactInstanceDelegate,
intentUri: String?,
sdkVersion: String?,
notification: ExponentNotification?,
isShellApp: Boolean,
extraNativeModules: List<Any>?,
extraExpoPackages: List<Package>?,
progressListener: DevBundleDownloadProgressListener
): RNObject {
if (isCrashed || !delegate.isInForeground) {
// Can sometimes get here after an error has occurred. Return early or else we'll hit
// a null pointer at mReactRootView.startReactApplication
return RNObject("com.facebook.react.ReactInstanceManager")
}
val experienceProperties = mapOf<String, Any?>(
KernelConstants.MANIFEST_URL_KEY to manifestUrl,
KernelConstants.LINKING_URI_KEY to linkingUri,
KernelConstants.INTENT_URI_KEY to intentUri,
KernelConstants.IS_HEADLESS_KEY to false
)
val instanceManagerBuilderProperties = InstanceManagerBuilderProperties(
application = application,
jsBundlePath = jsBundlePath,
experienceProperties = experienceProperties,
expoPackages = extraExpoPackages,
exponentPackageDelegate = delegate.exponentPackageDelegate,
manifest = manifest!!,
singletonModules = ExponentPackage.getOrCreateSingletonModules(applicationContext, manifest, extraExpoPackages)
)
val versionedUtils = RNObject("host.exp.exponent.VersionedUtils").loadVersion(sdkVersion!!)
val builder = versionedUtils.callRecursive(
"getReactInstanceManagerBuilder",
instanceManagerBuilderProperties
)!!
builder.call("setCurrentActivity", this)
// ReactNativeInstance is considered to be resumed when it has its activity attached, which is expected to be the case here
builder.call(
"setInitialLifecycleState",
RNObject.versionedEnum(sdkVersion, "com.facebook.react.common.LifecycleState", "RESUMED")
)
if (extraNativeModules != null) {
for (nativeModule in extraNativeModules) {
builder.call("addPackage", nativeModule)
}
}
if (delegate.isDebugModeEnabled) {
val debuggerHost = manifest!!.getDebuggerHost()
val mainModuleName = manifest!!.getMainModuleName()
Exponent.enableDeveloperSupport(debuggerHost, mainModuleName, builder)
val devLoadingView =
RNObject("com.facebook.react.devsupport.DevLoadingViewController").loadVersion(sdkVersion)
devLoadingView.callRecursive("setDevLoadingEnabled", false)
val devBundleDownloadListener =
RNObject("host.exp.exponent.ExponentDevBundleDownloadListener")
.loadVersion(sdkVersion)
.construct(progressListener)
builder.callRecursive("setDevBundleDownloadListener", devBundleDownloadListener.get())
} else {
waitForReactAndFinishLoading()
}
val bundle = Bundle()
val exponentProps = JSONObject()
if (notification != null) {
bundle.putString("notification", notification.body) // Deprecated
try {
exponentProps.put("notification", notification.toJSONObject("selected"))
} catch (e: JSONException) {
e.printStackTrace()
}
}
try {
exponentProps.put("manifestString", manifest.toString())
exponentProps.put("shell", isShellApp)
exponentProps.put("initialUri", intentUri)
} catch (e: JSONException) {
EXL.e(TAG, e)
}
val metadata = exponentSharedPreferences.getExperienceMetadata(experienceKey!!)
if (metadata != null) {
// TODO: fix this. this is the only place that EXPERIENCE_METADATA_UNREAD_REMOTE_NOTIFICATIONS is sent to the experience,
// we need to send them with the standard notification events so that you can get all the unread notification through an event
// Copy unreadNotifications into exponentProps
if (metadata.has(ExponentSharedPreferences.EXPERIENCE_METADATA_UNREAD_REMOTE_NOTIFICATIONS)) {
try {
val unreadNotifications =
metadata.getJSONArray(ExponentSharedPreferences.EXPERIENCE_METADATA_UNREAD_REMOTE_NOTIFICATIONS)
delegate.handleUnreadNotifications(unreadNotifications)
} catch (e: JSONException) {
e.printStackTrace()
}
metadata.remove(ExponentSharedPreferences.EXPERIENCE_METADATA_UNREAD_REMOTE_NOTIFICATIONS)
}
exponentSharedPreferences.updateExperienceMetadata(experienceKey!!, metadata)
}
try {
bundle.putBundle("exp", BundleJSONConverter.convertToBundle(exponentProps))
} catch (e: JSONException) {
throw Error("JSONObject failed to be converted to Bundle", e)
}
if (!delegate.isInForeground) {
return RNObject("com.facebook.react.ReactInstanceManager")
}
Analytics.markEvent(Analytics.TimedEvent.STARTED_LOADING_REACT_NATIVE)
val mReactInstanceManager = builder.callRecursive("build")!!
val devSettings =
mReactInstanceManager.callRecursive("getDevSupportManager")!!.callRecursive("getDevSettings")
if (devSettings != null) {
devSettings.setField("exponentActivityId", activityId)
if (devSettings.call("isRemoteJSDebugEnabled") as Boolean) {
waitForReactAndFinishLoading()
}
}
mReactInstanceManager.onHostResume(this, this)
val appKey = manifest!!.getAppKey()
reactRootView.call(
"startReactApplication",
mReactInstanceManager.get(),
appKey ?: KernelConstants.DEFAULT_APPLICATION_KEY,
initialProps(bundle)
)
// Requesting layout to make sure {@link ReactRootView} attached to {@link ReactInstanceManager}
// Otherwise, {@link ReactRootView} will hang in {@link waitForReactRootViewToHaveChildrenAndRunCallback}.
// Originally react-native will automatically attach after `startReactApplication`.
// After https://github.com/facebook/react-native/commit/2c896d35782cd04c8,
// the only remaining path is by `onMeasure`.
reactRootView.call("requestLayout")
return mReactInstanceManager
}
protected fun shouldShowErrorScreen(errorMessage: ExponentErrorMessage): Boolean {
if (isLoading) {
// Don't hit ErrorRecoveryManager until bridge is initialized.
// This is the same on iOS.
return true
}
val errorRecoveryManager = ErrorRecoveryManager.getInstance(experienceKey!!)
errorRecoveryManager.markErrored()
if (!errorRecoveryManager.shouldReloadOnError()) {
return true
}
if (!KernelProvider.instance.reloadVisibleExperience(manifestUrl!!)) {
// Kernel couldn't reload, show error screen
return true
}
errorQueue.clear()
try {
val eventProperties = JSONObject().apply {
put(Analytics.USER_ERROR_MESSAGE, errorMessage.userErrorMessage())
put(Analytics.DEVELOPER_ERROR_MESSAGE, errorMessage.developerErrorMessage())
put(Analytics.MANIFEST_URL, manifestUrl)
}
Analytics.logEvent(Analytics.AnalyticsEvent.ERROR_RELOADED, eventProperties)
} catch (e: Exception) {
EXL.e(TAG, e.message)
}
return false
}
fun onEventMainThread(event: AddedExperienceEventEvent) {
if (manifestUrl != null && manifestUrl == event.manifestUrl) {
pollForEventsToSendToRN()
}
}
fun onEvent(event: ExperienceContentLoaded?) {}
private fun pollForEventsToSendToRN() {
if (manifestUrl == null) {
return
}
try {
val rctDeviceEventEmitter =
RNObject("com.facebook.react.modules.core.DeviceEventManagerModule\$RCTDeviceEventEmitter")
rctDeviceEventEmitter.loadVersion(detachSdkVersion!!)
val existingEmitter = reactInstanceManager.callRecursive("getCurrentReactContext")!!
.callRecursive("getJSModule", rctDeviceEventEmitter.rnClass())
if (existingEmitter != null) {
val events = KernelProvider.instance.consumeExperienceEvents(manifestUrl!!)
for ((eventName, eventPayload) in events) {
existingEmitter.call("emit", eventName, eventPayload)
}
}
} catch (e: Throwable) {
EXL.e(TAG, e)
}
}
// for getting global permission
override fun checkSelfPermission(permission: String): Int {
return super.checkPermission(permission, Process.myPid(), Process.myUid())
}
override fun shouldShowRequestPermissionRationale(permission: String): Boolean {
// in scoped application we don't have `don't ask again` button
return if (!Constants.isStandaloneApp() && checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED) {
true
} else super.shouldShowRequestPermissionRationale(permission)
}
override fun requestPermissions(
permissions: Array<String>,
requestCode: Int,
listener: PermissionListener
) {
if (requestCode == ScopedPermissionsRequester.EXPONENT_PERMISSIONS_REQUEST) {
val name = manifest!!.getName()
scopedPermissionsRequester = ScopedPermissionsRequester(experienceKey!!)
scopedPermissionsRequester!!.requestPermissions(this, name ?: "", permissions, listener)
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
super.requestPermissions(permissions, requestCode)
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
if (requestCode == ScopedPermissionsRequester.EXPONENT_PERMISSIONS_REQUEST) {
if (permissions.isNotEmpty() && grantResults.size == permissions.size && scopedPermissionsRequester != null) {
if (scopedPermissionsRequester!!.onRequestPermissionsResult(permissions, grantResults)) {
scopedPermissionsRequester = null
}
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
}
// for getting scoped permission
override fun checkPermission(permission: String, pid: Int, uid: Int): Int {
val globalResult = super.checkPermission(permission, pid, uid)
return expoKernelServiceRegistry.permissionsKernelService.getPermissions(
globalResult,
packageManager,
permission,
experienceKey!!
)
}
val devSupportManager: RNObject?
get() = reactInstanceManager.takeIf { it.isNotNull }?.callRecursive("getDevSupportManager")
// deprecated in favor of Expo.Linking.makeUrl
// TODO: remove this
private val linkingUri: String?
get() = if (Constants.SHELL_APP_SCHEME != null) {
Constants.SHELL_APP_SCHEME + "://"
} else {
val uri = Uri.parse(manifestUrl)
val host = uri.host
if (host != null && (
host == "exp.host" || host == "expo.io" || host == "exp.direct" || host == "expo.test" ||
host.endsWith(".exp.host") || host.endsWith(".expo.io") || host.endsWith(".exp.direct") || host.endsWith(
".expo.test"
)
)
) {
val pathSegments = uri.pathSegments
val builder = uri.buildUpon()
builder.path(null)
for (segment in pathSegments) {
if (ExponentManifest.DEEP_LINK_SEPARATOR == segment) {
break
}
builder.appendEncodedPath(segment)
}
builder.appendEncodedPath(ExponentManifest.DEEP_LINK_SEPARATOR_WITH_SLASH).build()
.toString()
} else {
manifestUrl
}
}
companion object {
private val TAG = ReactNativeActivity::class.java.simpleName
private const val VIEW_TEST_INTERVAL_MS: Long = 20
@JvmStatic protected var errorQueue: Queue<ExponentError> = LinkedList()
}
}
| bsd-3-clause | 99731d546005a381a91b8828555efe59 | 34.372129 | 141 | 0.722227 | 4.844379 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/completion/tests/testData/smartMultiFile/NotImportedGetValue/NotImportedGetValue.kt | 13 | 431 | package main
import dependency.X1
import dependency.X2
import dependency.X3
import dependency.Y1
import dependency.Y2
import dependency.Y3
fun createX1() = X1()
fun createX2() = X2()
fun createX3() = X3()
fun createY1() = Y1()
fun createY2() = Y2()
fun createY3() = Y3()
class C {
val property by <caret>
}
// EXIST: createX1
// ABSENT: createX2
// EXIST: createX3
// EXIST: createY1
// ABSENT: createY2
// EXIST: createY3
| apache-2.0 | ef8f5d6ff715f9b2155cf4704ef4ecb9 | 15.576923 | 27 | 0.698376 | 2.727848 | false | false | false | false |
ianhanniballake/muzei | legacy-standalone/src/main/java/com/google/android/apps/muzei/legacy/SendActionBroadcastReceiver.kt | 1 | 2046 | /*
* Copyright 2020 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.muzei.legacy
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
import com.google.android.apps.muzei.util.goAsync
import net.nurik.roman.muzei.legacy.BuildConfig
/**
* A [BroadcastReceiver] used to trigger actions on legacy sources
*/
class SendActionBroadcastReceiver : BroadcastReceiver() {
companion object {
private const val TAG = "SendActionReceiver"
private const val KEY_ID = "id"
fun createPendingIntent(
context: Context,
id: Int
): PendingIntent = PendingIntent.getBroadcast(context, id,
Intent(context, SendActionBroadcastReceiver::class.java).apply {
putExtra(KEY_ID, id)
}, PendingIntent.FLAG_UPDATE_CURRENT)
}
override fun onReceive(context: Context, intent: Intent) {
val id = intent.getIntExtra(KEY_ID, -1)
if (id == -1) {
return
}
goAsync {
val currentSource = LegacyDatabase.getInstance(context).sourceDao().getCurrentSource()
if (currentSource != null) {
if (BuildConfig.DEBUG) {
Log.d(TAG, "Sending command $id to ${currentSource.componentName}")
}
currentSource.sendAction(context, id)
}
}
}
}
| apache-2.0 | 198b79db0a570be7567759eb82b755cd | 33.677966 | 98 | 0.65738 | 4.577181 | false | false | false | false |
smmribeiro/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/VcsToolWindowFactory.kt | 1 | 6306 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.vcs.changes.ui
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.extensions.ExtensionPointListener
import com.intellij.openapi.extensions.PluginDescriptor
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.openapi.vcs.ProjectLevelVcsManager
import com.intellij.openapi.vcs.ProjectLevelVcsManager.VCS_CONFIGURATION_CHANGED
import com.intellij.openapi.vcs.VcsListener
import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager.Companion.CONTENT_PROVIDER_SUPPLIER_KEY
import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager.Companion.IS_IN_COMMIT_TOOLWINDOW_KEY
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ToolWindowFactory
import com.intellij.openapi.wm.ex.ToolWindowEx
import com.intellij.ui.ClientProperty
import com.intellij.ui.content.Content
import com.intellij.ui.content.ContentFactory
import com.intellij.vcs.commit.CommitModeManager
import java.awt.Component
import javax.swing.JPanel
private val Project.changesViewContentManager: ChangesViewContentI
get() = ChangesViewContentManager.getInstance(this)
private val IS_CONTENT_CREATED = Key.create<Boolean>("ToolWindow.IsContentCreated")
private val CHANGES_VIEW_EXTENSION = Key.create<ChangesViewContentEP>("Content.ChangesViewExtension")
private fun Content.getExtension(): ChangesViewContentEP? = getUserData(CHANGES_VIEW_EXTENSION)
abstract class VcsToolWindowFactory : ToolWindowFactory, DumbAware {
override fun init(window: ToolWindow) {
val project = (window as ToolWindowEx).project
updateState(project, window)
val connection = project.messageBus.connect()
connection.subscribe(VCS_CONFIGURATION_CHANGED, VcsListener {
runInEdt {
if (project.isDisposed) return@runInEdt
updateState(project, window)
}
})
connection.subscribe(ChangesViewContentManagerListener.TOPIC, object : ChangesViewContentManagerListener {
override fun toolWindowMappingChanged() {
updateState(project, window)
window.contentManagerIfCreated?.selectFirstContent()
}
})
CommitModeManager.subscribeOnCommitModeChange(connection, object : CommitModeManager.CommitModeListener {
override fun commitModeChanged() {
updateState(project, window)
window.contentManagerIfCreated?.selectFirstContent()
}
})
ChangesViewContentEP.EP_NAME.addExtensionPointListener(project, ExtensionListener(window), window.disposable)
}
override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) {
updateContent(project, toolWindow)
project.changesViewContentManager.attachToolWindow(toolWindow)
toolWindow.component.putClientProperty(IS_CONTENT_CREATED, true)
}
protected open fun updateState(project: Project, toolWindow: ToolWindow) {
updateAvailability(project, toolWindow)
updateContentIfCreated(project, toolWindow)
}
private fun updateAvailability(project: Project, toolWindow: ToolWindow) {
val available = shouldBeAvailable(project)
// force showing stripe button on adding initial mapping even if stripe button was manually removed by the user
if (available && !toolWindow.isAvailable) {
toolWindow.isShowStripeButton = true
}
toolWindow.isAvailable = available
}
private fun updateContentIfCreated(project: Project, toolWindow: ToolWindow) {
if (ClientProperty.get(toolWindow.component as Component?, IS_CONTENT_CREATED) != true) {
return
}
updateContent(project, toolWindow)
}
private fun updateContent(project: Project, toolWindow: ToolWindow) {
val changesViewContentManager = project.changesViewContentManager
val wasEmpty = toolWindow.contentManager.contentCount == 0
getExtensions(project, toolWindow).forEach { extension ->
val isVisible = extension.newPredicateInstance(project)?.test(project) != false
val content = changesViewContentManager.findContents { it.getExtension() === extension }.firstOrNull()
if (isVisible && content == null) {
changesViewContentManager.addContent(createExtensionContent(project, extension))
}
else if (!isVisible && content != null) {
changesViewContentManager.removeContent(content)
}
}
if (wasEmpty) toolWindow.contentManager.selectFirstContent()
}
private fun getExtensions(project: Project, toolWindow: ToolWindow): Collection<ChangesViewContentEP> {
return ChangesViewContentEP.EP_NAME.getExtensions(project).filter {
ChangesViewContentManager.getToolWindowId(project, it) == toolWindow.id
}
}
private fun createExtensionContent(project: Project, extension: ChangesViewContentEP): Content {
val displayName = extension.getDisplayName(project) ?: extension.tabName
return ContentFactory.SERVICE.getInstance().createContent(JPanel(null), displayName, false).apply {
isCloseable = false
tabName = extension.tabName //NON-NLS overridden by displayName above
putUserData(CHANGES_VIEW_EXTENSION, extension)
putUserData(CONTENT_PROVIDER_SUPPLIER_KEY) { extension.getInstance(project) }
putUserData(IS_IN_COMMIT_TOOLWINDOW_KEY, extension.isInCommitToolWindow)
extension.newPreloaderInstance(project)?.preloadTabContent(this)
}
}
private inner class ExtensionListener(private val toolWindow: ToolWindowEx) : ExtensionPointListener<ChangesViewContentEP> {
override fun extensionAdded(extension: ChangesViewContentEP, pluginDescriptor: PluginDescriptor) =
updateContentIfCreated(toolWindow.project, toolWindow)
override fun extensionRemoved(extension: ChangesViewContentEP, pluginDescriptor: PluginDescriptor) {
val contentManager = toolWindow.contentManagerIfCreated ?: return
val content = contentManager.contents.firstOrNull { it.getExtension() === extension } ?: return
toolWindow.project.changesViewContentManager.removeContent(content)
}
}
companion object {
internal val Project.vcsManager: ProjectLevelVcsManager
get() = ProjectLevelVcsManager.getInstance(this)
}
} | apache-2.0 | 761c01b595ad2c019ad1cc93fbda7b40 | 43.104895 | 126 | 0.779099 | 4.969267 | false | false | false | false |
edvin/kdbc | src/main/kotlin/kdbc/column.kt | 1 | 684 | package kdbc
import java.sql.ResultSet
interface ColumnOrTable
class Column<out T>(val table: Table, val name: String, val ddl: String?, val getter: ResultSet.(String) -> T?, var rs: () -> ResultSet) : ColumnOrTable {
override fun toString() = fullName
val fullName: String get() = if (table.tableAlias != null) "${table.tableAlias}.$name" else name
val alias: String get() = fullName.replace(".", "_")
val asAlias: String get() = if (table.tableAlias != null) "$fullName $alias" else alias
val value: T? get() = getter(rs(), alias)
val isNull: Boolean get() = value == null
val isNotNull: Boolean get() = !isNull
operator fun invoke(): T? = value
} | apache-2.0 | 3dfcfdf326ef537aed66f4e87df7e359 | 41.8125 | 154 | 0.662281 | 3.821229 | false | false | false | false |
cout970/Modeler | src/main/kotlin/com/cout970/modeler/gui/canvas/layout/LayoutTwo.kt | 1 | 3069 | package com.cout970.modeler.gui.canvas.layout
import com.cout970.glutilities.event.EventKeyUpdate
import com.cout970.modeler.core.config.Config
import com.cout970.modeler.gui.Gui
import com.cout970.modeler.gui.canvas.CanvasContainer
import com.cout970.modeler.util.next
import org.joml.Vector2f
import org.liquidengine.legui.component.optional.Orientation
/**
* Created by cout970 on 2017/06/09.
*/
class LayoutTwo(override val container: CanvasContainer) : ICanvasLayout {
var splitter = 0.5f
var orientation: Orientation = Orientation.HORIZONTAL
override fun updateCanvas() {
when (orientation) {
Orientation.VERTICAL -> {
container.canvas[0].apply {
size = Vector2f(container.panel.size.x, container.panel.size.y * splitter)
position = Vector2f()
}
container.canvas[1].apply {
size = Vector2f(container.panel.size.x, container.panel.size.y * (1 - splitter))
position = Vector2f(0f, container.panel.size.y * splitter)
}
}
Orientation.HORIZONTAL -> {
container.canvas[0].apply {
size = Vector2f(container.panel.size.x * splitter, container.panel.size.y)
position = Vector2f()
}
container.canvas[1].apply {
size = Vector2f(container.panel.size.x * (1 - splitter), container.panel.size.y)
position = Vector2f(container.panel.size.x * splitter, 0f)
}
}
}
}
override fun onEvent(gui: Gui, e: EventKeyUpdate): Boolean {
Config.keyBindings.apply {
when {
layoutChangeMode.check(e) -> runAction("layout.change.mode")
moveLayoutSplitterLeft.check(e) -> runAction("move.splitter.left")
moveLayoutSplitterRight.check(e) -> runAction("move.splitter.right")
newCanvas.check(e) -> runAction("canvas.new")
deleteCanvas.check(e) -> runAction("canvas.delete")
else -> return false
}
}
gui.root.reRender()
return true
}
override fun runAction(action: String) {
when (action) {
"layout.change.mode" -> orientation = orientation.next()
"move.splitter.left" -> if (orientation == Orientation.HORIZONTAL) splitter -= 1f / 32f
"move.splitter.right" -> if (orientation == Orientation.HORIZONTAL) splitter += 1f / 32f
"move.splitter.up" -> if (orientation == Orientation.VERTICAL) splitter -= 1f / 32f
"move.splitter.down" -> if (orientation == Orientation.VERTICAL) splitter += 1f / 32f
"canvas.new" -> {
container.newCanvas()
container.selectLayout()
}
"canvas.delete" -> {
container.removeCanvas(container.canvas.lastIndex)
container.selectLayout()
}
}
}
} | gpl-3.0 | 047f420d3912cece0ee624d9af9818e1 | 38.87013 | 100 | 0.576083 | 4.322535 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/decompiler/common/AnnotationLoaderForStubBuilderImpl.kt | 2 | 3895 | // 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.decompiler.common
import org.jetbrains.kotlin.metadata.ProtoBuf
import org.jetbrains.kotlin.metadata.deserialization.NameResolver
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.protobuf.MessageLite
import org.jetbrains.kotlin.serialization.SerializerExtensionProtocol
import org.jetbrains.kotlin.serialization.deserialization.AnnotatedCallableKind
import org.jetbrains.kotlin.serialization.deserialization.AnnotationAndConstantLoader
import org.jetbrains.kotlin.serialization.deserialization.ProtoContainer
import org.jetbrains.kotlin.serialization.deserialization.getClassId
import org.jetbrains.kotlin.types.KotlinType
class AnnotationLoaderForStubBuilderImpl(
private val protocol: SerializerExtensionProtocol
) : AnnotationAndConstantLoader<ClassId, Unit> {
override fun loadClassAnnotations(container: ProtoContainer.Class): List<ClassId> =
container.classProto.getExtension(protocol.classAnnotation).orEmpty().map { container.nameResolver.getClassId(it.id) }
override fun loadCallableAnnotations(
container: ProtoContainer,
proto: MessageLite,
kind: AnnotatedCallableKind
): List<ClassId> {
val annotations = when (proto) {
is ProtoBuf.Constructor -> proto.getExtension(protocol.constructorAnnotation)
is ProtoBuf.Function -> proto.getExtension(protocol.functionAnnotation)
is ProtoBuf.Property -> when (kind) {
AnnotatedCallableKind.PROPERTY -> proto.getExtension(protocol.propertyAnnotation)
AnnotatedCallableKind.PROPERTY_GETTER -> proto.getExtension(protocol.propertyGetterAnnotation)
AnnotatedCallableKind.PROPERTY_SETTER -> proto.getExtension(protocol.propertySetterAnnotation)
else -> error("Unsupported callable kind with property proto")
}
else -> error("Unknown message: $proto")
}.orEmpty()
return annotations.map { container.nameResolver.getClassId(it.id) }
}
override fun loadPropertyBackingFieldAnnotations(container: ProtoContainer, proto: ProtoBuf.Property): List<ClassId> =
emptyList()
override fun loadPropertyDelegateFieldAnnotations(container: ProtoContainer, proto: ProtoBuf.Property): List<ClassId> =
emptyList()
override fun loadEnumEntryAnnotations(container: ProtoContainer, proto: ProtoBuf.EnumEntry): List<ClassId> =
proto.getExtension(protocol.enumEntryAnnotation).orEmpty().map { container.nameResolver.getClassId(it.id) }
override fun loadValueParameterAnnotations(
container: ProtoContainer,
callableProto: MessageLite,
kind: AnnotatedCallableKind,
parameterIndex: Int,
proto: ProtoBuf.ValueParameter
): List<ClassId> =
proto.getExtension(protocol.parameterAnnotation).orEmpty().map { container.nameResolver.getClassId(it.id) }
override fun loadExtensionReceiverParameterAnnotations(
container: ProtoContainer,
proto: MessageLite,
kind: AnnotatedCallableKind
): List<ClassId> = emptyList()
override fun loadTypeAnnotations(
proto: ProtoBuf.Type,
nameResolver: NameResolver
): List<ClassId> =
proto.getExtension(protocol.typeAnnotation).orEmpty().map { nameResolver.getClassId(it.id) }
override fun loadTypeParameterAnnotations(proto: ProtoBuf.TypeParameter, nameResolver: NameResolver): List<ClassId> =
proto.getExtension(protocol.typeParameterAnnotation).orEmpty().map { nameResolver.getClassId(it.id) }
override fun loadPropertyConstant(
container: ProtoContainer,
proto: ProtoBuf.Property,
expectedType: KotlinType
) {
}
}
| apache-2.0 | c5a4dabe3f19b6d5d1e393d1768b8b31 | 47.08642 | 158 | 0.748395 | 5.045337 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/project-wizard/idea/src/org/jetbrains/kotlin/tools/projectWizard/wizard/service/IdeaJpsWizardService.kt | 1 | 10754 | // 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.tools.projectWizard.wizard.service
import com.intellij.codeInsight.daemon.impl.quickfix.OrderEntryFix
import com.intellij.ide.util.projectWizard.ModuleBuilder
import com.intellij.jarRepository.JarRepositoryManager
import com.intellij.jarRepository.RemoteRepositoryDescription
import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProviderImpl
import com.intellij.openapi.module.ModifiableModuleModel
import com.intellij.openapi.module.ModuleTypeId
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.*
import com.intellij.openapi.roots.libraries.ui.OrderRoot
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.util.PathUtil
import org.jetbrains.idea.maven.utils.library.RepositoryLibraryProperties
import org.jetbrains.jps.model.java.JavaResourceRootType
import org.jetbrains.jps.model.java.JavaSourceRootType
import org.jetbrains.kotlin.config.JvmTarget
import org.jetbrains.kotlin.idea.compiler.configuration.Kotlin2JvmCompilerArgumentsHolder
import org.jetbrains.kotlin.idea.facet.getOrCreateFacet
import org.jetbrains.kotlin.idea.facet.initializeIfNeeded
import org.jetbrains.kotlin.idea.formatter.KotlinStyleGuideCodeStyle.Companion.INSTANCE
import org.jetbrains.kotlin.idea.formatter.ProjectCodeStyleImporter
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.tools.projectWizard.core.*
import org.jetbrains.kotlin.tools.projectWizard.core.service.ProjectImportingWizardService
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.*
import org.jetbrains.kotlin.tools.projectWizard.library.MavenArtifact
import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.BuildSystemType
import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.SourcesetType
import org.jetbrains.kotlin.tools.projectWizard.wizard.IdeWizard
import org.jetbrains.kotlin.tools.projectWizard.wizard.NewProjectWizardModuleBuilder
import org.jetbrains.kotlin.idea.framework.KotlinSdkType
import org.jetbrains.kotlin.platform.jvm.JvmPlatforms
import org.jetbrains.kotlin.tools.projectWizard.moduleConfigurators.JvmModuleConfigurator
import org.jetbrains.kotlin.tools.projectWizard.moduleConfigurators.inContextOfModuleConfigurator
import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.Repository
import java.nio.file.Path
import java.util.*
import com.intellij.openapi.module.Module as IdeaModule
class IdeaJpsWizardService(
private val project: Project,
private val modulesModel: ModifiableModuleModel,
private val modulesBuilder: NewProjectWizardModuleBuilder,
private val ideWizard: IdeWizard
) : ProjectImportingWizardService, IdeaWizardService {
override fun isSuitableFor(buildSystemType: BuildSystemType): Boolean =
buildSystemType == BuildSystemType.Jps
override fun importProject(
reader: Reader,
path: Path,
modulesIrs: List<ModuleIR>,
buildSystem: BuildSystemType
): TaskResult<Unit> {
KotlinSdkType.setUpIfNeeded()
val projectImporter = ProjectImporter(project, modulesModel, path, modulesIrs)
modulesBuilder.addModuleConfigurationUpdater(
JpsModuleConfigurationUpdater(ideWizard.jpsData, projectImporter, project, reader)
)
projectImporter.import()
return UNIT_SUCCESS
}
}
private class JpsModuleConfigurationUpdater(
private val jpsData: IdeWizard.JpsData,
private val projectImporter: ProjectImporter,
private val project: Project,
private val reader: Reader
) : ModuleBuilder.ModuleConfigurationUpdater() {
override fun update(module: IdeaModule, rootModel: ModifiableRootModel) = with(jpsData) {
libraryOptionsPanel.apply()?.addLibraries(
rootModel,
ArrayList(),
librariesContainer
)
libraryDescription.finishLibConfiguration(module, rootModel, true)
setUpJvmTargetVersionForModules(module, rootModel)
ProjectCodeStyleImporter.apply(module.project, INSTANCE)
}
private fun setUpJvmTargetVersionForModules(module: IdeaModule, rootModel: ModifiableRootModel) {
val modules = projectImporter.modulesIrs
if (modules.all { it.jvmTarget() == modules.first().jvmTarget() }) {
Kotlin2JvmCompilerArgumentsHolder.getInstance(project).update {
jvmTarget = modules.first().jvmTarget().value
}
} else {
val jvmTarget = modules.first { it.name == module.name }.jvmTarget()
val modelsProvider = IdeModifiableModelsProviderImpl(project)
try {
val facet = module.getOrCreateFacet(modelsProvider, useProjectSettings = true, commitModel = true)
val platform = JvmTarget.fromString(jvmTarget.value)
?.let(JvmPlatforms::jvmPlatformByTargetVersion)
?: JvmPlatforms.defaultJvmPlatform
facet.configuration.settings.apply {
initializeIfNeeded(module, rootModel, platform)
targetPlatform = platform
}
} finally {
modelsProvider.dispose()
}
}
}
private fun ModuleIR.jvmTarget() = reader {
inContextOfModuleConfigurator(originalModule) {
JvmModuleConfigurator.targetJvmVersion.reference.settingValue
}
}
}
private class ProjectImporter(
private val project: Project,
private val modulesModel: ModifiableModuleModel,
private val path: Path,
val modulesIrs: List<ModuleIR>
) {
private val librariesPath: Path
get() = path / "libs"
fun import() = modulesIrs.mapSequence { moduleIR ->
convertModule(moduleIR).map { moduleIR to it }
}.map { irsToIdeaModule ->
val irsToIdeaModuleMap = irsToIdeaModule.associate { (ir, module) -> ir.name to module }
irsToIdeaModule.forEach { (moduleIr, ideaModule) ->
addModuleDependencies(moduleIr, ideaModule, irsToIdeaModuleMap)
}
} andThen safe { runWriteAction { modulesModel.commit() } }
private fun convertModule(moduleIr: ModuleIR): TaskResult<IdeaModule> {
val module = modulesModel.newModule(
(moduleIr.path / "${moduleIr.name}.iml").toString(),
ModuleTypeId.JAVA_MODULE
)
val rootModel = ModuleRootManager.getInstance(module).modifiableModel
val contentRoot = rootModel.addContentEntry(moduleIr.path.url)
SourcesetType.ALL.forEach { sourceset ->
val isTest = sourceset == SourcesetType.test
contentRoot.addSourceFolder(
(moduleIr.path / "src" / sourceset.name / "kotlin").url,
if (isTest) JavaSourceRootType.TEST_SOURCE else JavaSourceRootType.SOURCE
)
contentRoot.addSourceFolder(
(moduleIr.path / "src" / sourceset.name / "resources").url,
if (isTest) JavaResourceRootType.TEST_RESOURCE else JavaResourceRootType.RESOURCE
)
}
rootModel.inheritSdk()
runWriteAction { rootModel.commit() }
addLibrariesToTheModule(moduleIr, module)
return Success(module)
}
private fun addLibrariesToTheModule(moduleIr: ModuleIR, module: IdeaModule) {
moduleIr.irs.forEach { ir ->
if (ir is LibraryDependencyIR && !ir.isKotlinStdlib) {
attachLibraryToModule(ir, module)
}
}
}
private fun addModuleDependencies(
moduleIr: ModuleIR,
module: com.intellij.openapi.module.Module,
moduleNameToIdeaModuleMap: Map<String, IdeaModule>
) {
moduleIr.irs.forEach { ir ->
if (ir is ModuleDependencyIR) {
attachModuleDependencyToModule(ir, module, moduleNameToIdeaModuleMap)
}
}
}
private fun attachModuleDependencyToModule(
moduleDependency: ModuleDependencyIR,
module: IdeaModule,
moduleNameToIdeaModuleMap: Map<String, IdeaModule>
) {
val dependencyName = moduleDependency.path.parts.lastOrNull() ?: return
val dependencyModule = moduleNameToIdeaModuleMap[dependencyName] ?: return
ModuleRootModificationUtil.addDependency(module, dependencyModule)
}
private fun attachLibraryToModule(
libraryDependency: LibraryDependencyIR,
module: IdeaModule
) {
val artifact = libraryDependency.artifact as? MavenArtifact ?: return
val (classesRoots, sourcesRoots) = downloadLibraryAndGetItsClasses(libraryDependency, artifact)
ModuleRootModificationUtil.addModuleLibrary(
module,
if (classesRoots.size > 1) artifact.artifactId else null,
classesRoots,
sourcesRoots,
when (libraryDependency.dependencyType) {
DependencyType.MAIN -> DependencyScope.COMPILE
DependencyType.TEST -> DependencyScope.TEST
}
)
}
private fun downloadLibraryAndGetItsClasses(
libraryDependency: LibraryDependencyIR,
artifact: MavenArtifact
): LibraryClassesAndSources {
val libraryProperties = RepositoryLibraryProperties(
artifact.groupId,
artifact.artifactId,
libraryDependency.version.toString()
)
val orderRoots = JarRepositoryManager.loadDependenciesModal(
project,
libraryProperties,
true,
true,
librariesPath.toString(),
listOf(artifact.repository.asJPSRepository())
)
return LibraryClassesAndSources.fromOrderRoots(orderRoots)
}
private fun Repository.asJPSRepository() = RemoteRepositoryDescription(
idForMaven,
idForMaven,
url
)
private data class LibraryClassesAndSources(
val classes: List<String>,
val sources: List<String>
) {
companion object {
fun fromOrderRoots(orderRoots: Collection<OrderRoot>) = LibraryClassesAndSources(
orderRoots.filterRootTypes(OrderRootType.CLASSES),
orderRoots.filterRootTypes(OrderRootType.SOURCES)
)
private fun Collection<OrderRoot>.filterRootTypes(rootType: OrderRootType) =
filter { it.type == rootType }
.mapNotNull { PathUtil.getLocalPath(it.file) }
.let(OrderEntryFix::refreshAndConvertToUrls)
}
}
}
private val Path.url
get() = VfsUtil.pathToUrl(toString())
| apache-2.0 | b7c3de0d83a77f474f182bdec61fa64b | 40.361538 | 158 | 0.704017 | 5.142994 | false | true | false | false |
JetBrains/kotlin-native | runtime/src/main/kotlin/kotlin/native/concurrent/Internal.kt | 1 | 4045 | /*
* 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 kotlin.native.concurrent
import kotlin.native.internal.DescribeObjectForDebugging
import kotlin.native.internal.ExportForCppRuntime
import kotlin.native.internal.InternalForKotlinNative
import kotlin.native.internal.debugDescription
import kotlin.native.identityHashCode
import kotlin.reflect.KClass
import kotlinx.cinterop.*
// Implementation details.
@SymbolName("Kotlin_Worker_stateOfFuture")
external internal fun stateOfFuture(id: Int): Int
@SymbolName("Kotlin_Worker_consumeFuture")
@PublishedApi
external internal fun consumeFuture(id: Int): Any?
@SymbolName("Kotlin_Worker_waitForAnyFuture")
external internal fun waitForAnyFuture(versionToken: Int, millis: Int): Boolean
@SymbolName("Kotlin_Worker_versionToken")
external internal fun versionToken(): Int
@kotlin.native.internal.ExportForCompiler
internal fun executeImpl(worker: Worker, mode: TransferMode, producer: () -> Any?,
job: CPointer<CFunction<*>>): Future<Any?> =
Future<Any?>(executeInternal(worker.id, mode.value, producer, job))
@SymbolName("Kotlin_Worker_startInternal")
external internal fun startInternal(errorReporting: Boolean, name: String?): Int
@SymbolName("Kotlin_Worker_currentInternal")
external internal fun currentInternal(): Int
@SymbolName("Kotlin_Worker_requestTerminationWorkerInternal")
external internal fun requestTerminationInternal(id: Int, processScheduledJobs: Boolean): Int
@SymbolName("Kotlin_Worker_executeInternal")
external internal fun executeInternal(
id: Int, mode: Int, producer: () -> Any?, job: CPointer<CFunction<*>>): Int
@SymbolName("Kotlin_Worker_executeAfterInternal")
external internal fun executeAfterInternal(id: Int, operation: () -> Unit, afterMicroseconds: Long): Unit
@SymbolName("Kotlin_Worker_processQueueInternal")
external internal fun processQueueInternal(id: Int): Boolean
@SymbolName("Kotlin_Worker_parkInternal")
external internal fun parkInternal(id: Int, timeoutMicroseconds: Long, process: Boolean): Boolean
@SymbolName("Kotlin_Worker_getNameInternal")
external internal fun getWorkerNameInternal(id: Int): String?
@ExportForCppRuntime
internal fun ThrowWorkerUnsupported(): Unit =
throw UnsupportedOperationException("Workers are not supported")
@ExportForCppRuntime
internal fun ThrowWorkerInvalidState(): Unit =
throw IllegalStateException("Illegal transfer state")
@ExportForCppRuntime
internal fun WorkerLaunchpad(function: () -> Any?) = function()
@PublishedApi
@SymbolName("Kotlin_Worker_detachObjectGraphInternal")
external internal fun detachObjectGraphInternal(mode: Int, producer: () -> Any?): NativePtr
@PublishedApi
@SymbolName("Kotlin_Worker_attachObjectGraphInternal")
external internal fun attachObjectGraphInternal(stable: NativePtr): Any?
@SymbolName("Kotlin_Worker_freezeInternal")
internal external fun freezeInternal(it: Any?)
@SymbolName("Kotlin_Worker_isFrozenInternal")
internal external fun isFrozenInternal(it: Any?): Boolean
@ExportForCppRuntime
internal fun ThrowFreezingException(toFreeze: Any, blocker: Any): Nothing =
throw FreezingException(toFreeze, blocker)
@ExportForCppRuntime
internal fun ThrowInvalidMutabilityException(where: Any): Nothing {
val description = debugDescription(where::class, where.identityHashCode())
throw InvalidMutabilityException("mutation attempt of frozen $description")
}
@ExportForCppRuntime
internal fun ThrowIllegalObjectSharingException(typeInfo: NativePtr, address: NativePtr) {
val description = DescribeObjectForDebugging(typeInfo, address)
throw IncorrectDereferenceException("illegal attempt to access non-shared $description from other thread")
}
@SymbolName("Kotlin_AtomicReference_checkIfFrozen")
external internal fun checkIfFrozen(ref: Any?)
@InternalForKotlinNative
@SymbolName("Kotlin_Worker_waitTermination")
external public fun waitWorkerTermination(worker: Worker)
| apache-2.0 | d891dc9cbeca18dccce43d0f833db109 | 36.803738 | 110 | 0.797775 | 4.445055 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/references/KtIdeReferenceProviderService.kt | 4 | 3075 | // 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.references
import com.intellij.openapi.project.IndexNotReadyException
import com.intellij.psi.ContributedReferenceHost
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import com.intellij.psi.PsiReferenceService
import com.intellij.psi.impl.source.resolve.reference.ReferenceProvidersRegistry
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import com.intellij.psi.util.PsiModificationTracker
import com.intellij.util.containers.ConcurrentFactoryMap
import com.intellij.util.containers.MultiMap
import org.jetbrains.kotlin.psi.KotlinReferenceProvidersService
import org.jetbrains.kotlin.utils.SmartList
class KtIdeReferenceProviderService : KotlinReferenceProvidersService() {
private val originalProvidersBinding: MultiMap<Class<out PsiElement>, KotlinPsiReferenceProvider>
private val providersBindingCache: Map<Class<out PsiElement>, List<KotlinPsiReferenceProvider>>
init {
val registrar = KotlinPsiReferenceRegistrar()
KotlinReferenceProviderContributor.getInstance().registerReferenceProviders(registrar)
originalProvidersBinding = registrar.providers
providersBindingCache = ConcurrentFactoryMap.createMap<Class<out PsiElement>, List<KotlinPsiReferenceProvider>> { klass ->
val result = SmartList<KotlinPsiReferenceProvider>()
for (bindingClass in originalProvidersBinding.keySet()) {
if (bindingClass.isAssignableFrom(klass)) {
result.addAll(originalProvidersBinding.get(bindingClass))
}
}
result
}
}
private fun doGetKotlinReferencesFromProviders(context: PsiElement): Array<PsiReference> {
val providers: List<KotlinPsiReferenceProvider>? = providersBindingCache[context.javaClass]
if (providers.isNullOrEmpty()) return PsiReference.EMPTY_ARRAY
val result = SmartList<PsiReference>()
for (provider in providers) {
try {
result.addAll(provider.getReferencesByElement(context))
} catch (ignored: IndexNotReadyException) {
// Ignore and continue to next provider
}
}
if (result.isEmpty()) {
return PsiReference.EMPTY_ARRAY
}
return result.toTypedArray()
}
override fun getReferences(psiElement: PsiElement): Array<PsiReference> {
if (psiElement is ContributedReferenceHost) {
return ReferenceProvidersRegistry.getReferencesFromProviders(psiElement, PsiReferenceService.Hints.NO_HINTS)
}
return CachedValuesManager.getCachedValue(psiElement) {
CachedValueProvider.Result.create(
doGetKotlinReferencesFromProviders(psiElement),
PsiModificationTracker.MODIFICATION_COUNT
)
}
}
} | apache-2.0 | 4617f2fab0d282610e2fb5b65fee761e | 42.323944 | 158 | 0.728455 | 5.301724 | false | false | false | false |
vovagrechka/fucking-everything | alraune/alraune/src/main/java/alraune/fuckaround/FuckAround_UploadClassesAndExecuteRemotely1.kt | 1 | 3199 | package alraune.fuckaround
import alraune.*
import org.apache.tools.ant.Project
import org.apache.tools.ant.taskdefs.Jar
import org.apache.tools.ant.types.FileSet
import pieces100.*
import vgrechka.*
import java.io.File
import java.util.*
object FuckAround_UploadClassesAndExecuteRemotely1 {
class Secrets(
val url: String,
val rootToken: String)
@JvmStatic fun main(args: Array<String>) {
val f = this::main2
clog("Doing ${f.name}\n")
f()
clog("\nOK")
}
private fun main1() {
val responseText = HTTPPile.postJSON_bitchUnlessOK(
"${secrets.url}${ServeNashorn.pathInfo}",
jsonize(ServeNashorn.Request().fill(
rootToken = secrets.rootToken,
code = """
clog("So, we are going to conduct a motherfucking computation, OK?")
var a = 2, b = 3
clog(a + b)
clog("Yeah, that was something")
""")))
val response = dejsonizeBang(ServeNashorn.Response::class, responseText)
clog(response.output)
}
private fun main2() {
val distrDir = File("c:/tmp/${this::class.simpleName}")
val classesRoot = "E:/fegh/alraune/alraune/out/production/classes"
val classToUpload = ShitToUpload::class.java
val packageName = classToUpload.`package`.name
val packageDir = packageName.replace(".", "/")
val className = classToUpload.name.substring(packageName.length + 1)
// clog(packageDir)
// clog(className)
Alk.createDirOrCleanIfExists(distrDir)
val jarFile = File(distrDir.path + "/pizda.jar")
Jar().also {
it.project = Project()
it.destFile = jarFile
it.addFileset(FileSet().also {
it.dir = File(classesRoot)
val s = "$packageDir/$className*"
it.setIncludes(s)
})
it.level = 9
it.execute()
}
// clog("Packed shit to ${jarFile.path}")
val response = dejsonizeBang(ServeUploadClassesAndInvoke.Response::class, HTTPPile.postJSON_bitchUnlessOK(
secrets.url + ServeUploadClassesAndInvoke.pathInfo,
jsonize(ServeUploadClassesAndInvoke.Request().fill(
rootToken = secrets.rootToken,
jarBase64 = Base64.getEncoder().encodeToString(jarFile.readBytes()),
classToInstantiateAndInvoke = ShitToUpload::class.java.name))))
clog(response.output)
}
}
class ShitToUpload : ServeUploadClassesAndInvoke.Fart() {
val kind =
"young"
// "moderate"
override fun fart() {
out.ln("I am the $kind fart")
SubShit1("hello").say()
SubShit2("Alraune config name is `${alConfig.configName}`").alsoSay()
}
inner class SubShit1(val text: String) {
fun say() {
out.ln("${simpleClassName(this)} of ${kind} fart says: $text")
}
}
inner class SubShit2(val text: String) {
fun alsoSay() {
out.ln("${simpleClassName(this)} of ${kind} fart also says: $text")
}
}
}
| apache-2.0 | 8f1db54730f04200f2b594927d651cd5 | 31.313131 | 114 | 0.582995 | 4.187173 | false | false | false | false |
allotria/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/RiderUI.kt | 1 | 22347 | package com.jetbrains.packagesearch.intellij.plugin.ui
import com.intellij.ide.plugins.newui.TagComponent
import com.intellij.notification.Notification
import com.intellij.notification.NotificationType
import com.intellij.notification.Notifications
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.Presentation
import com.intellij.openapi.actionSystem.ex.CustomComponentAction
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.ComboBox
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.util.IconLoader
import com.intellij.openapi.util.NlsContexts.Checkbox
import com.intellij.openapi.util.NlsContexts.Label
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.ui.*
import com.intellij.ui.components.JBList
import com.intellij.ui.treeStructure.Tree
import com.intellij.util.ui.JBDimension
import com.intellij.util.ui.JBEmptyBorder
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.components.BorderLayoutPanel
import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle
import org.jetbrains.annotations.Nls
import java.awt.*
import java.awt.event.*
import java.io.File
import javax.swing.*
import javax.swing.table.TableCellEditor
import javax.swing.table.TableCellRenderer
import javax.swing.tree.MutableTreeNode
import kotlin.math.max
@Suppress("TooManyFunctions", "MagicNumber", "unused") // Adopted code...
class RiderUI {
companion object {
val MAIN_BG_COLOR: Color =
JBColor.namedColor("Plugins.background", JBColor { if (JBColor.isBright()) UIUtil.getListBackground() else Color(0x313335) })
val GRAY_COLOR: Color = JBColor.namedColor("Label.infoForeground", JBColor(Gray._120, Gray._135))
val HeaderBackgroundColor = MAIN_BG_COLOR
val SectionHeaderBackgroundColor = JBColor.namedColor("Plugins.SectionHeader.background", JBColor(0xF7F7F7, 0x3C3F41))
val UsualBackgroundColor = MAIN_BG_COLOR
private val HeaderFont: Font = UIUtil.getListFont().let { Font(it.family, Font.BOLD, it.size) }
val BigFont: Font = UIUtil.getListFont().let { Font(it.family, Font.BOLD, (it.size * 1.3).toInt()) }
const val BigHeaderHeight = 40
const val MediumHeaderHeight = 30
const val SmallHeaderHeight = 24
fun headerPanel(init: BorderLayoutPanel.() -> Unit) = object : BorderLayoutPanel() {
init {
border = JBEmptyBorder(2, 0, 2, 12)
}
override fun getBackground() = HeaderBackgroundColor
}.apply(init)
fun borderPanel(backgroundColor: Color = UsualBackgroundColor, init: BorderLayoutPanel.() -> Unit) = object : BorderLayoutPanel() {
override fun getBackground() = backgroundColor
}.apply(init)
fun boxPanel(backgroundColor: Color = UsualBackgroundColor, init: JPanel.() -> Unit) = object : JPanel() {
init {
layout = BoxLayout(this, BoxLayout.Y_AXIS)
}
override fun getBackground() = backgroundColor
}.apply(init)
fun flowPanel(backgroundColor: Color = UsualBackgroundColor, init: JPanel.() -> Unit) = object : JPanel() {
init {
layout = FlowLayout(FlowLayout.LEFT)
}
override fun getBackground() = backgroundColor
}.apply(init)
fun checkBox(@Checkbox title: String) = object : JCheckBox(title) {
override fun getBackground() = UsualBackgroundColor
}
fun menuItem(@Nls title: String, icon: Icon?, handler: () -> Unit): JMenuItem {
if (icon != null) {
return JMenuItem(title, icon).apply { addActionListener { handler() } }
}
return JMenuItem(title).apply { addActionListener { handler() } }
}
fun <TItem> comboBox(items: Array<TItem>) = ComboBox(items).apply {
background = UsualBackgroundColor
border = BorderFactory.createMatteBorder(1, 1, 1, 1, JBUI.CurrentTheme.CustomFrameDecorations.paneBackground())
}
fun <TItem> comboBox(comboBoxModel: ComboBoxModel<TItem>) = ComboBox(comboBoxModel).apply {
background = UsualBackgroundColor
border = BorderFactory.createMatteBorder(1, 1, 1, 1, JBUI.CurrentTheme.CustomFrameDecorations.paneBackground())
}
fun updateParentHeight(component: JComponent) {
if (component.parent != null) {
component.parent.maximumSize = Dimension(Int.MAX_VALUE, component.maximumSize.height)
}
}
fun createLabel() = JLabel().apply { font = UIUtil.getLabelFont() }
fun createHeaderLabel(@Label text: String = "") = JLabel(text).apply { font = HeaderFont }
fun createBigLabel(@Label text: String = "") = JLabel(text).apply { font = BigFont }
fun createPlatformTag(@Nls text: String = "") = object : TagComponent(text.toLowerCase()) {
override fun isInClickableArea(pt: Point?) = false
}.apply {
RelativeFont.TINY.install(this)
}
fun toHtml(color: Color) = String.format("#%02x%02x%02x", color.red, color.green, color.blue)
fun getTextColor(isSelected: Boolean) = when {
isSelected -> RiderColor(UIUtil.getListSelectionForeground(true))
else -> RiderColor(UIUtil.getListForeground())
}
fun getTextColor2(isSelected: Boolean) = when {
isSelected -> getTextColor(isSelected)
else -> RiderColor(Color.GRAY, Color.GRAY)
}
fun setHeight(component: JComponent, height: Int, keepWidth: Boolean = false, scale: Boolean = true) {
val scaledHeight = if (scale) JBUI.scale(height) else height
component.apply {
preferredSize = Dimension(if (keepWidth) preferredSize.width else 0, scaledHeight)
minimumSize = Dimension(if (keepWidth) minimumSize.width else 0, scaledHeight)
maximumSize = Dimension(if (keepWidth) maximumSize.width else Int.MAX_VALUE, scaledHeight)
}
}
fun setWidth(component: JComponent, width: Int) {
val scaledWidth = JBUI.scale(width)
component.preferredSize = Dimension(scaledWidth, 0)
component.minimumSize = Dimension(scaledWidth, 0)
component.maximumSize = Dimension(scaledWidth, Int.MAX_VALUE)
}
inline fun <reified T> addPopupHandler(list: JBList<T>, crossinline createPopup: (T) -> JPopupMenu) {
list.addMouseListener(object : PopupHandler() {
override fun invokePopup(comp: Component?, x: Int, y: Int) {
val index = list.locationToIndex(Point(x, y - 1))
if (index != -1) {
val element = (list.model as DefaultListModel<T>).get(index)
if (element != null) {
val popup = createPopup(element)
popup.show(list, x, y)
}
}
}
})
}
inline fun <reified T : MutableTreeNode> addClickHandler(tree: Tree, count: Int = 1, crossinline clickHandler: (T) -> Unit) {
tree.addMouseListener(object : MouseAdapter() {
override fun mouseClicked(e: MouseEvent) {
if (e.clickCount == count || count == 0) {
val path = tree.getPathForLocation(e.x, e.y)
if (path != null) {
val node = path.lastPathComponent
if (node is T) clickHandler(node)
}
}
}
})
}
inline fun <reified T : MutableTreeNode> addDoubleClickHandler(tree: Tree, crossinline clickHandler: (T) -> Unit) {
addClickHandler(tree, 2, clickHandler)
}
inline fun <reified T : JComponent> onMouseClicked(comp: T, crossinline handler: T.(MouseEvent) -> Unit) {
comp.addMouseListener(object : MouseAdapter() {
override fun mouseClicked(e: MouseEvent) = handler(comp, e)
})
}
inline fun <reified T : JComponent> onMouseDoubleClicked(comp: T, crossinline handler: T.(MouseEvent) -> Unit) {
comp.addMouseListener(object : MouseAdapter() {
override fun mouseClicked(e: MouseEvent) {
if (e.clickCount == 2) {
handler(comp, e)
}
}
})
}
inline fun <reified T : JComponent> onFocusGained(comp: T, crossinline handler: T.(FocusEvent) -> Unit) {
comp.addFocusListener(object : FocusAdapter() {
override fun focusGained(e: FocusEvent) = handler(comp, e)
})
}
fun verticalScrollPane(c: Component) = object : JScrollPane(
VerticalScrollPanelWrapper(c),
VERTICAL_SCROLLBAR_AS_NEEDED,
HORIZONTAL_SCROLLBAR_NEVER
) {
init {
border = BorderFactory.createEmptyBorder()
viewport.background = UsualBackgroundColor
}
}
fun overrideKeyStroke(c: JComponent, stroke: String, action: () -> Unit) = overrideKeyStroke(c, stroke, stroke, action)
fun overrideKeyStroke(c: JComponent, key: String, stroke: String, action: () -> Unit) {
val inputMap = c.getInputMap(JComponent.WHEN_FOCUSED)
inputMap.put(KeyStroke.getKeyStroke(stroke), key)
c.actionMap.put(key, object : AbstractAction() {
override fun actionPerformed(arg: ActionEvent) {
action()
}
})
}
fun <E> addKeyboardPopupHandler(list: JBList<E>, stroke: String, createPopup: (List<E>) -> JPopupMenu?) {
val action = {
if (list.selectedIndex >= 0) {
val popup = createPopup(list.selectedValuesList)
if (popup != null && popup.subElements.any()) {
val location = JBPopupFactory.getInstance().guessBestPopupLocation(list).getPoint(list)
popup.show(list, location.x, location.y)
ApplicationManager.getApplication().invokeLater {
MenuSelectionManager.defaultManager().selectedPath = arrayOf<MenuElement>(popup, popup.subElements.first())
}
}
}
}
overrideKeyStroke(list, "jlist:$stroke", stroke, action)
}
fun updateScroller(comp: JComponent) {
val scrollPane = UIUtil.getParentOfType(JScrollPane::class.java, comp)
if (scrollPane != null) {
scrollPane.revalidate()
scrollPane.repaint()
scrollPane.parent?.apply {
revalidate()
repaint()
}
}
}
fun combineIcons(icon1: Icon?, icon2: Icon?, horizontal: Boolean): Icon? = when {
icon1 == null && icon2 == null -> null
icon1 == null || icon2 == null -> icon1 ?: icon2
horizontal -> RowIcon(icon1, icon2)
else -> CompositeIcon(icon1, icon2, horizontal)
}
fun openFile(project: Project, path: String) {
val file = VfsUtil.findFileByIoFile(File(path), true)
if (file == null) {
Notifications.Bus.notify(
Notification(
Notifications.SYSTEM_MESSAGES_GROUP_ID,
PackageSearchBundle.message("packagesearch.ui.error.noSuchFile.title"),
PackageSearchBundle.message("packagesearch.ui.error.noSuchFile.message", path),
NotificationType.ERROR
), project
)
} else {
FileEditorManager.getInstance(project).openFile(file, true, true)
}
}
}
private class CompositeIcon(val icon1: Icon, val icon2: Icon, val horizontal: Boolean) : Icon {
override fun paintIcon(c: Component?, g: Graphics?, x: Int, y: Int) {
icon1.paintIcon(c, g, x, y)
if (horizontal) {
icon2.paintIcon(c, g, x + icon1.iconWidth, y)
} else {
icon2.paintIcon(c, g, x, y + icon2.iconWidth)
}
}
override fun getIconWidth() = if (horizontal) icon1.iconWidth + icon2.iconWidth else max(icon1.iconWidth, icon2.iconWidth)
override fun getIconHeight() = if (horizontal) max(icon1.iconHeight, icon2.iconHeight) else icon1.iconHeight + icon2.iconHeight
}
private class VerticalScrollPanelWrapper(content: Component) : JPanel(), Scrollable {
init {
layout = BoxLayout(this, BoxLayout.Y_AXIS)
add(content)
}
override fun getPreferredScrollableViewportSize(): Dimension = preferredSize
override fun getScrollableUnitIncrement(visibleRect: Rectangle, orientation: Int, direction: Int) = 10
override fun getScrollableBlockIncrement(visibleRect: Rectangle, orientation: Int, direction: Int) = 100
override fun getScrollableTracksViewportWidth() = true
override fun getScrollableTracksViewportHeight() = false
override fun getBackground() = UsualBackgroundColor
}
}
abstract class ButtonColumn(private val table: JTable, private val buttonSize: Int) :
AbstractCellEditor(), TableCellRenderer, TableCellEditor, ActionListener, MouseListener {
private fun JButton.prepare(): JButton {
isBorderPainted = false
isFocusPainted = false
preferredSize = JBDimension(buttonSize, buttonSize)
minimumSize = JBDimension(buttonSize, buttonSize)
maximumSize = JBDimension(buttonSize, buttonSize)
return this
}
protected val renderButton = JButton().prepare()
protected val editButton = JButton().prepare()
private var editorValue: Any? = null
private var isButtonColumnEditor: Boolean = false
private val emptyRenderer = JPanel(BorderLayout())
private val rendererWrapper = JPanel(BorderLayout())
private val editorWrapper = JPanel(BorderLayout())
abstract fun getIcon(row: Int, column: Int): Icon?
abstract fun actionPerformed(row: Int, column: Int)
init {
@Suppress("LeakingThis") // Adopted code
editButton.addActionListener(this)
}
fun install(vararg columns: Int) {
val self = this
for (column in columns) {
table.columnModel.getColumn(column).apply {
cellRenderer = self
cellEditor = self
resizable = false
minWidth = JBUI.scale(buttonSize + 2)
maxWidth = JBUI.scale(buttonSize + 2)
preferredWidth = JBUI.scale(buttonSize + 2)
}
}
table.addMouseListener(this)
}
override fun getTableCellRendererComponent(table: JTable, value: Any?, isSelected: Boolean, hasFocus: Boolean, row: Int, column: Int): Component {
val cellIcon = getIcon(row, column)
return buildComponent(table, isSelected, cellIcon, rendererWrapper, renderButton)
}
override fun getTableCellEditorComponent(table: JTable, value: Any?, isSelected: Boolean, row: Int, column: Int): Component {
val cellIcon = getIcon(row, column)
editorValue = value
return buildComponent(table, true, cellIcon, editorWrapper, editButton)
}
private fun buildComponent(
table: JTable,
isSelected: Boolean,
cellIcon: Icon?,
wrapperComponent: JPanel,
button: JButton
): Component {
if (cellIcon == null) {
return emptyRenderer.colored(table, isSelected)
}
val component = button.apply {
icon = cellIcon
disabledIcon = IconLoader.getDisabledIcon(cellIcon)
}.colored(table, isSelected)
wrapperComponent.removeAll()
wrapperComponent.add(component)
wrapperComponent.revalidate()
return wrapperComponent.colored(table, isSelected)
}
override fun getCellEditorValue() = editorValue
override fun actionPerformed(e: ActionEvent) {
val row = table.convertRowIndexToModel(table.editingRow)
val column = table.convertColumnIndexToModel(table.editingColumn)
fireEditingStopped()
if (row != -1) {
actionPerformed(row, column)
}
}
override fun mousePressed(e: MouseEvent) {
if (table.isEditing && table.cellEditor === this) {
isButtonColumnEditor = true
}
}
override fun mouseReleased(e: MouseEvent) {
if (isButtonColumnEditor && table.isEditing) {
table.cellEditor.stopCellEditing()
}
isButtonColumnEditor = false
}
override fun mouseClicked(e: MouseEvent) {
// No-op
}
override fun mouseEntered(e: MouseEvent) {
// No-op
}
override fun mouseExited(e: MouseEvent) {
// No-op
}
}
abstract class ComboBoxColumn(
private val table: JTable,
private val comboBoxSize: Int
) : AbstractCellEditor(), TableCellRenderer, TableCellEditor, ActionListener, MouseListener {
private fun prepareComboBox() = RiderUI.comboBox(CollectionComboBoxModel(emptyList<Any>()))
.apply {
setMinimumAndPreferredWidth(JBUI.scale(comboBoxSize))
maximumSize.width = JBUI.scale(comboBoxSize)
}
private val renderComboBox = prepareComboBox()
private val editComboBox = prepareComboBox().apply {
putClientProperty("JComboBox.isTableCellEditor", true)
}
private var editorValue: Any? = null
private var editingRow: Int = -1
private var editingColumn: Int = -1
private var isComboBoxEditor: Boolean = false
init {
editComboBox.addActionListener(this)
}
fun install(vararg columns: Int) {
val self = this
for (column in columns) {
table.columnModel.getColumn(column).apply {
cellRenderer = self
cellEditor = self
resizable = false
minWidth = JBUI.scale(comboBoxSize)
maxWidth = JBUI.scale(comboBoxSize)
preferredWidth = JBUI.scale(comboBoxSize)
}
}
table.addMouseListener(this)
}
@Suppress("LongParameterList")
open fun customizeComboBox(
table: JTable,
value: Any?,
isSelected: Boolean,
hasFocus: Boolean,
row: Int,
column: Int,
comboBox: ComboBox<*>
): ComboBox<*> = comboBox
open fun actionPerformed(row: Int, column: Int, selectedValue: Any?) = Unit
override fun getTableCellRendererComponent(table: JTable, value: Any?, isSelected: Boolean, hasFocus: Boolean, row: Int, column: Int): Component {
return buildComponent(table, isSelected, customizeComboBox(table, value, isSelected, hasFocus, row, column, renderComboBox))
}
override fun getTableCellEditorComponent(table: JTable, value: Any?, isSelected: Boolean, row: Int, column: Int): Component {
val notCurrentlyEditedRow = editingRow >= 0 && editingRow != row
val notCurrentlyEditedColumn = editingColumn >= 0 && editingColumn != column
if (editComboBox.isEditable && (notCurrentlyEditedRow || notCurrentlyEditedColumn)) {
// Fire action performed event with previous value, if we were manually editing a different row/column.
val editorValue = (editComboBox.editor.editorComponent as JTextField).text
actionPerformed(editingRow, editingColumn, editorValue)
}
// Time to edit the new one
editingRow = row
editingColumn = column
editorValue = value
return buildComponent(table, true, customizeComboBox(table, value, isSelected, isSelected, row, column, editComboBox))
}
private fun buildComponent(table: JTable, isSelected: Boolean, comboBox: ComboBox<*>): Component =
comboBox.colored(table, isSelected)
override fun getCellEditorValue() = editorValue
override fun actionPerformed(e: ActionEvent) {
val row = max(table.convertRowIndexToModel(table.editingRow), editingRow)
val column = max(table.convertColumnIndexToModel(table.editingColumn), editingColumn)
fireEditingStopped()
if (row != -1) {
actionPerformed(row, column, editComboBox.selectedItem)
}
}
override fun mousePressed(e: MouseEvent) {
if (table.isEditing && table.cellEditor === this) {
isComboBoxEditor = true
}
}
override fun mouseReleased(e: MouseEvent) {
if (!table.isEditing) {
editingRow = -1
editingColumn = -1
editorValue = null
}
}
override fun mouseClicked(e: MouseEvent) {
// No-op
}
override fun mouseEntered(e: MouseEvent) {
// No-op
}
override fun mouseExited(e: MouseEvent) {
// No-op
}
}
class RiderColor : JBColor {
constructor(regular: Color, dark: Color) : super(regular, dark)
constructor(regular: Color) : super(regular, regular)
}
class ComponentActionWrapper(private val myComponentCreator: () -> JComponent) : DumbAwareAction(),
CustomComponentAction {
override fun createCustomComponent(presentation: Presentation) = myComponentCreator()
override fun actionPerformed(e: AnActionEvent) {
// No-op
}
}
fun JBColor.toHtml() = RiderUI.toHtml(this)
fun Component.colored(table: JTable, isSelected: Boolean) = this.apply {
foreground = if (isSelected) table.selectionForeground else table.foreground
background = if (isSelected) table.selectionBackground else RiderUI.UsualBackgroundColor
}
fun Component.updateAndRepaint() {
this.invalidate()
this.repaint()
}
| apache-2.0 | fdc796ea72751eeb28d33ae7aebb660d | 37.796875 | 150 | 0.62429 | 4.878193 | false | false | false | false |
androidx/androidx | compose/material3/material3/integration-tests/material3-catalog/src/main/java/androidx/compose/material3/catalog/library/model/Components.kt | 3 | 11556 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.material3.catalog.library.model
import androidx.annotation.DrawableRes
import androidx.compose.material3.catalog.library.R
import androidx.compose.material3.catalog.library.util.ComponentGuidelinesUrl
import androidx.compose.material3.catalog.library.util.DocsUrl
import androidx.compose.material3.catalog.library.util.Material3SourceUrl
import androidx.compose.material3.catalog.library.util.PackageSummaryUrl
import androidx.compose.material3.catalog.library.util.StyleGuidelinesUrl
data class Component(
val id: Int,
val name: String,
val description: String,
@DrawableRes
val icon: Int = R.drawable.ic_component,
val tintIcon: Boolean = true,
val guidelinesUrl: String,
val docsUrl: String,
val sourceUrl: String,
val examples: List<Example>
)
private var nextId: Int = 1
private fun nextId(): Int = nextId.also { nextId += 1 }
// Components are ordered alphabetically by name.
private val Badge =
Component(
id = nextId(),
name = "Badge",
description =
"A badge can contain dynamic information, such as the presence of a new " +
"notification or a number of pending requests. Badges can be icon only or contain " +
"a short text.",
// No badge icon
guidelinesUrl = "$ComponentGuidelinesUrl/badge",
docsUrl = "$DocsUrl#badge",
sourceUrl = "$Material3SourceUrl/Badge.kt",
examples = BadgeExamples
)
private val BottomAppBars = Component(
id = nextId(),
name = "Bottom App Bar",
description = "A bottom app bar displays navigation and key actions at the bottom of mobile " +
"screens.",
// No bottom app bar icon
guidelinesUrl = "$ComponentGuidelinesUrl/bottom-app-bars",
docsUrl = "$DocsUrl#bottomappbar",
sourceUrl = "$Material3SourceUrl/AppBar.kt",
examples = BottomAppBarsExamples
)
private val Buttons = Component(
id = nextId(),
name = "Buttons",
description = "Buttons help people initiate actions, from sending an email, to sharing a " +
"document, to liking a post.",
// No buttons icon
guidelinesUrl = "$ComponentGuidelinesUrl/buttons",
docsUrl = "$PackageSummaryUrl#button",
sourceUrl = "$Material3SourceUrl/Button.kt",
examples = ButtonsExamples,
)
private val Card = Component(
id = nextId(),
name = "Card",
description = "Cards contain content and actions that relate information about a subject.",
// No card icon
guidelinesUrl = "$StyleGuidelinesUrl/cards",
docsUrl = "$PackageSummaryUrl#card",
sourceUrl = "$Material3SourceUrl/Card.kt",
examples = CardExamples
)
private val Checkboxes = Component(
id = nextId(),
name = "Checkboxes",
description = "Checkboxes allow the user to select one or more items from a set or turn an " +
"option on or off.",
// No checkbox icon
guidelinesUrl = "$ComponentGuidelinesUrl/checkboxes",
docsUrl = "$DocsUrl#checkbox",
sourceUrl = "$Material3SourceUrl/Checkbox.kt",
examples = CheckboxesExamples
)
private val Chips = Component(
id = nextId(),
name = "Chips",
description = "Chips allow users to enter information, make selections, filter content, or" +
" trigger actions.",
// No chip icon
guidelinesUrl = "$ComponentGuidelinesUrl/chips",
docsUrl = "$DocsUrl#chips",
sourceUrl = "$Material3SourceUrl/Chip.kt",
examples = ChipsExamples
)
private val Dialogs = Component(
id = nextId(),
name = "Dialogs",
description = "Dialogs provide important prompts in a user flow. They can require an action, " +
"communicate information, or help users accomplish a task.",
// No dialogs icon
guidelinesUrl = "$ComponentGuidelinesUrl/dialogs",
docsUrl = "$PackageSummaryUrl#alertdialog",
sourceUrl = "$Material3SourceUrl/AlertDialog.kt",
examples = DialogExamples
)
private val ExtendedFloatingActionButton = Component(
id = nextId(),
name = "Extended FAB",
description = "Extended FABs help people take primary actions. They're wider than FABs to " +
"accommodate a text label and larger target area.",
// No extended FAB icon
guidelinesUrl = "$ComponentGuidelinesUrl/extended-fab",
docsUrl = "$PackageSummaryUrl#extendedfloatingactionbutton",
sourceUrl = "$Material3SourceUrl/FloatingActionButton.kt",
examples = ExtendedFABExamples,
)
private val FloatingActionButtons = Component(
id = nextId(),
name = "Floating action buttons",
description = "The FAB represents the most important action on a screen. It puts key actions " +
"within reach.",
// No FABs icon
guidelinesUrl = "$ComponentGuidelinesUrl/floating-action-button",
docsUrl = "$PackageSummaryUrl#floatingactionbutton",
sourceUrl = "$Material3SourceUrl/FloatingActionButton.kt",
examples = FloatingActionButtonsExamples,
)
private val IconButtons = Component(
id = nextId(),
name = "Icon buttons",
description = "Icon buttons allow users to take actions and make choices with a single tap.",
// No icon-button icon
guidelinesUrl = "$ComponentGuidelinesUrl/icon-button",
docsUrl = "$PackageSummaryUrl#iconbutton",
sourceUrl = "$Material3SourceUrl/IconButton.kt",
examples = IconButtonExamples,
)
private val Lists = Component(
id = nextId(),
name = "Lists",
description = "Lists are continuous, vertical indexes of text or images.",
// No ListItem icon
tintIcon = true,
guidelinesUrl = "$ComponentGuidelinesUrl/list-item",
docsUrl = "$PackageSummaryUrl#listitem",
sourceUrl = "$Material3SourceUrl/ListItem.kt",
examples = ListsExamples,
)
private val Menus = Component(
id = nextId(),
name = "Menus",
description = "Menus display a list of choices on temporary surfaces.",
// No menu icon
guidelinesUrl = "$ComponentGuidelinesUrl/menus",
docsUrl = "$PackageSummaryUrl#dropdownmenu",
sourceUrl = "$Material3SourceUrl/Menu.kt",
examples = MenusExamples
)
private val NavigationBar = Component(
id = nextId(),
name = "Navigation bar",
description = "Navigation bars offer a persistent and convenient way to switch between " +
"primary destinations in an app.",
// No navigation bar icon
guidelinesUrl = "$ComponentGuidelinesUrl/navigation-bar",
docsUrl = "$PackageSummaryUrl#navigationbar",
sourceUrl = "$Material3SourceUrl/NavigationBar.kt",
examples = NavigationBarExamples
)
private val NavigationDrawer = Component(
id = nextId(),
name = "Navigation drawer",
description = "Navigation drawers provide ergonomic access to destinations in an app.",
// No navigation drawer icon
guidelinesUrl = "$ComponentGuidelinesUrl/navigation-drawer",
docsUrl = "$PackageSummaryUrl#navigationdrawer",
sourceUrl = "$Material3SourceUrl/NavigationDrawer.kt",
examples = NavigationDrawerExamples
)
private val NavigationRail = Component(
id = nextId(),
name = "Navigation rail",
description = "Navigation rails provide access to primary destinations in apps when using " +
"tablet and desktop screens.",
// No navigation rail icon
guidelinesUrl = "$ComponentGuidelinesUrl/navigation-rail",
docsUrl = "$PackageSummaryUrl#navigationrail",
sourceUrl = "$Material3SourceUrl/NavigationRail.kt",
examples = NavigationRailExamples
)
private val ProgressIndicators = Component(
id = nextId(),
name = "Progress indicators",
description = "Progress indicators express an unspecified wait time or display the length of " +
"a process.",
// No progress indicator icon
guidelinesUrl = "$ComponentGuidelinesUrl/progress-indicators",
docsUrl = "$DocsUrl#circularprogressindicator",
sourceUrl = "$Material3SourceUrl/ProgressIndicator.kt",
examples = ProgressIndicatorsExamples
)
private val RadioButtons = Component(
id = nextId(),
name = "Radio buttons",
description = "Radio buttons allow the user to select one option from a set.",
// No radio-button icon
guidelinesUrl = "$ComponentGuidelinesUrl/radio-buttons",
docsUrl = "$DocsUrl#radiobutton",
sourceUrl = "$Material3SourceUrl/RadioButton.kt",
examples = RadioButtonsExamples
)
private val Sliders = Component(
id = nextId(),
name = "Sliders",
description = "Sliders allow users to make selections from a range of values.",
// No slider icon
guidelinesUrl = "", // No guidelines yet
docsUrl = "", // No docs yet
sourceUrl = "$Material3SourceUrl/Slider.kt",
examples = SlidersExamples
)
private val Snackbars = Component(
id = nextId(),
name = "Snackbars",
description = "Snackbars provide brief messages about app processes at the bottom of the " +
"screen.",
// No snackbar icon
guidelinesUrl = "$ComponentGuidelinesUrl/snackbars",
docsUrl = "$DocsUrl#snackbar",
sourceUrl = "$Material3SourceUrl/Snackbar.kt",
examples = SnackbarsExamples
)
private val Switches = Component(
id = nextId(),
name = "Switches",
description = "Switches toggle the state of a single setting on or off.",
// No switch icon
// No guidelines yet
guidelinesUrl = "",
docsUrl = "",
sourceUrl = "$Material3SourceUrl/Switch.kt",
examples = SwitchExamples
)
private val Tabs = Component(
id = nextId(),
name = "Tabs",
description = "Tabs organize content across different screens, data sets, and other " +
"interactions.",
// No tabs icon
guidelinesUrl = "$ComponentGuidelinesUrl/tabs",
docsUrl = "$DocsUrl#tab",
sourceUrl = "$Material3SourceUrl/Tab.kt",
examples = TabsExamples
)
private val TextFields = Component(
id = nextId(),
name = "Text fields",
description = "Text fields let users enter and edit text.",
// No text fields icon
guidelinesUrl = "$ComponentGuidelinesUrl/text-fields",
docsUrl = "$DocsUrl#textfield",
sourceUrl = "$Material3SourceUrl/TextField.kt",
examples = TextFieldsExamples
)
private val TopAppBar = Component(
id = nextId(),
name = "Top app bar",
description = "Top app bars display information and actions at the top of a screen.",
// No top app bar icon
guidelinesUrl = "$ComponentGuidelinesUrl/top-app-bar",
docsUrl = "$PackageSummaryUrl#smalltopappbar",
sourceUrl = "$Material3SourceUrl/AppBar.kt",
examples = TopAppBarExamples
)
/** Components for the catalog, ordered alphabetically by name. */
val Components = listOf(
Badge,
BottomAppBars,
Buttons,
Card,
Checkboxes,
Chips,
Dialogs,
ExtendedFloatingActionButton,
FloatingActionButtons,
IconButtons,
Lists,
Menus,
NavigationBar,
NavigationDrawer,
NavigationRail,
ProgressIndicators,
RadioButtons,
Sliders,
Snackbars,
Switches,
Tabs,
TextFields,
TopAppBar
)
| apache-2.0 | cdb43a3a44edc0973a68b5c6c77a9d5d | 32.988235 | 100 | 0.696954 | 4.355824 | false | false | false | false |
SDS-Studios/ScoreKeeper | app/src/main/java/io/github/sdsstudios/ScoreKeeper/Fragment/EditPlayerFragment.kt | 1 | 1781 | package io.github.sdsstudios.ScoreKeeper.Fragment
import android.net.Uri
import android.os.Bundle
import android.support.v4.app.FragmentManager
import android.view.View
import io.github.sdsstudios.ScoreKeeper.R
import java.io.File
/**
* Created by sethsch1 on 05/11/17.
*/
open class EditPlayerFragment : PlayerFragment() {
companion object {
const val ARG_PLAYER_ID = "player_id"
fun showDialog(fragmentManager: FragmentManager, playerId: Long) {
val bundle = Bundle()
val fragment = EditPlayerFragment()
bundle.putLong(ARG_PLAYER_ID, playerId)
fragment.arguments = bundle
fragment.show(fragmentManager, TAG)
}
}
override var deleteIconOnDismiss: Boolean = false
override val title by lazy { getString(R.string.title_edit_player) }
override val posText by lazy { getString(R.string.pos_done) }
private val mPlayerId by lazy { arguments!!.getLong(ARG_PLAYER_ID) }
val player by lazy { playersViewModel.playerList.value!!.single { it.id == mPlayerId } }
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
if (player.iconName != null) {
outputUri = Uri.fromFile(File(
"${context!!.filesDir}/${player.iconName}"))
}
editTextName.setText(player.name)
playerIconLayout.setIcon(player.iconName)
}
override fun setSelectedColorIndex() {
selectedColor = player.color
}
override fun onPositiveButtonClick(iconName: String?) {
player.name = editTextName.text.toString()
player.iconName = iconName
player.color = selectedColor
playersViewModel.update(player)
}
} | gpl-3.0 | 0ed6949a4a9cdba6d3459be5eab623fb | 28.7 | 92 | 0.669848 | 4.419355 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/ui/GotItTooltip.kt | 7 | 29092 | // 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
import com.intellij.icons.AllIcons
import com.intellij.ide.BrowserUtil
import com.intellij.ide.HelpTooltip
import com.intellij.ide.IdeBundle
import com.intellij.ide.IdeEventQueue
import com.intellij.ide.util.PropertiesComponent
import com.intellij.internal.statistic.collectors.fus.ui.GotItUsageCollector
import com.intellij.internal.statistic.collectors.fus.ui.GotItUsageCollectorGroup
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.Presentation
import com.intellij.openapi.actionSystem.Shortcut
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.ui.popup.Balloon
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.ui.popup.JBPopupListener
import com.intellij.openapi.ui.popup.LightweightWindowEvent
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.IconLoader
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.text.HtmlBuilder
import com.intellij.openapi.util.text.HtmlChunk
import com.intellij.ui.awt.RelativePoint
import com.intellij.ui.components.JBLabel
import com.intellij.ui.components.labels.LinkLabel
import com.intellij.ui.components.labels.LinkListener
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.Alarm
import com.intellij.util.ui.*
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.NonNls
import java.awt.*
import java.awt.event.ActionListener
import java.awt.event.ComponentAdapter
import java.awt.event.ComponentEvent
import java.awt.event.KeyEvent
import java.io.StringReader
import java.net.URL
import javax.swing.*
import javax.swing.event.AncestorEvent
import javax.swing.text.*
import javax.swing.text.html.HTML
import javax.swing.text.html.HTMLDocument
import javax.swing.text.html.HTMLEditorKit
import javax.swing.text.html.StyleSheet
@Service(Service.Level.APP)
class GotItTooltipService {
val isFirstRun = checkFirstRun()
private fun checkFirstRun(): Boolean {
val prevRunBuild = PropertiesComponent.getInstance().getValue("gotit.previous.run")
val currentRunBuild = ApplicationInfo.getInstance().build.asString()
if (prevRunBuild != currentRunBuild) {
PropertiesComponent.getInstance().setValue("gotit.previous.run", currentRunBuild)
return true
}
return false
}
companion object {
fun getInstance(): GotItTooltipService = service()
}
}
/**
* The `id` is a unique identifier for the tooltip that will be used to store the tooltip state in [PropertiesComponent].
* Identifier has the following format: `place.where.used` (lowercase words separated with dots).
*
* Got It tooltip usage statistics can be properly gathered if its identifier prefix is registered in
* `plugin.xml` (`PlatformExtensions.xml`) with `com.intellij.statistics.gotItTooltipAllowlist` extension point.
* Prefix can cover a whole class of different Got It tooltips. If the prefix is shorter than the whole ID, then all different
* tooltip usages will be reported in one category described by the prefix.
*/
class GotItTooltip(@NonNls val id: String,
@Nls val text: String,
parentDisposable: Disposable? = null) : ToolbarActionTracker<Balloon>() {
@Nls
private var header: String = ""
@Nls
private var buttonLabel: String = IdeBundle.message("got.it.button.name")
private var shortcut: Shortcut? = null
private var icon: Icon? = null
private var timeout: Int = -1
private var link: LinkLabel<Unit>? = null
private var linkAction: () -> Unit = {}
private var maxWidth = MAX_WIDTH
private var showCloseShortcut = false
private var maxCount = 1
private var onBalloonCreated: (Balloon) -> Unit = {}
private var useContrastColors = false
// Ease the access (remove private or val to var) if fine-tuning is needed.
private val savedCount: (String) -> Int = { PropertiesComponent.getInstance().getInt(it, 0) }
var showCondition: (String) -> Boolean = { savedCount(it) in 0 until maxCount }
private val gotIt: (String) -> Unit = {
val count = savedCount(it)
if (count in 0 until maxCount) PropertiesComponent.getInstance().setValue(it, (count + 1).toString())
onGotIt()
}
private var onGotIt: () -> Unit = {}
private val alarm = Alarm()
private var balloon: Balloon? = null
private var nextToShow: GotItTooltip? = null // Next tooltip in the global queue
private var pendingRefresh = false
var position: Balloon.Position = Balloon.Position.below
init {
if (parentDisposable != null) {
Disposer.register(parentDisposable, this)
}
}
override fun assignTo(presentation: Presentation, pointProvider: (Component, Balloon) -> Point) {
this.pointProvider = pointProvider
presentation.putClientProperty(PRESENTATION_GOT_IT_KEY as Key<Any>, this)
Disposer.register(this, Disposable { presentation.putClientProperty(PRESENTATION_GOT_IT_KEY, null) })
}
/**
* Add an optional header to the tooltip.
*/
fun withHeader(@Nls header: String): GotItTooltip {
this.header = header
return this
}
/**
* Set preferred tooltip position relatively to the owner component.
*/
fun withPosition(position: Balloon.Position): GotItTooltip {
this.position = position
return this
}
/**
* Add optional shortcut after mandatory description (text).
*/
fun withShortcut(shortcut: Shortcut): GotItTooltip {
this.shortcut = shortcut
return this
}
/**
* Set alternative button text instead of default "Got It".
*/
fun withButtonLabel(@Nls label: String): GotItTooltip {
this.buttonLabel = label
return this
}
/**
* Add optional icon on the left of the header or description.
*/
fun withIcon(icon: Icon): GotItTooltip {
this.icon = icon
return this
}
/**
* Set the close timeout. If set, then the tooltip appears without the "Got It" button.
*/
@JvmOverloads
fun withTimeout(timeout: Int = DEFAULT_TIMEOUT): GotItTooltip {
if (timeout > 0) {
this.timeout = timeout
}
return this
}
/**
* Limit tooltip body width to the given value. By default, it's limited to `MAX_WIDTH` pixels.
*/
fun withMaxWidth(width: Int): GotItTooltip {
maxWidth = width
return this
}
/**
* Add an optional link to the tooltip.
*/
fun withLink(@Nls linkLabel: String, action: () -> Unit): GotItTooltip {
link = object : LinkLabel<Unit>(linkLabel, null) {
override fun getNormal(): Color = JBUI.CurrentTheme.GotItTooltip.linkForeground()
}
linkAction = action
return this
}
/**
* Add an optional link to the tooltip. Java version.
*/
fun withLink(@Nls linkLabel: String, action: Runnable): GotItTooltip {
return withLink(linkLabel) { action.run() }
}
/**
* Add an optional browser link to the tooltip. Link is rendered with arrow icon.
*/
fun withBrowserLink(@Nls linkLabel: String, url: URL): GotItTooltip {
link = object : LinkLabel<Unit>(linkLabel, AllIcons.Ide.External_link_arrow) {
override fun getNormal(): Color = JBUI.CurrentTheme.GotItTooltip.linkForeground()
}.apply { horizontalTextPosition = SwingConstants.LEFT }
linkAction = { BrowserUtil.browse(url) }
return this
}
/**
* Set number of times the tooltip is shown.
*/
fun withShowCount(count: Int): GotItTooltip {
if (count > 0) maxCount = count
return this
}
/**
* Set whether to use contrast tooltip colors.
*/
fun withContrastColors(contrastColors: Boolean): GotItTooltip {
useContrastColors = contrastColors
return this
}
/**
* Show close shortcut next to the "Got It" button.
*/
fun andShowCloseShortcut(): GotItTooltip {
showCloseShortcut = true
return this
}
/**
* Set the notification method that's called when actual [Balloon] is created.
*/
fun setOnBalloonCreated(callback: (Balloon) -> Unit): GotItTooltip {
onBalloonCreated = callback
return this
}
/**
* Returns `true` if this tooltip can be shown at the given properties settings.
*/
override fun canShow(): Boolean = showCondition("$PROPERTY_PREFIX.$id")
/**
* Show tooltip for the given component and point to the component.
*
* If the component is showing (see [Component.isShowing]) and has not empty bounds,
* then the tooltip is shown right away.
*
* If the component is showing but has empty bounds (technically not visible),
* then tooltip is shown asynchronously when the component gets resized to not empty bounds.
*
* If the component is not showing, then tooltip is shown asynchronously when component is added to the hierarchy
* and gets not empty bounds.
*/
override fun show(component: JComponent, pointProvider: (Component, Balloon) -> Point) {
if (canShow()) {
if (component.isShowing) {
if (!component.bounds.isEmpty) {
showImpl(component, pointProvider)
}
else {
component.addComponentListener(object : ComponentAdapter() {
override fun componentResized(event: ComponentEvent) {
if (!event.component.bounds.isEmpty) {
showImpl(event.component as JComponent, pointProvider)
}
}
}.also { Disposer.register(this, Disposable { component.removeComponentListener(it) }) })
}
}
else {
component.addAncestorListener(object : AncestorListenerAdapter() {
override fun ancestorAdded(ancestorEvent: AncestorEvent) {
if (!ancestorEvent.component.bounds.isEmpty) {
showImpl(ancestorEvent.component, pointProvider)
}
else {
ancestorEvent.component.addComponentListener(object : ComponentAdapter() {
override fun componentResized(componentEvent: ComponentEvent) {
if (!componentEvent.component.bounds.isEmpty) {
showImpl(componentEvent.component as JComponent, pointProvider)
}
}
}.also { Disposer.register(this@GotItTooltip, Disposable { component.removeComponentListener(it) }) })
}
}
override fun ancestorRemoved(ancestorEvent: AncestorEvent) {
balloon?.let {
it.hide(true)
GotItUsageCollector.instance.logClose(id, GotItUsageCollectorGroup.CloseType.AncestorRemoved)
}
balloon = null
}
}.also { Disposer.register(this, Disposable { component.removeAncestorListener(it) }) })
}
}
}
private fun showImpl(component: JComponent, pointProvider: (Component, Balloon) -> Point) {
if (canShow()) {
val balloonProperty = ClientProperty.get(component, BALLOON_PROPERTY)
if (balloonProperty == null) {
balloon = createAndShow(component, pointProvider).also { ClientProperty.put(component, BALLOON_PROPERTY, it) }
}
else if (balloonProperty is BalloonImpl && balloonProperty.isVisible) {
balloonProperty.revalidate()
}
}
else {
hidePopup()
}
}
override fun wasCreated(): Boolean {
return balloon != null
}
override fun init(component: JComponent, pointProvider: (Component, Balloon) -> Point) {
createAndShow(component, pointProvider)
}
fun createAndShow(component: JComponent, pointProvider: (Component, Balloon) -> Point): Balloon {
val tracker = object : PositionTracker<Balloon>(component) {
override fun recalculateLocation(balloon: Balloon): RelativePoint? =
if (getComponent().isShowing)
RelativePoint(component, pointProvider(component, balloon))
else {
balloon.hide(true)
GotItUsageCollector.instance.logClose(id, GotItUsageCollectorGroup.CloseType.AncestorRemoved)
null
}
}
val balloon = createBalloon().also {
val dispatcherDisposable = Disposer.newDisposable()
Disposer.register(this, dispatcherDisposable)
it.addListener(object : JBPopupListener {
override fun beforeShown(event: LightweightWindowEvent) {
GotItUsageCollector.instance.logOpen(id, savedCount("$PROPERTY_PREFIX.$id") + 1)
}
override fun onClosed(event: LightweightWindowEvent) {
HelpTooltip.setMasterPopupOpenCondition(tracker.component, null)
ClientProperty.put(tracker.component as JComponent, BALLOON_PROPERTY, null)
Disposer.dispose(dispatcherDisposable)
if (event.isOk) {
currentlyShown?.nextToShow = null
currentlyShown = null
gotIt()
}
else {
pendingRefresh = true
}
}
})
IdeEventQueue.getInstance().addDispatcher(IdeEventQueue.EventDispatcher { e ->
if (e is KeyEvent && KeymapUtil.isEventForAction(e, CLOSE_ACTION_NAME)) {
it.hide(true)
GotItUsageCollector.instance.logClose(id, GotItUsageCollectorGroup.CloseType.EscapeShortcutPressed)
true
}
else false
}, dispatcherDisposable)
HelpTooltip.setMasterPopupOpenCondition(tracker.component) {
it.isDisposed
}
onBalloonCreated(it)
}
this.balloon = balloon
when {
currentlyShown == null -> {
balloon.show(tracker, position)
currentlyShown = this
}
currentlyShown!!.pendingRefresh -> {
nextToShow = currentlyShown!!.nextToShow
balloon.show(tracker, position)
currentlyShown = this
}
else -> {
var tooltip = currentlyShown as GotItTooltip
while (tooltip.nextToShow != null) {
tooltip = tooltip.nextToShow as GotItTooltip
}
tooltip.scheduleNext(this) {
if (tracker.component.isShowing && !tracker.component.bounds.isEmpty) {
balloon.show(tracker, position)
currentlyShown = this@GotItTooltip
}
else {
nextToShow?.let { it.onGotIt() }
}
}
}
}
return balloon
}
fun gotIt() = gotIt("$PROPERTY_PREFIX.$id")
private fun scheduleNext(tooltip: GotItTooltip, show: () -> Unit) {
nextToShow = tooltip
onGotIt = show
}
private fun createBalloon(): Balloon {
var button: JButton? = null
val balloon = JBPopupFactory.getInstance()
.createBalloonBuilder(createContent { button = it })
.setDisposable(this)
.setHideOnAction(false)
.setHideOnClickOutside(false)
.setHideOnFrameResize(false)
.setHideOnKeyOutside(false)
.setHideOnClickOutside(false)
.setBlockClicksThroughBalloon(true)
.setBorderColor(JBUI.CurrentTheme.GotItTooltip.borderColor(useContrastColors))
.setCornerToPointerDistance(ARROW_SHIFT)
.setFillColor(JBUI.CurrentTheme.GotItTooltip.background(useContrastColors))
.setPointerSize(JBUI.size(16, 8))
.createBalloon().also { it.setAnimationEnabled(false) }
val collector = GotItUsageCollector.instance
link?.apply {
setListener(LinkListener { _, _ ->
linkAction()
balloon.hide(true)
collector.logClose(id, GotItUsageCollectorGroup.CloseType.LinkClick)
}, null)
}
button?.apply {
addActionListener(ActionListener {
balloon.hide(true)
collector.logClose(id, GotItUsageCollectorGroup.CloseType.ButtonClick)
})
}
if (timeout > 0) {
alarm.cancelAllRequests()
alarm.addRequest({
balloon.hide(true)
collector.logClose(id, GotItUsageCollectorGroup.CloseType.Timeout)
}, timeout)
}
return balloon
}
private fun createContent(buttonSupplier: (JButton) -> Unit): JComponent {
val panel = JPanel(GridBagLayout())
val gc = GridBag()
val left = if (icon != null) 8 else 0
val column = if (icon != null) 1 else 0
icon?.let { panel.add(JLabel(it), gc.nextLine().next().anchor(GridBagConstraints.BASELINE)) }
if (header.isNotEmpty()) {
if (icon == null) gc.nextLine()
val finalText = HtmlChunk.raw(header)
.bold()
.wrapWith(HtmlChunk.font(ColorUtil.toHtmlColor(JBUI.CurrentTheme.GotItTooltip.foreground(useContrastColors))))
.wrapWith(HtmlChunk.html())
.toString()
panel.add(JBLabel(finalText), gc.setColumn(column).anchor(GridBagConstraints.LINE_START).insetLeft(left))
}
val builder = HtmlBuilder()
builder.append(HtmlChunk.raw(text).wrapWith(HtmlChunk.font(ColorUtil.toHtmlColor(
JBUI.CurrentTheme.GotItTooltip.foreground(useContrastColors)))))
shortcut?.let {
builder.append(HtmlChunk.nbsp())
.append(HtmlChunk.nbsp())
.append(HtmlChunk.text(KeymapUtil.getShortcutText(it))
.wrapWith(HtmlChunk.font(ColorUtil.toHtmlColor(JBUI.CurrentTheme.GotItTooltip.shortcutForeground(useContrastColors)))))
}
if (icon == null || header.isNotEmpty()) gc.nextLine()
panel.add(LimitedWidthLabel(builder, maxWidth),
gc.setColumn(column).anchor(GridBagConstraints.LINE_START).insets(if (header.isNotEmpty()) 5 else 0, left, 0, 0))
link?.let {
panel.add(it, gc.nextLine().setColumn(column).anchor(GridBagConstraints.LINE_START).insets(5, left, 0, 0))
}
if (timeout <= 0) {
val button = JButton(buttonLabel).apply {
isFocusable = false
isOpaque = false
putClientProperty("gotItButton", true)
if (useContrastColors) {
border = JBUI.Borders.empty(0, 0, 5, 0)
background = Color(0, true)
putClientProperty("JButton.backgroundColor", JBUI.CurrentTheme.GotItTooltip.buttonBackgroundContrast())
putClientProperty("ActionToolbar.smallVariant", true) // remove shadow in darcula
foreground = JBUI.CurrentTheme.GotItTooltip.buttonForegroundContrast()
}
}
buttonSupplier(button)
if (showCloseShortcut) {
val buttonPanel = JPanel().apply { isOpaque = false }
buttonPanel.layout = BoxLayout(buttonPanel, BoxLayout.X_AXIS)
buttonPanel.add(button)
buttonPanel.add(Box.createHorizontalStrut(JBUIScale.scale(UIUtil.DEFAULT_HGAP)))
val closeShortcut = JLabel(KeymapUtil.getShortcutText(CLOSE_ACTION_NAME)).apply {
foreground = JBUI.CurrentTheme.GotItTooltip.shortcutForeground(useContrastColors)
}
buttonPanel.add(closeShortcut)
panel.add(buttonPanel, gc.nextLine().setColumn(column).insets(11, left, 0, 0).anchor(GridBagConstraints.LINE_START))
}
else {
panel.add(button, gc.nextLine().setColumn(column).insets(11, left, 0, 0).anchor(GridBagConstraints.LINE_START))
}
}
panel.background = JBUI.CurrentTheme.GotItTooltip.background(useContrastColors)
panel.border = PANEL_MARGINS
return panel
}
override fun dispose() {
hidePopup()
removeMeFromQueue()
}
private fun removeMeFromQueue() {
if (currentlyShown === this) currentlyShown = nextToShow
else {
var tooltip = currentlyShown
while (tooltip != null) {
if (tooltip.nextToShow === this) {
tooltip.nextToShow = nextToShow
break
}
tooltip = tooltip.nextToShow
}
}
}
override fun hidePopup() {
balloon?.hide(false)
balloon = null
}
override fun hideOrRepaint(component: JComponent) {
balloon?.let {
if (component.bounds.isEmpty) {
hidePopup()
}
else if (it is BalloonImpl && it.isVisible) {
it.revalidate()
}
}
}
companion object {
@JvmField
val ARROW_SHIFT = JBUIScale.scale(20) + Registry.intValue("ide.balloon.shadow.size") + BalloonImpl.ARC.get()
const val PROPERTY_PREFIX = "got.it.tooltip"
private val BALLOON_PROPERTY = Key<Balloon>("$PROPERTY_PREFIX.balloon")
private const val DEFAULT_TIMEOUT = 5000 // milliseconds
private const val CLOSE_ACTION_NAME = "CloseGotItTooltip"
private val MAX_WIDTH = JBUIScale.scale(280)
private val PANEL_MARGINS = JBUI.Borders.empty(7, 4, 9, 9)
internal fun findIcon(src: String): Icon? {
return IconLoader.findIcon(src, GotItTooltip::class.java.classLoader)
}
// Frequently used point providers
@JvmField
val TOP_MIDDLE: (Component, Any) -> Point = { it, _ -> Point(it.width / 2, 0) }
@JvmField
val LEFT_MIDDLE: (Component, Any) -> Point = { it, _ -> Point(0, it.height / 2) }
@JvmField
val RIGHT_MIDDLE: (Component, Any) -> Point = { it, _ -> Point(it.width, it.height / 2) }
@JvmField
val BOTTOM_MIDDLE: (Component, Any) -> Point = { it, _ -> Point(it.width / 2, it.height) }
@JvmField
val BOTTOM_LEFT: (Component, Any) -> Point = { it, _ -> Point(0, it.height) }
// Global tooltip queue start element
private var currentlyShown: GotItTooltip? = null
}
}
private class LimitedWidthLabel (htmlBuilder: HtmlBuilder, limit: Int) : JLabel() {
val htmlView: View
init {
var htmlText = htmlBuilder.wrapWith(HtmlChunk.div()).wrapWith(HtmlChunk.html()).toString()
var view = createHTMLView(this, htmlText)
var width = view.getPreferredSpan(View.X_AXIS)
if (width > limit) {
view = createHTMLView(this, htmlBuilder.wrapWith(HtmlChunk.div().attr("width", limit)).wrapWith(HtmlChunk.html()).toString())
width = rows(view).maxOfOrNull { it.getPreferredSpan(View.X_AXIS) } ?: limit.toFloat()
htmlText = htmlBuilder.wrapWith(HtmlChunk.div().attr("width", width.toInt())).wrapWith(HtmlChunk.html()).toString()
view = createHTMLView(this, htmlText)
}
htmlView = view
preferredSize = Dimension(view.getPreferredSpan(View.X_AXIS).toInt(), view.getPreferredSpan(View.Y_AXIS).toInt())
}
override fun paintComponent(g: Graphics) {
val rect = Rectangle(width, height)
JBInsets.removeFrom(rect, insets)
htmlView.paint(g, rect)
}
private fun rows(root: View): Collection<View> {
return ArrayList<View>().also { visit(root, it) }
}
private fun visit(view: View, collection: MutableCollection<View>) {
val cname: String? = view.javaClass.canonicalName
cname?.let { if (it.contains("ParagraphView.Row")) collection.add(view) }
for (i in 0 until view.viewCount) {
visit(view.getView(i), collection)
}
}
companion object {
private val editorKit = GotItEditorKit()
private fun createHTMLView(component: JComponent, html: String): View {
val document = editorKit.createDocument(component.font, component.foreground ?: UIUtil.getLabelForeground())
StringReader(html).use { editorKit.read(it, document, 0) }
val factory = editorKit.viewFactory
return RootView(component, factory, factory.create(document.defaultRootElement))
}
}
private class GotItEditorKit : HTMLEditorKit() {
companion object {
private const val STYLES = "p { margin-top: 0; margin-bottom: 0; margin-left: 0; margin-right: 0 }" +
"body { margin-top: 0; margin-bottom: 0; margin-left: 0; margin-right: 0 }"
}
//TODO: refactor to com.intellij.util.ui.ExtendableHTMLViewFactory
private val viewFactory = object : HTMLFactory() {
override fun create(elem: Element): View {
val attr = elem.attributes
if ("icon" == elem.name) {
val src = attr.getAttribute(HTML.Attribute.SRC) as String
val icon = GotItTooltip.findIcon(src)
if (icon != null) {
return GotItIconView(icon, elem)
}
}
return super.create(elem)
}
}
private val style = StyleSheet()
private var initialized = false
override fun getStyleSheet(): StyleSheet {
if (!initialized) {
StringReader(STYLES).use { style.loadRules(it, null) }
style.addStyleSheet(super.getStyleSheet())
initialized = true
}
return style
}
override fun getViewFactory(): ViewFactory = viewFactory
fun createDocument(font: Font, foreground: Color): Document {
val s = StyleSheet().also {
it.addStyleSheet(styleSheet)
it.addRule(displayPropertiesToCSS(font, foreground))
}
return HTMLDocument(s).also {
it.asynchronousLoadPriority = Int.MAX_VALUE
it.preservesUnknownTags = true
}
}
private fun displayPropertiesToCSS(font: Font?, fg: Color?): String {
val rule = StringBuilder("body {")
font?.let {
rule.append(" font-family: ").append(it.family).append(" ; ").append(" font-size: ").append(it.size).append("pt ;")
if (it.isBold) rule.append(" font-weight: 700 ; ")
if (it.isItalic) rule.append(" font-style: italic ; ")
}
fg?.let {
rule.append(" color: #")
if (it.red < 16) rule.append('0')
rule.append(Integer.toHexString(it.red))
if (it.green < 16) rule.append('0')
rule.append(Integer.toHexString(it.green))
if (it.blue < 16) rule.append('0')
rule.append(Integer.toHexString(it.blue))
rule.append(" ; ")
}
return rule.append(" }").toString()
}
}
private class GotItIconView(private val icon: Icon, elem: Element) : View(elem) {
private val hAlign = (elem.attributes.getAttribute(HTML.Attribute.HALIGN) as String?)?.toFloatOrNull() ?: 0.5f
private val vAlign = (elem.attributes.getAttribute(HTML.Attribute.VALIGN) as String?)?.toFloatOrNull() ?: 0.75f
override fun getPreferredSpan(axis: Int): Float =
(if (axis == X_AXIS) icon.iconWidth else icon.iconHeight).toFloat()
override fun getToolTipText(x: Float, y: Float, allocation: Shape): String? =
if (icon is IconWithToolTip) icon.getToolTip(true)
else
element.attributes.getAttribute(HTML.Attribute.ALT) as String?
override fun paint(g: Graphics, allocation: Shape) {
allocation.bounds.let { icon.paintIcon(null, g, it.x, it.y) }
}
override fun modelToView(pos: Int, a: Shape, b: Position.Bias?): Shape {
if (pos in startOffset..endOffset) {
val rect = a.bounds
if (pos == endOffset) {
rect.x += rect.width
}
rect.width = 0
return rect
}
throw BadLocationException("$pos not in range $startOffset,$endOffset", pos)
}
override fun getAlignment(axis: Int): Float =
if (axis == X_AXIS) hAlign else vAlign
override fun viewToModel(x: Float, y: Float, a: Shape, bias: Array<Position.Bias>): Int {
val alloc = a as Rectangle
if (x < alloc.x + alloc.width / 2f) {
bias[0] = Position.Bias.Forward
return startOffset
}
bias[0] = Position.Bias.Backward
return endOffset
}
}
private class RootView(private val host: JComponent, private val factory: ViewFactory, private val view: View) : View(null) {
private var width: Float = 0.0f
init {
view.parent = this
setSize(view.getPreferredSpan(X_AXIS), view.getPreferredSpan(Y_AXIS))
}
override fun preferenceChanged(child: View?, width: Boolean, height: Boolean) {
host.revalidate()
host.repaint()
}
override fun paint(g: Graphics, allocation: Shape) {
val bounds = allocation.bounds
view.setSize(bounds.width.toFloat(), bounds.height.toFloat())
view.paint(g, bounds)
}
override fun setParent(parent: View) {
throw Error("Can't set parent on root view")
}
override fun setSize(width: Float, height: Float) {
this.width = width
view.setSize(width, height)
}
// Mostly delegation
override fun getAttributes(): AttributeSet? = null
override fun getPreferredSpan(axis: Int): Float = if (axis == X_AXIS) width else view.getPreferredSpan(axis)
override fun getMinimumSpan(axis: Int): Float = view.getMinimumSpan(axis)
override fun getMaximumSpan(axis: Int): Float = Int.MAX_VALUE.toFloat()
override fun getAlignment(axis: Int): Float = view.getAlignment(axis)
override fun getViewCount(): Int = 1
override fun getView(n: Int) = view
override fun modelToView(pos: Int, a: Shape, b: Position.Bias): Shape = view.modelToView(pos, a, b)
override fun modelToView(p0: Int, b0: Position.Bias, p1: Int, b1: Position.Bias, a: Shape): Shape = view.modelToView(p0, b0, p1, b1, a)
override fun viewToModel(x: Float, y: Float, a: Shape, bias: Array<out Position.Bias>): Int = view.viewToModel(x, y, a, bias)
override fun getDocument(): Document = view.document
override fun getStartOffset(): Int = view.startOffset
override fun getEndOffset(): Int = view.endOffset
override fun getElement(): Element = view.element
override fun getContainer(): Container = host
override fun getViewFactory(): ViewFactory = factory
}
} | apache-2.0 | 3870aebfbd9d210f31254bfbaa3238de | 33.675805 | 139 | 0.670975 | 4.260067 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveDeclarations/MoveToKotlinFileProcessor.kt | 4 | 3607 | // 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.move.moveDeclarations
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.EmptyRunnable
import com.intellij.openapi.util.Ref
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiElement
import com.intellij.refactoring.move.MoveCallback
import com.intellij.refactoring.move.moveFilesOrDirectories.MoveFilesOrDirectoriesProcessor
import com.intellij.usageView.UsageInfo
import com.intellij.usageView.UsageViewDescriptor
import com.intellij.util.containers.MultiMap
import com.intellij.util.text.UniqueNameGenerator
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.psi.KtFile
class MoveToKotlinFileProcessor @JvmOverloads constructor(
project: Project,
private val sourceFile: KtFile,
private val targetDirectory: PsiDirectory,
private val targetFileName: String,
searchInComments: Boolean,
searchInNonJavaFiles: Boolean,
moveCallback: MoveCallback?,
prepareSuccessfulCallback: Runnable = EmptyRunnable.INSTANCE,
private val throwOnConflicts: Boolean = false
) : MoveFilesOrDirectoriesProcessor(
project,
arrayOf(sourceFile),
targetDirectory,
true,
searchInComments,
searchInNonJavaFiles,
moveCallback,
prepareSuccessfulCallback
) {
override fun getCommandName() = KotlinBundle.message("text.move.file.0", sourceFile.name)
override fun createUsageViewDescriptor(usages: Array<out UsageInfo>): UsageViewDescriptor {
return MoveFilesWithDeclarationsViewDescriptor(arrayOf(sourceFile), targetDirectory)
}
override fun preprocessUsages(refUsages: Ref<Array<UsageInfo>>): Boolean {
val (conflicts, usages) = preprocessConflictUsages(refUsages)
return showConflicts(conflicts, usages)
}
override fun showConflicts(conflicts: MultiMap<PsiElement, String>, usages: Array<out UsageInfo>?): Boolean {
if (throwOnConflicts && !conflicts.isEmpty) throw RefactoringConflictsFoundException()
return super.showConflicts(conflicts, usages)
}
private fun renameFileTemporarilyIfNeeded() {
if (targetDirectory.findFile(sourceFile.name) == null) return
val containingDirectory = sourceFile.containingDirectory ?: return
val temporaryName = UniqueNameGenerator.generateUniqueName("temp", "", ".kt") {
containingDirectory.findFile(it) == null
}
sourceFile.name = temporaryName
}
override fun performRefactoring(usages: Array<UsageInfo>) {
renameFileTemporarilyIfNeeded()
super.performRefactoring(usages)
sourceFile.name = targetFileName
}
companion object {
data class ConflictUsages(val conflicts: MultiMap<PsiElement, String>, @Suppress("ArrayInDataClass") val usages: Array<UsageInfo>)
fun preprocessConflictUsages(refUsages: Ref<Array<UsageInfo>>): ConflictUsages {
val usages: Array<UsageInfo> = refUsages.get()
val (conflictUsages, usagesToProcess) = usages.partition { it is ConflictUsageInfo }
val conflicts = MultiMap<PsiElement, String>()
for (conflictUsage in conflictUsages) {
conflicts.putValues(conflictUsage.element, (conflictUsage as ConflictUsageInfo).messages)
}
refUsages.set(usagesToProcess.toTypedArray())
return ConflictUsages(conflicts, usages)
}
}
}
| apache-2.0 | b80306be6e8be2112f688ec46b9ba9a7 | 39.077778 | 158 | 0.744663 | 5.073136 | false | false | false | false |
sewerk/Bill-Calculator | app/src/main/java/pl/srw/billcalculator/settings/details/dialog/PickingSettingsDialogFragment.kt | 1 | 2500 | package pl.srw.billcalculator.settings.details.dialog
import android.app.Dialog
import android.arch.lifecycle.ViewModelProviders
import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.support.v4.app.FragmentActivity
import android.support.v7.app.AlertDialog
import android.view.LayoutInflater
import android.widget.LinearLayout
import pl.srw.billcalculator.common.bundleOf
import pl.srw.billcalculator.databinding.SettingsPickingDialogItemBinding
import pl.srw.billcalculator.di.Dependencies
import pl.srw.billcalculator.settings.details.PickingSettingsDetailsListItem
import pl.srw.billcalculator.settings.details.SettingsDetailsVM
import pl.srw.billcalculator.settings.details.SettingsDetailsVMFactory
import javax.inject.Inject
private const val ARG_DATA = "Settings.details.dialog.picking.data"
class PickingSettingsDialogFragment : DialogFragment() {
companion object {
fun show(activity: FragmentActivity,
item: PickingSettingsDetailsListItem) {
val dialogFragment = PickingSettingsDialogFragment()
dialogFragment.arguments = bundleOf(ARG_DATA, item)
dialogFragment.show(activity.supportFragmentManager, null)
}
}
@Inject lateinit var vmFactory: SettingsDetailsVMFactory
private val data by lazy { arguments!!.getParcelable(ARG_DATA) as PickingSettingsDetailsListItem }
private val vm by lazy { ViewModelProviders.of(activity!!, vmFactory).get(SettingsDetailsVM::class.java)}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Dependencies.inject(this)
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return AlertDialog.Builder(context!!)
.setTitle(data.title)
.setView(prepareListView(data.options))
.create()
}
private fun prepareListView(options: List<Int>): LinearLayout {
val layoutInflater = LayoutInflater.from(context)
val group = LinearLayout(context)
group.orientation = LinearLayout.VERTICAL
for (optionTextId in options) {
SettingsPickingDialogItemBinding.inflate(layoutInflater, group, true).apply {
textId = optionTextId
isChecked = optionTextId == data.value
}.root.setOnClickListener {
vm.optionPicked(data.title, optionTextId)
dismiss()
}
}
return group
}
}
| mit | 9ce343c94f80dc0e976d4c677538d446 | 37.461538 | 109 | 0.7268 | 4.901961 | false | false | false | false |
loxal/FreeEthereum | free-ethereum-core/src/main/java/org/ethereum/net/client/Capability.kt | 1 | 2423 | /*
* The MIT License (MIT)
*
* Copyright 2017 Alexander Orlov <[email protected]>. All rights reserved.
* Copyright (c) [2016] [ <ether.camp> ]
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package org.ethereum.net.client
/**
* The protocols and versions of those protocols that this peer support
*/
class Capability(val name: String?, val version: Byte) : Comparable<Capability> {
val isEth: Boolean
get() = ETH == name
override fun equals(obj: Any?): Boolean {
if (this === obj) return true
if (obj !is Capability) return false
val other = obj
if (this.name == null)
return other.name == null
else
return this.name == other.name && this.version == other.version
}
override fun compareTo(o: Capability): Int {
val cmp = this.name!!.compareTo(o.name!!)
if (cmp != 0) {
return cmp
} else {
return java.lang.Byte.valueOf(this.version)!!.compareTo(o.version)
}
}
override fun hashCode(): Int {
var result = name!!.hashCode()
result = 31 * result + version.toInt()
return result
}
override fun toString(): String {
return name + ":" + version
}
companion object {
val P2P = "p2p"
val ETH = "eth"
val SHH = "shh"
val BZZ = "bzz"
}
} | mit | 96e94ee79aa68e0b1f9e332c469caa87 | 31.756757 | 83 | 0.65291 | 4.265845 | false | false | false | false |
rustamgaifullin/MP | app/src/main/kotlin/io/rg/mp/persistence/entity/Category.kt | 1 | 736 | package io.rg.mp.persistence.entity
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.ForeignKey.CASCADE
import androidx.room.Index
@Entity(tableName = "category",
primaryKeys = ["name", "spreadsheet_id"],
indices = [Index("spreadsheet_id")],
foreignKeys = [
ForeignKey(
entity = Spreadsheet::class,
parentColumns = arrayOf("id"),
childColumns = arrayOf("spreadsheet_id"),
onDelete = CASCADE
)]
)
data class Category(
@ColumnInfo(name = "name") var name: String,
@ColumnInfo(name = "spreadsheet_id") var spreadsheetId: String
) | mit | 3a79c5c8ae733397dca43f2b4b890b8c | 31.043478 | 70 | 0.615489 | 4.628931 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/JavaToKotlinConverter.kt | 2 | 16459 | // 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.j2k
import com.intellij.lang.java.JavaLanguage
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.RangeMarker
import com.intellij.openapi.progress.*
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Computable
import com.intellij.openapi.util.NlsContexts
import com.intellij.psi.*
import com.intellij.psi.impl.source.DummyHolder
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.idea.core.util.range
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.j2k.ast.Element
import org.jetbrains.kotlin.j2k.usageProcessing.ExternalCodeProcessor
import org.jetbrains.kotlin.j2k.usageProcessing.UsageProcessing
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.psiUtil.elementsInRange
import org.jetbrains.kotlin.psi.psiUtil.isAncestor
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import java.util.*
interface PostProcessor {
fun insertImport(file: KtFile, fqName: FqName)
val phasesCount: Int
fun doAdditionalProcessing(
target: JKPostProcessingTarget,
converterContext: ConverterContext?,
onPhaseChanged: ((Int, String) -> Unit)?
)
}
sealed class JKPostProcessingTarget
data class JKPieceOfCodePostProcessingTarget(
val file: KtFile,
val rangeMarker: RangeMarker
) : JKPostProcessingTarget()
data class JKMultipleFilesPostProcessingTarget(
val files: List<KtFile>
) : JKPostProcessingTarget()
fun JKPostProcessingTarget.elements() = when (this) {
is JKPieceOfCodePostProcessingTarget -> runReadAction {
val range = rangeMarker.range ?: return@runReadAction emptyList()
file.elementsInRange(range)
}
is JKMultipleFilesPostProcessingTarget -> files
}
fun JKPostProcessingTarget.files() = when (this) {
is JKPieceOfCodePostProcessingTarget -> listOf(file)
is JKMultipleFilesPostProcessingTarget -> files
}
enum class ParseContext {
TOP_LEVEL,
CODE_BLOCK
}
interface ExternalCodeProcessing {
fun prepareWriteOperation(progress: ProgressIndicator?): (List<KtFile>) -> Unit
}
data class ElementResult(val text: String, val importsToAdd: Set<FqName>, val parseContext: ParseContext)
data class Result(
val results: List<ElementResult?>,
val externalCodeProcessing: ExternalCodeProcessing?,
val converterContext: ConverterContext?
)
data class FilesResult(val results: List<String>, val externalCodeProcessing: ExternalCodeProcessing?)
interface ConverterContext
abstract class JavaToKotlinConverter {
protected abstract fun elementsToKotlin(inputElements: List<PsiElement>, processor: WithProgressProcessor): Result
abstract fun filesToKotlin(
files: List<PsiJavaFile>,
postProcessor: PostProcessor,
progress: ProgressIndicator = EmptyProgressIndicator()
): FilesResult
abstract fun elementsToKotlin(inputElements: List<PsiElement>): Result
}
class OldJavaToKotlinConverter(
private val project: Project,
private val settings: ConverterSettings,
private val services: JavaToKotlinConverterServices
) : JavaToKotlinConverter() {
companion object {
private val LOG = Logger.getInstance(JavaToKotlinConverter::class.java)
}
override fun filesToKotlin(
files: List<PsiJavaFile>,
postProcessor: PostProcessor,
progress: ProgressIndicator
): FilesResult {
val withProgressProcessor = OldWithProgressProcessor(progress, files)
val (results, externalCodeProcessing) = ApplicationManager.getApplication().runReadAction(Computable {
elementsToKotlin(files, withProgressProcessor)
})
val texts = withProgressProcessor.processItems(0.5, results.withIndex()) { pair ->
val (i, result) = pair
try {
val kotlinFile = ApplicationManager.getApplication().runReadAction(Computable {
KtPsiFactory(project).createAnalyzableFile("dummy.kt", result!!.text, files[i])
})
result!!.importsToAdd.forEach { postProcessor.insertImport(kotlinFile, it) }
AfterConversionPass(project, postProcessor).run(kotlinFile, converterContext = null, range = null, onPhaseChanged = null)
kotlinFile.text
} catch (e: ProcessCanceledException) {
throw e
} catch (t: Throwable) {
LOG.error(t)
result!!.text
}
}
return FilesResult(texts, externalCodeProcessing)
}
override fun elementsToKotlin(inputElements: List<PsiElement>, processor: WithProgressProcessor): Result {
try {
val usageProcessings = LinkedHashMap<PsiElement, MutableCollection<UsageProcessing>>()
val usageProcessingCollector: (UsageProcessing) -> Unit = {
usageProcessings.getOrPut(it.targetElement) { ArrayList() }.add(it)
}
fun inConversionScope(element: PsiElement) = inputElements.any { it.isAncestor(element, strict = false) }
val intermediateResults = processor.processItems(0.25, inputElements) { inputElement ->
Converter.create(inputElement, settings, services, ::inConversionScope, usageProcessingCollector).convert()
}.toMutableList()
val results = processor.processItems(0.25, intermediateResults.withIndex()) { pair ->
val (i, result) = pair
intermediateResults[i] = null // to not hold unused objects in the heap
result?.let {
val (text, importsToAdd) = it.codeGenerator(usageProcessings)
ElementResult(text, importsToAdd, it.parseContext)
}
}
val externalCodeProcessing = buildExternalCodeProcessing(usageProcessings, ::inConversionScope)
return Result(results, externalCodeProcessing, null)
} catch (e: ElementCreationStackTraceRequiredException) {
// if we got this exception then we need to turn element creation stack traces on to get better diagnostic
Element.saveCreationStacktraces = true
try {
return elementsToKotlin(inputElements)
} finally {
Element.saveCreationStacktraces = false
}
}
}
override fun elementsToKotlin(inputElements: List<PsiElement>): Result {
return elementsToKotlin(inputElements, OldWithProgressProcessor.DEFAULT)
}
private data class ReferenceInfo(
val reference: PsiReference,
val target: PsiElement,
val file: PsiFile,
val processings: Collection<UsageProcessing>
) {
val depth: Int by lazy(LazyThreadSafetyMode.NONE) { target.parentsWithSelf.takeWhile { it !is PsiFile }.count() }
val offset: Int by lazy(LazyThreadSafetyMode.NONE) { reference.element.textRange.startOffset }
}
private fun buildExternalCodeProcessing(
usageProcessings: Map<PsiElement, Collection<UsageProcessing>>,
inConversionScope: (PsiElement) -> Boolean
): ExternalCodeProcessing? {
if (usageProcessings.isEmpty()) return null
val map: Map<PsiElement, Collection<UsageProcessing>> = usageProcessings.values
.flatten()
.filter { it.javaCodeProcessors.isNotEmpty() || it.kotlinCodeProcessors.isNotEmpty() }
.groupBy { it.targetElement }
if (map.isEmpty()) return null
return object : ExternalCodeProcessing {
override fun prepareWriteOperation(progress: ProgressIndicator?): (List<KtFile>) -> Unit {
if (progress == null) error("Progress should not be null for old J2K")
val refs = ArrayList<ReferenceInfo>()
progress.text = KotlinJ2KBundle.message("text.searching.usages.to.update")
for ((i, entry) in map.entries.withIndex()) {
val psiElement = entry.key
val processings = entry.value
progress.text2 = (psiElement as? PsiNamedElement)?.name ?: ""
progress.checkCanceled()
ProgressManager.getInstance().runProcess(
{
val searchJava = processings.any { it.javaCodeProcessors.isNotEmpty() }
val searchKotlin = processings.any { it.kotlinCodeProcessors.isNotEmpty() }
services.referenceSearcher.findUsagesForExternalCodeProcessing(psiElement, searchJava, searchKotlin)
.filterNot { inConversionScope(it.element) }
.mapTo(refs) { ReferenceInfo(it, psiElement, it.element.containingFile, processings) }
},
ProgressPortionReporter(progress, i / map.size.toDouble(), 1.0 / map.size)
)
}
return { processUsages(refs) }
}
}
}
private fun processUsages(refs: Collection<ReferenceInfo>) {
for (fileRefs in refs.groupBy { it.file }.values) { // group by file for faster sorting
ReferenceLoop@
for ((reference, _, _, processings) in fileRefs.sortedWith(ReferenceComparator)) {
val processors = when (reference.element.language) {
JavaLanguage.INSTANCE -> processings.flatMap { it.javaCodeProcessors }
KotlinLanguage.INSTANCE -> processings.flatMap { it.kotlinCodeProcessors }
else -> continue@ReferenceLoop
}
checkReferenceValid(reference, null)
var references = listOf(reference)
for (processor in processors) {
references = references.flatMap { processor.processUsage(it)?.toList() ?: listOf(it) }
references.forEach { checkReferenceValid(it, processor) }
}
}
}
}
private fun checkReferenceValid(reference: PsiReference, afterProcessor: ExternalCodeProcessor?) {
val element = reference.element
assert(element.isValid && element.containingFile !is DummyHolder) {
"Reference $reference got invalidated" + (if (afterProcessor != null) " after processing with $afterProcessor" else "")
}
}
private object ReferenceComparator : Comparator<ReferenceInfo> {
override fun compare(info1: ReferenceInfo, info2: ReferenceInfo): Int {
val depth1 = info1.depth
val depth2 = info2.depth
if (depth1 != depth2) { // put deeper elements first to not invalidate them when processing ancestors
return -depth1.compareTo(depth2)
}
// process elements with the same deepness from right to left so that right-side of assignments is not invalidated by processing of the left one
return -info1.offset.compareTo(info2.offset)
}
}
}
interface WithProgressProcessor {
fun <TInputItem, TOutputItem> processItems(
fractionPortion: Double,
inputItems: Iterable<TInputItem>,
processItem: (TInputItem) -> TOutputItem
): List<TOutputItem>
fun updateState(fileIndex: Int?, phase: Int, description: String)
fun updateState(phase: Int, subPhase: Int, subPhaseCount: Int, fileIndex: Int?, description: String)
fun <T> process(action: () -> T): T
}
class OldWithProgressProcessor(private val progress: ProgressIndicator?, private val files: List<PsiJavaFile>?) : WithProgressProcessor {
companion object {
val DEFAULT = OldWithProgressProcessor(null, null)
}
private val progressText
@Suppress("DialogTitleCapitalization")
@NlsContexts.ProgressText
get() = KotlinJ2KBundle.message("text.converting.java.to.kotlin")
private val fileCount = files?.size ?: 0
private val fileCountText
@Nls
get() = KotlinJ2KBundle.message("text.files.count.0", fileCount, if (fileCount == 1) 1 else 2)
private var fraction = 0.0
private var pass = 1
override fun <TInputItem, TOutputItem> processItems(
fractionPortion: Double,
inputItems: Iterable<TInputItem>,
processItem: (TInputItem) -> TOutputItem
): List<TOutputItem> {
val outputItems = ArrayList<TOutputItem>()
// we use special process with EmptyProgressIndicator to avoid changing text in our progress by inheritors search inside etc
ProgressManager.getInstance().runProcess(
{
progress?.text = "$progressText ($fileCountText) - ${KotlinJ2KBundle.message("text.pass.of.3", pass)}"
progress?.isIndeterminate = false
for ((i, item) in inputItems.withIndex()) {
progress?.checkCanceled()
progress?.fraction = fraction + fractionPortion * i / fileCount
progress?.text2 = files!![i].virtualFile.presentableUrl
outputItems.add(processItem(item))
}
pass++
fraction += fractionPortion
},
EmptyProgressIndicator()
)
return outputItems
}
override fun <T> process(action: () -> T): T {
throw AbstractMethodError("Should not be called for old J2K")
}
override fun updateState(fileIndex: Int?, phase: Int, description: String) {
throw AbstractMethodError("Should not be called for old J2K")
}
override fun updateState(
phase: Int,
subPhase: Int,
subPhaseCount: Int,
fileIndex: Int?,
description: String
) {
error("Should not be called for old J2K")
}
}
class ProgressPortionReporter(
indicator: ProgressIndicator,
private val start: Double,
private val portion: Double
) : J2KDelegatingProgressIndicator(indicator) {
init {
fraction = 0.0
}
override fun start() {
fraction = 0.0
}
override fun stop() {
fraction = portion
}
override fun setFraction(fraction: Double) {
super.setFraction(start + (fraction * portion))
}
override fun getFraction(): Double {
return (super.getFraction() - start) / portion
}
override fun setText(text: String?) {
}
override fun setText2(text: String?) {
}
}
// Copied from com.intellij.ide.util.DelegatingProgressIndicator
open class J2KDelegatingProgressIndicator(indicator: ProgressIndicator) : WrappedProgressIndicator, StandardProgressIndicator {
protected val delegate: ProgressIndicator = indicator
override fun start() = delegate.start()
override fun stop() = delegate.stop()
override fun isRunning() = delegate.isRunning
override fun cancel() = delegate.cancel()
override fun isCanceled() = delegate.isCanceled
override fun setText(text: String?) {
delegate.text = text
}
override fun getText() = delegate.text
override fun setText2(text: String?) {
delegate.text2 = text
}
override fun getText2() = delegate.text2
override fun getFraction() = delegate.fraction
override fun setFraction(fraction: Double) {
delegate.fraction = fraction
}
override fun pushState() = delegate.pushState()
override fun popState() = delegate.popState()
override fun isModal() = delegate.isModal
override fun getModalityState() = delegate.modalityState
override fun setModalityProgress(modalityProgress: ProgressIndicator?) {
delegate.setModalityProgress(modalityProgress)
}
override fun isIndeterminate() = delegate.isIndeterminate
override fun setIndeterminate(indeterminate: Boolean) {
delegate.isIndeterminate = indeterminate
}
override fun checkCanceled() = delegate.checkCanceled()
override fun getOriginalProgressIndicator() = delegate
override fun isPopupWasShown() = delegate.isPopupWasShown
override fun isShowing() = delegate.isShowing
} | apache-2.0 | d11963b270dfd3a0e7796b589b4914e4 | 36.579909 | 158 | 0.665107 | 5.140225 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/ui/popup/list/PopupInlineActionsSupportImpl.kt | 1 | 4217 | // 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.popup.list
import com.intellij.icons.AllIcons
import com.intellij.ide.IdeBundle
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.ui.ExperimentalUI
import com.intellij.ui.popup.ActionPopupStep
import com.intellij.ui.popup.PopupFactoryImpl.ActionItem
import com.intellij.ui.popup.PopupFactoryImpl.InlineActionItem
import com.intellij.ui.popup.list.ListPopupImpl.ListWithInlineButtons
import java.awt.Point
import java.awt.event.InputEvent
import javax.swing.JComponent
import javax.swing.JList
class PopupInlineActionsSupportImpl(private val myListPopup: ListPopupImpl) : PopupInlineActionsSupport {
private val myStep = myListPopup.listStep as ActionPopupStep
override fun hasExtraButtons(element: Any?): Boolean = calcExtraButtonsCount(element) > 0
override fun calcExtraButtonsCount(element: Any?): Int {
if (!ExperimentalUI.isNewUI() || element !is ActionItem) return 0
var res = 0
res += myStep.getInlineActions(element).size
if (hasMoreButton(element)) res++
return res
}
override fun calcButtonIndex(element: Any?, point: Point): Int? {
if (element == null) return null
val buttonsCount: Int = calcExtraButtonsCount(element)
if (buttonsCount <= 0) return null
return calcButtonIndex(myListPopup.list, buttonsCount, point)
}
override fun runInlineAction(element: Any?, index: Int, event: InputEvent?) : Boolean {
val pair = getExtraButtonsActions(element, event)[index]
pair.first.run()
return pair.second
}
private fun getExtraButtonsActions(element: Any?, event: InputEvent?): List<Pair<Runnable, Boolean>> {
if (!ExperimentalUI.isNewUI() || element !is ActionItem) return emptyList()
val res: MutableList<Pair<Runnable, Boolean>> = mutableListOf()
res.addAll(myStep.getInlineActions(element).map {
item: InlineActionItem -> Pair(createInlineActionRunnable(item.action, event), true)
})
if (hasMoreButton(element)) res.add(Pair(createNextStepRunnable(element), false))
return res
}
override fun getExtraButtons(list: JList<*>, value: Any?, isSelected: Boolean): List<JComponent> {
if (value !is ActionItem) return emptyList()
val inlineActions = myStep.getInlineActions(value)
val res: MutableList<JComponent> = java.util.ArrayList()
val activeIndex = getActiveButtonIndex(list)
for (i in 0 until inlineActions.size) res.add(createActionButton(inlineActions[i], i == activeIndex, isSelected))
if (hasMoreButton(value)) res.add(createSubmenuButton(value, res.size == activeIndex))
return res
}
override fun getActiveButtonIndex(list: JList<*>): Int? = (list as? ListWithInlineButtons)?.selectedButtonIndex
private fun createSubmenuButton(value: ActionItem, active: Boolean): JComponent {
val icon = if (myStep.isFinal(value)) AllIcons.Actions.More else AllIcons.Icons.Ide.MenuArrow
return createExtraButton(icon, active)
}
private fun createActionButton(action: InlineActionItem, active: Boolean, isSelected: Boolean): JComponent =
createExtraButton(action.getIcon(isSelected), active)
override fun getActiveExtraButtonToolTipText(list: JList<*>, value: Any?): String? {
if (value !is ActionItem) return null
val inlineActions = myStep.getInlineActions(value)
val activeButton = getActiveButtonIndex(list) ?: return null
return if (activeButton == inlineActions.size)
IdeBundle.message("inline.actions.more.actions.text")
else
inlineActions.getOrNull(activeButton)?.text
}
private fun createNextStepRunnable(element: ActionItem) = Runnable { myListPopup.showNextStepPopup(myStep.onChosen(element, false), element) }
private fun createInlineActionRunnable(action: AnAction, inputEvent: InputEvent?) = Runnable { myStep.performAction(action, inputEvent) }
private fun hasMoreButton(element: ActionItem) = myStep.hasSubstep(element)
&& !myListPopup.isShowSubmenuOnHover
&& myStep.isFinal(element)
} | apache-2.0 | da6dc617a4f3da39cea0605a9b4dfce4 | 42.040816 | 144 | 0.736543 | 4.388137 | false | false | false | false |
smmribeiro/intellij-community | platform/execution-impl/src/com/intellij/execution/runToolbar/RunToolbarComponentService.kt | 1 | 4409 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.runToolbar
import com.intellij.application.subscribe
import com.intellij.execution.ExecutionListener
import com.intellij.execution.ExecutionManager
import com.intellij.execution.impl.ExecutionManagerImpl
import com.intellij.execution.process.ProcessHandler
import com.intellij.execution.runners.ExecutionEnvironment
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
class RunToolbarComponentService(val project: Project) {
companion object {
private val LOG = Logger.getInstance(RunToolbarComponentService::class.java)
}
private val extraSlots = RunToolbarSlotManager.getInstance(project)
init {
if (RunToolbarProcess.isAvailable) {
ExecutionManager.EXECUTION_TOPIC.subscribe(project, object : ExecutionListener {
override fun processNotStarted(executorId: String, env: ExecutionEnvironment) {
ApplicationManager.getApplication().invokeLater {
if (env.project == project) {
processNotStarted(env)
}
}
}
override fun processStarted(executorId: String, env: ExecutionEnvironment, handler: ProcessHandler) {
ApplicationManager.getApplication().invokeLater {
if (env.project == project) {
start(env)
}
}
}
override fun processTerminating(executorId: String, env: ExecutionEnvironment, handler: ProcessHandler) {
ApplicationManager.getApplication().invokeLater {
if (env.project == project) {
terminating(env)
}
}
}
override fun processTerminated(executorId: String, env: ExecutionEnvironment, handler: ProcessHandler, exitCode: Int) {
ApplicationManager.getApplication().invokeLater {
if (env.project == project) {
terminated(env)
}
}
}
})
extraSlots.addListener(object : ActiveListener {
override fun enabled() {
val environments = ExecutionManagerImpl.getAllDescriptors(project)
.mapNotNull { it.environment() }
.filter { it.contentToReuse?.processHandler?.isProcessTerminated == false }
if (RunToolbarProcess.logNeeded) LOG.info("ENABLED. put data ${environments.map { "$it (${it.executionId}); " }} RunToolbar")
environments.forEach {
extraSlots.processStarted(it)
}
}
override fun disabled() {
if (RunToolbarProcess.logNeeded) LOG.info("DISABLED RunToolbar")
super.disabled()
}
})
}
}
private fun start(env: ExecutionEnvironment) {
if (isRelevant(env)) {
if (RunToolbarProcess.logNeeded) LOG.info(
"new active: ${env.executor.id} ${env}, slot manager ${if (extraSlots.active) "ENABLED" else "DISABLED"} RunToolbar")
if (extraSlots.active) {
extraSlots.processStarted(env)
}
}
}
private fun processNotStarted(env: ExecutionEnvironment) {
if (env.getRunToolbarProcess() != null) {
if (RunToolbarProcess.logNeeded) LOG.info("Not started: ${env.executor.id} ${env} RunToolbar")
if (extraSlots.active) {
extraSlots.processNotStarted(env)
}
}
}
private fun terminated(env: ExecutionEnvironment) {
if (RunToolbarProcess.logNeeded) LOG.info(
"removed: ${env.executor.id} ${env}, slot manager ${if (extraSlots.active) "ENABLED" else "DISABLED"} RunToolbar")
if (extraSlots.active) {
extraSlots.processTerminated(env.executionId)
}
}
private fun terminating(env: ExecutionEnvironment) {
if (RunToolbarProcess.logNeeded) LOG.info(
"terminating: ${env.executor.id} ${env}, slot manager ${if (extraSlots.active) "ENABLED" else "DISABLED"} RunToolbar")
if (extraSlots.active) {
if (isRelevant(env)) {
extraSlots.processTerminating(env)
}
else {
extraSlots.processTerminated(env.executionId)
}
}
}
private fun isRelevant(environment: ExecutionEnvironment): Boolean {
return environment.contentToReuse != null && environment.getRunToolbarProcess() != null
}
} | apache-2.0 | 1b466b3ff67b2e39ddd45bf99958e08c | 36.058824 | 158 | 0.668859 | 4.893452 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/frontend-fir/testData/symbolsByPsi/annotations.kt | 2 | 2360 |
annotation class Anno(val param1: String, val param2: Int)
@Anno(param1 = "param", 2)
class X {
@Anno("funparam", 3)
fun x() {
}
}
// SYMBOLS:
/*
KtFirFunctionValueParameterSymbol:
annotatedType: [] kotlin/String
annotationClassIds: []
annotations: []
hasDefaultValue: false
isVararg: false
name: param1
origin: SOURCE
symbolKind: NON_PROPERTY_PARAMETER
KtFirFunctionValueParameterSymbol:
annotatedType: [] kotlin/Int
annotationClassIds: []
annotations: []
hasDefaultValue: false
isVararg: false
name: param2
origin: SOURCE
symbolKind: NON_PROPERTY_PARAMETER
KtFirConstructorSymbol:
annotatedType: [] Anno
annotationClassIds: []
annotations: []
containingClassIdIfNonLocal: Anno
dispatchType: null
isPrimary: true
origin: SOURCE
symbolKind: MEMBER
typeParameters: []
valueParameters: Could not render due to java.lang.ClassCastException: org.jetbrains.kotlin.idea.frontend.api.fir.symbols.KtFirFunctionValueParameterSymbol cannot be cast to org.jetbrains.kotlin.idea.frontend.api.fir.symbols.KtFirConstructorValueParameterSymbol
visibility: PUBLIC
KtFirClassOrObjectSymbol:
annotationClassIds: []
annotations: []
classIdIfNonLocal: Anno
classKind: ANNOTATION_CLASS
companionObject: null
isData: false
isExternal: false
isFun: false
isInline: false
isInner: false
modality: FINAL
name: Anno
origin: SOURCE
superTypes: [[] kotlin/Annotation]
symbolKind: TOP_LEVEL
typeParameters: []
visibility: PUBLIC
KtFirFunctionSymbol:
annotatedType: [] kotlin/Unit
annotationClassIds: [Anno]
annotations: [Anno(param1 = funparam, param2 = 3)]
callableIdIfNonLocal: X.x
dispatchType: X
isExtension: false
isExternal: false
isInline: false
isOperator: false
isOverride: false
isSuspend: false
modality: FINAL
name: x
origin: SOURCE
receiverType: null
symbolKind: MEMBER
typeParameters: []
valueParameters: []
visibility: PUBLIC
KtFirClassOrObjectSymbol:
annotationClassIds: [Anno]
annotations: [Anno(param1 = param, param2 = 2)]
classIdIfNonLocal: X
classKind: CLASS
companionObject: null
isData: false
isExternal: false
isFun: false
isInline: false
isInner: false
modality: FINAL
name: X
origin: SOURCE
superTypes: [[] kotlin/Any]
symbolKind: TOP_LEVEL
typeParameters: []
visibility: PUBLIC
*/
| apache-2.0 | 1505f8cc9d2214c133c4827141681200 | 21.47619 | 263 | 0.741949 | 4.346225 | false | false | false | false |
smmribeiro/intellij-community | platform/lang-impl/src/com/intellij/lang/documentation/ide/actions/DocumentationEditSourceAction.kt | 2 | 1635 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.lang.documentation.ide.actions
import com.intellij.lang.documentation.DocumentationTarget
import com.intellij.model.Pointer
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.actionSystem.UpdateInBackground
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.ReadAction
import com.intellij.util.OpenSourceUtil
import com.intellij.util.concurrency.AppExecutorUtil
import java.util.concurrent.Callable
internal class DocumentationEditSourceAction : AnAction(), UpdateInBackground {
private fun targetPointer(dc: DataContext): Pointer<out DocumentationTarget>? = documentationBrowser(dc)?.targetPointer
override fun update(e: AnActionEvent) {
e.presentation.isEnabledAndVisible = targetPointer(e.dataContext)?.dereference()?.navigatable != null
}
override fun actionPerformed(e: AnActionEvent) {
val dataContext = e.dataContext
val targetPointer = targetPointer(dataContext) ?: return
ReadAction.nonBlocking(Callable {
targetPointer.dereference()?.navigatable
}).finishOnUiThread(ModalityState.defaultModalityState()) { navigatable ->
if (navigatable != null) {
OpenSourceUtil.navigate(true, navigatable)
}
}.submit(AppExecutorUtil.getAppExecutorService())
dataContext.getData(DOCUMENTATION_POPUP)?.cancel()
}
}
| apache-2.0 | 758b441dcd5e269af7fafb1d56d54215 | 44.416667 | 158 | 0.799388 | 5.015337 | false | false | false | false |
smmribeiro/intellij-community | platform/service-container/src/com/intellij/serviceContainer/containerUtil.kt | 6 | 1806 | // 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.
@file:ApiStatus.Internal
package com.intellij.serviceContainer
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.openapi.components.Service
import com.intellij.openapi.extensions.PluginDescriptor
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import org.jetbrains.annotations.ApiStatus
import java.lang.reflect.Modifier
internal fun checkCanceledIfNotInClassInit() {
try {
ProgressManager.checkCanceled()
}
catch (e: ProcessCanceledException) {
// otherwise ExceptionInInitializerError happens and the class is screwed forever
@Suppress("SpellCheckingInspection")
if (!e.stackTrace.any { it.methodName == "<clinit>" }) {
throw e
}
}
}
internal fun isGettingServiceAllowedDuringPluginUnloading(descriptor: PluginDescriptor): Boolean {
return descriptor.isRequireRestart ||
descriptor.pluginId == PluginManagerCore.CORE_ID || descriptor.pluginId == PluginManagerCore.JAVA_PLUGIN_ID
}
@ApiStatus.Internal
fun throwAlreadyDisposedError(serviceDescription: String, componentManager: ComponentManagerImpl, indicator: ProgressIndicator?) {
val error = AlreadyDisposedException("Cannot create $serviceDescription because container is already disposed (container=${componentManager})")
if (indicator == null) {
throw error
}
else {
throw ProcessCanceledException(error)
}
}
internal fun isLightService(serviceClass: Class<*>): Boolean {
return Modifier.isFinal(serviceClass.modifiers) && serviceClass.isAnnotationPresent(Service::class.java)
} | apache-2.0 | c8b7457ea186cb65138140803094b604 | 39.155556 | 158 | 0.79402 | 4.867925 | false | false | false | false |
mchllngr/QuickOpen | app/src/main/java/de/mchllngr/quickopen/util/dialog/ApplicationListAdapter.kt | 1 | 1469 | package de.mchllngr.quickopen.util.dialog
import android.graphics.drawable.Drawable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import de.mchllngr.quickopen.R
data class ApplicationItem(
val name: String,
val icon: Drawable,
val onClick: () -> Unit
)
class ApplicationListAdapter(private val items: List<ApplicationItem>) : RecyclerView.Adapter<ApplicationListAdapter.ViewHolder>() {
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
) = ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.recycler_view_item, parent, false))
override fun onBindViewHolder(
holder: ViewHolder,
position: Int
) {
val item = items[position]
holder.icon.setImageDrawable(item.icon)
holder.name.text = item.name
holder.itemView.setOnClickListener { item.onClick() }
}
override fun getItemCount() = items.size
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val icon: ImageView = itemView.findViewById(R.id.icon)
val name: TextView = itemView.findViewById(R.id.name)
private val handle: ImageButton = itemView.findViewById(R.id.handle)
init {
handle.visibility = View.GONE
}
}
}
| apache-2.0 | 5a4b9c9a82df27e020291811c337c60f | 29.604167 | 132 | 0.716133 | 4.333333 | false | false | false | false |
NlRVANA/Unity | app/src/main/java/com/zwq65/unity/ui/contract/TabArticleContract.kt | 1 | 1380 | /*
* Copyright [2017] [NIRVANA PRIVATE LIMITED]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zwq65.unity.ui.contract
import com.zwq65.unity.data.network.retrofit.response.enity.Article
import com.zwq65.unity.ui._base.BaseContract
import com.zwq65.unity.ui._base.RefreshMvpView
import com.zwq65.unity.ui.fragment.TabArticleFragment
/**
* ================================================
* <p>
* Created by NIRVANA on 2017/08/31
* Contact with <[email protected]>
* ================================================
*/
interface TabArticleContract {
interface View<T : Article> : RefreshMvpView<T>
interface Presenter<V : BaseContract.View> : BaseContract.Presenter<V> {
fun setType(@TabArticleFragment.Type type: Int)
fun init()
fun loadDatas(isRefresh: Boolean?)
}
}
| apache-2.0 | 0b9b3b276cc75046762d6531207f768f | 31.857143 | 78 | 0.661594 | 4.070796 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/scripting/actions/types/RenameShortcutActionType.kt | 1 | 776 | package ch.rmy.android.http_shortcuts.scripting.actions.types
import ch.rmy.android.framework.extensions.takeUnlessEmpty
import ch.rmy.android.http_shortcuts.scripting.ActionAlias
import ch.rmy.android.http_shortcuts.scripting.actions.ActionDTO
class RenameShortcutActionType : BaseActionType() {
override val type = TYPE
override fun fromDTO(actionDTO: ActionDTO) = RenameShortcutAction(
shortcutNameOrId = actionDTO.getString(0)?.takeUnlessEmpty(),
name = actionDTO.getString(1) ?: "",
)
override fun getAlias() = ActionAlias(
functionName = FUNCTION_NAME,
parameters = 2,
)
companion object {
private const val TYPE = "rename_shortcut"
private const val FUNCTION_NAME = "renameShortcut"
}
}
| mit | 7d360b5688fb0f9720d41a659fd5e586 | 30.04 | 70 | 0.717784 | 4.240437 | false | false | false | false |
sksamuel/ktest | kotest-assertions/kotest-assertions-shared/src/commonMain/kotlin/io/kotest/assertions/eq/MapEq.kt | 1 | 1873 | package io.kotest.assertions.eq
import io.kotest.assertions.failure
import io.kotest.assertions.show.show
internal object MapEq : Eq<Map<*, *>?> {
override fun equals(actual: Map<*, *>?, expected: Map<*, *>?): Throwable? {
return when {
actual == null && expected == null -> null
actual != null && expected != null -> {
val haveUnequalKeys = eq(actual.keys, expected.keys)
if(haveUnequalKeys != null) generateError(actual, expected)
else {
val hasDifferentValue = actual.keys.any { key ->
eq(actual[key], expected[key]) != null
}
if(hasDifferentValue) generateError(actual, expected)
else null
}
}
else -> generateError(actual, expected)
}
}
}
private fun generateError(actual: Map<*, *>?, expected: Map<*, *>?): Throwable {
return failure(
buildFailureMessage(
actual,
expected
)
)
}
private fun buildFailureMessage(actual: Map<*, *>?, expected: Map<*, *>?): String {
val keysDifferentAt = when {
actual != null && expected != null -> {
val keysHavingDifferentValues = actual.keys.filterNot { expected[it] == actual[it] }
"Values differed at keys ${keysHavingDifferentValues.joinToString(limit = 10)}"
}
else -> ""
}
return "Expected\n${expected?.toFormattedString()}\nto be equal to\n${actual?.toFormattedString()}\n$keysDifferentAt"
}
private fun Map<*, *>.toFormattedString(): String {
if (isEmpty()) return "{}"
val indentation = " "
val newLine = "\n"
return toList()
.joinToString(
separator = ",$newLine",
prefix = "{$newLine",
postfix = "$newLine}",
limit = 10
) { "$indentation${it.first.show().value} = ${it.second.show().value}" }
}
| mit | 672237f1f252dc4670d07435ce1be5dd | 31.293103 | 120 | 0.573946 | 4.325635 | false | true | false | false |
breadwallet/breadwallet-android | app-core/src/main/java/com/breadwallet/tools/util/BRConstants.kt | 1 | 7261 | /**
* BreadWallet
*
* Created by Mihail Gutan <[email protected]> on 2/16/16.
* Copyright (c) 2016 breadwallet LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.breadwallet.tools.util
import java.math.RoundingMode
const val btc = "btc"
const val eth = "eth"
const val bch = "bch"
const val hbar = "hbar"
const val xtz = "xtz"
object BRConstants {
/**
* Boolean values as Strings.
*/
const val TRUE = "true"
const val FALSE = "false"
/**
* Permissions
*/
const val CAMERA_REQUEST_ID = 34
const val GEO_REQUEST_ID = 35
const val CAMERA_PERMISSIONS_RC = 36
/**
* Request codes for auth
*/
const val SHOW_PHRASE_REQUEST_CODE = 111
const val PAY_REQUEST_CODE = 112
const val PUT_PHRASE_NEW_WALLET_REQUEST_CODE = 114
const val PUT_PHRASE_RECOVERY_WALLET_REQUEST_CODE = 115
const val PAYMENT_PROTOCOL_REQUEST_CODE = 116
const val REQUEST_PHRASE_BITID = 117
const val PROVE_PHRASE_REQUEST = 119
const val UPLOAD_FILE_REQUEST = 120
/**
* Request codes for take picture
*/
const val SCANNER_REQUEST = 201
const val REQUEST_IMAGE_RC = 203
/**
* Currency units
*
*
* TODO: No longer supported, remove with the
* deletion of legacy.wallet.wallets.*
*/
@Deprecated("")
val CURRENT_UNIT_BITS = 0
@Deprecated("")
val CURRENT_UNIT_MBITS = 1
@Deprecated("")
val CURRENT_UNIT_BITCOINS = 2
const val BITS_SYMBOL = "\u0180"
const val ETH_SYMBOL = "\u039E"
const val BITCOIN_SYBMOL_OLD = "\u0243"
const val BITCOIN_SYMBOL = "\u20BF"
@JvmField
val ROUNDING_MODE = RoundingMode.HALF_EVEN
const val WRITE_AHEAD_LOGGING = true
/**
* Support Center article ids.
*/
const val FAQ_DISPLAY_CURRENCY = "display-currency"
const val FAQ_RECOVER_WALLET = "recover-wallet"
const val FAQ_RESCAN = "re-scan"
const val FAQ_SECURITY_CENTER = "security-center"
const val FAQ_PAPER_KEY = "paper-key"
const val FAQ_ENABLE_FINGERPRINT = "enable-fingerprint-authentication"
const val FAQ_TRANSACTION_DETAILS = "transaction-details"
const val FAQ_RECEIVE = "receive-tx"
const val FAQ_REQUEST_AMOUNT = "request-amount"
const val FAQ_SEND = "send-tx"
const val FAQ_WALLET_DISABLE = "wallet-disabled"
const val FAQ_RESET_PIN_WITH_PAPER_KEY = "reset-pin-paper-key"
const val FAQ_SET_PIN = "set-pin"
const val FAQ_IMPORT_WALLET = "import-wallet"
const val FAQ_WRITE_PAPER_KEY = "write-phrase"
const val FAQ_START_VIEW = "start-view"
const val FAQ_WIPE_WALLET = "wipe-wallet"
const val FAQ_LOOP_BUG = "android-loop-bug"
const val FAQ_BCH = "bitcoin-cash"
const val FAQ_UNSUPPORTED_TOKEN = "unsupported-token"
const val FAQ_FASTSYNC = "fastsync-explained"
/**
* API Constants
*/
const val HEADER_CONTENT_TYPE = "Content-Type"
const val HEADER_ACCEPT = "Accept"
// OkHttp standard; use for all outgoing HTTP requests.
const val CONTENT_TYPE_JSON_CHARSET_UTF8 = "application/json; charset=UTF-8"
// Server response content type; user to verify all incoming HTTP responses.
const val CONTENT_TYPE_JSON = "application/json"
const val CONTENT_TYPE_TEXT = "text/plain"
const val AUTHORIZATION = "Authorization"
/**
* Extra constants
*/
const val EXTRA_URL = "com.breadwallet.EXTRA_URL"
const val DRAWABLE = "drawable"
const val CURRENCY_PARAMETER_STRING_FORMAT = "%s?currency=%s"
/**
* Social media links and privacy policy URLS
*/
const val URL_PRIVACY_POLICY = "https://brd.com/privacy"
const val URL_TWITTER = "https://twitter.com/brdhq"
const val URL_REDDIT = "https://www.reddit.com/r/BRDapp/"
const val URL_BLOG = "https://brd.com/blog/"
const val URL_BRD_HOST = "brd.com"
const val WALLET_PAIR_PATH = "wallet-pair"
const val WALLET_LINK_PATH = "link-wallet"
const val STRING_RESOURCES_FILENAME = "string"
const val BREAD = "bread"
const val PROTOCOL = "https"
const val GZIP = "gzip"
const val CONTENT_ENCODING = "content-encoding"
const val METHOD = "method"
const val BODY = "body"
const val HEADERS = "headers"
const val CLOSE_ON = "closeOn"
const val CLOSE = "/_close"
const val ARTICLE_ID = "articleId"
const val URL = "url"
const val JSONRPC = "jsonrpc"
const val VERSION_2 = "2.0"
const val ETH_BALANCE = "eth_getBalance"
const val LATEST = "latest"
const val PARAMS = "params"
const val ID = "id"
const val RESULT = "result"
const val ACCOUNT = "account"
const val ETH_GAS_PRICE = "eth_gasPrice"
const val ETH_ESTIMATE_GAS = "eth_estimateGas"
const val ETH_SEND_RAW_TRANSACTION = "eth_sendRawTransaction"
const val ERROR = "error"
const val CODE = "code"
const val MESSAGE = "message"
const val HASH = "hash"
const val TO = "to"
const val FROM = "from"
const val CONTRACT_ADDRESS = "contractAddress"
const val ADDRESS = "address"
const val VALUE = "value"
const val GAS = "gas"
const val GAS_PRICE = "gasPrice"
const val NONCE = "nonce"
const val GAS_USED = "gasUsed"
const val BLOCK_NUMBER = "blockNumber"
const val ETH_BLOCK_NUMBER = "eth_blockNumber"
const val ETH_TRANSACTION_COUNT = "eth_getTransactionCount"
const val BLOCK_HASH = "blockHash"
const val LOG_INDEX = "logIndex"
const val INPUT = "input"
const val CONFIRMATIONS = "confirmations"
const val TRANSACTION_INDEX = "transactionIndex"
const val TIMESTAMP = "timeStamp"
const val IS_ERROR = "isError"
const val TOPICS = "topics"
const val DATA = "data"
const val DATE = "Date"
const val TRANSACTION_HASH = "transactionHash"
const val CHECKOUT = "checkout"
const val GET = "GET"
const val POST = "POST"
const val HEADER_WWW_AUTHENTICATE = "www-authenticate"
const val NAME = "name"
const val TOKEN = "token"
const val STAGING = "staging"
const val STAGE = "stage"
const val CURRENCY_ERC20 = "erc20"
const val RATES = "rates"
const val CURRENCY = "currency"
const val UTF_8 = "UTF-8"
const val USD = "USD"
}
| mit | 6d06d65256c72a7e1d37cdf130548c9e | 33.741627 | 80 | 0.670018 | 3.72359 | false | false | false | false |
paoloach/zdomus | temperature_monitor/app/src/main/java/it/achdjian/paolo/temperaturemonitor/domusEngine/rest/JSonPowerNode.kt | 1 | 613 | package it.achdjian.paolo.temperaturemonitor.domusEngine.rest
/**
* Created by Paolo Achdjian on 8/25/17.
*/
data class JSonPowerNode(val error: Boolean, val nwkId: String, val powerLevel: String, val powerMode: String, val availablePowerSource: Int, val currentPowerSource: Int) {
companion object {
val MAIN_POWER = 1
val RECHARGEABLE_BATTERY = 2
val DISPOSABLE_BATTERY = 4
val LEVEL_CRITICAL = "CRITICAL"
val LEVEL_33 = "LEVEL_33"
val LEVEL_66 = "LEVEL_66"
val LEVEL_FULL = "LEVEL_100"
}
constructor() : this(true, "0", "", "", 0, 0) {}
} | gpl-2.0 | 19e1d7d8793feadae0ac7d376a0cbab5 | 33.111111 | 172 | 0.642741 | 3.64881 | false | false | false | false |
kamedon/Validation | sample/src/main/java/com/kamedon/sample/MainActivity.kt | 1 | 1673 | package com.kamedon.sample
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.widget.EditText
import android.widget.Toast
import com.kamedon.validation.Validation
class MainActivity : AppCompatActivity() {
val registerBtn by lazy {
findViewById<View>(R.id.btnRegister)
}
val nameEdit by lazy {
findViewById<EditText>(R.id.userNameEdit)
}
val ageEdit by lazy {
findViewById<EditText>(R.id.userAgeEdit)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val validation = Validation<User> {
"name"{
be { name.length >= 5 } not "name: 5 characters or more"
be { name.length <= 10 } not "name: 10 characters or less"
}
"age"{
be { age >= 20 } not "age: Over 20 years old"
}
}
registerBtn.setOnClickListener {
val ageText = ageEdit.text?.toString() ?: ""
val age = if (ageText.isBlank()) {
0
} else {
ageText.toInt()
}
val user = User(nameEdit.text?.toString() ?: "", age)
val errors = validation.validate(user)
if (errors.isEmpty()) {
Toast.makeText(applicationContext, "valid data!", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(applicationContext, "errors: $errors", Toast.LENGTH_SHORT).show()
}
}
}
}
class User(val name: String, val age: Int)
| mit | a35de3896a2e654f794b43f301d182ab | 26.883333 | 96 | 0.573222 | 4.356771 | false | false | false | false |
fuzhouch/qbranch | core/src/main/kotlin/net/dummydigit/qbranch/DeserializerBase.kt | 1 | 2527 | package net.dummydigit.qbranch
import net.dummydigit.qbranch.generic.*
import net.dummydigit.qbranch.protocols.TaggedProtocolReader
internal interface DeserializerBase {
fun deserialize(reader: TaggedProtocolReader) : Any
companion object {
fun createDeserializerByTypeArg(typeArg : QTypeArg<*>) : DeserializerBase {
return when (typeArg) {
is VectorT<*> -> {
val elementDeserializer = createDeserializerByTypeArg(typeArg.elementT)
VectorDeserializer(elementDeserializer)
}
is SetT<*> -> {
val elementDeserializer = createDeserializerByTypeArg(typeArg.elementT)
SetDeserializer(elementDeserializer)
}
is ListT<*> -> {
val elementDeserializer = createDeserializerByTypeArg(typeArg.elementT)
ListDeserializer(elementDeserializer)
}
is MapT<*, *> -> {
val keyDeserializer = createDeserializerByTypeArg(typeArg.keyT)
val valueDeserializer = createDeserializerByTypeArg(typeArg.valueT)
MapDeserializer(keyDeserializer, valueDeserializer)
}
is StructT<*> -> {
StructDeserializer(typeArg, isBaseClass = false)
}
is BuiltinQTypeArg.PrimitiveT<*> -> {
when (typeArg.dataType) {
BondDataType.BT_BOOL -> { BuiltinTypeDeserializer.Bool }
BondDataType.BT_INT8 -> { BuiltinTypeDeserializer.Int8 }
BondDataType.BT_INT16 -> { BuiltinTypeDeserializer.Int16 }
BondDataType.BT_INT32 -> { BuiltinTypeDeserializer.Int32 }
BondDataType.BT_UINT8 -> { BuiltinTypeDeserializer.UInt8 }
BondDataType.BT_UINT16 -> { BuiltinTypeDeserializer.UInt16 }
BondDataType.BT_UINT32 -> { BuiltinTypeDeserializer.UInt32 }
BondDataType.BT_UINT64 -> { BuiltinTypeDeserializer.UInt64 }
BondDataType.BT_FLOAT -> { BuiltinTypeDeserializer.Float }
BondDataType.BT_DOUBLE -> { BuiltinTypeDeserializer.Double }
else -> { throw NotImplementedError() }
}
}
else -> { throw NotImplementedError() }
}
}
}
} | mit | ef14760c34c0e8703bf282a65e878c64 | 43.350877 | 91 | 0.553621 | 5.628062 | false | false | false | false |
vjache/klips | src/main/java/org/klips/engine/PatternMatcher.kt | 1 | 2059 | package org.klips.engine
import org.klips.dsl.Facet
import org.klips.dsl.Facet.FacetRef
import org.klips.dsl.Fact
import java.util.*
class PatternMatcher(val pattern: Fact) {
private val patternIndex = LinkedHashMap<Facet<*>, MutableSet<Int>>(pattern.facets.size)
private val refIndex : Map<Facet<*>, MutableSet<Int>>
private val refIndexBind : Map<FacetRef<*>, Int>
private val constIndex : Map<Facet<*>, MutableSet<Int>>
private val patternJavaClass = pattern.javaClass
val refs : Set<FacetRef<*>>
get() = refIndexBind.keys
init{
for(i in pattern.facets.indices)
{
val facet = pattern.facets[i]
if(facet in patternIndex) patternIndex[facet]!!.add(i)
else patternIndex[facet] = mutableSetOf(i)
}
refIndex = patternIndex.filter { it.key is FacetRef<*> } // TODO: #1 See bellow
constIndex = patternIndex.filter { it.key is Facet.ConstFacet<*> }
refIndexBind = mutableMapOf<FacetRef<*>, Int>().apply{
for(e in refIndex) {
val key = e.key
if(key is FacetRef<*>) // TODO: #1 Probably need to make stronger typisation for refIndex.keys
put(key, e.value.first())
}
}
}
fun match(fact: Fact): Boolean {
val actJavaClass = fact.javaClass
if(!patternJavaClass.isAssignableFrom(actJavaClass))
return false
for (i in 0..pattern.facets.size - 1) {
val f = pattern.facets[i]
if (!f.match(fact.facets[i])) return false
}
return refIndex.all {
var x:Facet<*>? = null
for(i in it.value)
{
if(x == null)
x = fact.facets[i]
else if(x != fact.facets[i])
return false
}
return true
}
}
fun bind(fact: Fact): Binding? {
if(!match(fact)) return null
return FactBinding(fact, refIndexBind)
}
} | apache-2.0 | 47c0b2dc4395f5e427d1ccc7c3cbd02f | 27.611111 | 110 | 0.558038 | 4.126253 | false | false | false | false |
thomasnield/kotlin-statistics | src/main/kotlin/org/nield/kotlinstatistics/Aggregation.kt | 1 | 1098 | package org.nield.kotlinstatistics
inline fun <T,K,R> Sequence<T>.groupApply(crossinline keySelector: (T) -> K, crossinline aggregation: (Iterable<T>) -> R): Map<K, R> {
val map = mutableMapOf<K,MutableList<T>>()
for (item in this) {
val key = keySelector(item)
val list = map.computeIfAbsent(key) { mutableListOf() }
list += item
}
val aggregatedMap = mutableMapOf<K,R>()
for ((key, value) in map) {
aggregatedMap.put(key, aggregation(value))
}
return aggregatedMap
}
inline fun <T,V,K,R> Sequence<T>.groupApply(crossinline keySelector: (T) -> K, crossinline valueSelector: (T) -> V, crossinline aggregation: (Iterable<V>) -> R): Map<K, R> {
val map = mutableMapOf<K, MutableList<V>>()
for (item in this) {
val key = keySelector(item)
val list = map.computeIfAbsent(key) { mutableListOf() }
list += valueSelector(item)
}
val aggregatedMap = mutableMapOf<K, R>()
for (entry in map.entries) {
aggregatedMap.put(entry.key, aggregation(entry.value))
}
return aggregatedMap
} | apache-2.0 | b8d6dcfeabeb1fcc2e02dc48ce99e9d9 | 31.323529 | 173 | 0.634791 | 3.74744 | false | false | false | false |
googlecodelabs/android-datastore | app/src/main/java/com/codelab/android/datastore/ui/TasksAdapter.kt | 1 | 1614 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.codelab.android.datastore.ui
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import com.codelab.android.datastore.data.Task
class TasksAdapter : ListAdapter<Task, TaskViewHolder>(TASKS_COMPARATOR) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TaskViewHolder {
return TaskViewHolder.create(parent)
}
override fun onBindViewHolder(holder: TaskViewHolder, position: Int) {
val repoItem = getItem(position)
if (repoItem != null) {
holder.bind(repoItem)
}
}
companion object {
private val TASKS_COMPARATOR = object : DiffUtil.ItemCallback<Task>() {
override fun areItemsTheSame(oldItem: Task, newItem: Task): Boolean =
oldItem.name == newItem.name
override fun areContentsTheSame(oldItem: Task, newItem: Task): Boolean =
oldItem == newItem
}
}
}
| apache-2.0 | 4bdd8aaf30a71732e234081620b3aed8 | 34.086957 | 87 | 0.704461 | 4.611429 | false | false | false | false |
AndroidX/constraintlayout | projects/ComposeConstraintLayout/app/src/main/java/com/example/constraintlayout/MotionCarouselDemos.kt | 2 | 32662 | /*
* Copyright (C) 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.constraintlayout
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.Dimension
import androidx.constraintlayout.compose.MotionCarousel
import androidx.constraintlayout.compose.MotionCarouselScope
import androidx.constraintlayout.compose.MotionLayoutScope
import androidx.constraintlayout.compose.MotionScene
import androidx.constraintlayout.compose.items
import androidx.constraintlayout.compose.itemsWithProperties
import androidx.constraintlayout.compose.layoutId
import androidx.core.math.MathUtils
/**
* This file contains several MotionCarousel demos, walking you through simple ones
* to more complex ones, using JSON or DSL MotionScene and advanced animations/transitions.
*
* It's recommended to go through the examples in order to get a good overview of MotionCarousel.
*
* CarouselDemo1: basic self-contained carousel with 3 slots (in JSON)
* CarouselDemo2: expanding on demo1, adding a transition and some keyframes
* CarouselDemo3: factorizing MotionCarousel of Demo1 & 2 in a reusable MySimpleCarousel composable
* CarouselDemo4: rewriting Demo3 using a MotionScene DSL instead of the JSON description
* CarouselDemo5: simple refactoring of the DSL from Demo4 using derived constraintsets
* CarouselDemo6: implementing a more complex carousel with 5 slots in both JSON and DSL
* CarouselDemo7: using Demo6 carousel but with animated cards in the carousel
*/
data class CardInfo(val index : Int, val text: String, val color: Color)
var colors = arrayListOf<Color>(Color(255, 100, 200),
Color.Green, Color.Blue, Color.Cyan, Color.Yellow, Color.Gray,
Color.Magenta, Color.LightGray)
val cardsExample = arrayListOf<CardInfo>(
CardInfo(0, "Card 1", colors[0 % colors.size]),
CardInfo(1, "Card 2", colors[1 % colors.size]),
CardInfo(2, "Card 3", colors[2 % colors.size]),
CardInfo(3, "Card 4", colors[3 % colors.size]),
CardInfo(4, "Card 5", colors[4 % colors.size]),
CardInfo(5, "Card 6", colors[5 % colors.size]),
CardInfo(6, "Card 7", colors[6 % colors.size]),
CardInfo(7, "Card 8", colors[7 % colors.size]),
CardInfo(8, "Card 9", colors[8 % colors.size]),
)
/**
* Helper function
*/
inline val Dp.asDimension : Dimension
get() = Dimension.value(this)
/**
* Simple Carousel demo
*
* We are using a motionScene with 3 states positioning 3 slots,
* slot0, slot1 and slot2, with the "initial" slot being slot1 positioned
* in the center of the screen, slot0 on its left, slot2 on its right.
* As slot1 is the "initial" slot, initialSlotIndex is 1 and numSlots is 3.
*
* ```
* next [slot0] [slot1] | [slot2] |
* start [slot0] | [slot1] | [slot2]
* previous | [slot0] | [slot1] [slot2]
* ```
*
* We are using the above data (cardsExample) that we pass to the
* items() function, which leads to the item passed to be a CardInfo.
*
* We then use the CardInfo to display a colored card.
*/
@Preview
@Composable
fun CarouselDemo1() {
val motionScene = MotionScene(content = """
{
ConstraintSets: {
start: {
slot0: {
width: 200,
height: 400,
end: [ 'parent', 'start', 8 ],
centerVertically: 'parent'
},
slot1: {
width: 200,
height: 400,
center: 'parent'
},
slot2: {
width: 200,
height: 400,
start: [ 'parent', 'end', 8 ],
centerVertically: 'parent'
}
},
next: {
slot0: {
width: 200,
height: 400,
end: [ 'slot1', 'start', 8 ],
centerVertically: 'parent'
},
slot1: {
width: 200,
height: 400,
end: [ 'parent', 'start', 8 ],
centerVertically: 'parent'
},
slot2: {
width: 200,
height: 400,
center: 'parent'
}
},
previous: {
slot0: {
width: 200,
height: 400,
center: 'parent'
},
slot1: {
width: 200,
height: 400,
start: [ 'parent', 'end', 8 ],
centerVertically: 'parent'
},
slot2: {
width: 200,
height: 400,
start: [ 'slot1', 'end', 8 ],
centerVertically: 'parent'
}
}
},
Transitions: {
forward: {
from: 'start',
to: 'next',
},
backward: {
from: 'start',
to: 'previous',
}
}
}
""")
MotionCarousel(motionScene, 1, 3) {
items(cardsExample) { card ->
val color = card.color
val label = card.text
Box(
modifier = Modifier
.fillMaxSize()
.padding(4.dp)
.background(color)
.padding(4.dp)
) {
Column(modifier = Modifier
.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally) {
Text("$label")
}
}
}
}
}
/**
* Simple Carousel demo, take 2
*
* Based on the previous demo, we simply add a transition defining
* a couple of keyframes applying a scale factor on the slots. We could
* create any kind of keyframes here to make the transition more interesting.
*/
@Preview
@Composable
fun CarouselDemo2() {
val motionScene = MotionScene(content = """
{
ConstraintSets: {
start: {
slot0: {
width: 200,
height: 400,
end: [ 'parent', 'start', 8 ],
centerVertically: 'parent'
},
slot1: {
width: 200,
height: 400,
center: 'parent'
},
slot2: {
width: 200,
height: 400,
start: [ 'parent', 'end', 8 ],
centerVertically: 'parent'
}
},
next: {
slot0: {
width: 200,
height: 400,
end: [ 'slot1', 'start', 8 ],
centerVertically: 'parent'
},
slot1: {
width: 200,
height: 400,
end: [ 'parent', 'start', 8 ],
centerVertically: 'parent'
},
slot2: {
width: 200,
height: 400,
center: 'parent'
}
},
previous: {
slot0: {
width: 200,
height: 400,
center: 'parent'
},
slot1: {
width: 200,
height: 400,
start: [ 'parent', 'end', 8 ],
centerVertically: 'parent'
},
slot2: {
width: 200,
height: 400,
start: [ 'slot1', 'end', 8 ],
centerVertically: 'parent'
}
}
},
Transitions: {
forward: {
from: 'start',
to: 'next',
KeyFrames: {
KeyAttributes: [
{
target: ['slot0', 'slot1', 'slot2'],
frames: [50],
scaleX: .3,
scaleY: .3
}
]
}
},
backward: {
from: 'start',
to: 'previous',
KeyFrames: {
KeyAttributes: [
{
target: ['slot0', 'slot1', 'slot2'],
frames: [50],
scaleX: .3,
scaleY: .3
}
]
}
}
}
}
""")
MotionCarousel(motionScene, 1, 3) {
items(cardsExample) { card ->
val i = card.index
val color = card.color
val label = card.text
Box(
modifier = Modifier
.fillMaxSize()
.padding(4.dp)
.background(color)
.padding(4.dp)
) {
Column(modifier = Modifier
.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally) {
Text("$label")
}
} }
}
}
/**
* The previous examples were all self-contained, but in practice
* you likely will want to encapsulate your Carousel in its own
* composable, to be able to reuse it more easily.
*
* We do that here by defining a MySimpleCarousel function that takes
* a MotionCarouselScope, and reusing the same motionScene
* as in CarouselDemo2.
*/
@Composable
fun MySimpleCarousel(content: MotionCarouselScope.() -> Unit) {
val motionScene = MotionScene(content = """
{
ConstraintSets: {
start: {
slot0: {
width: 200,
height: 400,
end: [ 'parent', 'start', 8 ],
centerVertically: 'parent'
},
slot1: {
width: 200,
height: 400,
center: 'parent'
},
slot2: {
width: 200,
height: 400,
start: [ 'parent', 'end', 8 ],
centerVertically: 'parent'
}
},
next: {
slot0: {
width: 200,
height: 400,
end: [ 'slot1', 'start', 8 ],
centerVertically: 'parent'
},
slot1: {
width: 200,
height: 400,
end: [ 'parent', 'start', 8 ],
centerVertically: 'parent'
},
slot2: {
width: 200,
height: 400,
center: 'parent'
}
},
previous: {
slot0: {
width: 200,
height: 400,
center: 'parent'
},
slot1: {
width: 200,
height: 400,
start: [ 'parent', 'end', 8 ],
centerVertically: 'parent'
},
slot2: {
width: 200,
height: 400,
start: [ 'slot1', 'end', 8 ],
centerVertically: 'parent'
}
}
},
Transitions: {
forward: {
from: 'start',
to: 'next',
KeyFrames: {
KeyAttributes: [
{
target: ['slot0', 'slot1', 'slot2'],
frames: [50],
scaleX: .3,
scaleY: .3
}
]
}
},
backward: {
from: 'start',
to: 'previous',
KeyFrames: {
KeyAttributes: [
{
target: ['slot0', 'slot1', 'slot2'],
frames: [50],
scaleX: .3,
scaleY: .3
}
]
}
}
}
}
""")
MotionCarousel(motionScene, 1, 3, content = content)
}
/**
* Similarly, we can extract the content that we put in the Carousel
* slots to its own composable, MyCard
*/
@Composable
fun MyCard(item: CardInfo) {
val i = item.index
val color = item.color
val label = item.text
Box(
modifier = Modifier
.fillMaxSize()
.padding(4.dp)
.background(color)
.padding(4.dp)
) {
Column(modifier = Modifier
.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally) {
Text("$label")
}
}
}
/**
* We now can rewrite CarouselDemo2 by using MySimpleCarousel instead, referencing MyCard,
* resulting in a very readable usage.
*/
@Preview
@Composable
fun CarouselDemo3() {
MySimpleCarousel() {
items(cardsExample) { card ->
MyCard(card)
}
}
}
/**
* Of course, we can use the new MotionLayout DSL instead of JSON to write the Carousel :)
* Let's rewrite MySimpleCarousel with the DSL.
*/
@Composable
fun MySimpleCarouselDSL(content: MotionCarouselScope.() -> Unit) {
val motionScene = MotionScene {
val slot0 = createRefFor("slot0")
val slot1 = createRefFor("slot1")
val slot2 = createRefFor("slot2")
val startState = constraintSet("start") {
constrain(slot0) {
width = 200.dp.asDimension
height = 400.dp.asDimension
end.linkTo(parent.start, 8.dp)
centerVerticallyTo(parent)
}
constrain(slot1) {
width = 200.dp.asDimension
height = 400.dp.asDimension
centerTo(parent)
}
constrain(slot2) {
width = 200.dp.asDimension
height = 400.dp.asDimension
start.linkTo(parent.end, 8.dp)
centerVerticallyTo(parent)
}
}
val nextState = constraintSet("next") {
constrain(slot0) {
width = 200.dp.asDimension
height = 400.dp.asDimension
end.linkTo(slot1.start, 8.dp)
centerVerticallyTo(parent)
}
constrain(slot1) {
width = 200.dp.asDimension
height = 400.dp.asDimension
end.linkTo(parent.start, 8.dp)
centerVerticallyTo(parent)
}
constrain(slot2) {
width = 200.dp.asDimension
height = 400.dp.asDimension
centerTo(parent)
}
}
val previousState = constraintSet("previous") {
constrain(slot0) {
width = 200.dp.asDimension
height = 400.dp.asDimension
centerTo(parent)
}
constrain(slot1) {
width = 200.dp.asDimension
height = 400.dp.asDimension
start.linkTo(parent.end, 8.dp)
centerVerticallyTo(parent)
}
constrain(slot2) {
width = 200.dp.asDimension
height = 400.dp.asDimension
start.linkTo(slot1.end, 8.dp)
centerVerticallyTo(parent)
}
}
transition("forward", startState, nextState) {
keyAttributes(slot0, slot1, slot2) {
frame(50) {
scaleX = .3f
scaleY = .3f
}
}
}
transition("backward", startState, previousState) {
keyAttributes(slot0, slot1, slot2) {
frame(50) {
scaleX = .3f
scaleY = .3f
}
}
}
}
MotionCarousel(motionScene, 1, 3, content = content)
}
/**
* As you can see, we can easily change CarouselDemo3 to reference MySimpleCarouselDSL instead
* for a similar result.
*/
@Preview
@Composable
fun CarouselDemo4() {
MySimpleCarouselDSL() {
items(cardsExample) { card ->
MyCard(card)
}
}
}
/**
* Note, we can also refactor the DSL a little bit to share common constraints,
* by creating a base state and having the other constraintsets be derived from it
* (This trick also works in JSON, incidentally)
*/
@Composable
fun MySimpleCarouselDSL2(content: MotionCarouselScope.() -> Unit) {
val motionScene = MotionScene {
val slot0 = createRefFor("slot0")
val slot1 = createRefFor("slot1")
val slot2 = createRefFor("slot2")
val baseState = constraintSet("base") {
constrain(slot0) {
width = 200.dp.asDimension
height = 400.dp.asDimension
}
constrain(slot1) {
width = 200.dp.asDimension
height = 400.dp.asDimension
}
constrain(slot2) {
width = 200.dp.asDimension
height = 400.dp.asDimension
}
}
val startState = constraintSet("start", baseState) {
constrain(slot0) {
end.linkTo(parent.start, 8.dp)
centerVerticallyTo(parent)
}
constrain(slot1) {
centerTo(parent)
}
constrain(slot2) {
start.linkTo(parent.end, 8.dp)
centerVerticallyTo(parent)
}
}
val nextState = constraintSet("next", baseState) {
constrain(slot0) {
end.linkTo(slot1.start, 8.dp)
centerVerticallyTo(parent)
}
constrain(slot1) {
end.linkTo(parent.start, 8.dp)
centerVerticallyTo(parent)
}
constrain(slot2) {
centerTo(parent)
}
}
val previousState = constraintSet("previous", baseState) {
constrain(slot0) {
centerTo(parent)
}
constrain(slot1) {
start.linkTo(parent.end, 8.dp)
centerVerticallyTo(parent)
}
constrain(slot2) {
start.linkTo(slot1.end, 8.dp)
centerVerticallyTo(parent)
}
}
transition("forward", startState, nextState) {
keyAttributes(slot0, slot1, slot2) {
frame(50) {
scaleX = .3f
scaleY = .3f
}
}
}
transition("backward", startState, previousState) {
keyAttributes(slot0, slot1, slot2) {
frame(50) {
scaleX = .3f
scaleY = .3f
}
}
}
}
MotionCarousel(motionScene, 1, 3, content = content)
}
/**
* As you can see, we can easily change CarouselDemo3 to reference MySimpleCarouselDSL instead
* for a similar result.
*/
@Preview
@Composable
fun CarouselDemo5() {
MySimpleCarouselDSL2() {
items(cardsExample) { card ->
MyCard(card)
}
}
}
/**
* Let's do another example with a more complex MotionScene using 5 slots,
* encapsulated in its own MyCarouselDSL function as well
*/
@Composable
fun MyCarouselDSL(content: MotionCarouselScope.() -> Unit) {
val motionScene = MotionScene {
val slot0 = createRefFor("slot0")
val slot1 = createRefFor("slot1")
val slot2 = createRefFor("slot2")
val slot3 = createRefFor("slot3")
val slot4 = createRefFor("slot4")
val startState = constraintSet("start") {
constrain(slot0) {
width = 100.dp.asDimension
height = 200.dp.asDimension
end.linkTo(parent.start, 8.dp)
centerVerticallyTo(parent)
customColor("mainColor", Color.Blue)
}
constrain(slot1) {
width = 100.dp.asDimension
height = 200.dp.asDimension
start.linkTo(parent.start, 8.dp)
centerVerticallyTo(parent)
customColor("mainColor", Color.Blue)
}
constrain(slot2) {
width = 150.dp.asDimension
height = 250.dp.asDimension
centerTo(parent)
rotationX = 5f
rotationY = 360f
customColor("mainColor", Color.Red)
customFloat("main", 1.0f)
}
constrain(slot3) {
width = 100.dp.asDimension
height = 200.dp.asDimension
end.linkTo(parent.end, 8.dp)
centerVerticallyTo(parent)
customColor("mainColor", Color.Blue)
}
constrain(slot4) {
width = 100.dp.asDimension
height = 200.dp.asDimension
start.linkTo(parent.end, 8.dp)
centerVerticallyTo(parent)
customColor("mainColor", Color.Blue)
}
}
val nextState = constraintSet("next") {
constrain(slot0) {
width = 100.dp.asDimension
height = 200.dp.asDimension
end.linkTo(slot1.start, 8.dp)
centerVerticallyTo(parent)
customColor("mainColor", Color.Blue)
}
constrain(slot1) {
width = 100.dp.asDimension
height = 200.dp.asDimension
end.linkTo(parent.start, 8.dp)
centerVerticallyTo(parent)
customColor("mainColor", Color.Blue)
}
constrain(slot2) {
width = 100.dp.asDimension
height = 200.dp.asDimension
start.linkTo(parent.start, 8.dp)
centerVerticallyTo(parent)
customColor("mainColor", Color.Blue)
}
constrain(slot3) {
width = 150.dp.asDimension
height = 250.dp.asDimension
centerTo(parent)
rotationX = 5f
customColor("mainColor", Color.Red)
customFloat("main", 1.0f)
}
constrain(slot4) {
width = 100.dp.asDimension
height = 200.dp.asDimension
end.linkTo(parent.end, 8.dp)
centerVerticallyTo(parent)
customColor("mainColor", Color.Blue)
}
}
val previousState = constraintSet("previous") {
constrain(slot0) {
width = 100.dp.asDimension
height = 200.dp.asDimension
start.linkTo(parent.start, 8.dp)
centerVerticallyTo(parent)
customColor("mainColor", Color.Blue)
}
constrain(slot1) {
width = 150.dp.asDimension
height = 250.dp.asDimension
centerTo(parent)
rotationX = 5f
customColor("mainColor", Color.Red)
customFloat("main", 1.0f)
}
constrain(slot2) {
width = 100.dp.asDimension
height = 200.dp.asDimension
end.linkTo(parent.end, 8.dp)
centerVerticallyTo(parent)
customColor("mainColor", Color.Blue)
}
constrain(slot3) {
width = 100.dp.asDimension
height = 200.dp.asDimension
start.linkTo(parent.end, 8.dp)
centerVerticallyTo(parent)
customColor("mainColor", Color.Blue)
}
constrain(slot4) {
width = 100.dp.asDimension
height = 200.dp.asDimension
start.linkTo(slot3.end, 8.dp)
centerVerticallyTo(parent)
customColor("mainColor", Color.Blue)
}
}
transition("forward", startState, nextState) {}
transition("backward", startState, previousState) {}
}
MotionCarousel(motionScene, 2, 5, content = content)
}
/**
* For completeness' sake, we can write the same Carousel in JSON instead of the DSL
*/
@Composable
fun MyCarouselJSON(content: MotionCarouselScope.() -> Unit) {
val motionScene = MotionScene("""{
Header: {
exportAs: 'carousel'
},
ConstraintSets: {
start: {
slot0: {
width: 100,
height: 200,
end: ['parent','start', 8],
centerVertically: 'parent',
custom: {
mainColor: '#0000FF'
}
},
slot1: {
width: 100,
height: 200,
start: ['parent','start', 8],
centerVertically: 'parent',
custom: {
mainColor: '#0000FF'
}
},
slot2: {
width: 150,
height: 250,
centerHorizontally: 'parent',
centerVertically: 'parent',
rotationX: 5,
rotationY: 360,
custom: {
mainColor: '#FF0000',
main: 1.0
}
},
slot3: {
width: 100,
height: 200,
end: ['parent','end', 8],
centerVertically: 'parent',
custom: {
mainColor: '#0000FF'
}
},
slot4: {
width: 100,
height: 200,
start: ['parent','end', 8],
centerVertically: 'parent',
custom: {
mainColor: '#0000FF'
}
}
},
next: {
slot0: {
width: 100,
height: 200,
end: ['slot1','start', 8],
centerVertically: 'parent',
custom: {
mainColor: '#0000FF'
}
},
slot1: {
width: 100,
height: 200,
end: ['parent','start', 8],
centerVertically: 'parent',
custom: {
mainColor: '#0000FF'
}
},
slot2: {
width: 100,
height: 200,
start: ['parent','start',8],
centerVertically: 'parent',
custom: {
mainColor: '#0000FF'
}
},
slot3: {
width: 150,
height: 250,
centerHorizontally: 'parent',
centerVertically: 'parent',
rotationX: 5,
//rotationY: 360,
custom: {
mainColor: '#FF0000',
main: 1.0
}
},
slot4: {
width: 100,
height: 200,
end: ['parent','end', 8],
centerVertically: 'parent',
custom: {
mainColor: '#0000FF'
}
}
},
previous: {
slot0: {
width: 100,
height: 200,
start: ['parent','start', 8],
centerVertically: 'parent',
custom: {
mainColor: '#0000FF'
}
},
slot1: {
width: 150,
height: 250,
centerHorizontally: 'parent',
centerVertically: 'parent',
rotationX: 5,
//rotationY: 360,
custom: {
mainColor: '#FF0000',
main: 1.0
}
},
slot2: {
width: 100,
height: 200,
end: ['parent','end', 8],
centerVertically: 'parent',
custom: {
mainColor: '#0000FF'
}
},
slot3: {
width: 100,
height: 200,
start: ['parent','end', 8],
centerVertically: 'parent',
custom: {
mainColor: '#0000FF'
}
},
slot4: {
width: 100,
height: 200,
start: ['slot3','end', 8],
centerVertically: 'parent',
custom: {
mainColor: '#0000FF'
}
}
}
},
Transitions: {
forward: {
from: 'start',
to: 'next',
},
backward: {
from: 'start',
to: 'previous',
},
}
}""")
MotionCarousel(motionScene, 2, 5, content = content, showSlots = false)
}
/**
* The resulting demo, still using MyCard() for the content
*/
@Preview
@Composable
fun CarouselDemo6() {
// or
// MyCarouselJSON()
MyCarouselDSL() {
items(cardsExample) { card ->
MyCard(card)
}
}
}
/**
* Finally, you might want to have the "selected" item of your carousel
* being painted or acting differently than the rest -- how could you implement this?
*
* One approach is to define custom properties directly in the MotionScene, and
* retrieving them at runtime.
*
* You might have noticed that this is exactly what we did in the MotionScene used for
* the previous CarouselDemo6 example -- we defined a "mainColor" as well as a "main" property
* that we assign to our "selected" slot.
*
* We can then simply retrieve those properties by using itemsWithProperties() instead of items(),
* and pass them to a new AnimatedCard composable
*/
@Preview
@Composable
fun CarouselDemo7() {
MyCarouselDSL() {
itemsWithProperties(cardsExample) { card, properties ->
AnimatedCard(properties, card)
}
}
}
/**
* This is using the custom properties we defined in the motion scene to do something a little
* more interesting -- here each card will have an intrinsic color, but will revert to a default
* color unless the card is the current selection (recognized by the attribute "main"). While we
* are at it, let's use a gradient too!
*/
@Composable
fun AnimatedCard(properties: State<MotionLayoutScope.MotionProperties>, item: CardInfo) {
val i = item.index
val label = item.text
var v = properties.value.float("main")
if (v == Float.NaN) {
v = 0f
}
val color = Color(
MathUtils.clamp(item.color.red * v, 0f, 1f),
MathUtils.clamp(item.color.green * v, 0f, 1f),
MathUtils.clamp(item.color.blue * v, 0f, 1f)
)
val endColor = properties.value.color("mainColor")
val gradient = Brush.verticalGradient(0f to endColor,
0.5f to color, 1f to endColor)
val textColor = Color(
MathUtils.clamp( 1 - v, 0f, 1f),
MathUtils.clamp( 1 - v, 0f, 1f),
MathUtils.clamp( 1 - v, 0f, 1f)
)
Box(
modifier = Modifier
.fillMaxSize()
.layoutId("card$i", "box")
.padding(4.dp)
.clip(RoundedCornerShape(20.dp))
.background(gradient)
.padding(4.dp)
) {
Column(modifier = Modifier
.width(100.dp)
.fillMaxHeight(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally) {
Text(color = textColor, text = "$label")
}
}
} | apache-2.0 | 2fcb3dc19b2c626cf16ab84fd19059d9 | 29.497666 | 99 | 0.490478 | 4.658679 | false | false | false | false |
duftler/orca | orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/handler/StartTaskHandlerTest.kt | 1 | 4871 | /*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.q.handler
import com.netflix.spinnaker.orca.ExecutionStatus.RUNNING
import com.netflix.spinnaker.orca.StageResolver
import com.netflix.spinnaker.orca.TaskResolver
import com.netflix.spinnaker.orca.api.SimpleStage
import com.netflix.spinnaker.orca.events.TaskStarted
import com.netflix.spinnaker.orca.fixture.pipeline
import com.netflix.spinnaker.orca.fixture.stage
import com.netflix.spinnaker.orca.pipeline.DefaultStageDefinitionBuilderFactory
import com.netflix.spinnaker.orca.pipeline.model.Execution.ExecutionType.PIPELINE
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.orca.pipeline.util.ContextParameterProcessor
import com.netflix.spinnaker.orca.q.DummyTask
import com.netflix.spinnaker.orca.q.RunTask
import com.netflix.spinnaker.orca.q.StartTask
import com.netflix.spinnaker.orca.q.buildTasks
import com.netflix.spinnaker.orca.q.singleTaskStage
import com.netflix.spinnaker.q.Queue
import com.netflix.spinnaker.time.fixedClock
import com.nhaarman.mockito_kotlin.argumentCaptor
import com.nhaarman.mockito_kotlin.check
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.doThrow
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.reset
import com.nhaarman.mockito_kotlin.verify
import com.nhaarman.mockito_kotlin.whenever
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.lifecycle.CachingMode.GROUP
import org.jetbrains.spek.subject.SubjectSpek
import org.junit.jupiter.api.Assertions.assertThrows
import org.springframework.context.ApplicationEventPublisher
object StartTaskHandlerTest : SubjectSpek<StartTaskHandler>({
val queue: Queue = mock()
val repository: ExecutionRepository = mock()
val publisher: ApplicationEventPublisher = mock()
val taskResolver = TaskResolver(emptyList())
val stageResolver = StageResolver(emptyList(), emptyList<SimpleStage<Object>>())
val clock = fixedClock()
subject(GROUP) {
StartTaskHandler(queue, repository, ContextParameterProcessor(), DefaultStageDefinitionBuilderFactory(stageResolver), publisher, taskResolver, clock)
}
fun resetMocks() = reset(queue, repository, publisher)
describe("when a task starts") {
val pipeline = pipeline {
stage {
type = singleTaskStage.type
singleTaskStage.buildTasks(this)
}
}
val message = StartTask(pipeline.type, pipeline.id, "foo", pipeline.stages.first().id, "1")
beforeGroup {
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("marks the task as running") {
verify(repository).storeStage(check {
it.tasks.first().apply {
assertThat(status).isEqualTo(RUNNING)
assertThat(startTime).isEqualTo(clock.millis())
}
})
}
it("runs the task") {
verify(queue).push(RunTask(
message.executionType,
message.executionId,
"foo",
message.stageId,
message.taskId,
DummyTask::class.java
))
}
it("publishes an event") {
argumentCaptor<TaskStarted>().apply {
verify(publisher).publishEvent(capture())
firstValue.apply {
assertThat(executionType).isEqualTo(pipeline.type)
assertThat(executionId).isEqualTo(pipeline.id)
assertThat(stageId).isEqualTo(message.stageId)
assertThat(taskId).isEqualTo(message.taskId)
}
}
}
}
describe("when the execution repository has a problem") {
val pipeline = pipeline {
stage {
type = singleTaskStage.type
singleTaskStage.buildTasks(this)
}
}
val message = StartTask(pipeline.type, pipeline.id, "foo", pipeline.stages.first().id, "1")
beforeGroup {
whenever(repository.retrieve(PIPELINE, message.executionId)) doThrow NullPointerException()
}
afterGroup(::resetMocks)
it("propagates any exception") {
assertThrows(NullPointerException::class.java) {
subject.handle(message)
}
}
}
})
| apache-2.0 | 03c40c748909feb17066eb990c579f92 | 33.546099 | 153 | 0.739273 | 4.408145 | false | false | false | false |
AlekseyZhelo/LBM | lbmlib/src/main/kotlin/com/alekseyzhelo/lbm/momenta/Momenta.kt | 1 | 7984 | package com.alekseyzhelo.lbm.momenta
import com.alekseyzhelo.lbm.boundary.BoundaryPosition
import com.alekseyzhelo.lbm.core.cell.CellD2Q9
import com.alekseyzhelo.lbm.core.lattice.DescriptorD2Q9
import com.alekseyzhelo.lbm.statistics.LatticeStatistics
import com.alekseyzhelo.lbm.util.computeEquilibrium
import com.alekseyzhelo.lbm.util.computeFneq
import com.alekseyzhelo.lbm.util.normSquare
/**
* @author Aleks on 09-07-2016.
*/
interface Momenta {
fun computeRho(cell: CellD2Q9): Double
fun computeU(cell: CellD2Q9, rho: Double): DoubleArray
fun computeRhoU(cell: CellD2Q9): DoubleArray
fun computeBufferRho(cell: CellD2Q9): Double
fun computeBufferU(cell: CellD2Q9, rho: Double): DoubleArray
fun computeBufferRhoU(cell: CellD2Q9): DoubleArray
fun defineRho(cell: CellD2Q9, rho: Double) {
val oldRho = computeRho(cell)
val U = computeU(cell, oldRho)
val uSqr = normSquare(U)
val fNeq = computeFneq(cell, oldRho, U)
for (i in 0..DescriptorD2Q9.Q - 1) {
cell[i] = computeEquilibrium(i, rho, U, uSqr) + fNeq[i]
}
}
fun defineU(cell: CellD2Q9, U: DoubleArray) {
val rho = computeRho(cell)
val oldU = computeU(cell, rho)
val uSqr = normSquare(U)
val fNeq = computeFneq(cell, rho, oldU)
for (i in 0..DescriptorD2Q9.Q - 1) {
cell[i] = computeEquilibrium(i, rho, U, uSqr) + fNeq[i]
}
}
fun defineRhoU(cell: CellD2Q9, rho: Double, U: DoubleArray) {
val oldRho = computeRho(cell)
val oldU = computeU(cell, rho)
val uSqr = normSquare(U)
val fNeq = computeFneq(cell, oldRho, oldU)
for (i in 0..DescriptorD2Q9.Q - 1) {
cell[i] = computeEquilibrium(i, rho, U, uSqr) + fNeq[i]
}
}
}
object BulkMomenta : Momenta {
/**
* computeRho and computeU can be further optimized by computing them simultaneously.
* (See OpenLB lbHelpers2D.h:132+)
*/
override fun computeRho(cell: CellD2Q9): Double {
val rho = cell[0] + cell[1] + cell[2] + cell[3] + cell[4] + cell[5] + cell[6] + cell[7] + cell[8]
LatticeStatistics.gatherMinMaxDensity(rho)
return rho
}
override fun computeU(cell: CellD2Q9, rho: Double): DoubleArray {
if (rho == 0.0) { // TODO clutch, find a way to remove
cell.U[0] = 0.0
cell.U[1] = 0.0
return cell.U
}
cell.U[0] = (cell[1] + cell[5] + cell[8] - cell[3] - cell[6] - cell[7]) / rho
cell.U[1] = (cell[2] + cell[5] + cell[6] - cell[4] - cell[7] - cell[8]) / rho
LatticeStatistics.gatherMaxVelocity(cell.U)
return cell.U
}
override fun computeRhoU(cell: CellD2Q9): DoubleArray {
val rho = cell[0] + cell[1] + cell[2] + cell[3] + cell[4] + cell[5] + cell[6] + cell[7] + cell[8]
LatticeStatistics.gatherMinMaxDensity(rho)
if (rho == 0.0) { // TODO clutch, find a way to remove
cell.U[0] = 0.0
cell.U[1] = 0.0
return cell.U
}
cell.U[0] = (cell[1] + cell[5] + cell[8] - cell[3] - cell[6] - cell[7]) / rho
cell.U[1] = (cell[2] + cell[5] + cell[6] - cell[4] - cell[7] - cell[8]) / rho
LatticeStatistics.gatherMaxVelocity(cell.U)
return cell.U
}
override fun computeBufferRho(cell: CellD2Q9): Double {
val rho =
cell.fBuf[0] + cell.fBuf[1] + cell.fBuf[2] + cell.fBuf[3] + cell.fBuf[4] + cell.fBuf[5] + cell.fBuf[6] + cell.fBuf[7] + cell.fBuf[8]
LatticeStatistics.gatherMinMaxDensity(rho)
return rho
}
override fun computeBufferU(cell: CellD2Q9, rho: Double): DoubleArray {
if (rho == 0.0) { // TODO clutch, find a way to remove
cell.U[0] = 0.0
cell.U[1] = 0.0
return cell.U
}
cell.U[0] = (cell.fBuf[1] + cell.fBuf[5] + cell.fBuf[8] - cell.fBuf[3] - cell.fBuf[6] - cell.fBuf[7]) / rho
cell.U[1] = (cell.fBuf[2] + cell.fBuf[5] + cell.fBuf[6] - cell.fBuf[4] - cell.fBuf[7] - cell.fBuf[8]) / rho
LatticeStatistics.gatherMaxVelocity(cell.U)
return cell.U
}
override fun computeBufferRhoU(cell: CellD2Q9): DoubleArray {
val rho =
cell.fBuf[0] + cell.fBuf[1] + cell.fBuf[2] + cell.fBuf[3] + cell.fBuf[4] + cell.fBuf[5] + cell.fBuf[6] + cell.fBuf[7] + cell.fBuf[8]
LatticeStatistics.gatherMinMaxDensity(rho)
if (rho == 0.0) { // TODO clutch, find a way to remove
cell.U[0] = 0.0
cell.U[1] = 0.0
return cell.U
}
cell.U[0] = (cell.fBuf[1] + cell.fBuf[5] + cell.fBuf[8] - cell.fBuf[3] - cell.fBuf[6] - cell.fBuf[7]) / rho
cell.U[1] = (cell.fBuf[2] + cell.fBuf[5] + cell.fBuf[6] - cell.fBuf[4] - cell.fBuf[7] - cell.fBuf[8]) / rho
LatticeStatistics.gatherMaxVelocity(cell.U)
return cell.U
}
}
// TODO: does not work :(
class BoundaryMomenta(val position: BoundaryPosition) : Momenta {
/**
* computeRho and computeU can be further optimized by computing them simultaneously.
* (See OpenLB lbHelpers2D.h:132+)
*/
override fun computeRho(cell: CellD2Q9): Double {
var rho = 0.0
for (f in position.inside) {
rho += cell[f]
}
LatticeStatistics.gatherMinMaxDensity(rho)
return rho
}
override fun computeU(cell: CellD2Q9, rho: Double): DoubleArray {
cell.U[0] = 0.0
cell.U[1] = 0.0
if (rho == 0.0) { // TODO clutch, find a way to remove
return cell.U
}
for (f in position.inside) {
cell.U[0] += cell[f] * DescriptorD2Q9.c[f][0]
cell.U[1] += cell[f] * DescriptorD2Q9.c[f][1]
}
cell.U[0] /= rho
cell.U[1] /= rho
LatticeStatistics.gatherMaxVelocity(cell.U)
return cell.U
}
override fun computeRhoU(cell: CellD2Q9): DoubleArray {
var rho = 0.0
for (f in position.inside) {
rho += cell[f]
}
LatticeStatistics.gatherMinMaxDensity(rho)
cell.U[0] = 0.0
cell.U[1] = 0.0
if (rho == 0.0) { // TODO clutch, find a way to remove
return cell.U
}
for (f in position.inside) {
cell.U[0] += cell[f] * DescriptorD2Q9.c[f][0]
cell.U[1] += cell[f] * DescriptorD2Q9.c[f][1]
}
cell.U[0] /= rho
cell.U[1] /= rho
LatticeStatistics.gatherMaxVelocity(cell.U)
return cell.U
}
override fun computeBufferRho(cell: CellD2Q9): Double {
var rho = 0.0
for (f in position.inside) {
rho += cell.fBuf[f]
}
LatticeStatistics.gatherMinMaxDensity(rho)
return rho
}
override fun computeBufferU(cell: CellD2Q9, rho: Double): DoubleArray {
cell.U[0] = 0.0
cell.U[1] = 0.0
if (rho == 0.0) { // TODO clutch, find a way to remove
return cell.U
}
for (f in position.inside) {
cell.U[0] += cell.fBuf[f] * DescriptorD2Q9.c[f][0]
cell.U[1] += cell.fBuf[f] * DescriptorD2Q9.c[f][1]
}
cell.U[0] /= rho
cell.U[1] /= rho
LatticeStatistics.gatherMaxVelocity(cell.U)
return cell.U
}
override fun computeBufferRhoU(cell: CellD2Q9): DoubleArray {
var rho = 0.0
for (f in position.inside) {
rho += cell.fBuf[f]
}
LatticeStatistics.gatherMinMaxDensity(rho)
cell.U[0] = 0.0
cell.U[1] = 0.0
if (rho == 0.0) { // TODO clutch, find a way to remove
return cell.U
}
for (f in position.inside) {
cell.U[0] += cell.fBuf[f] * DescriptorD2Q9.c[f][0]
cell.U[1] += cell.fBuf[f] * DescriptorD2Q9.c[f][1]
}
cell.U[0] /= rho
cell.U[1] /= rho
LatticeStatistics.gatherMaxVelocity(cell.U)
return cell.U
}
} | apache-2.0 | 504ed0b30f25c60cafb362a12b338574 | 33.270386 | 144 | 0.564128 | 2.918129 | false | false | false | false |
elect86/modern-jogl-examples | src/main/kotlin/glNext/test.kt | 2 | 1075 | package glNext
/**
* Created by GBarbieri on 11.04.2017.
*/
class Person private constructor(val name: String, val surname: String, val age: Int) {
private constructor(builder: Builder) : this(builder.name, builder.surname, builder.age)
companion object {
fun create(init: Builder.() -> Unit) = Builder(init).build()
}
class Builder private constructor() {
constructor(init: Builder.() -> Unit) : this() {
init()
}
lateinit var name: String
lateinit var surname: String
var age: Int = 0
fun name(init: Builder.() -> String) = apply { name = init() }
fun surname(init: Builder.() -> String) = apply { surname = init() }
fun age(init: Builder.() -> Int) = apply { age = init() }
fun build() = Person(this)
}
}
fun main(args: Array<String>) {
Person.create {
name { "Peter" }
surname { "Slesarew" }
age { 28 }
}
// OR
Person.create {
name = "Peter"
surname = "Slesarew"
age = 28
}
} | mit | ec29894a96529b0cab14bd6fd3881556 | 20.959184 | 92 | 0.547907 | 3.894928 | false | false | false | false |
ujpv/intellij-rust | src/main/kotlin/org/rust/ide/folding/RustFoldingBuilder.kt | 1 | 2962 | package org.rust.ide.folding
import com.intellij.lang.ASTNode
import com.intellij.lang.folding.FoldingBuilderEx
import com.intellij.lang.folding.FoldingDescriptor
import com.intellij.openapi.editor.Document
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiTreeUtil
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.impl.RustFile
import java.util.*
class RustFoldingBuilder() : FoldingBuilderEx(), DumbAware {
override fun getPlaceholderText(node: ASTNode): String = if (node.psi is PsiComment) "/* ... */" else "{...}"
override fun buildFoldRegions(root: PsiElement, document: Document, quick: Boolean): Array<out FoldingDescriptor> {
if (root !is RustFile) return emptyArray()
val descriptors: MutableList<FoldingDescriptor> = ArrayList()
val visitor = FoldingVisitor(descriptors)
PsiTreeUtil.processElements(root) { it.accept(visitor); true }
return descriptors.toTypedArray()
}
private class FoldingVisitor(private val descriptors: MutableList<FoldingDescriptor>) : RustElementVisitor() {
override fun visitStructExprBody(o: RustStructExprBodyElement) = fold(o)
override fun visitEnumBody(o: RustEnumBodyElement) = fold(o)
override fun visitBlockFields(o: RustBlockFieldsElement) = fold(o)
override fun visitBlock(o: RustBlockElement) = fold(o)
override fun visitMatchBody(o: RustMatchBodyElement) = fold(o)
override fun visitUseGlobList(o: RustUseGlobListElement) = fold(o)
override fun visitTraitItem(o: RustTraitItemElement) = foldBetween(o, o.lbrace, o.rbrace)
override fun visitModItem(o: RustModItemElement) = foldBetween(o, o.lbrace, o.rbrace)
override fun visitMacroArg(o: RustMacroArgElement) = foldBetween(o, o.lbrace, o.rbrace)
override fun visitImplItem(o: RustImplItemElement) = foldBetween(o, o.lbrace, o.rbrace)
override fun visitComment(comment: PsiComment) {
if (comment.tokenType == RustTokenElementTypes.BLOCK_COMMENT) {
fold(comment)
}
}
override fun visitStructItem(o: RustStructItemElement) {
val blockFields = o.blockFields
if (blockFields != null) {
fold(blockFields)
}
}
private fun fold(element: PsiElement) {
descriptors += FoldingDescriptor(element.node, element.textRange)
}
private fun foldBetween(element: PsiElement, left: PsiElement?, right: PsiElement?) {
if (left != null && right != null) {
val range = TextRange(left.textOffset, right.textOffset + 1)
descriptors += FoldingDescriptor(element.node, range)
}
}
}
override fun isCollapsedByDefault(node: ASTNode): Boolean = false
}
| mit | d386e1ce9b3c8efdcfff03451ff7a6a7 | 37.467532 | 119 | 0.690749 | 4.420896 | false | false | false | false |
etesync/android | app/src/main/java/com/etesync/syncadapter/ui/importlocal/LocalCalendarImportFragment.kt | 1 | 10075 | package com.etesync.syncadapter.ui.importlocal
import android.accounts.Account
import android.app.ProgressDialog
import android.content.Context
import android.os.AsyncTask
import android.os.Bundle
import android.provider.CalendarContract
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseExpandableListAdapter
import android.widget.ExpandableListView
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.ListFragment
import androidx.fragment.app.commit
import at.bitfire.ical4android.CalendarStorageException
import com.etesync.syncadapter.R
import com.etesync.syncadapter.log.Logger
import com.etesync.syncadapter.model.CollectionInfo
import com.etesync.syncadapter.resource.LocalCalendar
import com.etesync.syncadapter.resource.LocalEvent
class LocalCalendarImportFragment : ListFragment() {
private lateinit var account: Account
private lateinit var uid: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
retainInstance = true
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_local_calendar_import, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
importAccount()
}
protected fun importAccount() {
val calendarAccountList = CalendarAccount.loadAll(context!!.contentResolver)
val listCalendar = listView as ExpandableListView
val adapter = ExpandableListAdapter(context!!, calendarAccountList)
listCalendar.setAdapter(adapter)
listCalendar.setOnChildClickListener { aExpandableListView, aView, groupPosition, childPosition, aL ->
ImportEvents().execute(calendarAccountList[groupPosition].getCalendars()[childPosition])
false
}
}
private inner class ExpandableListAdapter(private val context: Context, private val calendarAccounts: List<CalendarAccount>) : BaseExpandableListAdapter() {
private val accountResolver: AccountResolver
init {
this.accountResolver = AccountResolver(context)
}
private inner class ChildViewHolder {
internal var textView: TextView? = null
}
private inner class GroupViewHolder {
internal var titleTextView: TextView? = null
internal var descriptionTextView: TextView? = null
internal var iconImageView: ImageView? = null
}
override fun getChild(groupPosition: Int, childPosititon: Int): Any {
return calendarAccounts[groupPosition].getCalendars()[childPosititon].displayName!!
}
override fun getChildId(groupPosition: Int, childPosition: Int): Long {
return childPosition.toLong()
}
override fun getChildView(groupPosition: Int, childPosition: Int,
isLastChild: Boolean, convertView: View?, parent: ViewGroup): View {
var convertView = convertView
val childText = getChild(groupPosition, childPosition) as String
val viewHolder: ChildViewHolder
if (convertView == null) {
val inflater = context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
convertView = inflater.inflate(R.layout.import_calendars_list_item, null)
}
if (convertView!!.tag != null) {
viewHolder = convertView.tag as ChildViewHolder
} else {
viewHolder = ChildViewHolder()
viewHolder.textView = convertView
.findViewById<View>(R.id.listItemText) as TextView
convertView.tag = viewHolder
}
viewHolder.textView!!.text = childText
return convertView
}
override fun getChildrenCount(groupPosition: Int): Int {
return calendarAccounts[groupPosition].getCalendars()
.size
}
override fun getGroup(groupPosition: Int): Any {
return calendarAccounts[groupPosition]
}
override fun getGroupCount(): Int {
return calendarAccounts.size
}
override fun getGroupId(groupPosition: Int): Long {
return groupPosition.toLong()
}
override fun getGroupView(groupPosition: Int, isExpanded: Boolean,
convertView: View?, parent: ViewGroup): View {
var convertView = convertView
val calendarAccount = getGroup(groupPosition) as CalendarAccount
val viewHolder: GroupViewHolder
if (convertView == null) {
val inflater = context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
convertView = inflater.inflate(R.layout.import_content_list_header, null)
}
if (convertView!!.tag != null) {
viewHolder = convertView.tag as GroupViewHolder
} else {
viewHolder = GroupViewHolder()
viewHolder.titleTextView = convertView
.findViewById<View>(R.id.title) as TextView
viewHolder.descriptionTextView = convertView
.findViewById<View>(R.id.description) as TextView
viewHolder.iconImageView = convertView.findViewById<View>(R.id.icon) as ImageView
convertView.tag = viewHolder
}
viewHolder.titleTextView!!.text = calendarAccount.accountName
val accountInfo = accountResolver.resolve(calendarAccount.accountType)
viewHolder.descriptionTextView!!.text = accountInfo.name
viewHolder.iconImageView!!.setImageDrawable(accountInfo.icon)
return convertView
}
override fun hasStableIds(): Boolean {
return false
}
override fun isChildSelectable(groupPosition: Int, childPosition: Int): Boolean {
return true
}
}
protected inner class ImportEvents : AsyncTask<LocalCalendar, Int, ResultFragment.ImportResult>() {
private lateinit var progressDialog: ProgressDialog
override fun onPreExecute() {
progressDialog = ProgressDialog(activity)
progressDialog.setTitle(R.string.import_dialog_title)
progressDialog.setMessage(getString(R.string.import_dialog_adding_entries))
progressDialog.setCanceledOnTouchOutside(false)
progressDialog.setCancelable(false)
progressDialog.isIndeterminate = false
progressDialog.setIcon(R.drawable.ic_import_export_black)
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL)
progressDialog.show()
}
override fun doInBackground(vararg calendars: LocalCalendar): ResultFragment.ImportResult {
return importEvents(calendars[0])
}
override fun onProgressUpdate(vararg progress: Int?) {
progressDialog.progress = progress[0]!!
}
override fun onPostExecute(result: ResultFragment.ImportResult) {
val activity = activity
if (activity == null) {
Logger.log.warning("Activity is null on import.")
return
}
if (progressDialog.isShowing && !activity.isDestroyed && !activity.isFinishing) {
progressDialog.dismiss()
}
onImportResult(result)
}
private fun importEvents(fromCalendar: LocalCalendar): ResultFragment.ImportResult {
val result = ResultFragment.ImportResult()
try {
val localCalendar = LocalCalendar.findByName(account,
context!!.contentResolver.acquireContentProviderClient(CalendarContract.CONTENT_URI)!!,
LocalCalendar.Factory, uid)
val localEvents = fromCalendar.findAll()
val total = localEvents.size
progressDialog.max = total
result.total = total.toLong()
var progress = 0
for (currentLocalEvent in localEvents) {
val event = currentLocalEvent.event
try {
localCalendar!!
var localEvent = if (event == null || event.uid == null)
null
else
localCalendar.findByUid(event.uid!!)
if (localEvent != null) {
localEvent.updateAsDirty(event!!)
result.updated++
} else {
localEvent = LocalEvent(localCalendar, event!!, event.uid, null)
localEvent.addAsDirty()
result.added++
}
} catch (e: CalendarStorageException) {
e.printStackTrace()
}
publishProgress(++progress)
}
} catch (e: Exception) {
e.printStackTrace()
result.e = e
}
return result
}
}
fun onImportResult(importResult: ResultFragment.ImportResult) {
val fragment = ResultFragment.newInstance(importResult)
parentFragmentManager.commit(true) {
add(fragment, "importResult")
}
}
companion object {
fun newInstance(account: Account, uid: String): LocalCalendarImportFragment {
val ret = LocalCalendarImportFragment()
ret.account = account
ret.uid = uid
return ret
}
}
}
| gpl-3.0 | 258f4a908e0863bce6c97d3d4bb109c3 | 37.454198 | 160 | 0.615186 | 5.850755 | false | false | false | false |
LorittaBot/Loritta | buildSrc/src/main/kotlin/GenerateOptimizedImage.kt | 1 | 10291 | import kotlinx.serialization.builtins.ListSerializer
import kotlinx.serialization.json.Json
import org.gradle.workers.WorkAction
import java.awt.Image
import java.awt.image.BufferedImage
import java.io.File
import javax.imageio.ImageIO
abstract class GenerateOptimizedImage : WorkAction<GenerateOptimizedImageParameters> {
override fun execute() {
val fileIndex = parameters.fileIndex.get()
val sourceFile = parameters.sourceFile.get().asFile
val temporaryFolder = parameters.temporaryFolder.get().asFile
val targetFile = parameters.targetFile.get().asFile
val targetFolder = parameters.targetFolder.get().asFile
val pngQuantPathString = parameters.pngQuantPathString.get()
val gifsiclePathString = parameters.gifsiclePathString.get()
try {
temporaryFolder.mkdirs()
targetFile.parentFile.mkdirs()
val targetFileRelativeToTheBaseFolder = targetFile.relativeTo(targetFolder)
val imageType = sourceFile.extension
val imagesInfo = mutableListOf<ImageInfo>()
when (imageType) {
"png" -> {
// Load the image
val originalImage = ImageIO.read(sourceFile)
println("Copying ${sourceFile}...")
// Copy current image as is
sourceFile.copyTo(targetFile, true)
optimizePNG(pngQuantPathString, targetFile)
val variations = mutableListOf<ImageInfo>()
// Optimize images based on our width sizes array
for (newWidth in ImageOptimizerTask.widthSizes.filter { originalImage.width >= it }) {
val newHeight = (newWidth * originalImage.height) / originalImage.width
println("Downscaling $sourceFile to ${newWidth}x${newHeight}...")
// Scale down to the width
val downscaledImage = toBufferedImage(
originalImage.getScaledInstance(
newWidth,
(newWidth * originalImage.height) / originalImage.width,
BufferedImage.SCALE_SMOOTH
)
)
val downscaledImageFile = File(
targetFile.parentFile,
targetFile.nameWithoutExtension + "_${newWidth}w.${targetFile.extension}"
)
ImageIO.write(
downscaledImage,
"png",
downscaledImageFile
)
optimizePNG(pngQuantPathString, downscaledImageFile)
variations.add(
ImageInfo(
downscaledImageFile.relativeTo(targetFolder).toString().replace("\\", "/"),
downscaledImage.width,
downscaledImage.height,
downscaledImageFile.length(),
null
)
)
}
val imageInfo = ImageInfo(
targetFileRelativeToTheBaseFolder.toString().replace("\\", "/"),
originalImage.width,
originalImage.height,
sourceFile.length(),
variations
)
imagesInfo.add(imageInfo)
}
"gif" -> {
// Load the image
// https://stackoverflow.com/a/39131371/7271796
val originalImage = ImageIO.read(sourceFile)
println("Copying ${sourceFile}...")
// Copy current image as is
sourceFile.copyTo(targetFile, true)
optimizeGIF(gifsiclePathString, targetFile, targetFile)
val variations = mutableListOf<ImageInfo>()
// Optimize images based on our width sizes array
for (newWidth in ImageOptimizerTask.widthSizes.filter { originalImage.width >= it }) {
val newHeight = (newWidth * originalImage.height) / originalImage.width
println("Downscaling $sourceFile to ${newWidth}x${newHeight}...")
val downscaledImageFile = File(
targetFile.parentFile,
targetFile.nameWithoutExtension + "_${newWidth}w.${targetFile.extension}"
)
resizeGIF(gifsiclePathString, sourceFile, downscaledImageFile, newWidth, newHeight)
optimizeGIF(gifsiclePathString, downscaledImageFile, downscaledImageFile)
variations.add(
ImageInfo(
downscaledImageFile.relativeTo(targetFolder).toString().replace("\\", "/"),
newWidth,
newHeight,
downscaledImageFile.length(),
null
)
)
}
val imageInfo = ImageInfo(
targetFileRelativeToTheBaseFolder.toString().replace("\\", "/"),
originalImage.width,
originalImage.height,
sourceFile.length(),
variations
)
imagesInfo.add(imageInfo)
}
else -> {
println("Copying $sourceFile (no optimizations)...")
// Copy current image as is
sourceFile.copyTo(targetFile, true)
}
}
// Yes, this is the "correct" way to do this
// It is weird, but it works... so, umm... yay?
// https://discuss.gradle.org/t/returning-data-from-a-gradle-workaction/32850
File(temporaryFolder, "$fileIndex.json")
.writeText(Json.encodeToString(ListSerializer(ImageInfo.serializer()), imagesInfo))
} catch (e: Exception) {
throw RuntimeException(e)
}
}
private fun optimizePNG(pngQuantPathString: String, file: File) {
val originalFileSize = file.length()
// https://stackoverflow.com/questions/39894913/how-do-i-get-the-best-png-compression-with-gulp-imagemin-plugins
val proc = ProcessBuilder(
pngQuantPathString,
"--quality=70-90",
"--strip",
"-f",
"--ext",
".png",
"--skip-if-larger",
"--speed",
"1",
file.absolutePath
).start()
val result = proc.inputStream.readAllBytes()
val errorStreamResult = proc.errorStream.readAllBytes()
val s = proc.waitFor()
// println("pngquant's input stream: ${result.toString(Charsets.UTF_8)}")
// println("pngquant's error stream: ${errorStreamResult.toString(Charsets.UTF_8)}")
// https://manpages.debian.org/testing/pngquant/pngquant.1.en.html
// 99 = if quality can't match what we want, pngquant exists with exit code 99
// 98 = If conversion results in a file larger than the original, the image won't be saved and pngquant will exit with status code 98.
if (s != 0 && s != 98 && s != 99) { // uuuh, this shouldn't happen if this is a PNG image...
error("Something went wrong while trying to optimize PNG image! Status = $s; Error stream: ${errorStreamResult.toString(Charsets.UTF_8)}")
}
val newFileSize = file.length()
println("Successfully optimized ${file.name}! $originalFileSize -> $newFileSize")
}
private fun resizeGIF(gifsiclePathString: String, file: File, output: File, width: Int, height: Int) {
val proc = ProcessBuilder(
gifsiclePathString,
"--resize",
"${width}x$height",
"-o",
"${output.absolutePath}",
file.absolutePath
).start()
val result = proc.inputStream.readAllBytes()
val errorStreamResult = proc.errorStream.readAllBytes()
val s = proc.waitFor()
if (s != 0) {
error("Something went wrong while trying to resize GIF image! Status = $s; Error stream: ${errorStreamResult.toString(Charsets.UTF_8)}")
}
println("Successfully resized ${file.name}!")
}
private fun optimizeGIF(gifsiclePathString: String, file: File, output: File) {
val proc = ProcessBuilder(
gifsiclePathString,
"-O3",
"--lossy=25", // Optimize GIFs a LOT
"--colors=64", // who cares about colors right
"-o",
"${output.absolutePath}",
file.absolutePath
).start()
val result = proc.inputStream.readAllBytes()
val errorStreamResult = proc.errorStream.readAllBytes()
val s = proc.waitFor()
if (s != 0) {
error("Something went wrong while trying to optimize GIF image! Status = $s; Error stream: ${errorStreamResult.toString(Charsets.UTF_8)}")
}
println("Successfully optimize ${file.name}!")
}
/**
* Converts a given Image into a BufferedImage
*
* @param img The Image to be converted
* @return The converted BufferedImage
*/
private fun toBufferedImage(img: Image): BufferedImage {
if (img is BufferedImage) {
return img
}
// Create a buffered image with transparency
val bimage = BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB)
// Draw the image on to the buffered image
val bGr = bimage.createGraphics()
bGr.drawImage(img, 0, 0, null)
bGr.dispose()
// Return the buffered image
return bimage
}
} | agpl-3.0 | 31592a17a0d71855ddfa6edc8de41942 | 38.891473 | 150 | 0.527743 | 5.608174 | false | false | false | false |
cbeyls/fosdem-companion-android | app/src/main/java/be/digitalia/fosdem/utils/XmlPullParserExt.kt | 1 | 1278 | package be.digitalia.fosdem.utils
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserFactory
val xmlPullParserFactory: XmlPullParserFactory by lazy {
XmlPullParserFactory.newInstance()
}
/*
* Checks if the current event is the end of the document
*/
inline val XmlPullParser.isEndDocument
get() = eventType == XmlPullParser.END_DOCUMENT
/*
* Checks if the current event is a start tag
*/
inline val XmlPullParser.isStartTag
get() = eventType == XmlPullParser.START_TAG
/*
* Checks if the current event is a start tag with the specified local name
*/
@Suppress("NOTHING_TO_INLINE")
inline fun XmlPullParser.isStartTag(name: String) = eventType == XmlPullParser.START_TAG && name == this.name
/*
* Go to the next event and check if the current event is an end tag with the specified local name
*/
@Suppress("NOTHING_TO_INLINE")
inline fun XmlPullParser.isNextEndTag(name: String) = next() == XmlPullParser.END_TAG && name == this.name
/*
* Skips the start tag and positions the reader on the corresponding end tag
*/
fun XmlPullParser.skipToEndTag() {
var type = next()
while (type != XmlPullParser.END_TAG) {
if (type == XmlPullParser.START_TAG) {
skipToEndTag()
}
type = next()
}
} | apache-2.0 | ab0ebd5a4147a14c7b2d947c237f2330 | 27.422222 | 109 | 0.712833 | 4.018868 | false | false | false | false |
christophpickl/gadsu | src/main/kotlin/at/cpickl/gadsu/development/view.kt | 1 | 3313 | package at.cpickl.gadsu.development
import at.cpickl.gadsu.global.IS_OS_WIN
import at.cpickl.gadsu.client.Client
import at.cpickl.gadsu.service.formatDateTime
import at.cpickl.gadsu.treatment.Treatment
import at.cpickl.gadsu.view.components.MyFrame
import at.cpickl.gadsu.view.components.panels.GridPanel
import at.cpickl.gadsu.view.swing.addCloseListener
import at.cpickl.gadsu.view.swing.bold
import at.cpickl.gadsu.view.swing.changeBackgroundForASec
import at.cpickl.gadsu.view.swing.opaque
import at.cpickl.gadsu.view.swing.scrolled
import java.awt.Color
import java.awt.Dimension
import java.awt.GridBagConstraints
import java.awt.Point
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JTextArea
class DevelopmentFrame(
initLocation: Point
): MyFrame("Development Console") {
private val txtClient = JLabel()
private val txtTreatment = JLabel()
private val events = JTextArea().apply {
name = "Development.EventsTextArea"
lineWrap = true
if (IS_OS_WIN) {
font = JLabel().font
}
}
init {
addCloseListener { close() }
txtClient.opaque()
txtTreatment.opaque()
val panel = GridPanel()
panel.border = MyFrame.BORDER_GAP
panel.c.anchor = GridBagConstraints.NORTHWEST
panel.c.fill = GridBagConstraints.HORIZONTAL
panel.c.weightx = 1.0
panel.c.weighty = 0.0
panel.add(JLabel("Current client: ").bold())
panel.c.gridy++
panel.add(txtClient)
panel.c.gridy++
panel.add(JLabel("Current treatment: ").bold())
panel.c.gridy++
panel.add(txtTreatment)
panel.c.gridy++
panel.c.weighty = 1.0
panel.c.fill = GridBagConstraints.BOTH
panel.add(events.scrolled())
// panel.c.gridy++
// panel.c.weighty = 0.0
// panel.c.fill = GridBagConstraints.NONE
// panel.c.anchor = GridBagConstraints.CENTER
// panel.add(ElementsStarView(bus, 40).apply { enforceSize(200, 180) })
contentPane.add(panel)
size = Dimension(400, 600)
location = initLocation
}
fun updateClient(client: Client?) {
update(txtClient, client, {
"""<html>${if (!it.yetPersisted) "EMPTY<br/>" else ""}Note: ${it.note}</html>"""
})
}
fun updateTreatment(treatment: Treatment?) {
update(txtTreatment, treatment, {
"""<html>${if (!it.yetPersisted) "EMPTY<br/>" else ""}Nr: ${it.number}<br/>Datum: ${it.date.formatDateTime()}</html>"""
})
}
fun start() {
isVisible = true
}
fun addEvent(event: Any) {
events.text = "${events.text}${event.javaClass.simpleName} ====> $event\n"
}
fun close() {
isVisible = false
dispose()
}
private fun <T> update(txt: JLabel, value: T?, function: (T) -> String) {
val text: String
if (value == null) {
text = "NULL"
} else {
text = function(value)
}
txt.text = text
txt.changeBackgroundForASec(Color.YELLOW)
}
}
var JComponent.debugColor: Color?
get() = null
set(value) {
if (Development.COLOR_ENABLED) {
opaque()
background = value
}
}
| apache-2.0 | 91cdefad2d6649d18941a1a8d6bde1f2 | 25.934959 | 131 | 0.615454 | 3.865811 | false | false | false | false |
christophpickl/kpotpourri | http4k/src/main/kotlin/com/github/christophpickl/kpotpourri/http4k/internal/internal_misc.kt | 1 | 1119 | package com.github.christophpickl.kpotpourri.http4k.internal
import com.github.christophpickl.kpotpourri.http4k.Request4k
import com.github.christophpickl.kpotpourri.http4k.Response4k
import com.github.christophpickl.kpotpourri.jackson4k.buildJackson4kMapper
import java.net.SocketTimeoutException
interface HttpClient {
fun execute(request4k: Request4k): Response4k
}
interface HttpClientFactory {
fun build(metaMap: MetaMap): HttpClient
}
internal val mapper = buildJackson4kMapper()
/**
* Meta data values for concrete implementations.
*/
open class MetaMap {
protected val map = HashMap<String, Any>()
operator fun get(key: String) = map[key]
override fun toString() = "${this.javaClass.simpleName}[map=$map]"
}
class MutableMetaMap : MetaMap() {
operator fun plusAssign(pair: Pair<String, Any>) {
map += pair
}
}
/**
* Abstraction when (implementation specific) timeout was triggered (connect, request).
*/
class TimeoutException(message: String, cause: Exception? = null): SocketTimeoutException(message) {
init {
cause?.let(this::initCause)
}
}
| apache-2.0 | 90508b456a74e7fff286513f718f5744 | 24.431818 | 100 | 0.74084 | 3.926316 | false | false | false | false |
pronghorn-tech/server | src/main/kotlin/tech/pronghorn/http/protocol/HttpUrlParser.kt | 1 | 5654 | /*
* Copyright 2017 Pronghorn Technology 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 tech.pronghorn.http.protocol
import tech.pronghorn.util.sliceToArray
import java.nio.ByteBuffer
private val RootURI = ValueHttpUrl("/")
private val StarURI = ValueHttpUrl("*")
private const val httpAsInt = 1752462448
private const val doubleSlashAsShort: Short = 12079
private const val secureByte: Byte = 0x73
public fun parseHttpUrl(buffer: ByteBuffer): HttpUrlParseResult {
if (!buffer.hasRemaining()) {
return IncompleteHttpUrl
}
var byte = buffer.get()
var pathContainsPercentEncoding = false
var pathStart = -1
var portStart = -1
var hostStart = -1
var queryParamStart = -1
var pathEnd = -1
var end = -1
var port: Int? = null
var isSecure: Boolean? = null
if (byte == forwardSlashByte) {
if (!buffer.hasRemaining()) {
return RootURI
}
pathStart = buffer.position() - 1
// abs_path
while (buffer.hasRemaining()) {
byte = buffer.get()
if (byte == percentByte) {
pathContainsPercentEncoding = true
}
else if (byte == questionByte) {
pathEnd = buffer.position() - 1
queryParamStart = buffer.position()
}
else if (byte == spaceByte) {
end = buffer.position() - 1
if (end - pathStart == 1) {
return RootURI
}
break
}
}
}
else if (byte == asteriskByte) {
// starURI
if (!buffer.hasRemaining() || buffer.get() == spaceByte) {
return StarURI
}
else {
return InvalidHttpUrl
}
}
else {
buffer.position(buffer.position() - 1)
// absoluteURI
if (buffer.remaining() < 4) {
return IncompleteHttpUrl
}
val firstFour = buffer.int
if (firstFour != httpAsInt) {
return InvalidHttpUrl
}
byte = buffer.get()
isSecure = byte == secureByte
if (isSecure) {
byte = buffer.get()
}
if (byte == colonByte) {
if (buffer.remaining() < 2) {
return IncompleteHttpUrl
}
val slashes = buffer.short
if (slashes != doubleSlashAsShort) {
return InvalidHttpUrl
}
}
else {
return InvalidHttpUrl
}
hostStart = buffer.position()
while (buffer.hasRemaining()) {
byte = buffer.get()
if (byte == colonByte) {
// parse port
portStart = buffer.position()
port = 0
while (buffer.hasRemaining()) {
val portByte = buffer.get()
if (portByte == forwardSlashByte) {
pathStart = buffer.position() - 1
break
}
else if (portByte == spaceByte) {
end = buffer.position() - 1
break
}
port = (port!! * 10) + (portByte - 48)
}
break
}
else if (byte == forwardSlashByte) {
pathStart = buffer.position() - 1
break
}
else if (byte == spaceByte) {
end = buffer.position() - 1
break
}
}
if (end == -1) {
while (buffer.hasRemaining()) {
byte = buffer.get()
if (byte == percentByte) {
pathContainsPercentEncoding = true
}
else if (byte == questionByte) {
pathEnd = buffer.position() - 1
queryParamStart = buffer.position()
break
}
else if (byte == spaceByte) {
end = buffer.position() - 1
break
}
}
}
}
if (end == -1) {
end = buffer.position()
}
if (pathEnd == -1) {
pathEnd = end
}
val path = if (pathStart != -1) {
buffer.sliceToArray(pathStart, pathEnd - pathStart)
}
else {
null
}
val prePath = if (pathStart != -1) {
pathStart
}
else {
end
}
val host = if (hostStart != -1) {
buffer.sliceToArray(hostStart, if (portStart != -1) portStart - 1 - hostStart else prePath - hostStart)
}
else {
null
}
val queryParams = if (queryParamStart != -1) {
buffer.sliceToArray(queryParamStart, end - queryParamStart)
}
else {
null
}
return ByteArrayHttpUrl(
path = path,
isSecure = isSecure,
host = host,
port = port,
queryParams = queryParams,
pathContainsPercentEncoding = pathContainsPercentEncoding
)
}
| apache-2.0 | 8f02d137806f1bbdd6fcebe635f95df4 | 26.052632 | 111 | 0.49717 | 4.763269 | false | false | false | false |
google/xplat | j2kt/jre/java/common/javaemul/lang/CauseHolder.kt | 1 | 1087 | /*
* Copyright 2022 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package javaemul.lang
import javaemul.internal.InternalPreconditions.Companion.checkState
class CauseHolder() {
// Holds the cause (a Throwable or null), or this, if no cause was set
private var thisOrCause: Any? = this
var cause: Throwable?
get() = if (hasCause()) thisOrCause as Throwable? else null
set(value: Throwable?) {
checkState(!hasCause(), "Can't overwrite cause")
thisOrCause = value
}
private fun hasCause(): Boolean = thisOrCause !== this
}
| apache-2.0 | 934484efcb88b4ce934d452f21f24d6b | 32.96875 | 75 | 0.720331 | 4.148855 | false | false | false | false |
DevCharly/kotlin-ant-dsl | generator/src/main/kotlin/com/devcharly/kotlin/ant/generator/codegen.kt | 1 | 14244 | /*
* Copyright 2016 Karl Tauber
*
* 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.devcharly.kotlin.ant.generator
import org.apache.tools.ant.Project
import org.apache.tools.ant.ProjectComponent
import org.apache.tools.ant.types.EnumeratedAttribute
import org.apache.tools.ant.types.ResourceCollection
import java.io.File
import java.lang.reflect.Method
import java.lang.reflect.Modifier
import java.util.*
const val HEADER = """/*
* Copyright 2016 Karl Tauber
*
* 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 """
const val DO_NOT_EDIT = """
/******************************************************************************
DO NOT EDIT - this file was generated
******************************************************************************/
"""
fun genTaskFile(task: Task, pkg: String): String {
val imports = HashSet<String>()
val funCode = genTaskFun(task, imports)
val nestedClassCode = genNestedClass(task, imports)
var code = genFileHeader(pkg, imports)
code += funCode
if (nestedClassCode != null) {
code += '\n'
code += nestedClassCode
}
code += genEnums(task)
return code
}
fun genTypeFile(task: Task, pkg: String): String {
val imports = HashSet<String>()
val nestedFunCode = genTypeNestedFun(task, null, "\t", imports)
val nestedInterface = genTypeNestedInterface(task, nestedFunCode, imports)
val initFunCode = genTypeInitFun(task, imports)
val nestedClassCode = genNestedClass(task, imports)
var code = genFileHeader(pkg, imports)
code += nestedInterface
val baseInterface = task.baseInterface
if (baseInterface != null && task.type != baseInterface && baseInterface.isAssignableFrom(task.type)) {
var cls: Class<*>? = task.type.superclass
while (cls != null && baseInterface.isAssignableFrom(cls)) {
if (!Modifier.isAbstract(cls.modifiers)) {
code += "\n"
code += genTypeNestedFun(task, cls.simpleName, "", imports)
}
cls = cls.superclass
}
code += "\n"
code += genTypeNestedFun(task, baseInterface.simpleName, "", imports)
}
if (initFunCode != null) {
code += "\n"
code += initFunCode
}
if (nestedClassCode != null) {
code += '\n'
code += nestedClassCode
}
code += genEnums(task)
return code
}
fun genTypeInitFile(task: Task, pkg: String): String {
val imports = HashSet<String>()
val initFunCode = genTypeInitFun(task, imports)
var code = genFileHeader(pkg, imports)
code += initFunCode
return code
}
fun genEnumFile(task: Task, pkg: String): String {
val imports = HashSet<String>()
var code = genFileHeader(pkg, imports)
code += genEnum(task.type)
return code
}
fun genFileHeader(pkg: String, imports: Set<String>): String {
var code = HEADER + pkg
val imports2 = HashSet<String>(imports)
if (pkg != "com.devcharly.kotlin.ant")
imports2.add("com.devcharly.kotlin.ant.*")
code += "\n\n"
imports2.sorted().forEach {
code += "import ${it.replace('$', '.')}\n"
}
code += DO_NOT_EDIT
code += '\n'
return code
}
fun genTaskFun(task: Task, imports: HashSet<String>): String {
imports.add(task.type.name)
// build parameters and initialization
val params = genParams(task, true, "\t", imports)
val init = genInit(task, "task", "\t\t", imports)
// build function
val funCode = "fun Ant.${task.taskName}(\n" +
params + ")\n" +
"{\n" +
"\t${task.type.simpleName}().execute(\"${task.taskName}\") { task ->\n" +
init +
"\t}\n" +
"}\n"
return funCode
}
fun genTypeInitFun(task: Task, imports: HashSet<String>): String? {
if (task.type.isInterface)
return null
imports.add(task.type.name)
// build parameters and initialization
val params = genParams(task, false, "\t", imports)
val init = genInit(task, "", "\t", imports)
val projectParam = if (needsProject(task)) {
imports.add(Project::class.java.name)
"\tproject: Project,\n"
} else
""
// build function
val funCode = "fun ${task.type.simpleName}._init(\n" +
projectParam +
params + ")\n" +
"{\n" +
init +
"}\n"
return funCode
}
fun genTypeNestedInterface(task: Task, body: String?, imports: HashSet<String>): String {
if (!task.hasConstructor && !task.type.isInterface)
return ""
imports.add(task.type.name)
return "interface I${task.type.simpleName}Nested " +
(if (hasProject(task.type)) ": INestedComponent " else "") +
"{\n" +
(if (body != null) "$body\n" else "") +
"\tfun _add${task.type.simpleName}(value: ${task.type.simpleName})\n" +
"}\n"
}
fun genTypeNestedFun(task: Task, forType: String?, indent: String, imports: HashSet<String>): String? {
if (task.type.isInterface)
return null
val params = genParams(task, true, "${indent}\t", imports)
val addType = forType ?: task.type.simpleName
val constrParam = if (task.projectAtConstructor) "component.project" else ""
var addCode = "${indent}\t_add${addType}(${task.type.simpleName}($constrParam).apply {\n"
if (hasProject(task.type))
addCode += "${indent}\t\tcomponent.project.setProjectReference(this);\n"
addCode += "${indent}\t\t_init("
if (needsProject(task))
addCode += "component.project, "
task.params.forEachIndexed { i, param ->
addCode += param.name
if (i < task.params.size - 1)
addCode += if ((i + 1) % 4 == 0) ",\n${indent}\t\t\t" else ", "
}
if (task.hasNested) {
if (!task.params.isEmpty())
addCode += ", "
addCode += "nested"
}
addCode += ")\n" +
"${indent}\t})\n"
val forTypeInterface = if (forType != null) "I${forType}Nested." else ""
return "${indent}fun $forTypeInterface${task.funName}(\n" +
params + ")\n" +
"${indent}{\n" +
addCode +
"${indent}}\n"
}
private fun genParams(task: Task, initNull: Boolean, indent: String, imports: HashSet<String>): String {
var params = ""
task.params.forEach {
if (!params.isEmpty())
params += ",\n"
params += "${indent}${it.name}: ${paramType(it.type)}?"
if (initNull)
params += " = null"
}
if (task.hasNested) {
if (!task.params.isEmpty())
params += ",\n"
params += "${indent}nested: (K${task.nestedClassName}.() -> Unit)?"
if (initNull)
params += " = null"
}
return params
}
private fun genInit(task: Task, varName: String, indent: String, imports: HashSet<String>): String {
var init = ""
// build parameters and initialization
val useThisDotProject = task.params.any { it.name == "project" }
task.params.forEach {
val varNameDot = if (varName == "") "" else "$varName."
init += "${indent}if (${it.name} != null)\n"
init += "${indent}\t$varNameDot${it.method.name}(${init(it.type, it.name, it.constructWithProject, useThisDotProject, imports)})\n"
}
if (task.hasNested) {
val varName2 = if (varName == "") "this" else varName
val projectParam = if (needsProject(task)) ", project" else ""
init += "${indent}if (nested != null)\n"
init += "${indent}\tnested(K${task.nestedClassName}($varName2$projectParam))\n"
}
return init
}
fun genNestedClass(task: Task, imports: HashSet<String>): String? {
if (!task.hasNested)
return null
val interfaces = ArrayList<Class<*>>()
task.addTypeMethods.forEach {
interfaces.add(it.parameterTypes[0])
}
val addTypeMethods = ArrayList<Method>()
addTypeMethods.addAll(task.addTypeMethods)
var code = ""
task.nested.forEach {
val n = getTask(it.type)
if (it.name == n.funName) {
val baseInterface = n.baseInterface
if (baseInterface != null &&
baseInterface.isAssignableFrom(it.type) &&
interfaces.contains(baseInterface))
return@forEach
if (it.method.parameterCount == 1 &&
it.method.parameterTypes[0] == it.type)
{
if (interfaces.contains(it.type))
return@forEach
interfaces.add(it.type)
addTypeMethods.add(it.method)
return@forEach
}
}
var nestedInitCode = "apply {\n"
if (hasProject(it.type))
nestedInitCode += "\t\t\tcomponent.project.setProjectReference(this)\n"
nestedInitCode += "\t\t\t_init("
if (needsProject(n))
nestedInitCode += if (needsProject(task)) "project, " else "component.project, "
nestedInitCode += "${n.params.joinToString { it.name }}"
if (n.hasNested) {
if (!n.params.isEmpty())
nestedInitCode += ", "
nestedInitCode += "nested"
}
nestedInitCode += ")\n" +
"\t\t}"
code += "\tfun ${unreserved(it.name)}(${genParams(n, true, "", imports).replace('\n', ' ')}) {\n"
if (it.method.parameterCount == 0)
code += "\t\tcomponent.${it.method.name}().$nestedInitCode\n"
else {
val constrParam = if (n.projectAtConstructor) "component.project" else ""
code += "\t\tcomponent.${it.method.name}(${it.type.simpleName}($constrParam).$nestedInitCode)\n"
imports.add(it.type.name)
}
code += "\t}\n"
}
addTypeMethods.forEach { addTypeMethod ->
val type = addTypeMethod.parameterTypes[0]
imports.add(type.name)
code += "\toverride fun _add${type.simpleName}(value: ${type.simpleName}) = component.${addTypeMethod.name}(value)\n"
}
if (task.addTextMethod != null)
code += "\toperator fun String.unaryPlus() = component.${task.addTextMethod.name}(this)\n"
code += "}\n"
val consOvr = if (interfaces.any { hasProject(it) }) "override " else ""
var code0 = "class K${task.nestedClassName}(${consOvr}val component: ${task.type.simpleName}"
if (needsProject(task))
code0 += ", val project: Project"
code0 += ")"
interfaces.forEachIndexed { i, it ->
code0 += if (i == 0) " :\n\t" else ",\n\t"
code0 += "I${it.simpleName}Nested"
}
code0 += if (interfaces.isEmpty()) " " else "\n"
code0 += "{\n"
return code0 + code
}
private fun genEnums(task: Task): String {
var code = ""
var enums = HashSet<Class<*>>()
for (param in task.params) {
if (!EnumeratedAttribute::class.java.isAssignableFrom(param.type) && !param.type.isEnum)
continue
if (!enums.add(param.type))
continue
val enclosingClass = param.type.enclosingClass
if (enclosingClass != task.type)
continue
if (code.isEmpty())
code += "\n"
code += genEnum(param.type)
}
return code
}
private fun genEnum(type: Class<*>): String {
var code = ""
if (EnumeratedAttribute::class.java.isAssignableFrom(type)) {
code += "enum class ${type.simpleName}(val value: String) { "
val e = type.newInstance() as EnumeratedAttribute
val values = e.values
// remove duplicate values
val values2 = values.filterIndexed { i, s ->
for (j in (i - 1) downTo 0) {
if (s.equals(values[j], ignoreCase = true))
return@filterIndexed false
}
true
}
code += values2.joinToString { "${it.toUpperCase().replace('-', '_')}(\"$it\")" }
code += " }\n"
} else if (type.isEnum) {
val origEnum = if (type.name.contains('$'))
type.name.substringAfterLast('.').replace('$', '.')
else
type.name // not a nested enum --> use full qualified name
val values = type.getMethod("values").invoke(null) as Array<java.lang.Enum<*>>
code += "enum class ${type.simpleName}(val value: $origEnum) {\n\t"
code += values.joinToString(",\n\t") { "${it.name().toUpperCase()}($origEnum.${it.name()})" }
code += "\n}\n"
}
return code
}
private fun paramType(type: Class<*>): String {
return when (type.name) {
"java.lang.String" -> "String"
"boolean" -> "Boolean"
"byte" -> "Byte"
"short" -> "Short"
"int" -> "Int"
"long" -> "Long"
"char" -> "Char"
"float" -> "Float"
"double" -> "Double"
"java.lang.Boolean" -> "Boolean"
"java.lang.Byte" -> "Byte"
"java.lang.Short" -> "Short"
"java.lang.Integer" -> "Int"
"java.lang.Long" -> "Long"
"java.lang.Character" -> "Char"
"java.lang.Float" -> "Float"
"java.lang.Double" -> "Double"
"java.io.File" -> "String"
else ->
if (EnumeratedAttribute::class.java.isAssignableFrom(type) || type.isEnum)
type.simpleName
else
"String"
}
}
private fun init(type: Class<*>, name: String, constructWithProject: Boolean,
useThisDotProject: Boolean, imports: HashSet<String>): String
{
return when (type.name) {
"java.lang.String" -> name
"boolean" -> name
"byte" -> name
"short" -> name
"int" -> name
"long" -> name
"char" -> name
"float" -> name
"double" -> name
"java.lang.Boolean" -> name
"java.lang.Byte" -> name
"java.lang.Short" -> name
"java.lang.Integer" -> name
"java.lang.Long" -> name
"java.lang.Character" -> name
"java.lang.Float" -> name
"java.lang.Double" -> name
"java.io.File" -> "${if (useThisDotProject) "this." else ""}project.resolveFile($name)"
else -> {
if (EnumeratedAttribute::class.java.isAssignableFrom(type)) {
if (type.enclosingClass != null)
imports.add(type.enclosingClass.name)
val simpleType = if (type.name.contains('$'))
type.name.substringAfterLast('.').replace('$', '.')
else
type.name // not a nested enum --> use full qualified name
"$simpleType().apply { this.value = $name.value }"
} else if (type.isEnum) {
"$name.value"
} else {
imports.add(type.name)
val simpleType = type.name.substringAfterLast('.')
if (constructWithProject) "$simpleType(project, $name)" else "$simpleType($name)"
}
}
}
}
private fun hasProject(cls: Class<*>): Boolean {
return ProjectComponent::class.java.isAssignableFrom(cls) ||
cls == ResourceCollection::class.java
}
private fun needsProject(task: Task): Boolean {
return if (hasProject(task.type))
false
else
task.params.any { it.type == File::class.java }
}
| apache-2.0 | f057a86857941c21da7e88e2432f282e | 27.318091 | 133 | 0.652485 | 3.185864 | false | false | false | false |
zametki/zametki | src/main/java/com/github/zametki/db/sql/GroupSql.kt | 1 | 1006 | package com.github.zametki.db.sql
import com.github.mjdbc.Bind
import com.github.mjdbc.BindBean
import com.github.mjdbc.Sql
import com.github.zametki.model.Group
import com.github.zametki.model.GroupId
import com.github.zametki.model.UserId
/**
* Set of 'group' table queries
*/
interface GroupSql {
@Sql("INSERT INTO groups (parent_id, user_id, name) VALUES (:parentId, :userId, :name)")
fun insert(@BindBean group: Group): GroupId
@Sql("SELECT * FROM groups WHERE id = :id")
fun getById(@Bind("id") id: GroupId): Group?
@Sql("SELECT id FROM groups WHERE user_id = :userId ORDER BY name")
fun getByUser(@Bind("userId") userId: UserId): List<GroupId>
@Sql("DELETE FROM groups WHERE id = :id")
fun delete(@Bind("id") id: GroupId)
@Sql("UPDATE groups SET parent_id = :parentId, name = :name WHERE id = :id")
fun update(@BindBean c: Group)
@Sql("SELECT id FROM groups WHERE parent_id = :id")
fun getSubgroups(@Bind("id") id: GroupId): List<GroupId>
}
| apache-2.0 | ae125aded2712269643c903b371665ad | 30.4375 | 92 | 0.686879 | 3.445205 | false | false | false | false |
luoyuan800/NeverEnd | dataModel/src/cn/luo/yuan/maze/model/real/level/OrgerRealLevel.kt | 1 | 3739 | package cn.luo.yuan.maze.model.real.level
/**
* Created by luoyuan on 2017/9/7.
*/
enum class OrgerRealLevel(val point: Int, val level: Int, val display: String) {
Bronze(5, 10, "开魔"), Silver(8, 10, "筑基"), Gold(15, 10, "魔丹"), Platinum(20, 10, "魔婴"), Diamond(30, 10, "化魔"), Adamas(40, 10, "玄魔"), Stars(40, 10, "真魔");
companion object {
fun getLevel(p: Long): String {
var point = p
if (point < Bronze.level * Bronze.point) {
return buildLevelString(Bronze, point)
}
point -= Bronze.level * Bronze.point
if (point < Silver.point * Silver.level) {
return buildLevelString(Silver, point)
}
point -= Bronze.level * Bronze.point + Silver.point * Silver.level
if (point < Gold.point * Gold.level) {
return buildLevelString(Gold, point)
}
point -= Bronze.level * Bronze.point + Silver.point * Silver.level + Gold.point * Gold.level
if (point < Platinum.point * Platinum.level) {
return buildLevelString(Platinum, point)
}
point -= Bronze.level * Bronze.point + Silver.point * Silver.level + Gold.point * Gold.level + Platinum.point * Platinum.level
if (point < Diamond.point * Diamond.level) {
return buildLevelString(Diamond, point)
}
point -= Bronze.level * Bronze.point + Silver.point * Silver.level + Gold.point * Gold.level + Platinum.point * Platinum.level + Diamond.point * Diamond.level
if (point < Adamas.point * Adamas.level) {
return buildLevelString(Adamas, point)
}
point -= Bronze.level * Bronze.point + Silver.point * Silver.level + Gold.point * Gold.level +
Platinum.point * Platinum.level + Diamond.point * Diamond.level + Adamas.point * Adamas.level
return buildLevelString(Stars, point)
}
private fun buildLevelString(level: OrgerRealLevel, point: Long) = "${level.display} + ${point / level.point}"
fun getCurrentLevel(p: Long): OrgerRealLevel {
var point = p
if (point < Bronze.level * Bronze.point) {
return Bronze
}
point -= Bronze.level * Bronze.point
if (point < Silver.point * Silver.level) {
return Silver
}
point -= Bronze.level * Bronze.point + Silver.point * Silver.level
if (point < Gold.point * Gold.level) {
return Gold
}
point -= Bronze.level * Bronze.point + Silver.point * Silver.level + Gold.point * Gold.level
if (point < Platinum.point * Platinum.level) {
return Platinum
}
point -= Bronze.level * Bronze.point + Silver.point * Silver.level + Gold.point * Gold.level + Platinum.point * Platinum.level
if (point < Diamond.point * Diamond.level) {
return Diamond
}
point -= Bronze.level * Bronze.point + Silver.point * Silver.level + Gold.point * Gold.level + Platinum.point * Platinum.level + Diamond.point * Diamond.level
if (point < Adamas.point * Adamas.level) {
return Adamas
}
point -= Bronze.level * Bronze.point + Silver.point * Silver.level + Gold.point * Gold.level +
Platinum.point * Platinum.level + Diamond.point * Diamond.level + Adamas.point * Adamas.level
return Stars
}
fun isLevelUp(cp: Long, pp:Long):Boolean{
return getCurrentLevel(cp)!= getCurrentLevel(pp)
}
}
} | bsd-3-clause | 6d27ab749aef8bececa2a3c2c074b688 | 47.842105 | 170 | 0.564807 | 3.530923 | false | false | false | false |
wireapp/wire-android | app/src/test/kotlin/com/waz/zclient/core/images/AssetKeyTest.kt | 1 | 2733 | package com.waz.zclient.core.images
import com.bumptech.glide.load.Option
import com.bumptech.glide.load.Options
import org.junit.Test
class AssetKeyTest {
@Test
fun `given two instances with same key, width, height and option, when equals is called, returns true`() {
val assetKey1 = AssetKey(KEY, WIDTH, HEIGHT, options)
val assetKey2 = AssetKey(KEY, WIDTH, HEIGHT, options)
assert(assetKey1.equals(assetKey2))
}
@Test
fun `given two instances with at least one property different, when equals is called, returns false`() {
val assetKey1 = AssetKey("otherKey", WIDTH, HEIGHT, options)
val assetKey2 = AssetKey(KEY, WIDTH, HEIGHT, options)
assert(!assetKey1.equals(assetKey2))
val assetKey3 = AssetKey(KEY, 4, HEIGHT, options)
val assetKey4 = AssetKey(KEY, WIDTH, HEIGHT, options)
assert(!assetKey3.equals(assetKey4))
val assetKey5 = AssetKey(KEY, WIDTH, 5, options)
val assetKey6 = AssetKey(KEY, WIDTH, HEIGHT, options)
assert(!assetKey5.equals(assetKey6))
val assetKey7 = AssetKey(KEY, WIDTH, HEIGHT, optionsWithMemory)
val assetKey8 = AssetKey(KEY, WIDTH, HEIGHT, options)
assert(!assetKey7.equals(assetKey8))
}
@Test
fun `given two instances with same key, width, height and option, when hashCode is called, returns true`() {
val assetKey1 = AssetKey(KEY, WIDTH, HEIGHT, options)
val assetKey2 = AssetKey(KEY, WIDTH, HEIGHT, options)
assert(assetKey1.hashCode() == assetKey2.hashCode())
}
@Test
fun `given two instances with at least one property different, when hashCode is called, returns false`() {
val assetKey1 = AssetKey("otherKey", WIDTH, HEIGHT, options)
val assetKey2 = AssetKey(KEY, WIDTH, HEIGHT, options)
assert(assetKey1.hashCode() != assetKey2.hashCode())
val assetKey3 = AssetKey(KEY, 4, HEIGHT, options)
val assetKey4 = AssetKey(KEY, WIDTH, HEIGHT, options)
assert(assetKey3.hashCode() != assetKey4.hashCode())
val assetKey5 = AssetKey(KEY, WIDTH, 5, options)
val assetKey6 = AssetKey(KEY, WIDTH, HEIGHT, options)
assert(assetKey5.hashCode() != assetKey6.hashCode())
val assetKey7 = AssetKey(KEY, WIDTH, HEIGHT, optionsWithMemory)
val assetKey8 = AssetKey(KEY, WIDTH, HEIGHT, options)
assert(assetKey7.hashCode() != assetKey8.hashCode())
}
companion object {
private const val KEY = "key"
private const val WIDTH = 2
private const val HEIGHT = 3
private val options = Options()
private val optionsWithMemory = Options().set(Option.memory("memory"), "memory")
}
}
| gpl-3.0 | 6ed91b8d72d044dfb57700a20e49e57c | 39.191176 | 112 | 0.665203 | 3.843882 | false | true | false | false |
square/leakcanary | shark/src/main/java/shark/OnAnalysisProgressListener.kt | 2 | 1549 | package shark
import java.util.Locale
/**
* Reports progress from the [HeapAnalyzer] as they occur, as [Step] values.
*
* This is a functional interface with which you can create a [OnAnalysisProgressListener] from a lambda.
*/
fun interface OnAnalysisProgressListener {
// These steps are defined in the order in which they occur.
enum class Step {
PARSING_HEAP_DUMP,
EXTRACTING_METADATA,
FINDING_RETAINED_OBJECTS,
FINDING_PATHS_TO_RETAINED_OBJECTS,
FINDING_DOMINATORS,
INSPECTING_OBJECTS,
COMPUTING_NATIVE_RETAINED_SIZE,
COMPUTING_RETAINED_SIZE,
BUILDING_LEAK_TRACES,
REPORTING_HEAP_ANALYSIS;
val humanReadableName: String
init {
val lowercaseName = name.replace("_", " ")
.toLowerCase(Locale.US)
humanReadableName =
lowercaseName.substring(0, 1).toUpperCase(Locale.US) + lowercaseName.substring(1)
}
}
fun onAnalysisProgress(step: Step)
companion object {
/**
* A no-op [OnAnalysisProgressListener]
*/
val NO_OP = OnAnalysisProgressListener {}
/**
* Utility function to create a [OnAnalysisProgressListener] from the passed in [block] lambda
* instead of using the anonymous `object : OnAnalysisProgressListener` syntax.
*
* Usage:
*
* ```kotlin
* val listener = OnAnalysisProgressListener {
*
* }
* ```
*/
inline operator fun invoke(crossinline block: (Step) -> Unit): OnAnalysisProgressListener =
OnAnalysisProgressListener { step -> block(step) }
}
}
| apache-2.0 | 759e6b0a53cf25c35597aad005699454 | 25.254237 | 105 | 0.673338 | 4.163978 | false | false | false | false |
google/horologist | auth-data/src/main/java/com/google/android/horologist/auth/data/oauth/devicegrant/impl/google/AuthDeviceGrantTokenRepositoryGoogleImpl.kt | 1 | 3944 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.horologist.auth.data.oauth.devicegrant.impl.google
import android.app.Application
import android.content.Intent
import android.net.Uri
import android.util.Log
import androidx.wear.remote.interactions.RemoteActivityHelper
import com.google.android.horologist.auth.data.ExperimentalHorologistAuthDataApi
import com.google.android.horologist.auth.data.oauth.common.impl.google.api.DeviceCodeResponse
import com.google.android.horologist.auth.data.oauth.common.impl.google.api.GoogleOAuthService
import com.google.android.horologist.auth.data.oauth.common.impl.google.api.GoogleOAuthService.Companion.GRANT_TYPE_PARAM_AUTH_DEVICE_GRANT_VALUE
import com.google.android.horologist.auth.data.oauth.devicegrant.AuthDeviceGrantTokenRepository
import com.google.android.horologist.auth.data.oauth.devicegrant.impl.AuthDeviceGrantDefaultConfig
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.delay
@ExperimentalHorologistAuthDataApi
public class AuthDeviceGrantTokenRepositoryGoogleImpl(
private val application: Application,
private val googleOAuthService: GoogleOAuthService
) : AuthDeviceGrantTokenRepository<AuthDeviceGrantDefaultConfig, DeviceCodeResponse, String> {
override suspend fun fetch(
config: AuthDeviceGrantDefaultConfig,
verificationInfoPayload: DeviceCodeResponse
): Result<String> {
RemoteActivityHelper(application).startRemoteActivity(
Intent(Intent.ACTION_VIEW).apply {
addCategory(Intent.CATEGORY_BROWSABLE)
data = Uri.parse(verificationInfoPayload.verificationUri)
},
null
)
return Result.success(
retrieveToken(
config,
verificationInfoPayload.deviceCode,
verificationInfoPayload.interval
)
)
}
/**
* Poll the Auth server for the token. This will only return when the user has finished their
* authorization flow on the paired device.
*
* For this sample the various exceptions aren't handled.
*/
private tailrec suspend fun retrieveToken(
config: AuthDeviceGrantDefaultConfig,
deviceCode: String,
interval: Int
): String {
Log.d(TAG, "Polling for token...")
return fetchToken(config, deviceCode).getOrElse {
Log.d(TAG, "No token yet. Waiting...")
delay(interval * 1000L)
return retrieveToken(config, deviceCode, interval)
}
}
private suspend fun fetchToken(
config: AuthDeviceGrantDefaultConfig,
deviceCode: String
): Result<String> {
return try {
val tokenResponse = googleOAuthService.token(
clientId = config.clientId,
clientSecret = config.clientSecret,
grantType = GRANT_TYPE_PARAM_AUTH_DEVICE_GRANT_VALUE,
deviceCode = deviceCode
)
Result.success(tokenResponse.accessToken)
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
e.printStackTrace()
Result.failure(e)
}
}
private companion object {
private val TAG = AuthDeviceGrantTokenRepositoryGoogleImpl::class.java.simpleName
}
}
| apache-2.0 | 647f82498ea0b1b6a119197da9849774 | 37.291262 | 145 | 0.701318 | 4.740385 | false | true | false | false |
fython/PackageTracker | mobile/src/main/kotlin/info/papdt/express/helper/ui/items/HomeListHeaderViewBinder.kt | 1 | 3224 | package info.papdt.express.helper.ui.items
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import info.papdt.express.helper.R
import info.papdt.express.helper.model.HomeListHeaderViewModel
import info.papdt.express.helper.ui.adapter.ItemViewHolder
import me.drakeet.multitype.ItemViewBinder
import moe.feng.kotlinyan.common.makeGone
import moe.feng.kotlinyan.common.makeVisible
import java.text.DateFormat
import java.util.*
object HomeListHeaderViewBinder
: ItemViewBinder<HomeListHeaderViewModel, HomeListHeaderViewBinder.ViewHolder>() {
override fun onCreateViewHolder(inflater: LayoutInflater, parent: ViewGroup): ViewHolder {
return ViewHolder(inflater.inflate(R.layout.home_list_header_layout, parent, false))
}
override fun onBindViewHolder(holder: ViewHolder, item: HomeListHeaderViewModel) {
holder.bind(item)
}
class ViewHolder(itemView: View) : ItemViewHolder<HomeListHeaderViewModel>(itemView) {
private val lastUpdateTime: TextView = itemView.findViewById(R.id.last_update_time_text)
private val filterKeywordText: TextView = itemView.findViewById(R.id.filter_keyword_text)
private val filterCompanyText: TextView = itemView.findViewById(R.id.filter_company_text)
private val filterCategoryText: TextView = itemView.findViewById(R.id.filter_category_text)
private val filterKeywordLayout: View = itemView.findViewById(R.id.filter_keyword_layout)
private val filterCompanyLayout: View = itemView.findViewById(R.id.filter_company_layout)
private val filterCategoryLayout: View = itemView.findViewById(R.id.filter_category_layout)
override fun onBind(item: HomeListHeaderViewModel) {
if (item.lastUpdateTime <= 0L) {
lastUpdateTime.setText(R.string.last_update_time_text_unknown)
} else {
lastUpdateTime.text = context.getString(
R.string.last_update_time_text_format,
DateFormat.getDateTimeInstance().format(Date(item.lastUpdateTime))
)
}
if (item.filterKeyword == null) {
filterKeywordLayout.makeGone()
} else {
filterKeywordLayout.makeVisible()
filterKeywordText.text = context.getString(
R.string.filter_keyword_text_format,
item.filterKeyword
)
}
if (item.filterCompanyName == null) {
filterCompanyLayout.makeGone()
} else {
filterCompanyLayout.makeVisible()
filterCompanyText.text = context.getString(
R.string.filter_company_text_format,
item.filterCompanyName
)
}
if (item.filterCategory.isNullOrEmpty()) {
filterCategoryLayout.makeGone()
} else {
filterCategoryLayout.makeVisible()
filterCategoryText.text = context.getString(R.string.filter_category_text_format, item.filterCategory)
}
}
}
} | gpl-3.0 | 6a7c86ac055eaa73fdd1e4bc166eb979 | 40.883117 | 118 | 0.66036 | 4.762186 | false | false | false | false |
jdinkla/groovy-java-ray-tracer | src/main/kotlin/net/dinkla/raytracer/cameras/IterativePinhole.kt | 1 | 3039 | /*
package net.dinkla.raytracer.cameras;
import net.dinkla.raytracer.colors.Color;
import net.dinkla.raytracer.colors.RGBColor;
import net.dinkla.raytracer.ViewPlane;
import net.dinkla.raytracer.films.IFilm;
import net.dinkla.raytracer.tracers.Tracer;
import net.dinkla.raytracer.utilities.Timer;
*/
/**
* Created by IntelliJ IDEA.
* User: Jörn Dinkla
* Date: 14.04.2010
* Time: 16:44:12
* To change this template use File | Settings | File Templates.
*//*
public class IterativePinhole extends Pinhole {
// static final Logger LOGGER = Logger.getLogger(Pinhole.class);
// int STEP_Y = 1;
// int STEP_X = 1;
// public double direction;
// public double zoom;
public IterativePinhole(ViewPlane viewPlane, Tracer tracer) {
super(viewPlane, tracer);
// this.direction = direction;
// this.zoom = zoom;
//viewPlane.size /= zoom;
}
@Override
public void render(IFilm film, final int frame) {
Timer t = new Timer();
t.reset();
int direction = 1024; // works fine
int s = 0;
while (direction > 0) {
int k = (int) Math.pow(2, s-1) - 1;
// System.out.println("direction=" + direction +", s=" + s + ", k=" + k);
for (int r = 0; r < viewPlane.resolution.vres; r++) {
if (-1 == k) {
int offset=0;
while (offset < viewPlane.resolution.hres) {
Color color = render(r, offset);
film.setBlock(0, offset, r, Math.min(direction, viewPlane.resolution.hres - 1 - offset), 1, color);
offset += direction;
}
// film.setBlock(0, 0, r, Math.min(direction, 32), 1, color);
} else {
int i=0;
int offset=direction;
while (offset < viewPlane.resolution.hres) {
Color color = render(r, offset);
film.setBlock(0, offset, r, Math.min(direction, viewPlane.resolution.hres - 1 - offset), 1, color);
// film.setBlock(0, offset, r, Math.min(direction, 16), 1, color);
i++;
offset = 2*direction*i+direction;
}
}
}
direction /= 2;
s++;
}
LOGGER.info("rendering took " + t.get() + " ms");
}
*/
/*
8 Punkte
0 8 0
1 4 4 8*i+4 i=0
2 2 2 6 4*i+2 i=0..1
3 1 1 3 5 7 2*i+1, i=0..3
16 Punkte
0 1 2 3 4 5 6 7 8 9 A B C D E F
0 16 0 32*i+16 i=-1
1 8 8 16*i+8 i=0
2 4 4 C 8*i+4 i=0..1 2^1-1
3 2 2 6 A E 4*i+2 i=0..3 2^2-1
4 1 1 3 5 7 9 B D F 2*i+1, i=0..7 2^3-1
*//*
}
*/
| apache-2.0 | 3361b5fac3abfdd3fe0c01e909f52287 | 30.645833 | 123 | 0.466096 | 3.561547 | false | false | false | false |
hotshotmentors/Yengg-App-Android | app/src/main/java/in/yeng/user/joinwithus/children/CrazyAmigosFragment.kt | 2 | 1927 | package `in`.yeng.user.joinwithus.children
import `in`.yeng.user.R
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
class CrazyAmigosFragment : Fragment() {
companion object {
val TAG: String = this::class.java.simpleName
}
private var _context: Context? = null
override fun onAttach(context: Context?) {
super.onAttach(context)
_context = context
}
override fun onDetach() {
super.onDetach()
_context = null
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
inflater.inflate(R.layout.join_crazy_amigos_fragment, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val email = view.findViewById<ImageView>(R.id.email_icon)
val call = view.findViewById<ImageView>(R.id.call_icon)
val joinTelegram = view.findViewById<View>(R.id.join_telegram)
email.setOnClickListener {
val intent = Intent(Intent.ACTION_SENDTO, Uri.fromParts(
"mailto", resources.getString(R.string.crazy_amigos_contact_email), null))
startActivity(Intent.createChooser(intent, "Send email..."))
}
call.setOnClickListener {
val intent = Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", resources.getString(R.string.crazy_amigos_contact_call), null))
startActivity(intent)
}
joinTelegram.setOnClickListener {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://t.me/pingfoundation"))
startActivity(intent)
}
}
} | gpl-3.0 | f6f0afacdebfb17f6d9277247d75c287 | 31.677966 | 136 | 0.679294 | 4.263274 | false | false | false | false |
exteso/alf.io-PI | backend/src/main/kotlin/alfio/pi/repository/ScanRepository.kt | 1 | 3249 | /*
* This file is part of alf.io.
*
* alf.io 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.
*
* alf.io 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 alf.io. If not, see <http://www.gnu.org/licenses/>.
*/
package alfio.pi.repository
import alfio.pi.model.Printer
import alfio.pi.model.UserAndPrinter
import alfio.pi.model.UserPrinter
import ch.digitalfondue.npjt.AffectedRowCountAndKey
import ch.digitalfondue.npjt.Bind
import ch.digitalfondue.npjt.Query
import ch.digitalfondue.npjt.QueryRepository
import java.util.*
@QueryRepository
interface PrinterRepository {
@Query("select * from printer")
fun loadAll(): List<Printer>
@Query("insert into printer(name, description, active) values(:name, :description, :active)")
fun insert(@Bind("name") name: String, @Bind("description") description: String?, @Bind("active") active: Boolean): AffectedRowCountAndKey<Int>
@Query("select printer.id as id, printer.name as name, printer.description as description from printer, user_printer where user_printer.user_id_fk = :userId and user_printer.printer_id_fk = printer.id")
fun findByUserId(@Bind("userId") userId: Int): Optional<Printer>
@Query("select * from printer where id = :id")
fun findById(@Bind("id") printerId: Int): Printer
@Query("select * from printer where id = :id")
fun findOptionalById(@Bind("id") printerId: Int): Optional<Printer>
@Query("update printer set active = :state where id = :id")
fun toggleActivation(@Bind("id") id: Int, @Bind("state") state: Boolean): Int
}
@QueryRepository
interface UserPrinterRepository {
@Query("insert into user_printer(user_id_fk, printer_id_fk) values(:userId, :printerId)")
fun insert(@Bind("userId") userId: Int, @Bind("printerId") printerId: Int): Int
@Query("update user_printer set printer_id_fk = :printerId where user_id_fk = :userId")
fun update(@Bind("userId") userId: Int, @Bind("printerId") printerId: Int): Int
@Query("delete from user_printer where user_id_fk = :userId")
fun delete(@Bind("userId") userId: Int): Int
@Query("select * from user_printer a, printer b where a.user_id_fk = :userId and a.printer_id_fk = b.id and b.active = true")
fun getOptionalActivePrinter(@Bind("userId") userId: Int): Optional<UserPrinter>
@Query("select * from user_printer a, printer b where a.user_id_fk = :userId and a.printer_id_fk = b.id")
fun getOptionalUserPrinter(@Bind("userId") userId: Int): Optional<UserPrinter>
@Query("select u.username as username, u.id as user_id, p.id as printer_id, p.name as printer_name, p.description as printer_description, p.active as printer_active from user u, printer p, user_printer up where up.user_id_fk = u.id and up.printer_id_fk = p.id")
fun loadAll(): List<UserAndPrinter>
} | gpl-3.0 | b329f9585af1b35a4d04cbf2da671d5a | 44.774648 | 265 | 0.721761 | 3.654668 | false | false | false | false |
spinnaker/front50 | front50-sql/src/main/kotlin/com/netflix/spinnaker/config/CompositeStorageServiceConfiguration.kt | 2 | 3393 | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.config
import com.netflix.spectator.api.Registry
import com.netflix.spinnaker.front50.migrations.StorageServiceMigrator
import com.netflix.spinnaker.front50.model.CompositeStorageService
import com.netflix.spinnaker.front50.model.StorageService
import com.netflix.spinnaker.front50.model.tag.EntityTagsDAO
import com.netflix.spinnaker.kork.dynamicconfig.DynamicConfigService
import com.netflix.spinnaker.kork.web.context.RequestContextProvider
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.ApplicationContext
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Primary
@Configuration
@EnableConfigurationProperties(StorageServiceMigratorConfigurationProperties::class)
class CompositeStorageServiceConfiguration(
private val storageServices: List<StorageService>,
private val applicationContext: ApplicationContext,
private val properties: StorageServiceMigratorConfigurationProperties,
private val dynamicConfigService: DynamicConfigService,
private val registry: Registry
) {
@Bean
@Primary
@ConditionalOnProperty("spinnaker.migration.compositeStorageService.enabled")
fun compositeStorageService() =
CompositeStorageService(
dynamicConfigService,
registry,
findStorageService(properties.primaryClass, properties.primaryName),
findStorageService(properties.previousClass, properties.previousName)
)
@Bean
@ConditionalOnProperty("spinnaker.migration.compositeStorageService.enabled")
fun storageServiceMigrator(
entityTagsDAO: EntityTagsDAO,
contextProvider: RequestContextProvider
) =
StorageServiceMigrator(
dynamicConfigService,
registry,
findStorageService(properties.primaryClass, properties.primaryName),
findStorageService(properties.previousClass, properties.previousName),
entityTagsDAO,
contextProvider
)
private fun findStorageService(
className: String?,
beanName: String?
): StorageService {
return if (className != null && className.isNotBlank()) {
storageServices.first { it.javaClass.canonicalName == className }
} else {
applicationContext.getBean(beanName) as StorageService
}
}
}
@ConfigurationProperties("spinnaker.migration")
data class StorageServiceMigratorConfigurationProperties(
var primaryClass: String? = null,
var previousClass: String? = null,
var primaryName: String? = null,
var previousName: String? = null,
var writeOnly: Boolean = false
)
| apache-2.0 | d2811df2370596549119ff48b56384b8 | 37.556818 | 84 | 0.798703 | 4.931686 | false | true | false | false |
kibotu/RecyclerViewPresenter | lib/src/main/java/net/kibotu/android/recyclerviewpresenter/CircularDataSource.kt | 1 | 3089 | package net.kibotu.android.recyclerviewpresenter
import androidx.lifecycle.MutableLiveData
import androidx.paging.DataSource
import androidx.paging.PageKeyedDataSource
import net.kibotu.android.recyclerviewpresenter.cirkle.circular
import java.util.*
class CircularDataSource<T>(private val data: List<PresenterViewModel<T>>, val generateUuid: Boolean = true) : PageKeyedDataSource<Int, PresenterViewModel<T>>() {
override fun loadInitial(params: LoadInitialParams<Int>, callback: LoadInitialCallback<Int, PresenterViewModel<T>>) {
val fromIndex = 0
val toIndex = (fromIndex + params.requestedLoadSize - 1)
val previousKey = fromIndex - 1
val nextKey = toIndex + 1
val list = data.circular().subList(fromIndex, toIndex + 1)
setNewUuid(list, fromIndex, toIndex)
log("[loadInitial] data=${data.size} result=${list.size} from=$fromIndex toIndex=$toIndex previousKey=$previousKey nextKey=$nextKey requestedLoadSize=${params.requestedLoadSize} placeholdersEnabled=${params.placeholdersEnabled} result=${list.map { it.model }}")
callback.onResult(list, previousKey, nextKey)
}
override fun loadAfter(params: LoadParams<Int>, callback: LoadCallback<Int, PresenterViewModel<T>>) {
val fromIndex = params.key
val toIndex = (fromIndex + params.requestedLoadSize - 1)
val nextKey = toIndex + 1
val list = data.circular().subList(fromIndex, toIndex + 1)
setNewUuid(list, fromIndex, toIndex)
log("[loadAfter] result=${list.size} from=$fromIndex toIndex=$toIndex nextKey=$nextKey requestedLoadSize=${params.requestedLoadSize} result=${list.map { it.model }}")
callback.onResult(list, nextKey)
}
override fun loadBefore(params: LoadParams<Int>, callback: LoadCallback<Int, PresenterViewModel<T>>) {
val fromIndex = params.key
val toIndex = (fromIndex - params.requestedLoadSize - 1)
val previousKey = fromIndex - 1
val list = data.circular().subList(fromIndex, toIndex + 1).reversed()
setNewUuid(list, fromIndex, toIndex)
log("[loadBefore] result=${list.size} from=$fromIndex toIndex=$toIndex previousKey=$previousKey requestedLoadSize=${params.requestedLoadSize} result=${list.map { it.model }}")
callback.onResult(list, previousKey)
}
private fun setNewUuid(list: List<PresenterViewModel<T>>, fromIndex: Int, toIndex: Int) {
if (!generateUuid)
return
list.forEachIndexed { index, item ->
item.uuid = UUID.randomUUID().toString() // (fromIndex - toIndex + index).toString()
}
}
class Factory<T>(var data: List<PresenterViewModel<T>>, val generateUuid: Boolean = true) : DataSource.Factory<Int, PresenterViewModel<T>>() {
private val dataSource by lazy { MutableLiveData<CircularDataSource<T>>() }
override fun create() = CircularDataSource(data, generateUuid).also {
dataSource.postValue(it)
}
fun invalidate() {
dataSource.value?.invalidate()
}
}
} | apache-2.0 | 3e1419b07bf1b6168b453b7e284dcdfe | 38.615385 | 269 | 0.688896 | 4.75963 | false | false | false | false |
team401/2017-Robot-Code | src/main/java/org/team401/lib/LoopManager.kt | 1 | 1246 | package org.team401.lib
import edu.wpi.first.wpilibj.Notifier
import org.team401.lib.CrashTracker
import org.team401.robot.Constants
import java.util.ArrayList
class LoopManager(val period: Double = Constants.LOOP_PERIOD) {
private var running = false
private val notifier: Notifier
private val loops: MutableList<Loop> = ArrayList()
init {
notifier = Notifier {
if (running) {
loops.forEach {
try {
it.onLoop()
} catch (t: Throwable) {
CrashTracker.logThrowableCrash(t)
println("Error in loop: $t")
}
}
}
}
}
@Synchronized
fun register(loop: Loop) {
loops.add(loop)
}
@Synchronized
fun start() {
if (!running) {
println("Starting periodic loops")
loops.forEach {
try {
it.onStart()
} catch (t: Throwable) {
CrashTracker.logThrowableCrash(t)
println("Error starting loop: $it")
}
}
notifier.startPeriodic(period)
running = true
}
}
@Synchronized
fun stop() {
if (running) {
println("Stopping periodic loops")
notifier.stop()
loops.forEach {
try {
it.onStop()
} catch (t: Throwable) {
CrashTracker.logThrowableCrash(t)
println("Error stopping loop: $it")
}
}
running = false
}
}
} | gpl-3.0 | dce08789a318017aad98606eca151990 | 17.338235 | 63 | 0.638844 | 3.130653 | false | false | false | false |
uber/RIBs | android/libraries/rib-base/src/main/kotlin/com/uber/rib/core/Interactor.kt | 1 | 5541 | /*
* Copyright (C) 2017. Uber Technologies
*
* 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.uber.rib.core
import androidx.annotation.CallSuper
import androidx.annotation.VisibleForTesting
import com.jakewharton.rxrelay2.BehaviorRelay
import com.uber.autodispose.lifecycle.CorrespondingEventsFunction
import com.uber.autodispose.lifecycle.LifecycleEndedException
import com.uber.autodispose.lifecycle.LifecycleScopeProvider
import com.uber.autodispose.lifecycle.LifecycleScopes
import com.uber.rib.core.lifecycle.InteractorEvent
import io.reactivex.CompletableSource
import io.reactivex.Observable
import javax.inject.Inject
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
/**
* The base implementation for all [Interactor]s.
*
* @param <P> the type of [Presenter].
* @param <R> the type of [Router].
*/
abstract class Interactor<P : Any, R : Router<*>> : LifecycleScopeProvider<InteractorEvent>, InteractorType {
@Inject
lateinit var injectedPresenter: P
internal var actualPresenter: P? = null
private val behaviorRelay = BehaviorRelay.create<InteractorEvent>()
private val lifecycleRelay = behaviorRelay.toSerialized()
private val routerDelegate = InitOnceProperty<R>()
/** @return the router for this interactor. */
open var router: R by routerDelegate
protected set
constructor()
protected constructor(presenter: P) {
this.actualPresenter = presenter
}
/** @return an observable of this controller's lifecycle events. */
override fun lifecycle(): Observable<InteractorEvent> {
return lifecycleRelay.hide()
}
/** @return true if the controller is attached, false if not. */
override fun isAttached() = behaviorRelay.value === InteractorEvent.ACTIVE
/**
* Called when attached. The presenter will automatically be added when this happens.
*
* @param savedInstanceState the saved [Bundle].
*/
@CallSuper
protected open fun didBecomeActive(savedInstanceState: Bundle?) {
}
/**
* Handle an activity back press.
*
* @return whether this interactor took action in response to a back press.
*/
open override fun handleBackPress(): Boolean {
return false
}
/**
* Called when detached. The [Interactor] should do its cleanup here. Note: View will be
* removed automatically so [Interactor] doesn't have to remove its view here.
*/
protected open fun willResignActive() {}
internal fun onSaveInstanceStateInternal(outState: Bundle) {
onSaveInstanceState(outState)
}
/**
* Called when saving state.
*
* @param outState the saved [Bundle].
*/
protected open fun onSaveInstanceState(outState: Bundle) {}
public open fun dispatchAttach(savedInstanceState: Bundle?) {
lifecycleRelay.accept(InteractorEvent.ACTIVE)
(getPresenter() as? Presenter)?.dispatchLoad()
didBecomeActive(savedInstanceState)
}
public open fun dispatchDetach(): P {
(getPresenter() as? Presenter)?.dispatchUnload()
willResignActive()
lifecycleRelay.accept(InteractorEvent.INACTIVE)
return getPresenter()
}
internal fun setRouterInternal(router: Router<*>) {
if (routerDelegate != null) {
this.router = router as R
}
}
/** @return the currently attached presenter if there is one */
@VisibleForTesting
private fun getPresenter(): P {
val presenter: P? = try {
if (actualPresenter != null)
actualPresenter
else
injectedPresenter
} catch (e: UninitializedPropertyAccessException) {
actualPresenter
}
checkNotNull(presenter) { "Attempting to get interactor's presenter before being set." }
return presenter
}
@VisibleForTesting
internal fun setPresenter(presenter: P) {
actualPresenter = presenter
}
override fun correspondingEvents(): CorrespondingEventsFunction<InteractorEvent> {
return LIFECYCLE_MAP_FUNCTION
}
override fun peekLifecycle(): InteractorEvent? {
return behaviorRelay.value
}
final override fun requestScope(): CompletableSource {
return LifecycleScopes.resolveScopeFromLifecycle(this)
}
private inner class InitOnceProperty<T> : ReadWriteProperty<Any, T> {
private var backingField: T? = null
override fun getValue(thisRef: Any, property: KProperty<*>): T {
if (backingField == null) {
throw IllegalStateException("Attempting to get value before it has been set.")
}
return backingField as T
}
override fun setValue(thisRef: Any, property: KProperty<*>, value: T) {
if (backingField != null) {
throw IllegalStateException("Attempting to set value after it has been set.")
} else {
backingField = value
}
}
}
companion object {
private val LIFECYCLE_MAP_FUNCTION = CorrespondingEventsFunction { interactorEvent: InteractorEvent ->
when (interactorEvent) {
InteractorEvent.ACTIVE -> return@CorrespondingEventsFunction InteractorEvent.INACTIVE
else -> throw LifecycleEndedException()
}
}
}
}
| apache-2.0 | 671f702128054f217045dcb21eb990d2 | 30.305085 | 109 | 0.723877 | 4.668071 | false | false | false | false |
requery/requery | requery-android/example-kotlin/src/main/kotlin/io/requery/android/example/app/CreatePeople.kt | 1 | 2107 | package io.requery.android.example.app
import io.reactivex.Observable
import io.requery.Persistable
import io.requery.android.example.app.model.AddressEntity
import io.requery.android.example.app.model.Person
import io.requery.android.example.app.model.PersonEntity
import io.requery.reactivex.KotlinReactiveEntityStore
import java.util.*
import java.util.concurrent.Callable
class CreatePeople(val data: KotlinReactiveEntityStore<Persistable>) : Callable<Observable<Iterable<Person>>> {
override fun call(): Observable<Iterable<Person>> {
val firstNames = arrayOf("Alice", "Bob", "Carol", "Chloe", "Dan", "Emily", "Emma", "Eric",
"Eva", "Frank", "Gary", "Helen", "Jack", "James", "Jane", "Kevin", "Laura", "Leon",
"Lilly", "Mary", "Maria", "Mia", "Nick", "Oliver", "Olivia", "Patrick", "Robert",
"Stan", "Vivian", "Wesley", "Zoe")
val lastNames = arrayOf("Hall", "Hill", "Smith", "Lee", "Jones", "Taylor", "Williams",
"Jackson", "Stone", "Brown", "Thomas", "Clark", "Lewis", "Miller", "Walker", "Fox",
"Robinson", "Wilson", "Cook", "Carter", "Cooper", "Martin")
val random = Random()
val people = TreeSet(Comparator<Person> { lhs, rhs -> lhs.name.compareTo(rhs.name) })
// creating many people (but only with unique names)
for (i in 0..2999) {
val person = PersonEntity()
val first = firstNames[random.nextInt(firstNames.size)]
val last = lastNames[random.nextInt(lastNames.size)]
person.name = first + " " + last
person.uuid = UUID.randomUUID()
person.email = Character.toLowerCase(first[0]) + last.toLowerCase() + "@gmail.com"
val address = AddressEntity()
address.line1 = "123 Market St"
address.zip = "94105"
address.city = "San Francisco"
address.state = "CA"
address.country = "US"
person.address = address
people.add(person)
}
return data.insert(people).toObservable()
}
}
| apache-2.0 | 9d57c20e63d41069ea5266b84dc6c965 | 44.804348 | 111 | 0.6056 | 3.696491 | false | false | false | false |
square/duktape-android | zipline/src/commonMain/kotlin/app/cash/zipline/internal/bridge/Endpoint.kt | 1 | 5285 | /*
* Copyright (C) 2021 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 app.cash.zipline.internal.bridge
import app.cash.zipline.EventListener
import app.cash.zipline.ZiplineService
import app.cash.zipline.internal.passByReferencePrefix
import app.cash.zipline.ziplineServiceSerializer
import kotlin.coroutines.Continuation
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.serialization.json.Json
import kotlinx.serialization.modules.SerializersModule
/**
* An outbound channel for delivering calls to the other platform, and an inbound channel for
* receiving calls from the other platform.
*/
class Endpoint internal constructor(
internal val scope: CoroutineScope,
internal val userSerializersModule: SerializersModule,
internal val eventListener: EventListener,
internal val outboundChannel: CallChannel,
) {
internal val inboundServices = mutableMapOf<String, InboundService<*>>()
private var nextId = 1
internal val incompleteContinuations = mutableSetOf<Continuation<*>>()
val serviceNames: Set<String>
get() = inboundServices.keys.toSet()
val clientNames: Set<String>
get() = outboundChannel.serviceNamesArray().toSet()
/** This uses both Zipline-provided serializers and user-provided serializers. */
internal val json: Json = Json {
useArrayPolymorphism = true
// For backwards-compatibility, allow new fields to be introduced.
ignoreUnknownKeys = true
// Because host and JS may disagree on default values, it's best to encode them.
encodeDefaults = true
// Support map keys whose values are arrays or objects.
allowStructuredMapKeys = true
serializersModule = SerializersModule {
contextual(PassByReference::class, PassByReferenceSerializer(this@Endpoint))
contextual(Throwable::class, ThrowableSerializer)
contextual(Flow::class) { serializers ->
FlowSerializer(
ziplineServiceSerializer<FlowZiplineService<Any?>>(
FlowZiplineService::class,
serializers
)
)
}
include(userSerializersModule)
}
}
internal val callCodec = CallCodec(this)
internal val inboundChannel = object : CallChannel {
override fun serviceNamesArray(): Array<String> {
return serviceNames.toTypedArray()
}
override fun call(callJson: String): String {
val internalCall = callCodec.decodeCall(callJson)
val inboundService = internalCall.inboundService!!
val externalCall = callCodec.lastInboundCall!!
return when {
internalCall.suspendCallback != null -> inboundService.callSuspending(
internalCall,
externalCall,
internalCall.suspendCallback
)
else -> inboundService.call(
internalCall,
externalCall
)
}
}
override fun disconnect(instanceName: String): Boolean {
return inboundServices.remove(instanceName) != null
}
}
@Suppress("UNUSED_PARAMETER") // Parameters are used by the compiler plug-in.
fun <T : ZiplineService> bind(name: String, instance: T) {
error("unexpected call to Endpoint.bind: is the Zipline plugin configured?")
}
@PublishedApi
internal fun <T : ZiplineService> bind(
name: String,
service: T,
adapter: ZiplineServiceAdapter<T>
) {
eventListener.bindService(name, service)
val functions = adapter.ziplineFunctions(json.serializersModule)
inboundServices[name] = InboundService(service, this, functions)
}
@Suppress("UNUSED_PARAMETER") // Parameter is used by the compiler plug-in.
fun <T : ZiplineService> take(name: String): T {
error("unexpected call to Endpoint.take: is the Zipline plugin configured?")
}
@PublishedApi
internal fun <T : ZiplineService> take(name: String, adapter: ZiplineServiceAdapter<T>): T {
// Detect leaked old services when creating new services.
detectLeaks()
val functions = adapter.ziplineFunctions(json.serializersModule)
val callHandler = OutboundCallHandler(name, this, functions)
val result = adapter.outboundService(callHandler)
eventListener.takeService(name, result)
trackLeaks(eventListener, name, callHandler, result)
return result
}
@PublishedApi
internal fun remove(name: String): InboundService<*>? {
return inboundServices.remove(name)
}
@PublishedApi
internal fun remove(service: ZiplineService) {
val i = inboundServices.values.iterator()
while (i.hasNext()) {
val inboundService = i.next()
if (inboundService.service === service) {
i.remove()
return
}
}
}
internal fun generatePassByReferenceName(): String {
return "$passByReferencePrefix${nextId++}"
}
}
| apache-2.0 | a4d6ae15ffc55d7be5e74d7e3fd59b9f | 31.623457 | 94 | 0.717313 | 4.648197 | false | false | false | false |
Yubyf/QuoteLock | app/src/main/java/com/crossbowffs/quotelock/components/ContextMenuRecyclerView.kt | 1 | 1110 | package com.crossbowffs.quotelock.components
import android.content.Context
import android.util.AttributeSet
import android.view.ContextMenu
import android.view.View
import androidx.recyclerview.widget.RecyclerView
/**
* @author Yubyf
*/
class ContextMenuRecyclerView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0,
) : RecyclerView(context, attrs, defStyleAttr) {
private var contextMenuInfo: ContextMenuInfo? = null
override fun getContextMenuInfo(): ContextMenu.ContextMenuInfo? {
return contextMenuInfo
}
override fun showContextMenuForChild(originalView: View?): Boolean {
if (originalView == null) {
return false
}
val position = getChildAdapterPosition(originalView)
if (position < 0) {
return false
}
contextMenuInfo = ContextMenuInfo(position, adapter?.getItemId(position) ?: -1)
return super.showContextMenuForChild(originalView)
}
class ContextMenuInfo(var position: Int, var id: Long) : ContextMenu.ContextMenuInfo
} | mit | b6b7c2aebb3fc2e141e0986f37dff999 | 28.236842 | 88 | 0.711712 | 4.805195 | false | false | false | false |
openhab/openhab.android | mobile/src/main/java/org/openhab/habdroid/ui/AbstractBaseActivity.kt | 1 | 14080 | /*
* Copyright (c) 2010-2022 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.habdroid.ui
import android.Manifest
import android.app.ActivityManager
import android.app.KeyguardManager
import android.content.Intent
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.graphics.BitmapFactory
import android.os.Build
import android.os.Bundle
import android.os.SystemClock
import android.provider.Settings
import android.util.Log
import android.view.View
import androidx.annotation.CallSuper
import androidx.annotation.ColorInt
import androidx.annotation.StringRes
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.biometric.BiometricManager
import androidx.biometric.BiometricPrompt
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.view.isInvisible
import com.google.android.material.snackbar.BaseTransientBottomBar
import com.google.android.material.snackbar.Snackbar
import kotlin.coroutines.CoroutineContext
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.asExecutor
import org.openhab.habdroid.BuildConfig
import org.openhab.habdroid.R
import org.openhab.habdroid.util.PrefKeys
import org.openhab.habdroid.util.ScreenLockMode
import org.openhab.habdroid.util.getActivityThemeId
import org.openhab.habdroid.util.getPrefs
import org.openhab.habdroid.util.getScreenLockMode
import org.openhab.habdroid.util.hasPermissions
import org.openhab.habdroid.util.resolveThemedColor
abstract class AbstractBaseActivity : AppCompatActivity(), CoroutineScope {
private val job = Job()
override val coroutineContext: CoroutineContext get() = Dispatchers.Main + job
protected open val forceNonFullscreen = false
private var authPrompt: AuthPrompt? = null
protected var lastSnackbar: Snackbar? = null
private set
private var snackbarQueue = mutableListOf<Snackbar>()
protected val isFullscreenEnabled: Boolean
get() = getPrefs().getBoolean(PrefKeys.FULLSCREEN, false)
@CallSuper
override fun onCreate(savedInstanceState: Bundle?) {
setTheme(getActivityThemeId())
val colorPrimary = resolveThemedColor(R.attr.colorPrimary)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
setTaskDescription(ActivityManager.TaskDescription(
getString(R.string.app_name),
R.mipmap.icon,
colorPrimary))
} else {
@Suppress("DEPRECATION")
setTaskDescription(ActivityManager.TaskDescription(
getString(R.string.app_name),
BitmapFactory.decodeResource(resources, R.mipmap.icon),
colorPrimary))
}
super.onCreate(savedInstanceState)
}
override fun onPostCreate(savedInstanceState: Bundle?) {
super.onPostCreate(savedInstanceState)
setNavigationBarColor()
}
@CallSuper
override fun onStart() {
super.onStart()
promptForDevicePasswordIfRequired()
}
@CallSuper
override fun onDestroy() {
super.onDestroy()
job.cancel()
}
@CallSuper
override fun onResume() {
super.onResume()
setFullscreen()
}
@Suppress("DEPRECATION") // TODO: Replace deprecated function
fun setFullscreen(isEnabled: Boolean = isFullscreenEnabled) {
var uiOptions = window.decorView.systemUiVisibility
val flags = (
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
or View.SYSTEM_UI_FLAG_FULLSCREEN
)
uiOptions = if (isEnabled && !forceNonFullscreen) {
uiOptions or flags
} else {
uiOptions and flags.inv()
}
window.decorView.systemUiVisibility = uiOptions
}
@Suppress("DEPRECATION") // TODO: Replace deprecated function
private fun setNavigationBarColor() {
val currentNightMode = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
@ColorInt val black = ContextCompat.getColor(this, R.color.black)
@ColorInt val windowColor = if (currentNightMode == Configuration.UI_MODE_NIGHT_YES) {
resolveThemedColor(android.R.attr.windowBackground, black)
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
resolveThemedColor(android.R.attr.windowBackground, black)
} else {
black
}
}
window.navigationBarColor = windowColor
val uiOptions = window.decorView.systemUiVisibility
val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR
} else {
0
}
window.decorView.systemUiVisibility = if (currentNightMode == Configuration.UI_MODE_NIGHT_YES) {
uiOptions and flags.inv()
} else {
uiOptions or flags
}
}
internal fun showSnackbar(
tag: String,
@StringRes messageResId: Int,
@BaseTransientBottomBar.Duration duration: Int = Snackbar.LENGTH_LONG,
@StringRes actionResId: Int = 0,
onClickListener: (() -> Unit)? = null
) {
showSnackbar(tag, getString(messageResId), duration, actionResId, onClickListener)
}
protected fun showSnackbar(
tag: String,
message: String,
@BaseTransientBottomBar.Duration duration: Int = Snackbar.LENGTH_LONG,
@StringRes actionResId: Int = 0,
onClickListener: (() -> Unit)? = null
) {
fun showNextSnackbar() {
if (lastSnackbar?.isShown == true || snackbarQueue.isEmpty()) {
Log.d(TAG, "No next snackbar to show")
return
}
val nextSnackbar = snackbarQueue.removeFirstOrNull()
nextSnackbar?.show()
lastSnackbar = nextSnackbar
}
if (tag.isEmpty()) {
throw IllegalArgumentException("Tag is empty")
}
val snackbar = Snackbar.make(findViewById(android.R.id.content), message, duration)
if (actionResId != 0 && onClickListener != null) {
snackbar.setAction(actionResId) { onClickListener() }
}
snackbar.view.tag = tag
snackbar.addCallback(object : BaseTransientBottomBar.BaseCallback<Snackbar>() {
override fun onShown(transientBottomBar: Snackbar?) {
super.onShown(transientBottomBar)
Log.d(TAG, "Show snackbar with tag $tag")
}
override fun onDismissed(transientBottomBar: Snackbar?, event: Int) {
super.onDismissed(transientBottomBar, event)
showNextSnackbar()
}
})
hideSnackbar(tag)
Log.d(TAG, "Queue snackbar with tag $tag")
snackbarQueue.add(snackbar)
showNextSnackbar()
}
protected fun hideSnackbar(tag: String) {
snackbarQueue.firstOrNull { it.view.tag == tag }?.let { snackbar ->
Log.d(TAG, "Remove snackbar with tag $tag from queue")
snackbarQueue.remove(snackbar)
}
if (lastSnackbar?.view?.tag == tag) {
Log.d(TAG, "Hide snackbar with tag $tag")
lastSnackbar?.dismiss()
lastSnackbar = null
}
}
/**
* Requests permissions if not already granted. Makes sure to comply with
* * Google Play Store policy
* * Android R background location permission
*/
fun requestPermissionsIfRequired(permissions: Array<String>?, requestCode: Int) {
var permissionsToRequest = permissions
?.filter { !hasPermissions(arrayOf(it)) }
?.toTypedArray()
if (permissionsToRequest.isNullOrEmpty() || hasPermissions(permissionsToRequest)) {
return
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R &&
permissionsToRequest.contains(Manifest.permission.ACCESS_BACKGROUND_LOCATION)
) {
if (permissionsToRequest.size > 1) {
Log.d(TAG, "Remove background location from permissions to request")
permissionsToRequest = permissionsToRequest.toMutableList().apply {
remove(Manifest.permission.ACCESS_BACKGROUND_LOCATION)
}.toTypedArray()
} else {
showSnackbar(
PreferencesActivity.SNACKBAR_TAG_BG_TASKS_MISSING_PERMISSION_LOCATION,
getString(
R.string.settings_background_tasks_permission_denied_background_location,
packageManager.backgroundPermissionOptionLabel
),
Snackbar.LENGTH_LONG,
android.R.string.ok
) {
Intent(Settings.ACTION_APPLICATION_SETTINGS).apply {
putExtra(Settings.EXTRA_APP_PACKAGE, BuildConfig.APPLICATION_ID)
startActivity(this)
}
}
return
}
}
if (
permissionsToRequest.contains(Manifest.permission.ACCESS_BACKGROUND_LOCATION) ||
permissionsToRequest.contains(Manifest.permission.ACCESS_FINE_LOCATION) ||
permissionsToRequest.contains(Manifest.permission.ACCESS_COARSE_LOCATION)
) {
Log.d(TAG, "Show dialog to inform user about location permissions")
AlertDialog.Builder(this)
.setMessage(R.string.settings_location_permissions_required)
.setPositiveButton(R.string.settings_background_tasks_permission_allow) { _, _ ->
Log.d(TAG, "Request ${permissionsToRequest.contentToString()} permission")
ActivityCompat.requestPermissions(this, permissionsToRequest, requestCode)
}
.setNegativeButton(android.R.string.cancel) { _, _ ->
onRequestPermissionsResult(
requestCode,
permissionsToRequest,
intArrayOf(PackageManager.PERMISSION_DENIED)
)
}
.show()
} else {
Log.d(TAG, "Request ${permissionsToRequest.contentToString()} permission")
ActivityCompat.requestPermissions(this, permissionsToRequest, requestCode)
}
}
private fun promptForDevicePassword() {
val km = getSystemService(KEYGUARD_SERVICE) as KeyguardManager
val locked = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) km.isDeviceSecure else km.isKeyguardSecure
if (locked) {
authPrompt = AuthPrompt()
authPrompt?.authenticate()
}
}
internal open fun doesLockModeRequirePrompt(mode: ScreenLockMode): Boolean {
return mode != ScreenLockMode.Disabled
}
private fun promptForDevicePasswordIfRequired() {
if (authPrompt != null) {
return
}
if (doesLockModeRequirePrompt(getPrefs().getScreenLockMode(this))) {
if (timestampNeedsReauth(lastAuthenticationTimestamp)) {
promptForDevicePassword()
}
} else {
// Reset last authentication timestamp when going from an activity requiring authentication to an
// activity that does not require authentication, so that the prompt will re-appear when going back
// to the activity requiring authentication
lastAuthenticationTimestamp = 0L
}
}
private fun timestampNeedsReauth(ts: Long) =
ts == 0L || SystemClock.elapsedRealtime() - ts > AUTHENTICATION_VALIDITY_PERIOD
private inner class AuthPrompt : BiometricPrompt.AuthenticationCallback() {
private val contentView = findViewById<View>(R.id.activity_content)
private val prompt = BiometricPrompt(this@AbstractBaseActivity, Dispatchers.Main.asExecutor(), this)
fun authenticate() {
val descriptionResId = if (getPrefs().getScreenLockMode(contentView.context) == ScreenLockMode.KioskMode) {
R.string.screen_lock_unlock_preferences_description
} else {
R.string.screen_lock_unlock_screen_description
}
val info = BiometricPrompt.PromptInfo.Builder()
.setTitle(getString(R.string.app_name))
.setDescription(getString(descriptionResId))
.setAllowedAuthenticators(
BiometricManager.Authenticators.BIOMETRIC_STRONG or
BiometricManager.Authenticators.BIOMETRIC_WEAK or
BiometricManager.Authenticators.DEVICE_CREDENTIAL
)
.build()
contentView.isInvisible = true
prompt.authenticate(info)
}
override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
super.onAuthenticationError(errorCode, errString)
finish()
}
override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
super.onAuthenticationSucceeded(result)
lastAuthenticationTimestamp = SystemClock.elapsedRealtime()
contentView.isInvisible = false
authPrompt = null
}
}
companion object {
private val TAG = AbstractBaseActivity::class.java.simpleName
private const val AUTHENTICATION_VALIDITY_PERIOD = 2 * 60 * 1000L
var lastAuthenticationTimestamp = 0L
}
}
| epl-1.0 | 5428f3f142bfde304ec5aa4e2ddee50a | 37.895028 | 119 | 0.640554 | 5.144319 | false | false | false | false |
Retronic/life-in-space | core/src/main/kotlin/com/retronicgames/utils/IntVector2.kt | 1 | 1809 | package com.retronicgames.utils
open class IntVector2(x: Int, y: Int) {
private val callbacks = arrayListOf<(oldX: Int, oldY: Int, newX: Int, newY: Int) -> Unit>()
constructor() : this(Int.MIN_VALUE, Int.MIN_VALUE)
companion object {
val MINUS_ONE = IntVector2(-1, -1)
val ZERO = IntVector2(0, 0)
val ONE = IntVector2(1, 1)
}
protected var _x: Int = x
protected var _y: Int = y
open var x: Int
get() = _x
protected set(value) {
val old = _x
_x = value
fireChange(old, _y)
}
open var y: Int
get() = _y
protected set(value) {
val old = _y
_y = value
fireChange(_x, old)
}
protected fun fireChange(oldX: Int, oldY: Int) {
if (oldX == _x && oldY == _y) return
callbacks.forEach { it(oldX, oldY, _x, _y) }
}
fun onChange(function: (oldX: Int, oldY: Int, newX: Int, newY: Int) -> Unit) {
callbacks.add(function)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is IntVector2) return false
if (x != other.x) return false
if (y != other.y) return false
return true
}
override fun hashCode(): Int {
var result = x
result += 31 * result + y
return result
}
infix operator fun compareTo(other: IntVector2): Int {
return (x + y).compareTo(other.x + other.y)
}
override fun toString(): String {
return "[$x, $y]"
}
}
class MutableIntVector2(x: Int, y: Int) : IntVector2(x, y) {
constructor() : this(Int.MIN_VALUE, Int.MIN_VALUE)
override var x: Int
get() = super.x
set(value) {
super.x = value
}
override var y: Int
get() = super.y
set(value) {
super.y = value
}
fun set(other: IntVector2) = set(other.x, other.y)
fun set(x: Int, y: Int): MutableIntVector2 {
val oldX = _x
val oldY = _y
_x = x
_y = y
fireChange(oldX, oldY)
return this
}
}
| gpl-3.0 | 631f8562de5a4d8c79f3ae2b90f1b922 | 17.649485 | 92 | 0.614151 | 2.676036 | false | false | false | false |
mingdroid/tumbviewer | app/src/main/java/com/nutrition/express/ui/post/blog/PostListActivity.kt | 1 | 8676 | package com.nutrition.express.ui.post.blog
import android.content.Intent
import android.media.AudioManager
import android.os.Bundle
import android.text.TextUtils
import android.view.Menu
import android.view.MenuItem
import androidx.activity.viewModels
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.nutrition.express.R
import com.nutrition.express.application.BaseActivity
import com.nutrition.express.application.toast
import com.nutrition.express.common.CommonRVAdapter
import com.nutrition.express.databinding.ActivityBlogPostsBinding
import com.nutrition.express.model.api.Resource
import com.nutrition.express.model.data.bean.PhotoPostsItem
import com.nutrition.express.model.data.bean.VideoPostsItem
import com.nutrition.express.model.api.bean.BlogPosts
import com.nutrition.express.model.api.bean.PostsItem
import com.nutrition.express.ui.likes.LikesActivity
import com.nutrition.express.ui.main.UserViewModel
import com.nutrition.express.util.getInt
import com.nutrition.express.util.putInt
import java.util.*
class PostListActivity : BaseActivity() {
private lateinit var binding: ActivityBlogPostsBinding
private lateinit var blogName: String
private var followItem: MenuItem? = null
private var followed = false
private val TYPES = arrayOf("", "video", "photo")
private val FILTER_TYPE = "filter_type"
private var filter: Int = 0
private var offset: Int = 0
private var reset: Boolean = false
private val userViewModel: UserViewModel by viewModels()
private val blogViewModel: BlogViewModel by viewModels()
private lateinit var adapter: CommonRVAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityBlogPostsBinding.inflate(layoutInflater)
setContentView(binding.root)
setSupportActionBar(binding.toolBar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
blogName = intent.getStringExtra("blog_name") ?: ""
supportActionBar?.title = blogName
filter = getInt(FILTER_TYPE)
if (filter >= TYPES.size) {
filter = 0
}
adapter = CommonRVAdapter.adapter {
addViewType(PhotoPostsItem::class, R.layout.item_post) { PhotoPostVH(it)}
addViewType(VideoPostsItem::class,R.layout.item_video_post) {VideoPostVH(it)}
loadListener = object : CommonRVAdapter.OnLoadListener {
override fun retry() {
blogViewModel.fetchBlogPosts(blogName, TYPES[filter], offset)
}
override fun loadNextPage() {
blogViewModel.fetchBlogPosts(blogName, TYPES[filter], offset)
}
}
}
binding.recyclerView.layoutManager = LinearLayoutManager(this)
binding.recyclerView.adapter = adapter
initViewModel()
volumeControlStream = AudioManager.STREAM_MUSIC
}
private fun initViewModel() {
blogViewModel.blogPostsData.observe(this, Observer {
when (it) {
is Resource.Success -> {
if (it.data == null) {
adapter.showLoadingFinish()
} else {
showPosts(it.data)
}
}
is Resource.Error -> adapter.showLoadingFailure(it.message)
is Resource.Loading -> {}
}
})
blogViewModel.deletePostData.observe(this, Observer {
when (it) {
is Resource.Success -> {
val list = adapter.getData()
for (index in list.indices) {
val item = list[index]
if (item is PostsItem) {
if (it.data == item.id.toString()) {
adapter.remove(index)
}
}
}
}
is Resource.Error -> toast(it.message)
is Resource.Loading -> {}
}
})
blogViewModel.fetchBlogPosts(blogName, TYPES[filter], offset)
userViewModel.followData.observe(this, Observer {
when (it) {
is Resource.Success -> onFollowed()
is Resource.Error -> toast(it.message)
is Resource.Loading -> {}
}
})
userViewModel.unFollowData.observe(this, Observer {
when (it) {
is Resource.Success -> onUnfollowed()
is Resource.Error -> toast(it.message)
is Resource.Loading -> {}
}
})
}
private fun reloading(which: Int) {
adapter.showReloading()
reset = true
offset = 0
filter = which
blogViewModel.fetchBlogPosts(blogName, TYPES[filter], offset)
putInt(FILTER_TYPE, which)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
var isAdmin = false
if (intent != null) {
isAdmin = intent.getBooleanExtra("is_admin", false)
}
menuInflater.inflate(R.menu.menu_blog, menu)
followItem = menu.findItem(R.id.blog_follow)
if (isAdmin) {
followItem?.isVisible = false
}
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
android.R.id.home -> {
finish()
true
}
R.id.blog_follow -> {
if (followed) {
userViewModel.unFollow(blogName)
} else {
userViewModel.follow(blogName)
}
true
}
R.id.post_filter -> {
showFilterDialog()
true
}
R.id.blog_likes -> {
val intent = Intent(this, LikesActivity::class.java)
intent.putExtra("blog_name", blogName)
startActivity(intent)
true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun showFilterDialog() {
AlertDialog.Builder(this).run {
setSingleChoiceItems(R.array.post_filter_type, filter) { dialog, which ->
dialog.dismiss()
reloading(which)
}
create()
show()
}
}
private fun onFollowed() {
followItem?.let {
it.title = getString(R.string.blog_unfollow)
it.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER)
followed = true
}
}
private fun onUnfollowed() {
followItem?.let {
it.title = getString(R.string.blog_follow)
it.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM)
followed = false
}
}
private fun showPosts(blogPosts: BlogPosts) {
offset += blogPosts.list.size
var hasNext = true
if (blogPosts.list.size < 20 || offset >= blogPosts.count) {
hasNext = false
}
val isAdmin = blogPosts.blogInfo.isAdmin
if (isAdmin) {
followItem?.isVisible = false
} else if (blogPosts.blogInfo.isFollowed) {
onFollowed()
} else {
onUnfollowed()
}
val postsItems: MutableList<PhotoPostsItem> = ArrayList(blogPosts.list.size)
if (filter == 0) {
//trim to only show videos and photos
for (item in blogPosts.list) {
item.isAdmin = isAdmin
if (TextUtils.equals(item.type, "video")) {
postsItems.add(VideoPostsItem(item))
} else if (TextUtils.equals(item.type, "photo")) {
postsItems.add(PhotoPostsItem(item))
}
}
} else if (filter == 1) {
for (item in blogPosts.list) {
item.isAdmin = isAdmin
postsItems.add(VideoPostsItem(item))
}
} else if (filter == 2) {
for (item in blogPosts.list) {
item.isAdmin = isAdmin
postsItems.add(PhotoPostsItem(item))
}
}
if (reset) {
adapter.resetData(postsItems.toTypedArray(), hasNext)
reset = false
} else {
adapter.append(postsItems.toTypedArray(), hasNext)
}
}
private fun wrap() {
}
}
| apache-2.0 | 936afd979e29f730b5abf4c9e572d7fe | 33.15748 | 89 | 0.566851 | 4.838818 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.