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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
JetBrains/intellij-community | platform/workspaceModel/storage/testEntities/testSrc/com/intellij/workspaceModel/storage/entities/test/api/EntititesWithPersistentId.kt | 1 | 2922 | package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.WorkspaceEntity
import kotlin.jvm.JvmName
import kotlin.jvm.JvmOverloads
import kotlin.jvm.JvmStatic
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.MutableEntityStorage
interface FirstEntityWithPId : WorkspaceEntityWithSymbolicId {
val data: String
override val symbolicId: FirstPId
get() {
return FirstPId(data)
}
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : FirstEntityWithPId, WorkspaceEntity.Builder<FirstEntityWithPId>, ObjBuilder<FirstEntityWithPId> {
override var entitySource: EntitySource
override var data: String
}
companion object : Type<FirstEntityWithPId, Builder>() {
@JvmOverloads
@JvmStatic
@JvmName("create")
operator fun invoke(data: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): FirstEntityWithPId {
val builder = builder()
builder.data = data
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: FirstEntityWithPId, modification: FirstEntityWithPId.Builder.() -> Unit) = modifyEntity(
FirstEntityWithPId.Builder::class.java, entity, modification)
//endregion
data class FirstPId(override val presentableName: String) : SymbolicEntityId<FirstEntityWithPId>
interface SecondEntityWithPId : WorkspaceEntityWithSymbolicId {
val data: String
override val symbolicId: SecondPId
get() = SecondPId(data)
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : SecondEntityWithPId, WorkspaceEntity.Builder<SecondEntityWithPId>, ObjBuilder<SecondEntityWithPId> {
override var entitySource: EntitySource
override var data: String
}
companion object : Type<SecondEntityWithPId, Builder>() {
@JvmOverloads
@JvmStatic
@JvmName("create")
operator fun invoke(data: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): SecondEntityWithPId {
val builder = builder()
builder.data = data
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: SecondEntityWithPId, modification: SecondEntityWithPId.Builder.() -> Unit) = modifyEntity(
SecondEntityWithPId.Builder::class.java, entity, modification)
//endregion
data class SecondPId(override val presentableName: String) : SymbolicEntityId<SecondEntityWithPId>
data class TestPId(var presentableName: String, val aaa: Int?, var angry: Boolean) | apache-2.0 | 6749ee34b58582907a8948c15457cb08 | 32.215909 | 136 | 0.767283 | 5.020619 | false | false | false | false |
google/j2cl | transpiler/java/com/google/j2cl/transpiler/backend/kotlin/MemberRenderer.kt | 1 | 7954 | /*
* Copyright 2021 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.j2cl.transpiler.backend.kotlin
import com.google.j2cl.common.InternalCompilerError
import com.google.j2cl.transpiler.ast.ArrayTypeDescriptor
import com.google.j2cl.transpiler.ast.AstUtils.getConstructorInvocation
import com.google.j2cl.transpiler.ast.AstUtils.isConstructorInvocationStatement
import com.google.j2cl.transpiler.ast.Field
import com.google.j2cl.transpiler.ast.HasName
import com.google.j2cl.transpiler.ast.InitializerBlock
import com.google.j2cl.transpiler.ast.Member as JavaMember
import com.google.j2cl.transpiler.ast.Method
import com.google.j2cl.transpiler.ast.MethodDescriptor
import com.google.j2cl.transpiler.ast.MethodDescriptor.ParameterDescriptor
import com.google.j2cl.transpiler.ast.PrimitiveTypes
import com.google.j2cl.transpiler.ast.ReturnStatement
import com.google.j2cl.transpiler.ast.Statement
import com.google.j2cl.transpiler.ast.TypeDescriptors
import com.google.j2cl.transpiler.backend.kotlin.ast.CompanionObject
import com.google.j2cl.transpiler.backend.kotlin.ast.Member
internal fun Renderer.render(member: Member) {
when (member) {
is Member.WithCompanionObject -> render(member.companionObject)
is Member.WithJavaMember -> renderMember(member.javaMember)
is Member.WithType -> renderType(member.type)
}
}
private fun Renderer.render(companionObject: CompanionObject) {
render("companion object ")
renderInCurlyBrackets {
renderNewLine()
renderSeparatedWithEmptyLine(companionObject.members) { render(it) }
}
}
private fun Renderer.renderMember(member: JavaMember) {
when (member) {
is Method -> renderMethod(member)
is Field -> renderField(member)
is InitializerBlock -> renderInitializerBlock(member)
else -> throw InternalCompilerError("Unhandled ${member::class}")
}
}
private fun Renderer.renderMethod(method: Method) {
renderMethodHeader(method)
if (!method.isAbstract && !method.isNative) {
val statements = getStatements(method)
// Constructors with no statements can be rendered without curly braces.
if (!method.isConstructor || statements.isNotEmpty()) {
render(" ")
if (method.descriptor.isKtProperty) render("get() ")
copy(currentReturnLabelIdentifier = null).run {
renderInCurlyBrackets {
if (method.descriptor.isTodo) {
renderNewLine()
renderTodo("J2KT: not yet supported")
} else {
renderStatements(statements)
}
}
}
}
}
}
private fun Renderer.getStatements(method: Method): List<Statement> {
if (!method.descriptor.isKtDisabled) {
return method.body.statements.filter { !isConstructorInvocationStatement(it) }
}
if (TypeDescriptors.isPrimitiveVoid(method.descriptor.returnTypeDescriptor)) {
return listOf()
}
return listOf(
ReturnStatement.newBuilder()
.setSourcePosition(method.sourcePosition)
.setExpression(method.descriptor.returnTypeDescriptor.defaultValue)
.build()
)
}
private fun Renderer.renderField(field: Field) {
val isFinal = field.descriptor.isFinal
val typeDescriptor = field.descriptor.typeDescriptor
if (field.isCompileTimeConstant && field.isStatic) {
render("const ")
} else {
renderJvmFieldAnnotation()
}
render(if (isFinal) "val " else "var ")
renderIdentifier(field.descriptor.ktMangledName)
render(": ")
renderTypeDescriptor(typeDescriptor)
field.initializer?.let { initializer ->
render(" = ")
renderExpression(initializer)
}
}
private fun Renderer.renderJvmFieldAnnotation() {
render("@")
renderQualifiedName("kotlin.jvm.JvmField")
render(" ")
}
private fun Renderer.renderJvmStaticAnnotation() {
render("@")
renderQualifiedName("kotlin.jvm.JvmStatic")
renderNewLine()
}
private fun Renderer.renderInitializerBlock(initializerBlock: InitializerBlock) {
render("init ")
renderStatement(initializerBlock.block)
}
private fun Renderer.renderMethodHeader(method: Method) {
if (method.isStatic) {
renderJvmStaticAnnotation()
}
val methodDescriptor = method.descriptor
renderMethodModifiers(methodDescriptor)
if (methodDescriptor.isConstructor) {
render("constructor")
} else {
render(if (method.descriptor.isKtProperty) "val " else "fun ")
val typeParameters = methodDescriptor.typeParameterTypeDescriptors
if (typeParameters.isNotEmpty()) {
renderTypeParameters(methodDescriptor.typeParameterTypeDescriptors)
render(" ")
}
renderIdentifier(methodDescriptor.ktMangledName)
}
if (!method.descriptor.isKtProperty) {
renderMethodParameters(method)
}
if (methodDescriptor.isConstructor) {
renderConstructorInvocation(method)
} else {
renderMethodReturnType(methodDescriptor)
}
renderWhereClause(methodDescriptor.typeParameterTypeDescriptors)
}
private fun Renderer.renderMethodModifiers(methodDescriptor: MethodDescriptor) {
if (!methodDescriptor.enclosingTypeDescriptor.typeDeclaration.isInterface) {
if (methodDescriptor.isNative) {
render("external ")
}
if (methodDescriptor.isAbstract) {
render("abstract ")
} else if (
!methodDescriptor.isFinal &&
!methodDescriptor.isConstructor &&
!methodDescriptor.isStatic &&
!methodDescriptor.visibility.isPrivate
) {
render("open ")
}
}
if (methodDescriptor.isJavaOverride) {
render("override ")
}
}
private fun Renderer.renderMethodParameters(method: Method) {
val parameterDescriptors = method.descriptor.parameterDescriptors
val parameters = method.parameters
val renderObjCNameAnnotation =
method.descriptor.visibility.needsObjCNameAnnotation && !method.descriptor.isJavaOverride
val renderWithNewLines = renderObjCNameAnnotation && parameters.isNotEmpty()
renderInParentheses {
renderIndentedIf(renderWithNewLines) {
renderCommaSeparated(0 until parameters.size) { index ->
if (renderWithNewLines) renderNewLine()
renderParameter(
parameterDescriptors[index],
parameters[index],
renderObjCNameAnnotation = renderObjCNameAnnotation
)
}
}
if (renderWithNewLines) renderNewLine()
}
}
private fun Renderer.renderParameter(
parameterDescriptor: ParameterDescriptor,
name: HasName,
renderObjCNameAnnotation: Boolean = false
) {
val parameterTypeDescriptor = parameterDescriptor.typeDescriptor
val renderedTypeDescriptor =
if (!parameterDescriptor.isVarargs) parameterTypeDescriptor
else (parameterTypeDescriptor as ArrayTypeDescriptor).componentTypeDescriptor!!
if (parameterDescriptor.isVarargs) render("vararg ")
if (renderObjCNameAnnotation) renderObjCNameAnnotation(parameterDescriptor)
renderName(name)
render(": ")
renderTypeDescriptor(renderedTypeDescriptor)
}
internal fun Renderer.renderMethodReturnType(methodDescriptor: MethodDescriptor) {
val returnTypeDescriptor = methodDescriptor.returnTypeDescriptor
if (returnTypeDescriptor != PrimitiveTypes.VOID) {
render(": ")
renderTypeDescriptor(returnTypeDescriptor)
}
}
private fun Renderer.renderConstructorInvocation(method: Method) {
getConstructorInvocation(method)?.let { constructorInvocation ->
render(": ")
render(if (constructorInvocation.target.inSameTypeAs(method.descriptor)) "this" else "super")
renderInvocationArguments(constructorInvocation)
}
}
| apache-2.0 | cafb71d7ed9953bc3192e9545498978f | 32.561181 | 97 | 0.751949 | 4.46603 | false | false | false | false |
JetBrains/intellij-community | platform/service-container/src/com/intellij/serviceContainer/ComponentManagerImpl.kt | 1 | 59802 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplaceNegatedIsEmptyWithIsNotEmpty", "ReplaceGetOrSet", "ReplacePutWithAssignment", "OVERRIDE_DEPRECATION")
package com.intellij.serviceContainer
import com.intellij.diagnostic.*
import com.intellij.ide.plugins.*
import com.intellij.ide.plugins.cl.PluginAwareClassLoader
import com.intellij.idea.AppMode.*
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.*
import com.intellij.openapi.components.*
import com.intellij.openapi.components.ServiceDescriptor.PreloadMode
import com.intellij.openapi.components.impl.stores.IComponentStore
import com.intellij.openapi.diagnostic.Attachment
import com.intellij.openapi.diagnostic.ControlFlowException
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.*
import com.intellij.openapi.extensions.impl.ExtensionPointImpl
import com.intellij.openapi.extensions.impl.ExtensionsAreaImpl
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.util.Condition
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.SystemInfoRt
import com.intellij.openapi.util.UserDataHolderBase
import com.intellij.util.childScope
import com.intellij.util.messages.*
import com.intellij.util.messages.impl.MessageBusEx
import com.intellij.util.messages.impl.MessageBusImpl
import com.intellij.util.runSuppressing
import kotlinx.coroutines.*
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.TestOnly
import org.picocontainer.ComponentAdapter
import org.picocontainer.PicoContainer
import java.lang.invoke.MethodHandles
import java.lang.invoke.MethodType
import java.lang.reflect.Constructor
import java.lang.reflect.InvocationTargetException
import java.lang.reflect.Modifier
import java.util.*
import java.util.concurrent.*
import java.util.concurrent.CancellationException
import java.util.concurrent.atomic.AtomicReference
internal val LOG = logger<ComponentManagerImpl>()
private val constructorParameterResolver = ConstructorParameterResolver()
private val methodLookup = MethodHandles.lookup()
private val emptyConstructorMethodType = MethodType.methodType(Void.TYPE)
@ApiStatus.Internal
abstract class ComponentManagerImpl(
internal val parent: ComponentManagerImpl?,
setExtensionsRootArea: Boolean = parent == null
) : ComponentManager, Disposable.Parent, MessageBusOwner, UserDataHolderBase(), ComponentManagerEx, ComponentStoreOwner {
protected enum class ContainerState {
PRE_INIT, COMPONENT_CREATED, DISPOSE_IN_PROGRESS, DISPOSED, DISPOSE_COMPLETED
}
companion object {
@JvmField
@Volatile
@ApiStatus.Internal
var mainScope: CoroutineScope? = null
@ApiStatus.Internal
@JvmField val fakeCorePluginDescriptor = DefaultPluginDescriptor(PluginManagerCore.CORE_ID, null)
@Suppress("ReplaceJavaStaticMethodWithKotlinAnalog")
@ApiStatus.Internal
@JvmField val badWorkspaceComponents: Set<String> = java.util.Set.of(
"jetbrains.buildServer.codeInspection.InspectionPassRegistrar",
"jetbrains.buildServer.testStatus.TestStatusPassRegistrar",
"jetbrains.buildServer.customBuild.lang.gutterActions.CustomBuildParametersGutterActionsHighlightingPassRegistrar",
)
// not as file level function to avoid scope cluttering
@ApiStatus.Internal
fun createAllServices(componentManager: ComponentManagerImpl, requireEdt: Set<String>, requireReadAction: Set<String>) {
for (o in componentManager.componentKeyToAdapter.values) {
if (o !is ServiceComponentAdapter) {
continue
}
val implementation = o.descriptor.serviceImplementation
try {
if (implementation == "org.jetbrains.plugins.groovy.mvc.MvcConsole") {
// NPE in RunnerContentUi.setLeftToolbar
continue
}
val init = { o.getInstance<Any>(componentManager, null) }
when {
requireEdt.contains(implementation) -> invokeAndWaitIfNeeded(null, init)
requireReadAction.contains(implementation) -> runReadAction(init)
else -> init()
}
}
catch (e: Throwable) {
LOG.error("Cannot create $implementation", e)
}
}
}
}
private val componentKeyToAdapter = ConcurrentHashMap<Any, ComponentAdapter>()
private val componentAdapters = LinkedHashSetWrapper<MyComponentAdapter>()
private val serviceInstanceHotCache = ConcurrentHashMap<Class<*>, Any?>()
protected val containerState = AtomicReference(ContainerState.PRE_INIT)
protected val containerStateName: String
get() = containerState.get().name
private val _extensionArea by lazy { ExtensionsAreaImpl(this) }
private var messageBus: MessageBusImpl? = null
private var handlingInitComponentError = false
@Volatile
private var isServicePreloadingCancelled = false
@Suppress("LeakingThis")
internal val serviceParentDisposable = Disposer.newDisposable("services of ${javaClass.name}@${System.identityHashCode(this)}")
protected open val isLightServiceSupported = parent?.parent == null
protected open val isMessageBusSupported = parent?.parent == null
protected open val isComponentSupported = true
protected open val isExtensionSupported = true
@Volatile
internal var componentContainerIsReadonly: String? = null
private val coroutineScope: CoroutineScope? = when {
parent == null -> mainScope?.childScope(Dispatchers.Default) ?: CoroutineScope(SupervisorJob())
parent.parent == null -> parent.coroutineScope!!.childScope()
else -> null
}
@Suppress("MemberVisibilityCanBePrivate")
fun getCoroutineScope(): CoroutineScope = coroutineScope ?: throw RuntimeException("Module doesn't have coroutineScope")
override val componentStore: IComponentStore
get() = getService(IComponentStore::class.java)!!
init {
if (setExtensionsRootArea) {
Extensions.setRootArea(_extensionArea)
}
}
private val picoContainerAdapter: PicoContainer = object : PicoContainer {
override fun getComponentInstance(componentKey: Any): Any? {
return [email protected](componentKey)
}
override fun getComponentInstanceOfType(componentType: Class<*>): Any? {
throw UnsupportedOperationException("Do not use getComponentInstanceOfType()")
}
}
internal fun getComponentInstance(componentKey: Any): Any? {
assertComponentsSupported()
val adapter = componentKeyToAdapter.get(componentKey)
?: if (componentKey is Class<*>) componentKeyToAdapter.get(componentKey.name) else null
return if (adapter == null) parent?.getComponentInstance(componentKey) else adapter.componentInstance
}
@Deprecated("Use ComponentManager API", level = DeprecationLevel.ERROR)
final override fun getPicoContainer(): PicoContainer {
checkState()
return picoContainerAdapter
}
private fun registerAdapter(componentAdapter: ComponentAdapter, pluginDescriptor: PluginDescriptor?) {
if (componentKeyToAdapter.putIfAbsent(componentAdapter.componentKey, componentAdapter) != null) {
val error = "Key ${componentAdapter.componentKey} duplicated"
if (pluginDescriptor == null) {
throw PluginException.createByClass(error, null, componentAdapter.javaClass)
}
else {
throw PluginException(error, null, pluginDescriptor.pluginId)
}
}
}
fun forbidGettingServices(reason: String): AccessToken {
val token = object : AccessToken() {
override fun finish() {
componentContainerIsReadonly = null
}
}
componentContainerIsReadonly = reason
return token
}
private fun checkState() {
if (containerState.get() == ContainerState.DISPOSE_COMPLETED) {
ProgressManager.checkCanceled()
throw AlreadyDisposedException("Already disposed: $this")
}
}
override fun getMessageBus(): MessageBus {
if (containerState.get() >= ContainerState.DISPOSE_IN_PROGRESS) {
ProgressManager.checkCanceled()
throw AlreadyDisposedException("Already disposed: $this")
}
val messageBus = messageBus
if (messageBus == null || !isMessageBusSupported) {
LOG.error("Do not use module level message bus")
return getOrCreateMessageBusUnderLock()
}
return messageBus
}
fun getDeprecatedModuleLevelMessageBus(): MessageBus {
if (containerState.get() >= ContainerState.DISPOSE_IN_PROGRESS) {
ProgressManager.checkCanceled()
throw AlreadyDisposedException("Already disposed: $this")
}
return messageBus ?: getOrCreateMessageBusUnderLock()
}
final override fun getExtensionArea(): ExtensionsAreaImpl {
if (!isExtensionSupported) {
error("Extensions aren't supported")
}
return _extensionArea
}
fun registerComponents() {
registerComponents(modules = PluginManagerCore.getPluginSet().getEnabledModules(),
app = getApplication(),
precomputedExtensionModel = null,
listenerCallbacks = null)
}
open fun registerComponents(modules: List<IdeaPluginDescriptorImpl>,
app: Application?,
precomputedExtensionModel: PrecomputedExtensionModel?,
listenerCallbacks: MutableList<in Runnable>?) {
val activityNamePrefix = activityNamePrefix()
var map: ConcurrentMap<String, MutableList<ListenerDescriptor>>? = null
val isHeadless = app == null || app.isHeadlessEnvironment
val isUnitTestMode = app?.isUnitTestMode ?: false
var activity = activityNamePrefix?.let { StartUpMeasurer.startActivity("${it}service and ep registration") }
// register services before registering extensions because plugins can access services in their
// extensions which can be invoked right away if the plugin is loaded dynamically
val extensionPoints = if (precomputedExtensionModel == null) HashMap(extensionArea.extensionPoints) else null
for (rootModule in modules) {
executeRegisterTask(rootModule) { module ->
val containerDescriptor = getContainerDescriptor(module)
registerServices(containerDescriptor.services, module)
registerComponents(module, containerDescriptor, isHeadless)
containerDescriptor.listeners?.let { listeners ->
var m = map
if (m == null) {
m = ConcurrentHashMap()
map = m
}
for (listener in listeners) {
if ((isUnitTestMode && !listener.activeInTestMode) || (isHeadless && !listener.activeInHeadlessMode)) {
continue
}
if (listener.os != null && !isSuitableForOs(listener.os)) {
continue
}
listener.pluginDescriptor = module
m.computeIfAbsent(listener.topicClassName) { ArrayList() }.add(listener)
}
}
if (extensionPoints != null) {
containerDescriptor.extensionPoints?.let {
ExtensionsAreaImpl.createExtensionPoints(it, this, extensionPoints, module)
}
}
}
}
if (activity != null) {
activity = activity.endAndStart("${activityNamePrefix}extension registration")
}
if (precomputedExtensionModel == null) {
val immutableExtensionPoints = if (extensionPoints!!.isEmpty()) Collections.emptyMap() else java.util.Map.copyOf(extensionPoints)
extensionArea.extensionPoints = immutableExtensionPoints
for (rootModule in modules) {
executeRegisterTask(rootModule) { module ->
module.registerExtensions(immutableExtensionPoints, getContainerDescriptor(module), listenerCallbacks)
}
}
}
else {
registerExtensionPointsAndExtensionByPrecomputedModel(precomputedExtensionModel, listenerCallbacks)
}
activity?.end()
// app - phase must be set before getMessageBus()
if (parent == null && !LoadingState.COMPONENTS_REGISTERED.isOccurred /* loading plugin on the fly */) {
StartUpMeasurer.setCurrentState(LoadingState.COMPONENTS_REGISTERED)
}
// ensuring that `messageBus` is created, regardless of the lazy listener map state
if (isMessageBusSupported) {
val messageBus = getOrCreateMessageBusUnderLock()
map?.let {
(messageBus as MessageBusEx).setLazyListeners(it)
}
}
}
private fun registerExtensionPointsAndExtensionByPrecomputedModel(precomputedExtensionModel: PrecomputedExtensionModel,
listenerCallbacks: MutableList<in Runnable>?) {
assert(extensionArea.extensionPoints.isEmpty())
val n = precomputedExtensionModel.pluginDescriptors.size
if (n == 0) {
return
}
val result = HashMap<String, ExtensionPointImpl<*>>(precomputedExtensionModel.extensionPointTotalCount)
for (i in 0 until n) {
ExtensionsAreaImpl.createExtensionPoints(precomputedExtensionModel.extensionPoints[i],
this,
result,
precomputedExtensionModel.pluginDescriptors[i])
}
val immutableExtensionPoints = java.util.Map.copyOf(result)
extensionArea.extensionPoints = immutableExtensionPoints
for ((name, pairs) in precomputedExtensionModel.nameToExtensions) {
val point = immutableExtensionPoints.get(name) ?: continue
for ((pluginDescriptor, list) in pairs) {
if (!list.isEmpty()) {
point.registerExtensions(list, pluginDescriptor, listenerCallbacks)
}
}
}
}
private fun registerComponents(pluginDescriptor: IdeaPluginDescriptor, containerDescriptor: ContainerDescriptor, headless: Boolean) {
for (descriptor in (containerDescriptor.components ?: return)) {
var implementationClassName = descriptor.implementationClass
if (headless && descriptor.headlessImplementationClass != null) {
if (descriptor.headlessImplementationClass.isEmpty()) {
continue
}
implementationClassName = descriptor.headlessImplementationClass
}
if (descriptor.os != null && !isSuitableForOs(descriptor.os)) {
continue
}
if (!isComponentSuitable(descriptor)) {
continue
}
val componentClassName = descriptor.interfaceClass ?: descriptor.implementationClass!!
try {
registerComponent(
interfaceClassName = componentClassName,
implementationClassName = implementationClassName,
config = descriptor,
pluginDescriptor = pluginDescriptor,
)
}
catch (e: Throwable) {
handleInitComponentError(e, componentClassName, pluginDescriptor.pluginId)
}
}
}
fun createInitOldComponentsTask(): (() -> Unit)? {
if (componentAdapters.getImmutableSet().isEmpty()) {
return null
}
return {
for (componentAdapter in componentAdapters.getImmutableSet()) {
componentAdapter.getInstance<Any>(this, keyClass = null)
}
}
}
@Suppress("DuplicatedCode")
@Deprecated(message = "Use createComponents")
protected fun createComponents() {
LOG.assertTrue(containerState.get() == ContainerState.PRE_INIT)
val activity = when (val activityNamePrefix = activityNamePrefix()) {
null -> null
else -> StartUpMeasurer.startActivity("$activityNamePrefix${StartUpMeasurer.Activities.CREATE_COMPONENTS_SUFFIX}")
}
for (componentAdapter in componentAdapters.getImmutableSet()) {
componentAdapter.getInstance<Any>(this, keyClass = null)
}
activity?.end()
LOG.assertTrue(containerState.compareAndSet(ContainerState.PRE_INIT, ContainerState.COMPONENT_CREATED))
}
@Suppress("DuplicatedCode")
protected suspend fun createComponentsNonBlocking() {
LOG.assertTrue(containerState.get() == ContainerState.PRE_INIT)
val activity = when (val activityNamePrefix = activityNamePrefix()) {
null -> null
else -> StartUpMeasurer.startActivity("$activityNamePrefix${StartUpMeasurer.Activities.CREATE_COMPONENTS_SUFFIX}")
}
for (componentAdapter in componentAdapters.getImmutableSet()) {
componentAdapter.getInstanceAsync<Any>(this, keyClass = null).await()
}
activity?.end()
LOG.assertTrue(containerState.compareAndSet(ContainerState.PRE_INIT, ContainerState.COMPONENT_CREATED))
}
@TestOnly
fun registerComponentImplementation(key: Class<*>, implementation: Class<*>, shouldBeRegistered: Boolean) {
checkState()
val oldAdapter = componentKeyToAdapter.remove(key) as MyComponentAdapter?
if (shouldBeRegistered) {
LOG.assertTrue(oldAdapter != null)
}
serviceInstanceHotCache.remove(key)
val pluginDescriptor = oldAdapter?.pluginDescriptor ?: DefaultPluginDescriptor("test registerComponentImplementation")
val newAdapter = MyComponentAdapter(componentKey = key,
implementationClassName = implementation.name,
pluginDescriptor = pluginDescriptor,
componentManager = this,
deferred = CompletableDeferred(),
implementationClass = implementation)
componentKeyToAdapter.put(key, newAdapter)
if (oldAdapter == null) {
componentAdapters.add(newAdapter)
}
else {
componentAdapters.replace(oldAdapter, newAdapter)
}
}
@TestOnly
fun <T : Any> replaceComponentInstance(componentKey: Class<T>, componentImplementation: T, parentDisposable: Disposable?) {
checkState()
val oldAdapter = componentKeyToAdapter.get(componentKey) as MyComponentAdapter
val implClass = componentImplementation::class.java
val newAdapter = MyComponentAdapter(componentKey = componentKey,
implementationClassName = implClass.name,
pluginDescriptor = oldAdapter.pluginDescriptor,
componentManager = this,
deferred = CompletableDeferred(value = componentImplementation),
implementationClass = implClass)
componentKeyToAdapter.put(componentKey, newAdapter)
componentAdapters.replace(oldAdapter, newAdapter)
serviceInstanceHotCache.remove(componentKey)
if (parentDisposable != null) {
Disposer.register(parentDisposable) {
@Suppress("DEPRECATION")
if (componentImplementation is Disposable && !Disposer.isDisposed(componentImplementation)) {
Disposer.dispose(componentImplementation)
}
componentKeyToAdapter.put(componentKey, oldAdapter)
componentAdapters.replace(newAdapter, oldAdapter)
serviceInstanceHotCache.remove(componentKey)
}
}
}
private fun registerComponent(
interfaceClassName: String,
implementationClassName: String?,
config: ComponentConfig,
pluginDescriptor: IdeaPluginDescriptor,
) {
val interfaceClass = pluginDescriptor.classLoader.loadClass(interfaceClassName)
val options = config.options
if (config.overrides) {
unregisterComponent(interfaceClass) ?: throw PluginException("$config does not override anything", pluginDescriptor.pluginId)
}
// implementationClass == null means we want to unregister this component
if (implementationClassName == null) {
return
}
if (options != null && java.lang.Boolean.parseBoolean(options.get("workspace")) &&
!badWorkspaceComponents.contains(implementationClassName)) {
LOG.error("workspace option is deprecated (implementationClass=$implementationClassName)")
}
val adapter = MyComponentAdapter(interfaceClass, implementationClassName, pluginDescriptor, this, CompletableDeferred(), null)
registerAdapter(adapter, adapter.pluginDescriptor)
componentAdapters.add(adapter)
}
open fun getApplication(): Application? {
return if (parent == null || this is Application) this as Application else parent.getApplication()
}
protected fun registerServices(services: List<ServiceDescriptor>, pluginDescriptor: IdeaPluginDescriptor) {
checkState()
val app = getApplication()!!
for (descriptor in services) {
if (!isServiceSuitable(descriptor) || descriptor.os != null && !isSuitableForOs(descriptor.os)) {
continue
}
// Allow to re-define service implementations in plugins.
// Empty serviceImplementation means we want to unregister service.
val key = descriptor.getInterface()
if (descriptor.overrides && componentKeyToAdapter.remove(key) == null) {
throw PluginException("Service $key doesn't override anything", pluginDescriptor.pluginId)
}
// empty serviceImplementation means we want to unregister service
val implementation = when {
descriptor.testServiceImplementation != null && app.isUnitTestMode -> descriptor.testServiceImplementation
descriptor.headlessImplementation != null && app.isHeadlessEnvironment -> descriptor.headlessImplementation
else -> descriptor.serviceImplementation
}
if (implementation != null) {
val componentAdapter = ServiceComponentAdapter(descriptor, pluginDescriptor, this)
val existingAdapter = componentKeyToAdapter.putIfAbsent(key, componentAdapter)
if (existingAdapter != null) {
throw PluginException("Key $key duplicated; existingAdapter: $existingAdapter; descriptor: ${descriptor.implementation}; app: $app; current plugin: ${pluginDescriptor.pluginId}", pluginDescriptor.pluginId)
}
}
}
}
internal fun handleInitComponentError(error: Throwable, componentClassName: String, pluginId: PluginId) {
if (handlingInitComponentError) {
return
}
handlingInitComponentError = true
try {
// not logged but thrown PluginException means some fatal error
if (error is StartupAbortedException || error is ProcessCanceledException || error is PluginException) {
throw error
}
var effectivePluginId = pluginId
if (effectivePluginId == PluginManagerCore.CORE_ID) {
effectivePluginId = PluginManagerCore.getPluginDescriptorOrPlatformByClassName(componentClassName)?.pluginId
?: PluginManagerCore.CORE_ID
}
throw PluginException("Fatal error initializing '$componentClassName'", error, effectivePluginId)
}
finally {
handlingInitComponentError = false
}
}
internal fun initializeComponent(component: Any, serviceDescriptor: ServiceDescriptor?, pluginId: PluginId?) {
if (serviceDescriptor == null || !isPreInitialized(component)) {
LoadingState.CONFIGURATION_STORE_INITIALIZED.checkOccurred()
componentStore.initComponent(component, serviceDescriptor, pluginId)
}
}
protected open fun isPreInitialized(component: Any): Boolean {
return component is PathMacroManager || component is IComponentStore || component is MessageBusFactory
}
protected abstract fun getContainerDescriptor(pluginDescriptor: IdeaPluginDescriptorImpl): ContainerDescriptor
final override fun <T : Any> getComponent(key: Class<T>): T? {
assertComponentsSupported()
checkState()
val adapter = getComponentAdapter(key)
if (adapter == null) {
checkCanceledIfNotInClassInit()
if (containerState.get() == ContainerState.DISPOSE_COMPLETED) {
throwAlreadyDisposedError(key.name, this)
}
return null
}
if (adapter is ServiceComponentAdapter) {
LOG.error("$key it is a service, use getService instead of getComponent")
}
if (adapter is BaseComponentAdapter) {
if (parent != null && adapter.componentManager !== this) {
LOG.error("getComponent must be called on appropriate container (current: $this, expected: ${adapter.componentManager})")
}
if (containerState.get() == ContainerState.DISPOSE_COMPLETED) {
adapter.throwAlreadyDisposedError(this)
}
return adapter.getInstance(adapter.componentManager, key)
}
else {
@Suppress("UNCHECKED_CAST")
return (adapter as LightServiceComponentAdapter).componentInstance as T
}
}
final override fun <T : Any> getService(serviceClass: Class<T>): T? {
// `computeIfAbsent` cannot be used because of recursive update
@Suppress("UNCHECKED_CAST")
var result = serviceInstanceHotCache.get(serviceClass) as T?
if (result == null) {
result = doGetService(serviceClass, true) ?: return postGetService(serviceClass, createIfNeeded = true)
serviceInstanceHotCache.putIfAbsent(serviceClass, result)
}
return result
}
final override suspend fun <T : Any> getServiceAsync(keyClass: Class<T>): Deferred<T> {
return getServiceAsyncIfDefined(keyClass) ?: throw RuntimeException("service is not defined for key ${keyClass.name}")
}
suspend fun <T : Any> getServiceAsyncIfDefined(keyClass: Class<T>): Deferred<T>? {
val key = keyClass.name
val adapter = componentKeyToAdapter.get(key) ?: return null
if (adapter !is ServiceComponentAdapter) {
throw RuntimeException("$adapter is not a service (key=$key)")
}
return adapter.getInstanceAsync(componentManager = this, keyClass = keyClass)
}
protected open fun <T : Any> postGetService(serviceClass: Class<T>, createIfNeeded: Boolean): T? = null
final override fun <T : Any> getServiceIfCreated(serviceClass: Class<T>): T? {
@Suppress("UNCHECKED_CAST")
var result = serviceInstanceHotCache.get(serviceClass) as T?
if (result != null) {
return result
}
result = doGetService(serviceClass, createIfNeeded = false)
if (result == null) {
return postGetService(serviceClass, createIfNeeded = false)
}
else {
serviceInstanceHotCache.putIfAbsent(serviceClass, result)
return result
}
}
protected open fun <T : Any> doGetService(serviceClass: Class<T>, createIfNeeded: Boolean): T? {
val key = serviceClass.name
val adapter = componentKeyToAdapter.get(key)
if (adapter is ServiceComponentAdapter) {
if (createIfNeeded && containerState.get() == ContainerState.DISPOSE_COMPLETED) {
throwAlreadyDisposedError(adapter.toString(), this)
}
return adapter.getInstance(this, serviceClass, createIfNeeded)
}
else if (adapter is LightServiceComponentAdapter) {
if (createIfNeeded && containerState.get() == ContainerState.DISPOSE_COMPLETED) {
throwAlreadyDisposedError(adapter.toString(), this)
}
@Suppress("UNCHECKED_CAST")
return adapter.componentInstance as T
}
if (isLightServiceSupported && isLightService(serviceClass)) {
return if (createIfNeeded) getOrCreateLightService(serviceClass) else null
}
checkCanceledIfNotInClassInit()
// if the container is fully disposed, all adapters may be removed
if (containerState.get() == ContainerState.DISPOSE_COMPLETED) {
if (!createIfNeeded) {
return null
}
throwAlreadyDisposedError(serviceClass.name, this)
}
if (parent != null) {
val result = parent.doGetService(serviceClass, createIfNeeded)
if (result != null) {
LOG.error("$key is registered as application service, but requested as project one")
return result
}
}
if (isLightServiceSupported && !serviceClass.isInterface && !Modifier.isFinal(serviceClass.modifiers) &&
serviceClass.isAnnotationPresent(Service::class.java)) {
throw PluginException.createByClass("Light service class $serviceClass must be final", null, serviceClass)
}
val result = getComponent(serviceClass) ?: return null
PluginException.logPluginError(LOG,
"$key requested as a service, but it is a component - " +
"convert it to a service or change call to " +
if (parent == null) "ApplicationManager.getApplication().getComponent()" else "project.getComponent()",
null, serviceClass)
return result
}
private fun <T : Any> getOrCreateLightService(serviceClass: Class<T>): T {
checkThatCreatingOfLightServiceIsAllowed(serviceClass)
synchronized(serviceClass) {
val adapter = componentKeyToAdapter.get(serviceClass.name) as LightServiceComponentAdapter?
if (adapter != null) {
@Suppress("UNCHECKED_CAST")
return adapter.componentInstance as T
}
LoadingState.COMPONENTS_REGISTERED.checkOccurred()
var result: T? = null
if (!isUnderIndicatorOrJob()) {
result = createLightService(serviceClass)
}
else {
ProgressManager.getInstance().executeNonCancelableSection {
result = createLightService(serviceClass)
}
}
result!!.let {
registerAdapter(LightServiceComponentAdapter(it), pluginDescriptor = null)
return it
}
}
}
private fun checkThatCreatingOfLightServiceIsAllowed(serviceClass: Class<*>) {
if (isDisposed) {
throwAlreadyDisposedError("light service ${serviceClass.name}", this)
}
// assertion only for non-platform plugins
val classLoader = serviceClass.classLoader
if (classLoader is PluginAwareClassLoader && !isGettingServiceAllowedDuringPluginUnloading(classLoader.pluginDescriptor)) {
componentContainerIsReadonly?.let {
val error = AlreadyDisposedException(
"Cannot create light service ${serviceClass.name} because container in read-only mode (reason=$it, container=$this"
)
throw if (!isUnderIndicatorOrJob()) error else ProcessCanceledException(error)
}
}
}
@Synchronized
private fun getOrCreateMessageBusUnderLock(): MessageBus {
var messageBus = this.messageBus
if (messageBus != null) {
return messageBus
}
messageBus = getApplication()!!.getService(MessageBusFactory::class.java).createMessageBus(this, parent?.messageBus) as MessageBusImpl
if (StartUpMeasurer.isMeasuringPluginStartupCosts()) {
messageBus.setMessageDeliveryListener { topic, messageName, handler, duration ->
if (!StartUpMeasurer.isMeasuringPluginStartupCosts()) {
messageBus.setMessageDeliveryListener(null)
return@setMessageDeliveryListener
}
logMessageBusDelivery(topic, messageName, handler, duration)
}
}
registerServiceInstance(MessageBus::class.java, messageBus, fakeCorePluginDescriptor)
this.messageBus = messageBus
return messageBus
}
protected open fun logMessageBusDelivery(topic: Topic<*>, messageName: String, handler: Any, duration: Long) {
val loader = handler.javaClass.classLoader
val pluginId = if (loader is PluginAwareClassLoader) loader.pluginId.idString else PluginManagerCore.CORE_ID.idString
StartUpMeasurer.addPluginCost(pluginId, "MessageBus", duration)
}
/**
* Use only if approved by core team.
*/
fun registerComponent(key: Class<*>, implementation: Class<*>, pluginDescriptor: PluginDescriptor, override: Boolean) {
assertComponentsSupported()
checkState()
val adapter = MyComponentAdapter(key, implementation.name, pluginDescriptor, this, CompletableDeferred(), implementation)
if (override) {
overrideAdapter(adapter, pluginDescriptor)
componentAdapters.replace(adapter)
}
else {
registerAdapter(adapter, pluginDescriptor)
componentAdapters.add(adapter)
}
}
private fun overrideAdapter(adapter: ComponentAdapter, pluginDescriptor: PluginDescriptor) {
val componentKey = adapter.componentKey
if (componentKeyToAdapter.put(componentKey, adapter) == null) {
componentKeyToAdapter.remove(componentKey)
throw PluginException("Key $componentKey doesn't override anything", pluginDescriptor.pluginId)
}
}
/**
* Use only if approved by core team.
*/
fun registerService(
serviceInterface: Class<*>,
implementation: Class<*>,
pluginDescriptor: PluginDescriptor,
override: Boolean,
) {
checkState()
val descriptor = ServiceDescriptor(serviceInterface.name, implementation.name, null, null, false,
null, PreloadMode.FALSE, null, null)
val adapter = ServiceComponentAdapter(descriptor, pluginDescriptor, this, implementation)
if (override) {
overrideAdapter(adapter, pluginDescriptor)
}
else {
registerAdapter(adapter, pluginDescriptor)
}
serviceInstanceHotCache.remove(serviceInterface)
}
/**
* Use only if approved by core team.
*/
fun <T : Any> registerServiceInstance(serviceInterface: Class<T>, instance: T, pluginDescriptor: PluginDescriptor) {
val serviceKey = serviceInterface.name
checkState()
val descriptor = ServiceDescriptor(serviceKey, instance.javaClass.name, null, null, false,
null, PreloadMode.FALSE, null, null)
componentKeyToAdapter.put(serviceKey, ServiceComponentAdapter(descriptor = descriptor,
pluginDescriptor = pluginDescriptor,
componentManager = this,
implementationClass = instance.javaClass,
deferred = CompletableDeferred(value = instance)))
serviceInstanceHotCache.put(serviceInterface, instance)
}
@Suppress("DuplicatedCode")
@TestOnly
fun <T : Any> replaceServiceInstance(serviceInterface: Class<T>, instance: T, parentDisposable: Disposable) {
checkState()
if (isLightService(serviceInterface)) {
val adapter = LightServiceComponentAdapter(instance)
val key = adapter.componentKey
componentKeyToAdapter.put(key, adapter)
Disposer.register(parentDisposable) {
componentKeyToAdapter.remove(key)
serviceInstanceHotCache.remove(serviceInterface)
}
serviceInstanceHotCache.put(serviceInterface, instance)
}
else {
val key = serviceInterface.name
val oldAdapter = componentKeyToAdapter.get(key) as ServiceComponentAdapter
val newAdapter = ServiceComponentAdapter(descriptor = oldAdapter.descriptor,
pluginDescriptor = oldAdapter.pluginDescriptor,
componentManager = this,
implementationClass = oldAdapter.getImplementationClass(),
deferred = CompletableDeferred(value = instance))
componentKeyToAdapter.put(key, newAdapter)
serviceInstanceHotCache.put(serviceInterface, instance)
@Suppress("DuplicatedCode")
Disposer.register(parentDisposable) {
@Suppress("DEPRECATION")
if (instance is Disposable && !Disposer.isDisposed(instance)) {
Disposer.dispose(instance)
}
componentKeyToAdapter.put(key, oldAdapter)
serviceInstanceHotCache.remove(serviceInterface)
}
}
}
@TestOnly
fun unregisterService(serviceInterface: Class<*>) {
val key = serviceInterface.name
when (val adapter = componentKeyToAdapter.remove(key)) {
null -> error("Trying to unregister $key service which is not registered")
!is ServiceComponentAdapter -> error("$key service should be registered as a service, but was ${adapter::class.java}")
}
serviceInstanceHotCache.remove(serviceInterface)
}
@Suppress("DuplicatedCode")
fun <T : Any> replaceRegularServiceInstance(serviceInterface: Class<T>, instance: T) {
checkState()
val key = serviceInterface.name
val oldAdapter = componentKeyToAdapter.get(key) as ServiceComponentAdapter
val newAdapter = ServiceComponentAdapter(descriptor = oldAdapter.descriptor,
pluginDescriptor = oldAdapter.pluginDescriptor,
componentManager = this,
implementationClass = oldAdapter.getImplementationClass(),
deferred = CompletableDeferred(value = instance))
componentKeyToAdapter.put(key, newAdapter)
serviceInstanceHotCache.put(serviceInterface, instance)
(oldAdapter.getInitializedInstance() as? Disposable)?.let(Disposer::dispose)
serviceInstanceHotCache.put(serviceInterface, instance)
}
private fun <T : Any> createLightService(serviceClass: Class<T>): T {
val startTime = StartUpMeasurer.getCurrentTime()
val pluginId = (serviceClass.classLoader as? PluginAwareClassLoader)?.pluginId ?: PluginManagerCore.CORE_ID
val result = instantiateClass(serviceClass, pluginId)
if (result is Disposable) {
Disposer.register(serviceParentDisposable, result)
}
initializeComponent(result, null, pluginId)
StartUpMeasurer.addCompletedActivity(startTime, serviceClass, getActivityCategory(isExtension = false), pluginId.idString)
return result
}
final override fun <T : Any> loadClass(className: String, pluginDescriptor: PluginDescriptor): Class<T> {
@Suppress("UNCHECKED_CAST")
return doLoadClass(className, pluginDescriptor) as Class<T>
}
final override fun <T : Any> instantiateClass(aClass: Class<T>, pluginId: PluginId): T {
checkCanceledIfNotInClassInit()
try {
if (parent == null) {
@Suppress("UNCHECKED_CAST")
return MethodHandles.privateLookupIn(aClass, methodLookup).findConstructor(aClass, emptyConstructorMethodType).invoke() as T
}
else {
val constructors: Array<Constructor<*>> = aClass.declaredConstructors
var constructor = if (constructors.size > 1) {
// see ConfigurableEP - prefer constructor that accepts our instance
constructors.firstOrNull { it.parameterCount == 1 && it.parameterTypes[0].isAssignableFrom(javaClass) }
}
else {
null
}
if (constructor == null) {
constructors.sortBy { it.parameterCount }
constructor = constructors.first()
}
constructor.isAccessible = true
@Suppress("UNCHECKED_CAST")
if (constructor.parameterCount == 1) {
return constructor.newInstance(getActualContainerInstance()) as T
}
else {
@Suppress("UNCHECKED_CAST")
return MethodHandles.privateLookupIn(aClass, methodLookup).unreflectConstructor(constructor).invoke() as T
}
}
}
catch (e: Throwable) {
if (e is InvocationTargetException) {
val targetException = e.targetException
if (targetException is ControlFlowException) {
throw targetException
}
}
else if (e is ControlFlowException) {
throw e
}
throw PluginException("Cannot create class ${aClass.name} (classloader=${aClass.classLoader})", e, pluginId)
}
}
protected open fun getActualContainerInstance(): ComponentManager = this
final override fun <T : Any> instantiateClassWithConstructorInjection(aClass: Class<T>, key: Any, pluginId: PluginId): T {
return instantiateUsingPicoContainer(aClass, key, pluginId, this, constructorParameterResolver)
}
internal open val isGetComponentAdapterOfTypeCheckEnabled: Boolean
get() = true
final override fun <T : Any> instantiateClass(className: String, pluginDescriptor: PluginDescriptor): T {
val pluginId = pluginDescriptor.pluginId
try {
@Suppress("UNCHECKED_CAST")
return instantiateClass(doLoadClass(className, pluginDescriptor) as Class<T>, pluginId)
}
catch (e: Throwable) {
when {
e is PluginException || e is ExtensionNotApplicableException || e is ProcessCanceledException -> throw e
e.cause is NoSuchMethodException || e.cause is IllegalArgumentException -> {
throw PluginException("Class constructor must not have parameters: $className", e, pluginId)
}
else -> throw PluginException(e, pluginDescriptor.pluginId)
}
}
}
final override fun createListener(descriptor: ListenerDescriptor): Any {
val pluginDescriptor = descriptor.pluginDescriptor
val aClass = try {
doLoadClass(descriptor.listenerClassName, pluginDescriptor)
}
catch (e: Throwable) {
throw PluginException("Cannot create listener ${descriptor.listenerClassName}", e, pluginDescriptor.pluginId)
}
return instantiateClass(aClass, pluginDescriptor.pluginId)
}
final override fun logError(error: Throwable, pluginId: PluginId) {
if (error is ProcessCanceledException || error is ExtensionNotApplicableException) {
throw error
}
LOG.error(createPluginExceptionIfNeeded(error, pluginId))
}
final override fun createError(error: Throwable, pluginId: PluginId): RuntimeException {
return when (val effectiveError: Throwable = if (error is InvocationTargetException) error.targetException else error) {
is ProcessCanceledException, is ExtensionNotApplicableException, is PluginException -> effectiveError as RuntimeException
else -> PluginException(effectiveError, pluginId)
}
}
final override fun createError(message: String, pluginId: PluginId) = PluginException(message, pluginId)
final override fun createError(message: String,
error: Throwable?,
pluginId: PluginId,
attachments: MutableMap<String, String>?): RuntimeException {
return PluginException(message, error, pluginId, attachments?.map { Attachment(it.key, it.value) } ?: emptyList())
}
open fun unloadServices(services: List<ServiceDescriptor>, pluginId: PluginId) {
checkState()
if (!services.isEmpty()) {
val store = componentStore
for (service in services) {
val adapter = (componentKeyToAdapter.remove(service.`interface`) ?: continue) as ServiceComponentAdapter
val instance = adapter.getInitializedInstance() ?: continue
if (instance is Disposable) {
Disposer.dispose(instance)
}
store.unloadComponent(instance)
}
}
if (isLightServiceSupported) {
val store = componentStore
val iterator = componentKeyToAdapter.values.iterator()
while (iterator.hasNext()) {
val adapter = iterator.next() as? LightServiceComponentAdapter ?: continue
val instance = adapter.componentInstance
if ((instance.javaClass.classLoader as? PluginAwareClassLoader)?.pluginId == pluginId) {
if (instance is Disposable) {
Disposer.dispose(instance)
}
store.unloadComponent(instance)
iterator.remove()
}
}
}
serviceInstanceHotCache.clear()
}
open fun activityNamePrefix(): String? = null
fun preloadServices(modules: List<IdeaPluginDescriptorImpl>,
activityPrefix: String,
syncScope: CoroutineScope,
onlyIfAwait: Boolean = false) {
val asyncScope = coroutineScope!!
for (plugin in modules) {
for (service in getContainerDescriptor(plugin).services) {
if (!isServiceSuitable(service) || (service.os != null && !isSuitableForOs(service.os))) {
continue
}
val scope: CoroutineScope = when (service.preload) {
PreloadMode.TRUE -> if (onlyIfAwait) null else asyncScope
PreloadMode.NOT_HEADLESS -> if (onlyIfAwait || getApplication()!!.isHeadlessEnvironment) null else asyncScope
PreloadMode.NOT_LIGHT_EDIT -> if (onlyIfAwait || isLightEdit()) null else asyncScope
PreloadMode.AWAIT -> syncScope
PreloadMode.FALSE -> null
else -> throw IllegalStateException("Unknown preload mode ${service.preload}")
} ?: continue
if (isServicePreloadingCancelled) {
return
}
scope.launch {
val activity = StartUpMeasurer.startActivity("${service.`interface`} preloading")
val job = preloadService(service) ?: return@launch
if (scope === syncScope) {
job.join()
activity.end()
}
else {
job.invokeOnCompletion { activity.end() }
}
}
}
}
postPreloadServices(modules, activityPrefix, syncScope, onlyIfAwait)
}
protected open fun postPreloadServices(modules: List<IdeaPluginDescriptorImpl>,
activityPrefix: String,
syncScope: CoroutineScope,
onlyIfAwait: Boolean) {
}
@OptIn(ExperimentalCoroutinesApi::class)
protected open suspend fun preloadService(service: ServiceDescriptor): Job? {
val adapter = componentKeyToAdapter.get(service.getInterface()) as ServiceComponentAdapter? ?: return null
val deferred = adapter.getInstanceAsync<Any>(componentManager = this, keyClass = null)
if (deferred.isCompleted) {
val instance = deferred.getCompleted()
val implClass = instance.javaClass
// well, we don't know the interface class, so we cannot add any service to a hot cache
if (Modifier.isFinal(implClass.modifiers)) {
serviceInstanceHotCache.putIfAbsent(implClass, instance)
}
}
return deferred
}
override fun isDisposed(): Boolean {
return containerState.get() >= ContainerState.DISPOSE_IN_PROGRESS
}
final override fun beforeTreeDispose() {
stopServicePreloading()
ApplicationManager.getApplication().assertIsWriteThread()
if (!(containerState.compareAndSet(ContainerState.COMPONENT_CREATED, ContainerState.DISPOSE_IN_PROGRESS) ||
containerState.compareAndSet(ContainerState.PRE_INIT, ContainerState.DISPOSE_IN_PROGRESS))) {
// disposed in a recommended way using ProjectManager
return
}
// disposed directly using Disposer.dispose()
// we don't care that state DISPOSE_IN_PROGRESS is already set, and exceptions because of that are possible -
// use `ProjectManager` to close and dispose the project
startDispose()
}
fun startDispose() {
stopServicePreloading()
val messageBus = messageBus
runSuppressing(
{ Disposer.disposeChildren(this) { true } },
// There is a chance that someone will try to connect to the message bus and will get NPE because of disposed connection disposable,
// because the container state is not yet set to DISPOSE_IN_PROGRESS.
// So, 1) dispose connection children 2) set state DISPOSE_IN_PROGRESS 3) dispose connection
{ messageBus?.disposeConnectionChildren() },
{ containerState.set(ContainerState.DISPOSE_IN_PROGRESS) },
{ messageBus?.disposeConnection() }
)
}
override fun dispose() {
if (!containerState.compareAndSet(ContainerState.DISPOSE_IN_PROGRESS, ContainerState.DISPOSED)) {
throw IllegalStateException("Expected current state is DISPOSE_IN_PROGRESS, but actual state is ${containerState.get()} ($this)")
}
coroutineScope?.cancel("ComponentManagerImpl.dispose is called")
// dispose components and services
Disposer.dispose(serviceParentDisposable)
// release references to the service instances
componentKeyToAdapter.clear()
componentAdapters.clear()
serviceInstanceHotCache.clear()
messageBus?.let {
// Must be after disposing `serviceParentDisposable`, because message bus disposes child buses, so we must dispose all services first.
// For example, service ModuleManagerImpl disposes modules; each module, in turn, disposes module's message bus (child bus of application).
Disposer.dispose(it)
this.messageBus = null
}
if (!containerState.compareAndSet(ContainerState.DISPOSED, ContainerState.DISPOSE_COMPLETED)) {
throw IllegalStateException("Expected current state is DISPOSED, but actual state is ${containerState.get()} ($this)")
}
}
fun stopServicePreloading() {
isServicePreloadingCancelled = true
}
@Deprecated("Deprecated in Java")
@Suppress("DEPRECATION")
final override fun getComponent(name: String): BaseComponent? {
checkState()
for (componentAdapter in componentKeyToAdapter.values) {
if (componentAdapter is MyComponentAdapter) {
val instance = componentAdapter.getInitializedInstance()
if (instance is BaseComponent && name == instance.componentName) {
return instance
}
}
}
return null
}
fun <T : Any> getServiceByClassName(serviceClassName: String): T? {
checkState()
val adapter = componentKeyToAdapter.get(serviceClassName) as ServiceComponentAdapter?
return adapter?.getInstance(this, keyClass = null)
}
fun getServiceImplementation(key: Class<*>): Class<*>? {
checkState()
return (componentKeyToAdapter.get(key.name) as? ServiceComponentAdapter?)?.componentImplementation
}
open fun isServiceSuitable(descriptor: ServiceDescriptor): Boolean = descriptor.client == null
protected open fun isComponentSuitable(componentConfig: ComponentConfig): Boolean {
val options = componentConfig.options ?: return true
return !java.lang.Boolean.parseBoolean(options.get("internal")) || ApplicationManager.getApplication().isInternal
}
final override fun getDisposed(): Condition<*> = Condition<Any?> { isDisposed }
fun processComponentsAndServices(createIfNeeded: Boolean, filter: ((implClass: Class<*>) -> Boolean)? = null, processor: (Any) -> Unit) {
for (adapter in componentKeyToAdapter.values) {
if (adapter is BaseComponentAdapter) {
if (filter == null || filter(getImplClassSafe(adapter) ?: continue)) {
processor(adapter.getInstance(this, null, createIfNeeded = createIfNeeded) ?: continue)
}
}
else if (adapter is LightServiceComponentAdapter) {
val instance = adapter.componentInstance
if (filter == null || filter(instance::class.java)) {
processor(instance)
}
}
}
}
fun processAllImplementationClasses(processor: (componentClass: Class<*>, plugin: PluginDescriptor?) -> Unit) {
for (adapter in componentKeyToAdapter.values) {
if (adapter is ServiceComponentAdapter) {
processor(getImplClassSafe(adapter) ?: continue, adapter.pluginDescriptor)
}
else {
val pluginDescriptor = if (adapter is BaseComponentAdapter) adapter.pluginDescriptor else null
if (pluginDescriptor != null) {
val aClass = try {
adapter.componentImplementation
}
catch (e: Throwable) {
LOG.warn(e)
continue
}
processor(aClass, pluginDescriptor)
}
}
}
}
private fun getImplClassSafe(adapter: BaseComponentAdapter): Class<*>? {
return try {
adapter.getImplementationClass()
}
catch (e: PluginException) {
// well, the component is registered, but the required jar is not added to the classpath (community edition or junior IDE)
if (e.cause is ClassNotFoundException) {
LOG.warn(e.message)
}
else {
LOG.warn(e)
}
null
}
catch (e: CancellationException) {
throw e
}
catch (e: Throwable) {
LOG.warn(e)
null
}
}
internal fun getComponentAdapter(keyClass: Class<*>): ComponentAdapter? {
assertComponentsSupported()
val adapter = componentKeyToAdapter.get(keyClass) ?: componentKeyToAdapter.get(keyClass.name)
return if (adapter == null && parent != null) parent.getComponentAdapter(keyClass) else adapter
}
fun unregisterComponent(componentKey: Class<*>): ComponentAdapter? {
assertComponentsSupported()
val adapter = componentKeyToAdapter.remove(componentKey) ?: return null
componentAdapters.remove(adapter as MyComponentAdapter)
serviceInstanceHotCache.remove(componentKey)
return adapter
}
@TestOnly
fun registerComponentInstance(key: Class<*>, instance: Any) {
check(getApplication()!!.isUnitTestMode)
assertComponentsSupported()
val implClass = instance::class.java
val newAdapter = MyComponentAdapter(componentKey = key,
implementationClassName = implClass.name,
pluginDescriptor = fakeCorePluginDescriptor,
componentManager = this,
deferred = CompletableDeferred(value = instance),
implementationClass = implClass)
if (componentKeyToAdapter.putIfAbsent(newAdapter.componentKey, newAdapter) != null) {
throw IllegalStateException("Key ${newAdapter.componentKey} duplicated")
}
componentAdapters.add(newAdapter)
}
private fun assertComponentsSupported() {
if (!isComponentSupported) {
error("components aren't support")
}
}
// project level extension requires Project as constructor argument, so, for now, constructor injection is disabled only for app level
final override fun isInjectionForExtensionSupported() = parent != null
internal fun getComponentAdapterOfType(componentType: Class<*>): ComponentAdapter? {
componentKeyToAdapter.get(componentType)?.let {
return it
}
for (adapter in componentAdapters.getImmutableSet()) {
val descendant = adapter.componentImplementation
if (componentType === descendant || componentType.isAssignableFrom(descendant)) {
return adapter
}
}
return null
}
fun <T : Any> processInitializedComponents(aClass: Class<T>, processor: (T) -> Unit) {
// we must use instances only from our adapter (could be service or something else).
for (adapter in componentAdapters.getImmutableSet()) {
val component = adapter.getInitializedInstance()
if (component != null && aClass.isAssignableFrom(component.javaClass)) {
@Suppress("UNCHECKED_CAST")
processor(component as T)
}
}
}
fun <T : Any> collectInitializedComponents(aClass: Class<T>): List<T> {
// we must use instances only from our adapter (could be service or something else).
val result = mutableListOf<T>()
for (adapter in componentAdapters.getImmutableSet()) {
val component = adapter.getInitializedInstance()
if (component != null && aClass.isAssignableFrom(component.javaClass)) {
@Suppress("UNCHECKED_CAST")
result.add(component as T)
}
}
return result
}
final override fun getActivityCategory(isExtension: Boolean): ActivityCategory {
return when {
parent == null -> if (isExtension) ActivityCategory.APP_EXTENSION else ActivityCategory.APP_SERVICE
parent.parent == null -> if (isExtension) ActivityCategory.PROJECT_EXTENSION else ActivityCategory.PROJECT_SERVICE
else -> if (isExtension) ActivityCategory.MODULE_EXTENSION else ActivityCategory.MODULE_SERVICE
}
}
final override fun hasComponent(componentKey: Class<*>): Boolean {
val adapter = componentKeyToAdapter.get(componentKey) ?: componentKeyToAdapter.get(componentKey.name)
return adapter != null || (parent != null && parent.hasComponent(componentKey))
}
final override fun isSuitableForOs(os: ExtensionDescriptor.Os): Boolean {
return when (os) {
ExtensionDescriptor.Os.mac -> SystemInfoRt.isMac
ExtensionDescriptor.Os.linux -> SystemInfoRt.isLinux
ExtensionDescriptor.Os.windows -> SystemInfoRt.isWindows
ExtensionDescriptor.Os.unix -> SystemInfoRt.isUnix
ExtensionDescriptor.Os.freebsd -> SystemInfoRt.isFreeBSD
else -> throw IllegalArgumentException("Unknown OS '$os'")
}
}
}
/**
* A copy-on-write linked hash set.
*/
private class LinkedHashSetWrapper<T : Any> {
private val lock = Any()
@Volatile
private var immutableSet: Set<T>? = null
private var synchronizedSet = LinkedHashSet<T>()
fun add(element: T) {
synchronized(lock) {
if (!synchronizedSet.contains(element)) {
copySyncSetIfExposedAsImmutable().add(element)
}
}
}
fun remove(element: T) {
synchronized(lock) { copySyncSetIfExposedAsImmutable().remove(element) }
}
fun replace(old: T, new: T) {
synchronized(lock) {
val set = copySyncSetIfExposedAsImmutable()
set.remove(old)
set.add(new)
}
}
private fun copySyncSetIfExposedAsImmutable(): LinkedHashSet<T> {
if (immutableSet != null) {
immutableSet = null
synchronizedSet = LinkedHashSet(synchronizedSet)
}
return synchronizedSet
}
fun replace(element: T) {
synchronized(lock) {
val set = copySyncSetIfExposedAsImmutable()
set.remove(element)
set.add(element)
}
}
fun clear() {
synchronized(lock) {
immutableSet = null
synchronizedSet = LinkedHashSet()
}
}
fun getImmutableSet(): Set<T> {
var result = immutableSet
if (result == null) {
synchronized(lock) {
result = immutableSet
if (result == null) {
// Expose the same set as immutable. It should never be modified again. Next add/remove operations will copy synchronizedSet
result = Collections.unmodifiableSet(synchronizedSet)
immutableSet = result
}
}
}
return result!!
}
}
private fun createPluginExceptionIfNeeded(error: Throwable, pluginId: PluginId): RuntimeException {
return if (error is PluginException) error else PluginException(error, pluginId)
}
fun handleComponentError(t: Throwable, componentClassName: String?, pluginId: PluginId?) {
if (t is StartupAbortedException) {
throw t
}
val app = ApplicationManager.getApplication()
if (app != null && app.isUnitTestMode) {
throw t
}
var effectivePluginId = pluginId
if (effectivePluginId == null || PluginManagerCore.CORE_ID == effectivePluginId) {
if (componentClassName != null) {
effectivePluginId = PluginManager.getPluginByClassNameAsNoAccessToClass(componentClassName)
}
}
if (effectivePluginId != null && PluginManagerCore.CORE_ID != effectivePluginId) {
throw StartupAbortedException("Fatal error initializing plugin $effectivePluginId", PluginException(t, effectivePluginId))
}
else {
throw StartupAbortedException("Fatal error initializing '$componentClassName'", t)
}
}
private fun doLoadClass(name: String, pluginDescriptor: PluginDescriptor): Class<*> {
// maybe null in unit tests
val classLoader = pluginDescriptor.pluginClassLoader ?: ComponentManagerImpl::class.java.classLoader
if (classLoader is PluginAwareClassLoader) {
return classLoader.tryLoadingClass(name, true) ?: throw ClassNotFoundException("$name $classLoader")
}
else {
return classLoader.loadClass(name)
}
}
private class LightServiceComponentAdapter(private val initializedInstance: Any) : ComponentAdapter {
override fun getComponentKey(): String = initializedInstance.javaClass.name
override fun getComponentImplementation() = initializedInstance.javaClass
override fun getComponentInstance() = initializedInstance
override fun toString() = componentKey
}
private inline fun executeRegisterTask(mainPluginDescriptor: IdeaPluginDescriptorImpl,
crossinline task: (IdeaPluginDescriptorImpl) -> Unit) {
task(mainPluginDescriptor)
executeRegisterTaskForOldContent(mainPluginDescriptor, task)
}
| apache-2.0 | e318e90f0c152e9cd119a9d6d688dc3e | 37.706796 | 215 | 0.692903 | 5.209233 | false | false | false | false |
apollographql/apollo-android | apollo-compiler/src/main/kotlin/com/apollographql/apollo3/compiler/codegen/kotlin/file/OperationBuilder.kt | 1 | 7331 | package com.apollographql.apollo3.compiler.codegen.kotlin.file
import com.apollographql.apollo3.api.QueryDocumentMinifier
import com.apollographql.apollo3.compiler.applyIf
import com.apollographql.apollo3.compiler.codegen.Identifier.OPERATION_DOCUMENT
import com.apollographql.apollo3.compiler.codegen.Identifier.OPERATION_ID
import com.apollographql.apollo3.compiler.codegen.Identifier.OPERATION_NAME
import com.apollographql.apollo3.compiler.codegen.Identifier.document
import com.apollographql.apollo3.compiler.codegen.Identifier.id
import com.apollographql.apollo3.compiler.codegen.Identifier.name
import com.apollographql.apollo3.compiler.codegen.kotlin.CgFile
import com.apollographql.apollo3.compiler.codegen.kotlin.CgOutputFileBuilder
import com.apollographql.apollo3.compiler.codegen.kotlin.KotlinSymbols
import com.apollographql.apollo3.compiler.codegen.kotlin.KotlinContext
import com.apollographql.apollo3.compiler.codegen.kotlin.helpers.makeDataClass
import com.apollographql.apollo3.compiler.codegen.kotlin.helpers.maybeAddDescription
import com.apollographql.apollo3.compiler.codegen.kotlin.helpers.toNamedType
import com.apollographql.apollo3.compiler.codegen.kotlin.helpers.toParameterSpec
import com.apollographql.apollo3.compiler.codegen.kotlin.model.ModelBuilder
import com.apollographql.apollo3.compiler.codegen.maybeFlatten
import com.apollographql.apollo3.compiler.ir.IrOperation
import com.apollographql.apollo3.compiler.ir.IrOperationType
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.FunSpec
import com.squareup.kotlinpoet.KModifier
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.kotlinpoet.PropertySpec
import com.squareup.kotlinpoet.TypeName
import com.squareup.kotlinpoet.TypeSpec
class OperationBuilder(
private val context: KotlinContext,
private val generateFilterNotNull: Boolean,
private val operationId: String,
private val generateQueryDocument: Boolean,
private val operation: IrOperation,
flatten: Boolean,
) : CgOutputFileBuilder {
private val layout = context.layout
private val packageName = layout.operationPackageName(operation.filePath)
private val simpleName = layout.operationName(operation)
private val dataSuperClassName = when (operation.operationType) {
IrOperationType.Query -> KotlinSymbols.QueryData
IrOperationType.Mutation -> KotlinSymbols.MutationData
IrOperationType.Subscription -> KotlinSymbols.SubscriptionData
}
private val modelBuilders = operation.dataModelGroup.maybeFlatten(flatten).flatMap {
it.models
}.map {
ModelBuilder(
context = context,
model = it,
superClassName = if (it.id == operation.dataModelGroup.baseModelId) dataSuperClassName else null,
path = listOf(packageName, simpleName),
hasSubclassesInSamePackage = true,
)
}
override fun prepare() {
context.resolver.registerOperation(
operation.name,
ClassName(packageName, simpleName)
)
modelBuilders.forEach { it.prepare() }
}
override fun build(): CgFile {
return CgFile(
packageName = packageName,
fileName = simpleName,
typeSpecs = listOf(typeSpec())
)
}
fun typeSpec(): TypeSpec {
return TypeSpec.classBuilder(layout.operationName(operation))
.addSuperinterface(superInterfaceType())
.maybeAddDescription(operation.description)
.makeDataClass(operation.variables.map { it.toNamedType().toParameterSpec(context) })
.addFunction(operationIdFunSpec())
.addFunction(queryDocumentFunSpec(generateQueryDocument))
.addFunction(nameFunSpec())
.addFunction(serializeVariablesFunSpec())
.addFunction(adapterFunSpec())
.addFunction(rootFieldFunSpec())
.addTypes(dataTypeSpecs())
.addType(companionTypeSpec())
.build()
.maybeAddFilterNotNull(generateFilterNotNull)
}
private fun serializeVariablesFunSpec(): FunSpec = serializeVariablesFunSpec(
adapterClassName = context.resolver.resolveOperationVariablesAdapter(operation.name),
emptyMessage = "This operation doesn't have any variable"
)
private fun adapterFunSpec(): FunSpec {
return adapterFunSpec(
adapterTypeName = context.resolver.resolveModelAdapter(operation.dataModelGroup.baseModelId),
adaptedTypeName = context.resolver.resolveModel(operation.dataModelGroup.baseModelId)
)
}
private fun dataTypeSpecs(): List<TypeSpec> {
return modelBuilders.map {
it.build()
}
}
private fun superInterfaceType(): TypeName {
return when (operation.operationType) {
IrOperationType.Query -> KotlinSymbols.Query
IrOperationType.Mutation -> KotlinSymbols.Mutation
IrOperationType.Subscription -> KotlinSymbols.Subscription
}.parameterizedBy(
context.resolver.resolveModel(operation.dataModelGroup.baseModelId)
)
}
private fun operationIdFunSpec() = FunSpec.builder(id)
.addModifiers(KModifier.OVERRIDE)
.returns(KotlinSymbols.String)
.addStatement("return $OPERATION_ID")
.build()
private fun queryDocumentFunSpec(generateQueryDocument: Boolean) = FunSpec.builder(document)
.addModifiers(KModifier.OVERRIDE)
.returns(KotlinSymbols.String)
.apply {
if (generateQueryDocument) {
addStatement("return $OPERATION_DOCUMENT")
} else {
addStatement("error(\"The·query·document·was·removed·from·this·operation.·Use·generateQueryDocument.set(true)·if·you·need·it\")")
}
}
.build()
private fun nameFunSpec() = FunSpec.builder(name)
.addModifiers(KModifier.OVERRIDE)
.returns(KotlinSymbols.String)
.addStatement("return OPERATION_NAME")
.build()
private fun companionTypeSpec(): TypeSpec {
return TypeSpec.companionObjectBuilder()
.addProperty(PropertySpec.builder(OPERATION_ID, KotlinSymbols.String)
.addModifiers(KModifier.CONST)
.initializer("%S", operationId)
.build()
)
.applyIf(generateQueryDocument) {
addProperty(PropertySpec.builder(OPERATION_DOCUMENT, KotlinSymbols.String)
.addModifiers(KModifier.CONST)
.initializer("%S", QueryDocumentMinifier.minify(operation.sourceWithFragments))
.addKdoc("%L", """
The minimized GraphQL document being sent to the server to save a few bytes.
The un-minimized version is:
""".trimIndent() + operation.sourceWithFragments.escapeKdoc()
)
.build()
)
}
.addProperty(PropertySpec
.builder(OPERATION_NAME, KotlinSymbols.String)
.addModifiers(KModifier.CONST)
.initializer("%S", operation.name)
.build()
)
.build()
}
/**
* Things like `[${'$'}oo]` do not compile. See https://youtrack.jetbrains.com/issue/KT-43906
*/
private fun String.escapeKdoc(): String {
return replace("[", "\\[").replace("]", "\\]")
}
private fun rootFieldFunSpec(): FunSpec {
return rootFieldFunSpec(
context,
operation.typeCondition,
context.resolver.resolveOperationSelections(operation.name)
)
}
}
| mit | 95cd29a7f3fa74585402ecb223334eae | 37.314136 | 139 | 0.727385 | 4.694035 | false | false | false | false |
exercism/xkotlin | exercises/practice/diamond/.meta/src/reference/kotlin/DiamondPrinter.kt | 1 | 936 | import java.util.*
class DiamondPrinter {
companion object {
private const val A_INT = 'A'.code
private fun blank(length: Int): String {
return Collections.nCopies(length, " ").joinToString("")
}
}
fun printToList(chr: Char): List<String> {
val nRows = 2 * (chr.code - A_INT) + 1
val result = mutableListOf<String>()
// Populate the top rows.
for (nRow in 0 until (nRows + 1) / 2) {
val rowChr = (A_INT + nRow).toChar()
val leftHalfOfRow = blank((nRows - 1) / 2 - nRow) + rowChr + blank(nRow)
val rightHalfOfRow = leftHalfOfRow.reversed().drop(1)
val fullRow = "$leftHalfOfRow$rightHalfOfRow"
result.add(fullRow)
}
// Populate the bottom rows by 'reflecting' all rows above the middle row.
result.addAll(result.reversed().drop(1))
return result
}
}
| mit | 2b1077e1d2337038623a42ff079c0df0 | 25.742857 | 84 | 0.566239 | 3.774194 | false | false | false | false |
allotria/intellij-community | platform/vcs-code-review/src/com/intellij/util/ui/codereview/timeline/TimelineComponent.kt | 2 | 2145 | // 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.util.ui.codereview.timeline
import com.intellij.ide.plugins.newui.VerticalLayout
import com.intellij.ui.scale.JBUIScale
import java.awt.Component
import javax.swing.JComponent
import javax.swing.JPanel
import javax.swing.ListModel
import javax.swing.event.ListDataEvent
import javax.swing.event.ListDataListener
open class TimelineComponent<in T : TimelineItem>(
private val model: ListModel<T>,
protected val itemComponentFactory: TimelineItemComponentFactory<T>,
private val title: JComponent? = null,
offset: Int = JBUIScale.scale(20)
) : JPanel(VerticalLayout(offset)) {
init {
isOpaque = false
model.addListDataListener(object : ListDataListener {
override fun intervalRemoved(e: ListDataEvent) {
for (i in e.index1 downTo e.index0) {
remove(i.viewIndex())
}
revalidate()
repaint()
}
override fun intervalAdded(e: ListDataEvent) {
for (i in e.index0..e.index1) {
add(itemComponentFactory.createComponent(model.getElementAt(i)), VerticalLayout.FILL_HORIZONTAL, i.viewIndex())
}
revalidate()
repaint()
}
override fun contentsChanged(e: ListDataEvent) {
for (i in e.index1 downTo e.index0) {
remove(i.viewIndex())
}
for (i in e.index0..e.index1) {
add(itemComponentFactory.createComponent(model.getElementAt(i)), VerticalLayout.FILL_HORIZONTAL, i.viewIndex())
}
validate()
repaint()
}
})
if (title != null) {
add(title, VerticalLayout.FILL_HORIZONTAL, 0)
}
for (i in 0 until model.size) {
add(itemComponentFactory.createComponent(model.getElementAt(i)), VerticalLayout.FILL_HORIZONTAL, i.viewIndex())
}
}
private fun Int.viewIndex() =
if (title != null) {
this + 1
}
else {
this
}
final override fun add(comp: Component?, constraints: Any?, index: Int) {
super.add(comp, constraints, index)
}
} | apache-2.0 | 41b511cb35df6f19ed06a09c208576b2 | 29.225352 | 140 | 0.668998 | 4.117083 | false | false | false | false |
Raizlabs/DBFlow | processor/src/test/java/com/raizlabs/dbflow5/processor/test/ForeignKeyAccessCombinerTests.kt | 1 | 9096 | package com.dbflow5.processor.test
import com.dbflow5.processor.definition.column.Combiner
import com.dbflow5.processor.definition.column.ContentValuesCombiner
import com.dbflow5.processor.definition.column.ForeignKeyAccessCombiner
import com.dbflow5.processor.definition.column.ForeignKeyAccessField
import com.dbflow5.processor.definition.column.ForeignKeyLoadFromCursorCombiner
import com.dbflow5.processor.definition.column.PackagePrivateScopeColumnAccessor
import com.dbflow5.processor.definition.column.PartialLoadFromCursorAccessCombiner
import com.dbflow5.processor.definition.column.PrimaryReferenceAccessCombiner
import com.dbflow5.processor.definition.column.PrivateScopeColumnAccessor
import com.dbflow5.processor.definition.column.SqliteStatementAccessCombiner
import com.dbflow5.processor.definition.column.TypeConverterScopeColumnAccessor
import com.dbflow5.processor.definition.column.VisibleScopeColumnAccessor
import com.squareup.javapoet.ClassName
import com.squareup.javapoet.CodeBlock
import com.squareup.javapoet.NameAllocator
import com.squareup.javapoet.TypeName
import org.junit.Assert.assertEquals
import org.junit.Test
import java.util.*
import java.util.concurrent.atomic.AtomicInteger
/**
* Description:
*
* @author Andrew Grosner (fuzz)
*/
class ForeignKeyAccessCombinerTest {
@Test
fun test_canCombineSimpleCase() {
val foreignKeyAccessCombiner = ForeignKeyAccessCombiner(VisibleScopeColumnAccessor("name"))
foreignKeyAccessCombiner.fieldAccesses += ForeignKeyAccessField("test",
ContentValuesCombiner(Combiner(VisibleScopeColumnAccessor("test"), TypeName.get(String::class.java))))
foreignKeyAccessCombiner.fieldAccesses += ForeignKeyAccessField("test2",
ContentValuesCombiner(Combiner(PrivateScopeColumnAccessor("test2"), TypeName.get(Int::class.java))))
val builder = CodeBlock.builder()
foreignKeyAccessCombiner.addCode(builder, AtomicInteger(4))
assertEquals("if (model.name != null) {" +
"\n values.put(\"`test`\", model.name.test);" +
"\n values.put(\"`test2`\", model.name.getTest2());" +
"\n} else {" +
"\n values.putNull(\"`test`\");" +
"\n values.putNull(\"`test2`\");" +
"\n}",
builder.build().toString().trim())
}
@Test
fun test_canCombineSimplePrivateCase() {
val foreignKeyAccessCombiner = ForeignKeyAccessCombiner(PrivateScopeColumnAccessor("name"))
foreignKeyAccessCombiner.fieldAccesses += ForeignKeyAccessField("",
SqliteStatementAccessCombiner(Combiner(VisibleScopeColumnAccessor("test"), TypeName.get(String::class.java))))
val builder = CodeBlock.builder()
foreignKeyAccessCombiner.addCode(builder, AtomicInteger(4))
assertEquals("if (model.getName() != null) {" +
"\n statement.bindStringOrNull(4, model.getName().test);" +
"\n} else {" +
"\n statement.bindNull(4);" +
"\n}",
builder.build().toString().trim())
}
@Test
fun test_canCombinePackagePrivateCase() {
val foreignKeyAccessCombiner = ForeignKeyAccessCombiner(PackagePrivateScopeColumnAccessor("name",
"com.fuzz.android", "TestHelper"))
foreignKeyAccessCombiner.fieldAccesses += ForeignKeyAccessField("test",
PrimaryReferenceAccessCombiner(Combiner(PackagePrivateScopeColumnAccessor("test",
"com.fuzz.android", "TestHelper2"),
TypeName.get(String::class.java))))
val builder = CodeBlock.builder()
foreignKeyAccessCombiner.addCode(builder, AtomicInteger(4))
assertEquals("if (com.fuzz.android.TestHelper_Helper.getName(model) != null) {" +
"\n clause.and(test.eq(com.fuzz.android.TestHelper2_Helper.getTest(com.fuzz.android.TestHelper_Helper.getName(model))));" +
"\n} else {" +
"\n clause.and(test.eq((com.dbflow5.sql.language.IConditional) null));" +
"\n}",
builder.build().toString().trim())
}
@Test
fun test_canDoComplexCase() {
val foreignKeyAccessCombiner = ForeignKeyAccessCombiner(VisibleScopeColumnAccessor("modem"))
foreignKeyAccessCombiner.fieldAccesses += ForeignKeyAccessField("number",
ContentValuesCombiner(Combiner(PackagePrivateScopeColumnAccessor("number",
"com.fuzz", "AnotherHelper"),
TypeName.INT)))
foreignKeyAccessCombiner.fieldAccesses += ForeignKeyAccessField("date",
ContentValuesCombiner(Combiner(TypeConverterScopeColumnAccessor("global_converter", "date"),
TypeName.get(Date::class.java))))
val builder = CodeBlock.builder()
foreignKeyAccessCombiner.addCode(builder, AtomicInteger(1))
assertEquals("if (model.modem != null) {" +
"\n values.put(\"`number`\", com.fuzz.AnotherHelper\$Helper.getNumber(model.modem));" +
"\n values.put(\"`date`\", global_converter.getDBValue(model.modem.date));" +
"\n} else {" +
"\n values.putNull(\"`number`\");" +
"\n values.putNull(\"`date`\");" +
"\n}",
builder.build().toString().trim())
}
@Test
fun test_canLoadFromCursor() {
val foreignKeyAccessCombiner = ForeignKeyLoadFromCursorCombiner(VisibleScopeColumnAccessor("testModel1"),
ClassName.get("com.dbflow5.test.container", "ParentModel"),
ClassName.get("com.dbflow5.test.container", "ParentModel_Table"), false,
NameAllocator())
foreignKeyAccessCombiner.fieldAccesses += PartialLoadFromCursorAccessCombiner("testmodel_id",
"name", TypeName.get(String::class.java), false, null)
foreignKeyAccessCombiner.fieldAccesses += PartialLoadFromCursorAccessCombiner("testmodel_type",
"type", TypeName.get(String::class.java), false, null)
val builder = CodeBlock.builder()
foreignKeyAccessCombiner.addCode(builder, AtomicInteger(0))
assertEquals("int index_testmodel_id_ParentModel_Table = cursor.getColumnIndex(\"testmodel_id\");" +
"\nint index_testmodel_type_ParentModel_Table = cursor.getColumnIndex(\"testmodel_type\");" +
"\nif (index_testmodel_id_ParentModel_Table != -1 && !cursor.isNull(index_testmodel_id_ParentModel_Table) && index_testmodel_type_ParentModel_Table != -1 && !cursor.isNull(index_testmodel_type_ParentModel_Table)) {" +
"\n model.testModel1 = com.dbflow5.sql.language.SQLite.select().from(com.dbflow5.test.container.ParentModel.class).where()" +
"\n .and(com.dbflow5.test.container.ParentModel_Table.name.eq(cursor.getString(index_testmodel_id_ParentModel_Table)))" +
"\n .and(com.dbflow5.test.container.ParentModel_Table.type.eq(cursor.getString(index_testmodel_type_ParentModel_Table)))" +
"\n .querySingle();" +
"\n} else {" +
"\n model.testModel1 = null;" +
"\n}", builder.build().toString().trim())
}
@Test
fun test_canLoadFromCursorStubbed() {
val foreignKeyAccessCombiner = ForeignKeyLoadFromCursorCombiner(VisibleScopeColumnAccessor("testModel1"),
ClassName.get("com.dbflow5.test.container", "ParentModel"),
ClassName.get("com.dbflow5.test.container", "ParentModel_Table"), true,
NameAllocator())
foreignKeyAccessCombiner.fieldAccesses += PartialLoadFromCursorAccessCombiner("testmodel_id",
"name", TypeName.get(String::class.java), false, VisibleScopeColumnAccessor("name"))
foreignKeyAccessCombiner.fieldAccesses += PartialLoadFromCursorAccessCombiner("testmodel_type",
"type", TypeName.get(String::class.java), false, VisibleScopeColumnAccessor("type"))
val builder = CodeBlock.builder()
foreignKeyAccessCombiner.addCode(builder, AtomicInteger(0))
assertEquals("int index_testmodel_id_ParentModel_Table = cursor.getColumnIndex(\"testmodel_id\");" +
"\nint index_testmodel_type_ParentModel_Table = cursor.getColumnIndex(\"testmodel_type\");" +
"\nif (index_testmodel_id_ParentModel_Table != -1 && !cursor.isNull(index_testmodel_id_ParentModel_Table) && index_testmodel_type_ParentModel_Table != -1 && !cursor.isNull(index_testmodel_type_ParentModel_Table)) {" +
"\n model.testModel1 = new com.dbflow5.test.container.ParentModel();" +
"\n model.testModel1.name = cursor.getString(index_testmodel_id_ParentModel_Table);" +
"\n model.testModel1.type = cursor.getString(index_testmodel_type_ParentModel_Table);" +
"\n} else {" +
"\n model.testModel1 = null;" +
"\n}", builder.build().toString().trim())
}
} | mit | 87ace866a9b58140a5e9279598c364c8 | 54.133333 | 233 | 0.663369 | 4.871987 | false | true | false | false |
walkingice/MomoDict | app/src/main/java/org/zeroxlab/momodict/widget/BookRowPresenter.kt | 1 | 2695 | package org.zeroxlab.momodict.widget
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import org.zeroxlab.momodict.R
import org.zeroxlab.momodict.model.Book
class BookRowPresenter(listener: View.OnClickListener) : SelectorAdapter.Presenter<Book> {
val rmListener = listener
override fun onCreateViewHolder(parent: ViewGroup): androidx.recyclerview.widget.RecyclerView.ViewHolder {
val inflater = LayoutInflater.from(parent.context)
val group = inflater.inflate(R.layout.list_item_expandable, parent, false) as ViewGroup
val bookDetails = inflater.inflate(R.layout.book_detail, group, false) as ViewGroup
val holder = InnerViewHolder(group, bookDetails)
group.setOnClickListener({ v -> toggleExpand(holder) })
return holder
}
override fun onBindViewHolder(viewHolder: androidx.recyclerview.widget.RecyclerView.ViewHolder, item: Book) {
val holder = viewHolder as InnerViewHolder
holder.titleText.text = item.bookName
holder.arrowIcon.setImageLevel(IMG_LEVEL_UP)
holder.description.text = """
|Author: ${item.author}
|Words: ${item.wordCount}
|Date: ${item.date}
|Description: ${item.description}
""".trimMargin()
holder.rmBtn.setOnClickListener({ v ->
v.tag = item
rmListener.onClick(v)
})
}
override fun onUnbindViewHolder(viewHolder: androidx.recyclerview.widget.RecyclerView.ViewHolder) {}
private fun toggleExpand(holder: InnerViewHolder) {
val drawable = holder.arrowIcon.drawable
drawable.level = if (drawable.level == IMG_LEVEL_UP) IMG_LEVEL_DOWN else IMG_LEVEL_UP
holder.details.visibility = if (drawable.level == IMG_LEVEL_UP) View.GONE else View.VISIBLE
}
internal inner class InnerViewHolder(view: View, bookDetails: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(view) {
val titleText: TextView = view.findViewById(R.id.text_1) as TextView
val arrowIcon: ImageView = view.findViewById(R.id.img_1) as ImageView
val details: ViewGroup = view.findViewById(R.id.expand_details) as ViewGroup
val rmBtn: View = bookDetails.findViewById(R.id.btn_2)
val description: TextView = bookDetails.findViewById(R.id.text_2) as TextView
init {
details.addView(bookDetails)
}
}
companion object {
val IMG_LEVEL_DOWN = 1
val IMG_LEVEL_LEFT = 2
val IMG_LEVEL_UP = 3
}
}
| mit | 001df027129d3c9fe4913e6c3a1751ed | 39.223881 | 134 | 0.690538 | 4.346774 | false | false | false | false |
zdary/intellij-community | platform/platform-impl/src/com/intellij/ui/ToolbarActionTracker.kt | 1 | 4360 | // 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.ui
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.Presentation
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.registry.Registry
import com.intellij.ui.scale.JBUIScale
import java.awt.Component
import java.awt.Point
import java.awt.event.ComponentAdapter
import java.awt.event.ComponentEvent
import javax.swing.JComponent
import javax.swing.event.AncestorEvent
import org.jetbrains.annotations.ApiStatus.Experimental
import java.util.function.Consumer
@Experimental
abstract class ToolbarActionTracker: Disposable {
private var pointProvider: ((Component) -> Point)? = null
/**
* pointProvider - point in toolbar coordinates
*/
class ActionContext(val tracker: ToolbarActionTracker, val pointProvider: (Component) -> Point)
inner class MyComponentAdapter : ComponentAdapter() {
override fun componentMoved(event: ComponentEvent) {
hideOrRepaint(event.component as JComponent)
}
override fun componentResized(event: ComponentEvent) {
if (!wasCreated() && !event.component.bounds.isEmpty && event.component.isShowing && pointProvider != null) {
init(event.component as JComponent, pointProvider!!)
}
else {
hideOrRepaint(event.component as JComponent)
}
}
}
inner class MyAncestorAdapter(val component: JComponent) : AncestorListenerAdapter() {
override fun ancestorRemoved(event: AncestorEvent) {
hideOrRepaint(component)
hidePopup()
}
override fun ancestorMoved(event: AncestorEvent?) {
hideOrRepaint(component)
}
}
private val componentAdapter = MyComponentAdapter()
private var ancestorListener : MyAncestorAdapter? = null
protected fun followToolbarComponent(component: JComponent, toolbar: JComponent, pointProvider: (Component) -> Point) {
if (canShow()) {
this.pointProvider = pointProvider
component.addComponentListener(componentAdapter.also { Disposer.register(this, Disposable { component.removeComponentListener(it) }) })
ancestorListener = MyAncestorAdapter(component)
toolbar.addAncestorListener(ancestorListener.also{ Disposer.register(this, Disposable { component.removeAncestorListener(it) }) })
}
}
protected fun unfollowComponent(component: JComponent){
component.removeComponentListener(componentAdapter)
component.removeAncestorListener(ancestorListener)
}
/**
* Bind the tooltip to action's presentation. Then <code>ActionToolbar</code> starts following ActionButton with
* the tooltip if it can be shown. Term "follow" is used because ActionToolbar updates its content and ActionButton's
* showing status / location may change in time.
*/
abstract fun assignTo(presentation: Presentation, pointProvider: (Component) -> Point, disposeAction: Runnable? = null)
abstract fun wasCreated(): Boolean
abstract fun hidePopup()
abstract fun init(component: JComponent, pointProvider: (Component) -> Point)
abstract fun createAndShow(component: JComponent, pointProvider: (Component) -> Point): Any
abstract fun hideOrRepaint(component: JComponent)
abstract fun canShow(): Boolean
abstract fun show(component: JComponent, pointProvider: (Component) -> Point)
companion object {
const val PROPERTY_PREFIX = "toolbar.tracker"
val PRESENTATION_GOT_IT_KEY = Key<ActionContext>("${PROPERTY_PREFIX}.gotit.presentation")
val PRESENTATION_POPUP_KEY = Key<ActionContext>("${PROPERTY_PREFIX}.popup.presentation")
@JvmField
val ARROW_SHIFT = JBUIScale.scale(20) + Registry.intValue("ide.balloon.shadow.size") + BalloonImpl.ARC.get()
/**
* Use this method for following an ActionToolbar component.
*/
@JvmStatic
fun followToolbarComponent(presentation: Presentation, component: JComponent, toolbar: JComponent) {
presentation.getClientProperty(PRESENTATION_GOT_IT_KEY)?.let {
it.tracker.followToolbarComponent(component, toolbar, it.pointProvider)
}
presentation.getClientProperty(PRESENTATION_POPUP_KEY)?.let {
it.tracker.followToolbarComponent(component, toolbar, it.pointProvider)
}
}
}
} | apache-2.0 | 4018cf2aac15b28de19368b539f9f2e0 | 37.254386 | 141 | 0.750688 | 4.623542 | false | false | false | false |
leafclick/intellij-community | platform/diff-impl/tests/testSrc/com/intellij/diff/merge/MergeTestBase.kt | 1 | 14993 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.diff.merge
import com.intellij.diff.DiffContentFactoryImpl
import com.intellij.diff.HeavyDiffTestCase
import com.intellij.diff.contents.DocumentContent
import com.intellij.diff.merge.MergeTestBase.SidesState.*
import com.intellij.diff.merge.TextMergeViewer.MyThreesideViewer
import com.intellij.diff.tools.util.base.IgnorePolicy
import com.intellij.diff.tools.util.base.TextDiffSettingsHolder.TextDiffSettings
import com.intellij.diff.util.*
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.command.undo.UndoManager
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.fileEditor.impl.text.TextEditorProvider
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Couple
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.ui.UIUtil
abstract class MergeTestBase : HeavyDiffTestCase() {
fun test1(left: String, base: String, right: String, f: TestBuilder.() -> Unit) {
test(left, base, right, 1, f)
}
fun test2(left: String, base: String, right: String, f: TestBuilder.() -> Unit) {
test(left, base, right, 2, f)
}
fun testN(left: String, base: String, right: String, f: TestBuilder.() -> Unit) {
test(left, base, right, -1, f)
}
fun test(left: String, base: String, right: String, changesCount: Int, f: TestBuilder.() -> Unit) {
test(left, base, right, changesCount, IgnorePolicy.DEFAULT, f)
}
fun test(left: String, base: String, right: String, changesCount: Int, policy: IgnorePolicy, f: TestBuilder.() -> Unit) {
val contentFactory = DiffContentFactoryImpl()
val leftContent: DocumentContent = contentFactory.create(parseSource(left))
val baseContent: DocumentContent = contentFactory.create(parseSource(base))
val rightContent: DocumentContent = contentFactory.create(parseSource(right))
val outputContent: DocumentContent = contentFactory.create(parseSource(""))
outputContent.document.setReadOnly(false)
val context = MockMergeContext(project)
val request = MockMergeRequest(leftContent, baseContent, rightContent, outputContent)
val settings = TextDiffSettings()
settings.ignorePolicy = policy
context.putUserData(TextDiffSettings.KEY, settings)
val viewer = TextMergeTool.INSTANCE.createComponent(context, request) as TextMergeViewer
try {
val toolbar = viewer.init()
UIUtil.dispatchAllInvocationEvents()
val builder = TestBuilder(viewer, toolbar.toolbarActions ?: emptyList())
builder.assertChangesCount(changesCount)
builder.f()
}
finally {
Disposer.dispose(viewer)
}
}
inner class TestBuilder(val mergeViewer: TextMergeViewer, private val actions: List<AnAction>) {
val viewer: MyThreesideViewer = mergeViewer.viewer
val changes: List<TextMergeChange> = viewer.allChanges
val editor: EditorEx = viewer.editor
val document: Document = editor.document
private val textEditor = TextEditorProvider.getInstance().getTextEditor(editor)
private val undoManager = UndoManager.getInstance(project!!)
fun change(num: Int): TextMergeChange {
if (changes.size < num) throw Exception("changes: ${changes.size}, index: $num")
return changes[num]
}
fun activeChanges(): List<TextMergeChange> = viewer.changes
//
// Actions
//
fun runApplyNonConflictsAction(side: ThreeSide) {
runActionById(side.select("Left", "All", "Right")!!)
}
private fun runActionById(text: String): Boolean {
val action = actions.filter { text == it.templatePresentation.text }.single()
return runAction(action)
}
private fun runAction(action: AnAction): Boolean {
val actionEvent = AnActionEvent.createFromAnAction(action, null, ActionPlaces.MAIN_MENU, editor.dataContext)
action.update(actionEvent)
val success = actionEvent.presentation.isEnabledAndVisible
if (success) action.actionPerformed(actionEvent)
return success
}
//
// Modification
//
fun command(affected: TextMergeChange, f: () -> Unit) {
command(listOf(affected), f)
}
fun command(affected: List<TextMergeChange>? = null, f: () -> Unit) {
viewer.executeMergeCommand(null, affected, f)
UIUtil.dispatchAllInvocationEvents()
}
fun write(f: () -> Unit) {
ApplicationManager.getApplication().runWriteAction { CommandProcessor.getInstance().executeCommand(project, f, null, null) }
}
fun Int.ignore(side: Side, modifier: Boolean = false) {
val change = change(this)
command(change) { viewer.ignoreChange(change, side, modifier) }
}
fun Int.apply(side: Side, modifier: Boolean = false) {
val change = change(this)
command(change) { viewer.replaceChange(change, side, modifier) }
}
fun Int.resolve() {
val change = change(this)
command(change) {
assertTrue(change.isConflict && viewer.canResolveChangeAutomatically(change, ThreeSide.BASE))
viewer.resolveChangeAutomatically(change, ThreeSide.BASE)
}
}
fun Int.canResolveConflict(): Boolean {
val change = change(this)
return viewer.canResolveChangeAutomatically(change, ThreeSide.BASE)
}
//
// Text modification
//
fun insertText(offset: Int, newContent: CharSequence) {
replaceText(offset, offset, newContent)
}
fun deleteText(startOffset: Int, endOffset: Int) {
replaceText(startOffset, endOffset, "")
}
fun replaceText(startOffset: Int, endOffset: Int, newContent: CharSequence) {
write { document.replaceString(startOffset, endOffset, parseSource(newContent)) }
}
fun insertText(offset: LineCol, newContent: CharSequence) {
replaceText(offset.toOffset(), offset.toOffset(), newContent)
}
fun deleteText(startOffset: LineCol, endOffset: LineCol) {
replaceText(startOffset.toOffset(), endOffset.toOffset(), "")
}
fun replaceText(startOffset: LineCol, endOffset: LineCol, newContent: CharSequence) {
write { replaceText(startOffset.toOffset(), endOffset.toOffset(), newContent) }
}
fun replaceText(oldContent: CharSequence, newContent: CharSequence) {
write {
val range = findRange(parseSource(oldContent))
replaceText(range.first, range.second, newContent)
}
}
fun deleteText(oldContent: CharSequence) {
write {
val range = findRange(parseSource(oldContent))
replaceText(range.first, range.second, "")
}
}
fun insertTextBefore(oldContent: CharSequence, newContent: CharSequence) {
write { insertText(findRange(parseSource(oldContent)).first, newContent) }
}
fun insertTextAfter(oldContent: CharSequence, newContent: CharSequence) {
write { insertText(findRange(parseSource(oldContent)).second, newContent) }
}
private fun findRange(oldContent: CharSequence): Couple<Int> {
val text = document.charsSequence
val index1 = StringUtil.indexOf(text, oldContent)
assertTrue(index1 >= 0, "content - '\n$oldContent\n'\ntext - '\n$text'")
val index2 = StringUtil.indexOf(text, oldContent, index1 + 1)
assertTrue(index2 == -1, "content - '\n$oldContent\n'\ntext - '\n$text'")
return Couple(index1, index1 + oldContent.length)
}
//
// Undo
//
fun assertCantUndo() {
assertFalse(undoManager.isUndoAvailable(textEditor))
}
fun undo(count: Int = 1) {
if (count == -1) {
while (undoManager.isUndoAvailable(textEditor)) {
undoManager.undo(textEditor)
}
}
else {
for (i in 1..count) {
assertTrue(undoManager.isUndoAvailable(textEditor))
undoManager.undo(textEditor)
}
}
}
fun redo(count: Int = 1) {
if (count == -1) {
while (undoManager.isRedoAvailable(textEditor)) {
undoManager.redo(textEditor)
}
}
else {
for (i in 1..count) {
assertTrue(undoManager.isRedoAvailable(textEditor))
undoManager.redo(textEditor)
}
}
}
fun checkUndo(count: Int = -1, f: TestBuilder.() -> Unit) {
val initialState = ViewerState.recordState(viewer)
f()
UIUtil.dispatchAllInvocationEvents()
val afterState = ViewerState.recordState(viewer)
undo(count)
UIUtil.dispatchAllInvocationEvents()
val undoState = ViewerState.recordState(viewer)
redo(count)
UIUtil.dispatchAllInvocationEvents()
val redoState = ViewerState.recordState(viewer)
assertEquals(initialState, undoState)
assertEquals(afterState, redoState)
}
//
// Checks
//
fun assertChangesCount(expected: Int) {
if (expected == -1) return
val actual = activeChanges().size
assertEquals(expected, actual)
}
fun Int.assertType(type: TextDiffType, changeType: SidesState) {
assertType(type)
assertType(changeType)
}
fun Int.assertType(type: TextDiffType) {
val change = change(this)
assertEquals(change.diffType, type)
}
fun Int.assertType(changeType: SidesState) {
assertTrue(changeType != NONE)
val change = change(this)
val actual = change.type
val isLeftChange = changeType != RIGHT
val isRightChange = changeType != LEFT
assertEquals(Pair(isLeftChange, isRightChange), Pair(actual.isChange(Side.LEFT), actual.isChange(Side.RIGHT)))
}
fun Int.assertResolved(type: SidesState) {
val change = change(this)
val isLeftResolved = type == LEFT || type == BOTH
val isRightResolved = type == RIGHT || type == BOTH
assertEquals(Pair(isLeftResolved, isRightResolved), Pair(change.isResolved(Side.LEFT), change.isResolved(Side.RIGHT)))
}
fun Int.assertRange(start: Int, end: Int) {
val change = change(this)
assertEquals(Pair(start, end), Pair(change.startLine, change.endLine))
}
fun Int.assertRange(start1: Int, end1: Int, start2: Int, end2: Int, start3: Int, end3: Int) {
val change = change(this)
assertEquals(MergeRange(start1, end1, start2, end2, start3, end3),
MergeRange(change.getStartLine(ThreeSide.LEFT), change.getEndLine(ThreeSide.LEFT),
change.getStartLine(ThreeSide.BASE), change.getEndLine(ThreeSide.BASE),
change.getStartLine(ThreeSide.RIGHT), change.getEndLine(ThreeSide.RIGHT)))
}
fun Int.assertContent(expected: String, start: Int, end: Int) {
assertContent(expected)
assertRange(start, end)
}
fun Int.assertContent(expected: String) {
val change = change(this)
val document = editor.document
val actual = DiffUtil.getLinesContent(document, change.startLine, change.endLine)
assertEquals(parseSource(expected), actual)
}
fun assertContent(expected: String) {
val actual = viewer.editor.document.charsSequence
assertEquals(parseSource(expected), actual)
}
//
// Helpers
//
operator fun Int.not(): LineColHelper = LineColHelper(this)
operator fun LineColHelper.minus(col: Int): LineCol = LineCol(this.line, col)
inner class LineColHelper(val line: Int)
inner class LineCol(val line: Int, val col: Int) {
fun toOffset(): Int = editor.document.getLineStartOffset(line) + col
}
}
private class MockMergeContext(private val myProject: Project?) : MergeContext() {
override fun getProject(): Project? = myProject
override fun isFocusedInWindow(): Boolean = false
override fun requestFocusInWindow() {
}
override fun finishMerge(result: MergeResult) {
}
}
private class MockMergeRequest(val left: DocumentContent,
val base: DocumentContent,
val right: DocumentContent,
val output: DocumentContent) : TextMergeRequest() {
override fun getTitle(): String? = null
override fun applyResult(result: MergeResult) {
}
override fun getContents(): List<DocumentContent> = listOf(left, base, right)
override fun getOutputContent(): DocumentContent = output
override fun getContentTitles(): List<String?> = listOf(null, null, null)
}
enum class SidesState {
LEFT, RIGHT, BOTH, NONE
}
private data class ViewerState constructor(private val content: CharSequence,
private val changes: List<ViewerState.ChangeState>) {
companion object {
fun recordState(viewer: MyThreesideViewer): ViewerState {
val content = viewer.editor.document.immutableCharSequence
val changes = viewer.allChanges.map { recordChangeState(viewer, it) }
return ViewerState(content, changes)
}
private fun recordChangeState(viewer: MyThreesideViewer, change: TextMergeChange): ChangeState {
val document = viewer.editor.document
val content = DiffUtil.getLinesContent(document, change.startLine, change.endLine)
val resolved =
if (change.isResolved) BOTH
else if (change.isResolved(Side.LEFT)) LEFT
else if (change.isResolved(Side.RIGHT)) RIGHT
else NONE
val starts = Trio.from { change.getStartLine(it) }
val ends = Trio.from { change.getStartLine(it) }
return ChangeState(content, starts, ends, resolved)
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is ViewerState) return false
if (!StringUtil.equals(content, other.content)) return false
if (changes != other.changes) return false
return true
}
override fun hashCode(): Int = StringUtil.stringHashCode(content)
private data class ChangeState(private val content: CharSequence,
private val starts: Trio<Int>,
private val ends: Trio<Int>,
private val resolved: SidesState) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is ChangeState) return false
if (!StringUtil.equals(content, other.content)) return false
if (starts != other.starts) return false
if (ends != other.ends) return false
if (resolved != other.resolved) return false
return true
}
override fun hashCode(): Int = StringUtil.stringHashCode(content)
}
}
} | apache-2.0 | 387f37e7d068ff439a2c1b13a27fda47 | 33.788863 | 140 | 0.675382 | 4.648992 | false | false | false | false |
PeterVollmer/feel-at-home-android-client | Feel@Home/Feel@Home/src/main/java/club/frickel/feelathome/DeviceHandler.kt | 1 | 1754 | package club.frickel.feelathome
import android.content.Context
import android.os.AsyncTask
import android.preference.PreferenceManager
import android.util.Log
import android.widget.Toast
import com.fasterxml.jackson.core.type.TypeReference
import com.fasterxml.jackson.databind.ObjectMapper
import java.io.BufferedInputStream
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
abstract class DeviceHandler(protected var context: Context) : AsyncTask<Void, String, ArrayList<Device>>() {
override fun doInBackground(vararg params: Void): ArrayList<Device>? {
var deviceList: ArrayList<Device>? = null
val urlString = PreferenceManager.getDefaultSharedPreferences(context).getString(Constants.SERVER_URL, null)
if (urlString != null) {
try {
val url = URL(urlString + "/devices")
val urlConnection = url.openConnection() as HttpURLConnection
urlConnection.connectTimeout = 2000
val `in` = BufferedInputStream(urlConnection.inputStream)
deviceList = ObjectMapper().readValue<ArrayList<Device>>(`in`, object : TypeReference<ArrayList<Device>>() {
})
} catch (e: IOException) {
//e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
Log.d("DeviceHandler", "doInBackground: " + e.message)
return null
}
}
return deviceList
}
override fun onProgressUpdate(vararg error: String) {
Toast.makeText(context, error[0], Toast.LENGTH_SHORT).show()
}
abstract override fun onPostExecute(deviceList: ArrayList<Device>)
}
| gpl-2.0 | bf4efc50c209da6f5d0f6a3e843c0754 | 36.319149 | 124 | 0.68016 | 4.913165 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/lower/DeepCopyIrTreeWithDescriptors.kt | 1 | 35758 | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.backend.konan.lower
import org.jetbrains.kotlin.backend.common.CommonBackendContext
import org.jetbrains.kotlin.backend.common.IrElementTransformerVoidWithContext
import org.jetbrains.kotlin.backend.common.IrElementVisitorVoidWithContext
import org.jetbrains.kotlin.backend.common.lower.SimpleMemberScope
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.impl.*
import org.jetbrains.kotlin.ir.IrElement
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.declarations.impl.IrFunctionImpl
import org.jetbrains.kotlin.ir.descriptors.IrTemporaryVariableDescriptorImpl
import org.jetbrains.kotlin.ir.expressions.*
import org.jetbrains.kotlin.ir.expressions.impl.*
import org.jetbrains.kotlin.ir.util.DeepCopyIrTree
import org.jetbrains.kotlin.ir.visitors.acceptChildrenVoid
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperClassOrAny
import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperInterfaces
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeSubstitutor
import org.jetbrains.kotlin.types.Variance
import org.jetbrains.kotlin.types.typeUtil.makeNullable
class DeepCopyIrTreeWithDescriptors(val targetDescriptor: FunctionDescriptor,
val parentDescriptor: DeclarationDescriptor,
context: CommonBackendContext) {
private val descriptorSubstituteMap: MutableMap<DeclarationDescriptor, DeclarationDescriptor> = mutableMapOf()
private var typeSubstitutor: TypeSubstitutor? = null
private var nameIndex = 0
//-------------------------------------------------------------------------//
fun copy(irElement: IrElement, typeSubstitutor: TypeSubstitutor?): IrElement {
this.typeSubstitutor = typeSubstitutor
irElement.acceptChildrenVoid(DescriptorCollector())
return irElement.accept(InlineCopyIr(), null)
}
//-------------------------------------------------------------------------//
inner class DescriptorCollector: IrElementVisitorVoidWithContext() {
override fun visitElement(element: IrElement) {
element.acceptChildren(this, null)
}
//---------------------------------------------------------------------//
override fun visitClassNew(declaration: IrClass) {
val oldDescriptor = declaration.descriptor
val newDescriptor = copyClassDescriptor(oldDescriptor)
descriptorSubstituteMap[oldDescriptor] = newDescriptor
descriptorSubstituteMap[oldDescriptor.thisAsReceiverParameter] = newDescriptor.thisAsReceiverParameter
super.visitClassNew(declaration)
val constructors = oldDescriptor.constructors.map { oldConstructorDescriptor ->
descriptorSubstituteMap[oldConstructorDescriptor] as ClassConstructorDescriptor
}.toSet()
val oldPrimaryConstructor = oldDescriptor.unsubstitutedPrimaryConstructor
val primaryConstructor = oldPrimaryConstructor?.let { descriptorSubstituteMap[it] as ClassConstructorDescriptor }
val contributedDescriptors = oldDescriptor.unsubstitutedMemberScope
.getContributedDescriptors()
.map {
descriptorSubstituteMap[it]!!
}
newDescriptor.initialize(
SimpleMemberScope(contributedDescriptors),
constructors,
primaryConstructor
)
}
//---------------------------------------------------------------------//
override fun visitPropertyNew(declaration: IrProperty) {
copyPropertyOrField(declaration.descriptor)
super.visitPropertyNew(declaration)
}
//---------------------------------------------------------------------//
override fun visitFieldNew(declaration: IrField) {
val oldDescriptor = declaration.descriptor
if (descriptorSubstituteMap[oldDescriptor] == null) {
copyPropertyOrField(oldDescriptor) // A field without a property or a field of a delegated property.
}
super.visitFieldNew(declaration)
}
//---------------------------------------------------------------------//
override fun visitFunctionNew(declaration: IrFunction) {
val oldDescriptor = declaration.descriptor
if (oldDescriptor !is PropertyAccessorDescriptor) { // Property accessors are copied along with their property.
val oldContainingDeclaration =
if (oldDescriptor.visibility == Visibilities.LOCAL)
parentDescriptor
else
oldDescriptor.containingDeclaration
val newDescriptor = copyFunctionDescriptor(oldDescriptor, oldContainingDeclaration)
descriptorSubstituteMap[oldDescriptor] = newDescriptor
oldDescriptor.extensionReceiverParameter?.let{
descriptorSubstituteMap[it] = newDescriptor.extensionReceiverParameter!!
}
}
super.visitFunctionNew(declaration)
}
//---------------------------------------------------------------------//
override fun visitVariable(declaration: IrVariable) {
val oldDescriptor = declaration.descriptor
val oldContainingDeclaration = oldDescriptor.containingDeclaration
val newContainingDeclaration = descriptorSubstituteMap.getOrDefault(oldContainingDeclaration, oldContainingDeclaration)
val newDescriptor = IrTemporaryVariableDescriptorImpl(
containingDeclaration = newContainingDeclaration,
name = generateCopyName(oldDescriptor.name),
outType = substituteType(oldDescriptor.type)!!,
isMutable = oldDescriptor.isVar)
descriptorSubstituteMap[oldDescriptor] = newDescriptor
super.visitVariable(declaration)
}
//---------------------------------------------------------------------//
override fun visitCatch(aCatch: IrCatch) {
val oldDescriptor = aCatch.parameter
val oldContainingDeclaration = oldDescriptor.containingDeclaration
val newContainingDeclaration = descriptorSubstituteMap.getOrDefault(oldContainingDeclaration, oldContainingDeclaration)
val newDescriptor = IrTemporaryVariableDescriptorImpl(
containingDeclaration = newContainingDeclaration,
name = generateCopyName(oldDescriptor.name),
outType = substituteType(oldDescriptor.type)!!,
isMutable = oldDescriptor.isVar)
descriptorSubstituteMap[oldDescriptor] = newDescriptor
super.visitCatch(aCatch)
}
//--- Copy descriptors ------------------------------------------------//
private fun generateCopyName(name: Name): Name {
val declarationName = name.toString() // Name of declaration
val indexStr = (nameIndex++).toString() // Unique for inline target index
return Name.identifier(declarationName + "_" + indexStr)
}
//---------------------------------------------------------------------//
private fun copyFunctionDescriptor(oldDescriptor: CallableDescriptor, oldContainingDeclaration: DeclarationDescriptor): CallableDescriptor {
return when (oldDescriptor) {
is ConstructorDescriptor -> copyConstructorDescriptor(oldDescriptor)
is SimpleFunctionDescriptor -> copySimpleFunctionDescriptor(oldDescriptor, oldContainingDeclaration)
else -> TODO("Unsupported FunctionDescriptor subtype: $oldDescriptor")
}
}
//---------------------------------------------------------------------//
private fun copySimpleFunctionDescriptor(oldDescriptor: SimpleFunctionDescriptor, oldContainingDeclaration: DeclarationDescriptor) : FunctionDescriptor {
val newContainingDeclaration = descriptorSubstituteMap.getOrDefault(oldContainingDeclaration, oldContainingDeclaration)
return SimpleFunctionDescriptorImpl.create(
/* containingDeclaration = */ newContainingDeclaration,
/* annotations = */ oldDescriptor.annotations,
/* name = */ generateCopyName(oldDescriptor.name),
/* kind = */ oldDescriptor.kind,
/* source = */ oldDescriptor.source
).apply {
val oldDispatchReceiverParameter = oldDescriptor.dispatchReceiverParameter
val newDispatchReceiverParameter = oldDispatchReceiverParameter?.let { descriptorSubstituteMap.getOrDefault(it, it) as ReceiverParameterDescriptor }
val newTypeParameters = oldDescriptor.typeParameters // TODO substitute types
val newValueParameters = copyValueParameters(oldDescriptor.valueParameters, this)
val newReceiverParameterType = substituteType(oldDescriptor.extensionReceiverParameter?.type)
val newReturnType = substituteType(oldDescriptor.returnType)
initialize(
/* receiverParameterType = */ newReceiverParameterType,
/* dispatchReceiverParameter = */ newDispatchReceiverParameter,
/* typeParameters = */ newTypeParameters,
/* unsubstitutedValueParameters = */ newValueParameters,
/* unsubstitutedReturnType = */ newReturnType,
/* modality = */ oldDescriptor.modality,
/* visibility = */ oldDescriptor.visibility
)
isTailrec = oldDescriptor.isTailrec
isSuspend = oldDescriptor.isSuspend
overriddenDescriptors += oldDescriptor.overriddenDescriptors
}
}
//---------------------------------------------------------------------//
private fun copyConstructorDescriptor(oldDescriptor: ConstructorDescriptor) : FunctionDescriptor {
val oldContainingDeclaration = oldDescriptor.containingDeclaration
val newContainingDeclaration = descriptorSubstituteMap.getOrDefault(oldContainingDeclaration, oldContainingDeclaration)
return ClassConstructorDescriptorImpl.create(
/* containingDeclaration = */ newContainingDeclaration as ClassDescriptor,
/* annotations = */ oldDescriptor.annotations,
/* isPrimary = */ oldDescriptor.isPrimary,
/* source = */ oldDescriptor.source
).apply {
val newTypeParameters = oldDescriptor.typeParameters
val newValueParameters = copyValueParameters(oldDescriptor.valueParameters, this)
val receiverParameterType = substituteType(oldDescriptor.dispatchReceiverParameter?.type)
val returnType = substituteType(oldDescriptor.returnType)
initialize(
/* receiverParameterType = */ receiverParameterType,
/* dispatchReceiverParameter = */ null, // For constructor there is no explicit dispatch receiver.
/* typeParameters = */ newTypeParameters,
/* unsubstitutedValueParameters = */ newValueParameters,
/* unsubstitutedReturnType = */ returnType,
/* modality = */ oldDescriptor.modality,
/* visibility = */ oldDescriptor.visibility
)
}
}
//---------------------------------------------------------------------//
private fun copyPropertyOrField(oldDescriptor: PropertyDescriptor) {
val newDescriptor = copyPropertyDescriptor(oldDescriptor)
descriptorSubstituteMap[oldDescriptor] = newDescriptor
oldDescriptor.getter?.let {
descriptorSubstituteMap[it] = newDescriptor.getter!!
}
oldDescriptor.setter?.let {
descriptorSubstituteMap[it] = newDescriptor.setter!!
}
oldDescriptor.extensionReceiverParameter?.let{
descriptorSubstituteMap[it] = newDescriptor.extensionReceiverParameter!!
}
}
//---------------------------------------------------------------------//
private fun copyPropertyDescriptor(oldDescriptor: PropertyDescriptor): PropertyDescriptor {
val oldContainingDeclaration = oldDescriptor.containingDeclaration
val newContainingDeclaration = descriptorSubstituteMap.getOrDefault(oldContainingDeclaration, oldContainingDeclaration) as ClassDescriptor
return PropertyDescriptorImpl.create(
/* containingDeclaration = */ newContainingDeclaration,
/* annotations = */ oldDescriptor.annotations,
/* modality = */ oldDescriptor.modality,
/* visibility = */ oldDescriptor.visibility,
/* isVar = */ oldDescriptor.isVar,
/* name = */ oldDescriptor.name,
/* kind = */ oldDescriptor.kind,
/* source = */ oldDescriptor.source,
/* lateInit = */ oldDescriptor.isLateInit,
/* isConst = */ oldDescriptor.isConst,
/* isExpect = */ oldDescriptor.isExpect,
/* isActual = */ oldDescriptor.isActual,
/* isExternal = */ oldDescriptor.isExternal,
/* isDelegated = */ oldDescriptor.isDelegated
).apply {
setType(
/* outType = */ oldDescriptor.type,
/* typeParameters = */ oldDescriptor.typeParameters,
/* dispatchReceiverParameter = */ newContainingDeclaration.thisAsReceiverParameter,
/* receiverType = */ oldDescriptor.extensionReceiverParameter?.type)
initialize(
/* getter = */ oldDescriptor.getter?.let { copyPropertyGetterDescriptor(it, this) },
/* setter = */ oldDescriptor.setter?.let { copyPropertySetterDescriptor(it, this) })
overriddenDescriptors += oldDescriptor.overriddenDescriptors
}
}
//---------------------------------------------------------------------//
private fun copyPropertyGetterDescriptor(oldDescriptor: PropertyGetterDescriptor, newPropertyDescriptor: PropertyDescriptor)
: PropertyGetterDescriptorImpl {
return PropertyGetterDescriptorImpl(
/* correspondingProperty = */ newPropertyDescriptor,
/* annotations = */ oldDescriptor.annotations,
/* modality = */ oldDescriptor.modality,
/* visibility = */ oldDescriptor.visibility,
/* isDefault = */ oldDescriptor.isDefault,
/* isExternal = */ oldDescriptor.isExternal,
/* isInline = */ oldDescriptor.isInline,
/* kind = */ oldDescriptor.kind,
/* original = */ null,
/* source = */ oldDescriptor.source).apply {
initialize(oldDescriptor.returnType)
}
}
//---------------------------------------------------------------------//
private fun copyPropertySetterDescriptor(oldDescriptor: PropertySetterDescriptor, newPropertyDescriptor: PropertyDescriptor)
: PropertySetterDescriptorImpl {
return PropertySetterDescriptorImpl(
/* correspondingProperty = */ newPropertyDescriptor,
/* annotations = */ oldDescriptor.annotations,
/* modality = */ oldDescriptor.modality,
/* visibility = */ oldDescriptor.visibility,
/* isDefault = */ oldDescriptor.isDefault,
/* isExternal = */ oldDescriptor.isExternal,
/* isInline = */ oldDescriptor.isInline,
/* kind = */ oldDescriptor.kind,
/* original = */ null,
/* source = */ oldDescriptor.source).apply {
initialize(copyValueParameters(oldDescriptor.valueParameters, this).single())
}
}
//---------------------------------------------------------------------//
private fun copyClassDescriptor(oldDescriptor: ClassDescriptor): ClassDescriptorImpl {
val oldSuperClass = oldDescriptor.getSuperClassOrAny()
val newSuperClass = descriptorSubstituteMap.getOrDefault(oldSuperClass, oldSuperClass) as ClassDescriptor
val oldInterfaces = oldDescriptor.getSuperInterfaces()
val newInterfaces = oldInterfaces.map { descriptorSubstituteMap.getOrDefault(it, it) as ClassDescriptor }
val oldContainingDeclaration = oldDescriptor.containingDeclaration
val newContainingDeclaration = descriptorSubstituteMap.getOrDefault(oldContainingDeclaration, oldContainingDeclaration)
val newName = if (DescriptorUtils.isAnonymousObject(oldDescriptor)) // Anonymous objects are identified by their name.
oldDescriptor.name // We need to preserve it for LocalDeclarationsLowering.
else
generateCopyName(oldDescriptor.name)
val visibility = oldDescriptor.visibility
return object : ClassDescriptorImpl(
/* containingDeclaration = */ newContainingDeclaration,
/* name = */ newName,
/* modality = */ oldDescriptor.modality,
/* kind = */ oldDescriptor.kind,
/* supertypes = */ listOf(newSuperClass.defaultType) + newInterfaces.map { it.defaultType },
/* source = */ oldDescriptor.source,
/* isExternal = */ oldDescriptor.isExternal
) {
override fun getVisibility() = visibility
}
}
}
//-----------------------------------------------------------------------------//
inner class InlineCopyIr : DeepCopyIrTree() {
override fun mapClassDeclaration (descriptor: ClassDescriptor) = descriptorSubstituteMap.getOrDefault(descriptor, descriptor) as ClassDescriptor
override fun mapTypeAliasDeclaration (descriptor: TypeAliasDescriptor) = descriptorSubstituteMap.getOrDefault(descriptor, descriptor) as TypeAliasDescriptor
override fun mapFunctionDeclaration (descriptor: FunctionDescriptor) = descriptorSubstituteMap.getOrDefault(descriptor, descriptor) as FunctionDescriptor
override fun mapConstructorDeclaration (descriptor: ClassConstructorDescriptor) = descriptorSubstituteMap.getOrDefault(descriptor, descriptor) as ClassConstructorDescriptor
override fun mapPropertyDeclaration (descriptor: PropertyDescriptor) = descriptorSubstituteMap.getOrDefault(descriptor, descriptor) as PropertyDescriptor
override fun mapLocalPropertyDeclaration (descriptor: VariableDescriptorWithAccessors) = descriptorSubstituteMap.getOrDefault(descriptor, descriptor) as VariableDescriptorWithAccessors
override fun mapEnumEntryDeclaration (descriptor: ClassDescriptor) = descriptorSubstituteMap.getOrDefault(descriptor, descriptor) as ClassDescriptor
override fun mapVariableDeclaration (descriptor: VariableDescriptor) = descriptorSubstituteMap.getOrDefault(descriptor, descriptor) as VariableDescriptor
override fun mapErrorDeclaration (descriptor: DeclarationDescriptor) = descriptorSubstituteMap.getOrDefault(descriptor, descriptor)
override fun mapClassReference (descriptor: ClassDescriptor) = descriptorSubstituteMap.getOrDefault(descriptor, descriptor) as ClassDescriptor
override fun mapValueReference (descriptor: ValueDescriptor) = descriptorSubstituteMap.getOrDefault(descriptor, descriptor) as ValueDescriptor
override fun mapVariableReference (descriptor: VariableDescriptor) = descriptorSubstituteMap.getOrDefault(descriptor, descriptor) as VariableDescriptor
override fun mapPropertyReference (descriptor: PropertyDescriptor) = descriptorSubstituteMap.getOrDefault(descriptor, descriptor) as PropertyDescriptor
override fun mapCallee (descriptor: FunctionDescriptor) = descriptorSubstituteMap.getOrDefault(descriptor, descriptor) as FunctionDescriptor
override fun mapDelegatedConstructorCallee (descriptor: ClassConstructorDescriptor) = descriptorSubstituteMap.getOrDefault(descriptor, descriptor) as ClassConstructorDescriptor
override fun mapEnumConstructorCallee (descriptor: ClassConstructorDescriptor) = descriptorSubstituteMap.getOrDefault(descriptor, descriptor) as ClassConstructorDescriptor
override fun mapLocalPropertyReference (descriptor: VariableDescriptorWithAccessors) = descriptorSubstituteMap.getOrDefault(descriptor, descriptor) as VariableDescriptorWithAccessors
override fun mapClassifierReference (descriptor: ClassifierDescriptor) = descriptorSubstituteMap.getOrDefault(descriptor, descriptor) as ClassifierDescriptor
override fun mapReturnTarget (descriptor: FunctionDescriptor) = descriptorSubstituteMap.getOrDefault(descriptor, descriptor) as FunctionDescriptor
//---------------------------------------------------------------------//
override fun mapSuperQualifier(qualifier: ClassDescriptor?): ClassDescriptor? {
if (qualifier == null) return null
return descriptorSubstituteMap.getOrDefault(qualifier, qualifier) as ClassDescriptor
}
//--- Visits ----------------------------------------------------------//
override fun visitCall(expression: IrCall): IrCall {
if (expression !is IrCallImpl) return super.visitCall(expression)
val newDescriptor = mapCallee(expression.descriptor)
return IrCallImpl(
startOffset = expression.startOffset,
endOffset = expression.endOffset,
type = newDescriptor.returnType!!,
calleeDescriptor = newDescriptor,
typeArguments = substituteTypeArguments(expression.transformTypeArguments(newDescriptor)),
origin = expression.origin,
superQualifierDescriptor = mapSuperQualifier(expression.superQualifier)
).transformValueArguments(expression)
}
//---------------------------------------------------------------------//
override fun visitFunction(declaration: IrFunction): IrFunction =
IrFunctionImpl(
startOffset = declaration.startOffset,
endOffset = declaration.endOffset,
origin = mapDeclarationOrigin(declaration.origin),
descriptor = mapFunctionDeclaration(declaration.descriptor),
body = declaration.body?.transform(this, null)
).transformParameters(declaration)
//---------------------------------------------------------------------//
private fun <T : IrFunction> T.transformDefaults(original: T): T {
for (originalValueParameter in original.descriptor.valueParameters) {
val valueParameter = descriptor.valueParameters[originalValueParameter.index]
original.getDefault(originalValueParameter)?.let { irDefaultParameterValue ->
putDefault(valueParameter, irDefaultParameterValue.transform(this@InlineCopyIr, null))
}
}
return this
}
//---------------------------------------------------------------------//
fun getTypeOperatorReturnType(operator: IrTypeOperator, type: KotlinType) : KotlinType {
return when (operator) {
IrTypeOperator.CAST,
IrTypeOperator.IMPLICIT_CAST,
IrTypeOperator.IMPLICIT_NOTNULL,
IrTypeOperator.IMPLICIT_COERCION_TO_UNIT,
IrTypeOperator.IMPLICIT_INTEGER_COERCION -> type
IrTypeOperator.SAFE_CAST -> type.makeNullable()
IrTypeOperator.INSTANCEOF,
IrTypeOperator.NOT_INSTANCEOF -> context.builtIns.booleanType
}
}
//---------------------------------------------------------------------//
override fun visitTypeOperator(expression: IrTypeOperatorCall): IrTypeOperatorCall {
val typeOperand = substituteType(expression.typeOperand)!!
val returnType = getTypeOperatorReturnType(expression.operator, typeOperand)
return IrTypeOperatorCallImpl(
startOffset = expression.startOffset,
endOffset = expression.endOffset,
type = returnType,
operator = expression.operator,
typeOperand = typeOperand,
argument = expression.argument.transform(this, null)
)
}
//---------------------------------------------------------------------//
override fun visitReturn(expression: IrReturn): IrReturn =
IrReturnImpl(
startOffset = expression.startOffset,
endOffset = expression.endOffset,
type = substituteType(expression.type)!!,
returnTargetDescriptor = mapReturnTarget(expression.returnTarget),
value = expression.value.transform(this, null)
)
//---------------------------------------------------------------------//
override fun visitBlock(expression: IrBlock): IrBlock {
return if (expression is IrReturnableBlock) {
IrReturnableBlockImpl(
startOffset = expression.startOffset,
endOffset = expression.endOffset,
type = expression.type,
descriptor = expression.descriptor,
origin = mapStatementOrigin(expression.origin),
statements = expression.statements.map { it.transform(this, null) },
sourceFileName = expression.sourceFileName
)
} else {
super.visitBlock(expression)
}
}
//-------------------------------------------------------------------------//
override fun visitClassReference(expression: IrClassReference): IrClassReference {
val newExpressionType = substituteType(expression.type)!! // Substituted expression type.
val newDescriptorType = substituteType(expression.descriptor.defaultType)!! // Substituted type of referenced class.
val classDescriptor = newDescriptorType.constructor.declarationDescriptor!! // Get ClassifierDescriptor of the referenced class.
return IrClassReferenceImpl(
startOffset = expression.startOffset,
endOffset = expression.endOffset,
type = newExpressionType,
descriptor = classDescriptor
)
}
//-------------------------------------------------------------------------//
override fun visitGetClass(expression: IrGetClass): IrGetClass {
val type = substituteType(expression.type)!!
if (type == expression.type) return expression
return IrGetClassImpl(
startOffset = expression.startOffset,
endOffset = expression.endOffset,
type = type,
argument = expression.argument.transform(this, null)
)
}
//-------------------------------------------------------------------------//
override fun getNonTransformedLoop(irLoop: IrLoop): IrLoop {
return irLoop
}
}
//-------------------------------------------------------------------------//
private fun copyValueParameters(oldValueParameters: List <ValueParameterDescriptor>, containingDeclaration: CallableDescriptor): List <ValueParameterDescriptor> {
return oldValueParameters.map { oldDescriptor ->
val newDescriptor = ValueParameterDescriptorImpl(
containingDeclaration = containingDeclaration,
original = oldDescriptor.original,
index = oldDescriptor.index,
annotations = oldDescriptor.annotations,
name = oldDescriptor.name,
outType = substituteType(oldDescriptor.type)!!,
declaresDefaultValue = oldDescriptor.declaresDefaultValue(),
isCrossinline = oldDescriptor.isCrossinline,
isNoinline = oldDescriptor.isNoinline,
varargElementType = substituteType(oldDescriptor.varargElementType),
source = oldDescriptor.source
)
descriptorSubstituteMap[oldDescriptor] = newDescriptor
newDescriptor
}
}
//-------------------------------------------------------------------------//
private fun substituteType(oldType: KotlinType?): KotlinType? {
if (typeSubstitutor == null) return oldType
if (oldType == null) return oldType
return typeSubstitutor!!.substitute(oldType, Variance.INVARIANT) ?: oldType
}
//-------------------------------------------------------------------------//
private fun substituteTypeArguments(oldTypeArguments: Map <TypeParameterDescriptor, KotlinType>?): Map <TypeParameterDescriptor, KotlinType>? {
if (oldTypeArguments == null) return null
if (typeSubstitutor == null) return oldTypeArguments
val newTypeArguments = oldTypeArguments.entries.associate {
val typeParameterDescriptor = it.key
val oldTypeArgument = it.value
val newTypeArgument = substituteType(oldTypeArgument)!!
typeParameterDescriptor to newTypeArgument
}
return newTypeArguments
}
//-------------------------------------------------------------------------//
fun addCurrentSubstituteMap(globalSubstituteMap: MutableMap<DeclarationDescriptor, SubstitutedDescriptor>) {
descriptorSubstituteMap.forEach { t, u ->
globalSubstituteMap.put(t, SubstitutedDescriptor(targetDescriptor, u))
}
}
val context = context
}
class SubstitutedDescriptor(val inlinedFunction: FunctionDescriptor, val descriptor: DeclarationDescriptor)
class DescriptorSubstitutorForExternalScope(val globalSubstituteMap: MutableMap<DeclarationDescriptor, SubstitutedDescriptor>)
: IrElementTransformerVoidWithContext() {
override fun visitCall(expression: IrCall): IrExpression {
val oldExpression = super.visitCall(expression) as IrCall
val substitutedDescriptor = globalSubstituteMap[expression.descriptor.original]
?: return oldExpression
if (allScopes.any { it.scope.scopeOwner == substitutedDescriptor.inlinedFunction })
return oldExpression
return when (oldExpression) {
is IrCallImpl -> copyIrCallImpl(oldExpression, substitutedDescriptor)
is IrCallWithShallowCopy -> copyIrCallWithShallowCopy(oldExpression, substitutedDescriptor)
else -> oldExpression
}
}
//-------------------------------------------------------------------------//
private fun copyIrCallImpl(oldExpression: IrCallImpl, substitutedDescriptor: SubstitutedDescriptor): IrCallImpl {
val oldDescriptor = oldExpression.descriptor
val newDescriptor = substitutedDescriptor.descriptor as FunctionDescriptor
if (newDescriptor == oldDescriptor)
return oldExpression
val newExpression = IrCallImpl(
startOffset = oldExpression.startOffset,
endOffset = oldExpression.endOffset,
type = oldExpression.type,
calleeDescriptor = newDescriptor,
typeArguments = oldExpression.typeArguments,
origin = oldExpression.origin,
superQualifierDescriptor = oldExpression.superQualifier
).apply {
oldExpression.descriptor.valueParameters.forEach {
val valueArgument = oldExpression.getValueArgument(it)
putValueArgument(it.index, valueArgument)
}
extensionReceiver = oldExpression.extensionReceiver
dispatchReceiver = oldExpression.dispatchReceiver
}
return newExpression
}
//-------------------------------------------------------------------------//
private fun copyIrCallWithShallowCopy(oldExpression: IrCallWithShallowCopy, substitutedDescriptor: SubstitutedDescriptor): IrCall {
val oldDescriptor = oldExpression.descriptor
val newDescriptor = substitutedDescriptor.descriptor as FunctionDescriptor
if (newDescriptor == oldDescriptor)
return oldExpression
return oldExpression.shallowCopy(oldExpression.origin, newDescriptor, oldExpression.superQualifier)
}
}
| apache-2.0 | 2451cb7ae56a3f1fc78abc88d0c90abb | 52.85241 | 195 | 0.582275 | 6.986714 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/extensionFunctions/executionOrder.kt | 4 | 341 | var result = ""
fun getReceiver() : Int {
result += "getReceiver->"
return 1
}
fun getFun(b : Int.(Int)->Unit): Int.(Int)->Unit {
result += "getFun()->"
return b
}
fun box(): String {
getReceiver().(getFun({ result +="End" }))(1)
if(result != "getFun()->getReceiver->End") return "fail $result"
return "OK"
} | apache-2.0 | b558155267449c21985539631058dc51 | 17 | 68 | 0.557185 | 3.1 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/optimizations/DFGBuilder.kt | 1 | 29564 | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.backend.konan.optimizations
import org.jetbrains.kotlin.backend.common.descriptors.allParameters
import org.jetbrains.kotlin.backend.common.descriptors.isSuspend
import org.jetbrains.kotlin.backend.common.ir.ir2stringWhole
import org.jetbrains.kotlin.backend.common.peek
import org.jetbrains.kotlin.backend.common.pop
import org.jetbrains.kotlin.backend.common.push
import org.jetbrains.kotlin.backend.konan.Context
import org.jetbrains.kotlin.backend.konan.descriptors.isInterface
import org.jetbrains.kotlin.backend.konan.descriptors.target
import org.jetbrains.kotlin.backend.konan.ir.IrSuspendableExpression
import org.jetbrains.kotlin.backend.konan.ir.IrSuspensionPoint
import org.jetbrains.kotlin.backend.konan.llvm.functionName
import org.jetbrains.kotlin.backend.konan.llvm.localHash
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.ir.IrElement
import org.jetbrains.kotlin.ir.UNDEFINED_OFFSET
import org.jetbrains.kotlin.ir.declarations.IrField
import org.jetbrains.kotlin.ir.declarations.IrFunction
import org.jetbrains.kotlin.ir.declarations.IrModuleFragment
import org.jetbrains.kotlin.ir.declarations.IrVariable
import org.jetbrains.kotlin.ir.expressions.*
import org.jetbrains.kotlin.ir.expressions.impl.IrGetObjectValueImpl
import org.jetbrains.kotlin.ir.expressions.impl.IrGetValueImpl
import org.jetbrains.kotlin.ir.expressions.impl.IrSetFieldImpl
import org.jetbrains.kotlin.ir.expressions.impl.IrTypeOperatorCallImpl
import org.jetbrains.kotlin.ir.util.getArguments
import org.jetbrains.kotlin.ir.visitors.IrElementVisitorVoid
import org.jetbrains.kotlin.ir.visitors.acceptChildrenVoid
import org.jetbrains.kotlin.ir.visitors.acceptVoid
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.resolve.OverridingUtil
import org.jetbrains.kotlin.resolve.scopes.MemberScope
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.typeUtil.isNothing
import org.jetbrains.kotlin.types.typeUtil.isUnit
import org.jetbrains.kotlin.types.typeUtil.makeNotNullable
private fun computeErasure(type: KotlinType, erasure: MutableList<KotlinType>) {
val descriptor = type.constructor.declarationDescriptor
when (descriptor) {
is ClassDescriptor -> erasure += type.makeNotNullable()
is TypeParameterDescriptor -> {
descriptor.upperBounds.forEach {
computeErasure(it, erasure)
}
}
else -> TODO(descriptor.toString())
}
}
internal fun KotlinType.erasure(): List<KotlinType> {
val result = mutableListOf<KotlinType>()
computeErasure(this, result)
return result
}
private fun MemberScope.getOverridingOf(function: FunctionDescriptor) = when (function) {
is PropertyGetterDescriptor ->
this.getContributedVariables(function.correspondingProperty.name, NoLookupLocation.FROM_BACKEND)
.firstOrNull { OverridingUtil.overrides(it, function.correspondingProperty) }?.getter
is PropertySetterDescriptor ->
this.getContributedVariables(function.correspondingProperty.name, NoLookupLocation.FROM_BACKEND)
.firstOrNull { OverridingUtil.overrides(it, function.correspondingProperty) }?.setter
else -> this.getContributedFunctions(function.name, NoLookupLocation.FROM_BACKEND)
.firstOrNull { OverridingUtil.overrides(it, function) }
}
private fun IrTypeOperator.isCast() =
this == IrTypeOperator.CAST || this == IrTypeOperator.IMPLICIT_CAST || this == IrTypeOperator.SAFE_CAST
private class VariableValues {
val elementData = HashMap<VariableDescriptor, MutableSet<IrExpression>>()
fun addEmpty(variable: VariableDescriptor) =
elementData.getOrPut(variable, { mutableSetOf() })
fun add(variable: VariableDescriptor, element: IrExpression) =
elementData[variable]?.add(element)
fun add(variable: VariableDescriptor, elements: Set<IrExpression>) =
elementData[variable]?.addAll(elements)
fun get(variable: VariableDescriptor): Set<IrExpression>? =
elementData[variable]
fun computeClosure() {
elementData.forEach { key, _ ->
add(key, computeValueClosure(key))
}
}
// Computes closure of all possible values for given variable.
private fun computeValueClosure(value: VariableDescriptor): Set<IrExpression> {
val result = mutableSetOf<IrExpression>()
val seen = mutableSetOf<VariableDescriptor>()
dfs(value, seen, result)
return result
}
private fun dfs(value: VariableDescriptor, seen: MutableSet<VariableDescriptor>, result: MutableSet<IrExpression>) {
seen += value
val elements = elementData[value]
?: return
for (element in elements) {
if (element !is IrGetValue)
result += element
else {
val descriptor = element.descriptor
if (descriptor is VariableDescriptor && !seen.contains(descriptor))
dfs(descriptor, seen, result)
}
}
}
}
private class ExpressionValuesExtractor(val returnableBlockValues: Map<IrReturnableBlock, List<IrExpression>>,
val suspendableExpressionValues: Map<IrSuspendableExpression, List<IrSuspensionPoint>>) {
fun forEachValue(expression: IrExpression, block: (IrExpression) -> Unit) {
when (expression) {
is IrReturnableBlock -> returnableBlockValues[expression]!!.forEach { forEachValue(it, block) }
is IrSuspendableExpression ->
(suspendableExpressionValues[expression]!! + expression.result).forEach { forEachValue(it, block) }
is IrSuspensionPoint -> {
forEachValue(expression.result, block)
forEachValue(expression.resumeResult, block)
}
is IrContainerExpression -> {
if (expression.statements.isNotEmpty())
forEachValue(expression.statements.last() as IrExpression, block)
}
is IrWhen -> expression.branches.forEach { forEachValue(it.result, block) }
is IrMemberAccessExpression -> block(expression)
is IrGetValue -> block(expression)
is IrGetField -> block(expression)
is IrVararg -> /* Sometimes, we keep vararg till codegen phase (for constant arrays). */
block(expression)
is IrConst<*> -> block(expression)
is IrTypeOperatorCall -> {
if (!expression.operator.isCast())
block(expression)
else { // Propagate cast to sub-values.
forEachValue(expression.argument) { value ->
with(expression) {
block(IrTypeOperatorCallImpl(startOffset, endOffset, type, operator, typeOperand, value))
}
}
}
}
is IrTry -> {
forEachValue(expression.tryResult, block)
expression.catches.forEach { forEachValue(it.result, block) }
}
is IrGetObjectValue -> block(expression)
is IrFunctionReference -> block(expression)
is IrSetField -> block(expression)
else -> {
if ((expression.type.isUnit() || expression.type.isNothing())) {
block(IrGetObjectValueImpl(expression.startOffset, expression.endOffset,
expression.type, (expression.type.constructor.declarationDescriptor as ClassDescriptor)))
}
else TODO(ir2stringWhole(expression))
}
}
}
}
internal class ModuleDFG(val functions: Map<DataFlowIR.FunctionSymbol, DataFlowIR.Function>,
val symbolTable: DataFlowIR.SymbolTable)
internal class ModuleDFGBuilder(val context: Context, val irModule: IrModuleFragment) {
private val DEBUG = 0
private inline fun DEBUG_OUTPUT(severity: Int, block: () -> Unit) {
if (DEBUG > severity) block()
}
private val TAKE_NAMES = false // Take fqNames for all functions and types (for debug purposes).
private inline fun takeName(block: () -> String) = if (TAKE_NAMES) block() else null
private val module = DataFlowIR.Module(irModule.descriptor)
private val symbolTable = DataFlowIR.SymbolTable(context, irModule, module)
// Possible values of a returnable block.
private val returnableBlockValues = mutableMapOf<IrReturnableBlock, MutableList<IrExpression>>()
// All suspension points within specified suspendable expression.
private val suspendableExpressionValues = mutableMapOf<IrSuspendableExpression, MutableList<IrSuspensionPoint>>()
private val expressionValuesExtractor = ExpressionValuesExtractor(returnableBlockValues, suspendableExpressionValues)
fun build(): ModuleDFG {
val functions = mutableMapOf<DataFlowIR.FunctionSymbol, DataFlowIR.Function>()
irModule.accept(object : IrElementVisitorVoid {
override fun visitElement(element: IrElement) {
element.acceptChildrenVoid(this)
}
override fun visitFunction(declaration: IrFunction) {
declaration.body?.let {
DEBUG_OUTPUT(1) {
println("Analysing function ${declaration.descriptor}")
println("IR: ${ir2stringWhole(declaration)}")
}
analyze(declaration.descriptor, it)
}
}
override fun visitField(declaration: IrField) {
declaration.initializer?.let {
DEBUG_OUTPUT(1) {
println("Analysing global field ${declaration.descriptor}")
println("IR: ${ir2stringWhole(declaration)}")
}
analyze(declaration.descriptor, IrSetFieldImpl(it.startOffset, it.endOffset, declaration.symbol, null, it.expression))
}
}
private fun analyze(descriptor: CallableDescriptor, body: IrElement) {
// Find all interesting expressions, variables and functions.
val visitor = ElementFinderVisitor()
body.acceptVoid(visitor)
DEBUG_OUTPUT(1) {
println("FIRST PHASE")
visitor.variableValues.elementData.forEach { t, u ->
println("VAR $t:")
u.forEach {
println(" ${ir2stringWhole(it)}")
}
}
visitor.expressions.forEach { t ->
println("EXP ${ir2stringWhole(t)}")
}
}
// Compute transitive closure of possible values for variables.
visitor.variableValues.computeClosure()
DEBUG_OUTPUT(1) {
println("SECOND PHASE")
visitor.variableValues.elementData.forEach { t, u ->
println("VAR $t:")
u.forEach {
println(" ${ir2stringWhole(it)}")
}
}
}
val function = FunctionDFGBuilder(expressionValuesExtractor, visitor.variableValues,
descriptor, visitor.expressions, visitor.returnValues, visitor.thrownValues).build()
DEBUG_OUTPUT(1) {
function.debugOutput()
}
functions.put(function.symbol, function)
}
}, data = null)
DEBUG_OUTPUT(2) {
println("SYMBOL TABLE:")
symbolTable.classMap.forEach { descriptor, type ->
println(" DESCRIPTOR: $descriptor")
println(" TYPE: $type")
if (type !is DataFlowIR.Type.Declared)
return@forEach
println(" SUPER TYPES:")
type.superTypes.forEach { println(" $it") }
println(" VTABLE:")
type.vtable.forEach { println(" $it") }
println(" ITABLE:")
type.itable.forEach { println(" ${it.key} -> ${it.value}") }
}
}
return ModuleDFG(functions, symbolTable)
}
private inner class ElementFinderVisitor : IrElementVisitorVoid {
val expressions = mutableListOf<IrExpression>()
val variableValues = VariableValues()
val returnValues = mutableListOf<IrExpression>()
val thrownValues = mutableListOf<IrExpression>()
private val returnableBlocks = mutableMapOf<FunctionDescriptor, IrReturnableBlock>()
private val suspendableExpressionStack = mutableListOf<IrSuspendableExpression>()
override fun visitElement(element: IrElement) {
element.acceptChildrenVoid(this)
}
private fun assignVariable(variable: VariableDescriptor, value: IrExpression) {
expressionValuesExtractor.forEachValue(value) {
variableValues.add(variable, it)
}
}
override fun visitExpression(expression: IrExpression) {
when (expression) {
is IrMemberAccessExpression,
is IrGetField,
is IrGetObjectValue,
is IrVararg,
is IrConst<*>,
is IrTypeOperatorCall ->
expressions += expression
}
if (expression is IrReturnableBlock) {
returnableBlocks.put(expression.descriptor, expression)
returnableBlockValues.put(expression, mutableListOf())
}
if (expression is IrSuspendableExpression) {
suspendableExpressionStack.push(expression)
suspendableExpressionValues.put(expression, mutableListOf())
}
if (expression is IrSuspensionPoint)
suspendableExpressionValues[suspendableExpressionStack.peek()!!]!!.add(expression)
super.visitExpression(expression)
if (expression is IrReturnableBlock)
returnableBlocks.remove(expression.descriptor)
if (expression is IrSuspendableExpression)
suspendableExpressionStack.pop()
}
override fun visitSetField(expression: IrSetField) {
expressions += expression
super.visitSetField(expression)
}
// TODO: hack to overcome bad code in InlineConstructorsTransformation.
private val FQ_NAME_INLINE_CONSTRUCTOR = FqName("konan.internal.InlineConstructor")
override fun visitReturn(expression: IrReturn) {
val returnableBlock = returnableBlocks[expression.returnTarget]
if (returnableBlock != null) {
returnableBlockValues[returnableBlock]!!.add(expression.value)
} else { // Non-local return.
if (!expression.type.isUnit()) {
if (!expression.returnTarget.annotations.hasAnnotation(FQ_NAME_INLINE_CONSTRUCTOR)) // Not inline constructor.
returnValues += expression.value
}
}
super.visitReturn(expression)
}
override fun visitThrow(expression: IrThrow) {
thrownValues += expression.value
super.visitThrow(expression)
}
override fun visitSetVariable(expression: IrSetVariable) {
super.visitSetVariable(expression)
assignVariable(expression.descriptor, expression.value)
}
override fun visitVariable(declaration: IrVariable) {
variableValues.addEmpty(declaration.descriptor)
super.visitVariable(declaration)
declaration.initializer?.let { assignVariable(declaration.descriptor, it) }
}
}
private val doResumeFunctionDescriptor = context.getInternalClass("CoroutineImpl").unsubstitutedMemberScope
.getContributedFunctions(Name.identifier("doResume"), NoLookupLocation.FROM_BACKEND).single()
private val getContinuationSymbol = context.ir.symbols.getContinuation
private inner class FunctionDFGBuilder(val expressionValuesExtractor: ExpressionValuesExtractor,
val variableValues: VariableValues,
val descriptor: CallableDescriptor,
val expressions: List<IrExpression>,
val returnValues: List<IrExpression>,
val thrownValues: List<IrExpression>) {
private val allParameters = (descriptor as? FunctionDescriptor)?.allParameters ?: emptyList()
private val templateParameters = allParameters.withIndex().associateBy({ it.value }, { DataFlowIR.Node.Parameter(it.index) })
private val continuationParameter =
if (descriptor.isSuspend)
DataFlowIR.Node.Parameter(allParameters.size)
else {
if (doResumeFunctionDescriptor in descriptor.overriddenDescriptors) // <this> is a CoroutineImpl inheritor.
templateParameters[descriptor.dispatchReceiverParameter!!] // It is its own continuation.
else null
}
private fun getContinuation() = continuationParameter ?: error("Function $descriptor has no continuation parameter")
private val nodes = mutableMapOf<IrExpression, DataFlowIR.Node>()
private val variables = variableValues.elementData.keys.associateBy(
{ it },
{ DataFlowIR.Node.Variable(mutableListOf(), false) }
)
fun build(): DataFlowIR.Function {
expressions.forEach { getNode(it) }
val returnsNode = DataFlowIR.Node.Variable(returnValues.map { expressionToEdge(it) }, true)
val throwsNode = DataFlowIR.Node.Variable(thrownValues.map { expressionToEdge(it) }, true)
variables.forEach { descriptor, node ->
variableValues.elementData[descriptor]!!.forEach {
node.values += expressionToEdge(it)
}
}
val allNodes = nodes.values + variables.values + templateParameters.values + returnsNode + throwsNode +
(if (descriptor.isSuspend) listOf(continuationParameter!!) else emptyList())
return DataFlowIR.Function(
symbol = symbolTable.mapFunction(descriptor),
isGlobalInitializer = descriptor is PropertyDescriptor,
numberOfParameters = templateParameters.size + if (descriptor.isSuspend) 1 else 0,
body = DataFlowIR.FunctionBody(allNodes.distinct().toList(), returnsNode, throwsNode)
)
}
private fun expressionToEdge(expression: IrExpression) =
if (expression is IrTypeOperatorCall && expression.operator.isCast())
DataFlowIR.Edge(getNode(expression.argument), symbolTable.mapType(expression.typeOperand))
else DataFlowIR.Edge(getNode(expression), null)
private fun getNode(expression: IrExpression): DataFlowIR.Node {
if (expression is IrGetValue) {
val descriptor = expression.descriptor
if (descriptor is ParameterDescriptor)
return templateParameters[descriptor]!!
return variables[descriptor as VariableDescriptor]!!
}
return nodes.getOrPut(expression) {
DEBUG_OUTPUT(1) {
println("Converting expression")
println(ir2stringWhole(expression))
}
val values = mutableListOf<IrExpression>()
expressionValuesExtractor.forEachValue(expression) { values += it }
if (values.size != 1) {
DataFlowIR.Node.Variable(values.map { expressionToEdge(it) }, true)
} else {
val value = values[0]
if (value != expression) {
val edge = expressionToEdge(value)
if (edge.castToType == null)
edge.node
else
DataFlowIR.Node.Variable(listOf(edge), true)
} else {
when (value) {
is IrGetValue -> getNode(value)
is IrVararg,
is IrConst<*>,
is IrFunctionReference -> DataFlowIR.Node.Const(symbolTable.mapType(value.type))
is IrGetObjectValue -> DataFlowIR.Node.Singleton(
symbolTable.mapType(value.type),
if (value.type.isNothing()) // <Nothing> is not a singleton though its instance is get with <IrGetObject> operation.
null
else symbolTable.mapFunction(value.descriptor.constructors.single())
)
is IrCall -> {
if (value.symbol == getContinuationSymbol) {
getContinuation()
} else {
val callee = value.descriptor
val arguments = value.getArguments()
.map { expressionToEdge(it.second) }
.let {
if (callee.isSuspend)
it + DataFlowIR.Edge(getContinuation(), null)
else
it
}
if (callee is ConstructorDescriptor) {
DataFlowIR.Node.NewObject(
symbolTable.mapFunction(callee),
arguments,
symbolTable.mapClass(callee.constructedClass),
value
)
} else {
if (callee.isOverridable && value.superQualifier == null) {
val owner = callee.containingDeclaration as ClassDescriptor
val vTableBuilder = context.getVtableBuilder(owner)
if (owner.isInterface) {
DataFlowIR.Node.ItableCall(
symbolTable.mapFunction(callee.target),
symbolTable.mapClass(owner),
callee.functionName.localHash.value,
arguments,
symbolTable.mapType(callee.returnType!!),
value
)
} else {
val vtableIndex = vTableBuilder.vtableIndex(callee)
assert(vtableIndex >= 0, { "Unable to find function $callee in vtable of $owner" })
DataFlowIR.Node.VtableCall(
symbolTable.mapFunction(callee.target),
symbolTable.mapClass(owner),
vtableIndex,
arguments,
symbolTable.mapType(callee.returnType!!),
value
)
}
} else {
val actualCallee = (value.superQualifier?.unsubstitutedMemberScope?.getOverridingOf(callee) ?: callee).target
DataFlowIR.Node.StaticCall(
symbolTable.mapFunction(actualCallee),
arguments,
symbolTable.mapType(actualCallee.returnType!!),
actualCallee.dispatchReceiverParameter?.let { symbolTable.mapType(it.type) },
value
)
}
}
}
}
is IrDelegatingConstructorCall -> {
val thiz = IrGetValueImpl(UNDEFINED_OFFSET, UNDEFINED_OFFSET,
(descriptor as ConstructorDescriptor).constructedClass.thisAsReceiverParameter)
val arguments = listOf(thiz) + value.getArguments().map { it.second }
DataFlowIR.Node.StaticCall(
symbolTable.mapFunction(value.descriptor),
arguments.map { expressionToEdge(it) },
symbolTable.mapClass(context.builtIns.unit),
symbolTable.mapType(thiz.type),
value
)
}
is IrGetField -> {
val receiver = value.receiver?.let { expressionToEdge(it) }
val receiverType = value.receiver?.let { symbolTable.mapType(it.type) }
val name = value.descriptor.name.asString()
DataFlowIR.Node.FieldRead(
receiver,
DataFlowIR.Field(
receiverType,
name.localHash.value,
takeName { name }
)
)
}
is IrSetField -> {
val receiver = value.receiver?.let { expressionToEdge(it) }
val receiverType = value.receiver?.let { symbolTable.mapType(it.type) }
val name = value.descriptor.name.asString()
DataFlowIR.Node.FieldWrite(
receiver,
DataFlowIR.Field(
receiverType,
name.localHash.value,
takeName { name }
),
expressionToEdge(value.value)
)
}
is IrTypeOperatorCall -> {
assert(!value.operator.isCast(), { "Casts should've been handled earlier" })
expressionToEdge(value.argument) // Put argument as a separate vertex.
DataFlowIR.Node.Const(symbolTable.mapType(value.type)) // All operators except casts are basically constants.
}
else -> TODO("Unknown expression: ${ir2stringWhole(value)}")
}
}
}
}
}
}
} | apache-2.0 | 385a55b6ea47010a5bb53b8c62514393 | 46.99513 | 153 | 0.542146 | 6.101961 | false | false | false | false |
afollestad/photo-affix | engine/src/main/java/com/afollestad/photoaffix/engine/subengines/StitchEngine.kt | 1 | 9285 | /**
* Designed and developed by Aidan Follestad (@afollestad)
*
* 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.afollestad.photoaffix.engine.subengines
import android.graphics.Bitmap
import android.graphics.Bitmap.DENSITY_NONE
import android.graphics.Canvas
import android.graphics.Color.TRANSPARENT
import android.graphics.Paint
import android.graphics.Rect
import com.afollestad.photoaffix.engine.bitmaps.BitmapIterator
import com.afollestad.photoaffix.engine.bitmaps.BitmapManipulator
import com.afollestad.photoaffix.prefs.BgFillColor
import com.afollestad.photoaffix.prefs.ImageSpacingHorizontal
import com.afollestad.photoaffix.prefs.ImageSpacingVertical
import com.afollestad.photoaffix.prefs.ScalePriority
import com.afollestad.photoaffix.prefs.StackHorizontally
import com.afollestad.photoaffix.utilities.DpConverter
import com.afollestad.photoaffix.utilities.ext.safeRecycle
import com.afollestad.photoaffix.utilities.ext.toRoundedInt
import com.afollestad.rxkprefs.Pref
import org.jetbrains.annotations.TestOnly
import javax.inject.Inject
internal typealias CanvasCreator = (Bitmap) -> Canvas
internal typealias PaintCreator = () -> Paint
internal typealias RectCreator = (left: Int, top: Int, right: Int, bottom: Int) -> Rect
/** @author Aidan Follestad (afollestad) */
interface StitchEngine {
fun stitch(
bitmapIterator: BitmapIterator,
selectedScale: Double,
resultWidth: Int,
resultHeight: Int,
format: Bitmap.CompressFormat,
quality: Int
): ProcessingResult
}
class RealStitchEngine @Inject constructor(
private val dpConverter: DpConverter,
private val bitmapManipulator: BitmapManipulator,
@StackHorizontally private val stackHorizontallyPref: Pref<Boolean>,
@ScalePriority private val scalePriorityPref: Pref<Boolean>,
@ImageSpacingVertical private val spacingVerticalPref: Pref<Int>,
@ImageSpacingHorizontal private val spacingHorizontalPref: Pref<Int>,
@BgFillColor private val bgFillColorPref: Pref<Int>
) : StitchEngine {
private var canvasCreator: CanvasCreator = { Canvas(it) }
private var paintCreator: PaintCreator = {
Paint().apply {
isFilterBitmap = true
isAntiAlias = true
isDither = true
}
}
private var rectCreator: RectCreator = { l, t, r, b ->
Rect(l, t, r, b)
}
override fun stitch(
bitmapIterator: BitmapIterator,
selectedScale: Double,
resultWidth: Int,
resultHeight: Int,
format: Bitmap.CompressFormat,
quality: Int
): ProcessingResult {
val horizontalOrientation = stackHorizontallyPref.get()
return if (horizontalOrientation) {
stitchHorizontally(
bitmapIterator,
selectedScale,
resultWidth,
resultHeight,
format,
quality
)
} else {
stitchVertically(
bitmapIterator,
selectedScale,
resultWidth,
resultHeight,
format,
quality
)
}
}
private fun stitchHorizontally(
bitmapIterator: BitmapIterator,
selectedScale: Double,
resultWidth: Int,
resultHeight: Int,
format: Bitmap.CompressFormat,
quality: Int
): ProcessingResult {
val result = bitmapManipulator.createEmptyBitmap(resultWidth, resultHeight)
val spacingHorizontal = (spacingHorizontalPref.get().dp() *
selectedScale).toInt()
val resultCanvas = canvasCreator(result)
val paint = paintCreator()
val bgFillColor = bgFillColorPref.get()
if (bgFillColor != TRANSPARENT) {
// Fill the canvas (blank image) with the user's selected background fill color
resultCanvas.drawColor(bgFillColor)
}
// Used to set destination dimensions when drawn onto the canvas, e.g. when padding is used
var processedCount = 0
val scalingPriority = scalePriorityPref.get()
var currentX = 0
bitmapIterator.reset()
try {
for (options in bitmapIterator) {
processedCount++
val width = options.outWidth
val height = options.outHeight
val ratio = width.toFloat() / height.toFloat()
var scaledWidth = (width * selectedScale).toRoundedInt()
var scaledHeight = (height * selectedScale).toRoundedInt()
if (scalingPriority) {
// Scale up to largest height, fill total height
if (scaledHeight < resultHeight) {
scaledHeight = resultHeight
scaledWidth = (scaledHeight.toFloat() * ratio).toRoundedInt()
}
} else {
// Scale down to smallest height, fill total height
if (scaledHeight > resultHeight) {
scaledHeight = resultHeight
scaledWidth = (scaledHeight.toFloat() * ratio).toRoundedInt()
}
}
// Right is left plus width of the current image
val right = currentX + scaledWidth
val dstRect = rectCreator(
currentX,
0,
right,
scaledHeight
)
options.inJustDecodeBounds = false
options.inSampleSize = (dstRect.bottom - dstRect.top) / options.outHeight
val bm = bitmapIterator.currentBitmap()
try {
bm.density = DENSITY_NONE
resultCanvas.drawBitmap(bm, null, dstRect, paint)
} finally {
bm.safeRecycle()
}
currentX = dstRect.right + spacingHorizontal
}
} catch (e: Exception) {
bitmapIterator.reset()
return ProcessingResult(
processedCount = 0,
error = Exception("Unable to stitch your photos", e)
)
}
return ProcessingResult(
processedCount = processedCount,
output = result,
format = format,
quality = quality
)
}
private fun stitchVertically(
bitmapIterator: BitmapIterator,
selectedScale: Double,
resultWidth: Int,
resultHeight: Int,
format: Bitmap.CompressFormat,
quality: Int
): ProcessingResult {
val result = bitmapManipulator.createEmptyBitmap(resultWidth, resultHeight)
val spacingVertical = (spacingVerticalPref.get().dp() *
selectedScale).toInt()
val resultCanvas = canvasCreator(result)
val paint = paintCreator()
val bgFillColor = bgFillColorPref.get()
if (bgFillColor != TRANSPARENT) {
// Fill the canvas (blank image) with the user's selected background fill color
resultCanvas.drawColor(bgFillColor)
}
// Used to set destination dimensions when drawn onto the canvas, e.g. when padding is used
var processedCount = 0
val scalingPriority = scalePriorityPref.get()
var currentY = 0
bitmapIterator.reset()
try {
for (options in bitmapIterator) {
processedCount++
val width = options.outWidth
val height = options.outHeight
val ratio = height.toFloat() / width.toFloat()
var scaledWidth = (width * selectedScale).toRoundedInt()
var scaledHeight = (height * selectedScale).toRoundedInt()
if (scalingPriority) {
// Scale up to largest width, fill total width
if (scaledWidth < resultWidth) {
scaledWidth = resultWidth
scaledHeight = (scaledWidth.toFloat() * ratio).toRoundedInt()
}
} else {
// Scale down to smallest width, fill total width
if (scaledWidth > resultWidth) {
scaledWidth = resultWidth
scaledHeight = (scaledWidth.toFloat() * ratio).toRoundedInt()
}
}
// Bottom is top plus height of the current image
val bottom = currentY + scaledHeight
val dstRect = rectCreator(0, currentY, scaledWidth, bottom)
options.inJustDecodeBounds = false
options.inSampleSize = (dstRect.right - dstRect.left) / options.outWidth
val bm = bitmapIterator.currentBitmap()
try {
bm.density = DENSITY_NONE
resultCanvas.drawBitmap(bm, null, dstRect, paint)
} finally {
bm.safeRecycle()
}
currentY = dstRect.bottom + spacingVertical
}
} catch (e: Exception) {
bitmapIterator.reset()
return ProcessingResult(
processedCount = 0,
error = Exception("Unable to stitch your photos", e)
)
}
return ProcessingResult(
processedCount = processedCount,
output = result,
format = format,
quality = quality
)
}
@TestOnly internal fun setPaintCreator(creator: PaintCreator) {
this.paintCreator = creator
}
@TestOnly internal fun setCanvasCreator(creator: CanvasCreator) {
this.canvasCreator = creator
}
@TestOnly internal fun setRectCreator(creator: RectCreator) {
this.rectCreator = creator
}
private fun Int.dp() = dpConverter.toDp(this).toInt()
}
| apache-2.0 | 9d5a5ad9323c12144fb785b206c4cc42 | 30.262626 | 95 | 0.672159 | 4.663486 | false | false | false | false |
exponent/exponent | packages/expo-sqlite/android/src/main/java/expo/modules/sqlite/SQLiteHelpers.kt | 2 | 2679 | package expo.modules.sqlite
import java.io.File
import java.io.IOException
import java.util.ArrayList
@Throws(IOException::class)
internal fun ensureDirExists(dir: File): File {
if (!dir.isDirectory) {
if (dir.isFile) {
throw IOException("Path '$dir' points to a file, but must point to a directory.")
}
if (!dir.mkdirs()) {
var additionalErrorMessage = ""
if (dir.exists()) {
additionalErrorMessage = "Path already points to a non-normal file."
}
if (dir.parentFile == null) {
additionalErrorMessage = "Parent directory is null."
}
throw IOException("Couldn't create directory '$dir'. $additionalErrorMessage")
}
}
return dir
}
internal fun pluginResultsToPrimitiveData(results: List<SQLiteModule.SQLitePluginResult>): List<Any> {
return results.map { convertPluginResultToArray(it) }
}
private fun convertPluginResultToArray(result: SQLiteModule.SQLitePluginResult): List<Any?> {
val rowsContent = result.rows.map { row ->
row.map { value ->
when (value) {
null -> null
is String -> value
is Boolean -> value
else -> (value as Number).toDouble()
}
}
}
return arrayListOf(
result.error?.message,
result.insertId.toInt(),
result.rowsAffected,
result.columns,
rowsContent
)
}
private fun isPragma(str: String): Boolean {
return startsWithCaseInsensitive(str, "pragma")
}
private fun isPragmaReadOnly(str: String): Boolean {
return isPragma(str) && !str.contains('=')
}
internal fun isSelect(str: String): Boolean {
return startsWithCaseInsensitive(str, "select") || isPragmaReadOnly(str)
}
internal fun isInsert(str: String): Boolean {
return startsWithCaseInsensitive(str, "insert")
}
internal fun isUpdate(str: String): Boolean {
return startsWithCaseInsensitive(str, "update")
}
internal fun isDelete(str: String): Boolean {
return startsWithCaseInsensitive(str, "delete")
}
private fun startsWithCaseInsensitive(str: String, substr: String): Boolean {
return str.trimStart().startsWith(substr, true)
}
internal fun convertParamsToStringArray(paramArrayArg: ArrayList<Any?>): Array<String?> {
return paramArrayArg.map { param ->
when (param) {
is String -> unescapeBlob(param)
is Boolean -> if (param) "1" else "0"
is Double -> param.toString()
null -> null
else -> throw ClassCastException("Could not find proper SQLite data type for argument: $")
}
}.toTypedArray()
}
private fun unescapeBlob(str: String): String {
return str.replace("\u0001\u0001", "\u0000")
.replace("\u0001\u0002", "\u0001")
.replace("\u0002\u0002", "\u0002")
}
| bsd-3-clause | fcf063a65e947783635f4bef96fb4a2b | 26.90625 | 102 | 0.681971 | 3.945508 | false | false | false | false |
afollestad/assent | core/src/main/java/com/afollestad/assent/internal/Collections.kt | 1 | 1898 | /**
* Designed and developed by Aidan Follestad (@afollestad)
*
* 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.afollestad.assent.internal
import com.afollestad.assent.AssentResult
import com.afollestad.assent.Callback
import com.afollestad.assent.Permission
internal fun Set<Permission>.containsPermission(
permission: Permission
) = indexOfFirst { it.value == permission.value } > -1
internal fun Set<Permission>.equalsStrings(strings: Array<out String>): Boolean {
if (this.size != strings.size) {
return false
}
for ((i, perm) in this.withIndex()) {
if (perm.value != strings[i]) {
return false
}
}
return true
}
internal fun Set<Permission>.equalsPermissions(vararg permissions: Permission) =
equalsPermissions(permissions.toSet())
internal fun Set<Permission>.equalsPermissions(permissions: Set<Permission>): Boolean {
if (this.size != permissions.size) {
return false
}
for ((i, perm) in this.withIndex()) {
if (perm.value != permissions.elementAt(i).value) {
return false
}
}
return true
}
internal fun Set<Permission>.allValues(): Array<out String> =
map { it.value }.toTypedArray()
internal fun Array<out String>.toPermissions() =
map { Permission.parse(it) }.toSet()
internal fun List<Callback>.invokeAll(result: AssentResult) {
for (callback in this) {
callback.invoke(result)
}
}
| apache-2.0 | 6e4cc5e788d8bdaf50cd3ee6eaed824a | 29.126984 | 87 | 0.720232 | 3.970711 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/frontend-fir/src/org/jetbrains/kotlin/idea/frontend/api/fir/symbols/KtFirSyntheticJavaPropertySymbol.kt | 2 | 5592 | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.frontend.api.fir.symbols
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.fir.containingClass
import org.jetbrains.kotlin.fir.declarations.*
import org.jetbrains.kotlin.fir.declarations.synthetic.FirSyntheticProperty
import org.jetbrains.kotlin.idea.fir.findPsi
import org.jetbrains.kotlin.idea.fir.low.level.api.api.FirModuleResolveState
import org.jetbrains.kotlin.idea.frontend.api.ValidityToken
import org.jetbrains.kotlin.idea.frontend.api.fir.KtSymbolByFirBuilder
import org.jetbrains.kotlin.idea.frontend.api.fir.symbols.annotations.containsAnnotation
import org.jetbrains.kotlin.idea.frontend.api.fir.symbols.annotations.getAnnotationClassIds
import org.jetbrains.kotlin.idea.frontend.api.fir.symbols.annotations.toAnnotationsList
import org.jetbrains.kotlin.idea.frontend.api.fir.symbols.pointers.KtFirMemberPropertySymbolPointer
import org.jetbrains.kotlin.idea.frontend.api.fir.symbols.pointers.createSignature
import org.jetbrains.kotlin.idea.frontend.api.fir.utils.cached
import org.jetbrains.kotlin.idea.frontend.api.fir.utils.convertConstantExpression
import org.jetbrains.kotlin.idea.frontend.api.fir.utils.firRef
import org.jetbrains.kotlin.idea.frontend.api.symbols.*
import org.jetbrains.kotlin.idea.frontend.api.symbols.markers.*
import org.jetbrains.kotlin.idea.frontend.api.symbols.pointers.CanNotCreateSymbolPointerForLocalLibraryDeclarationException
import org.jetbrains.kotlin.idea.frontend.api.symbols.pointers.KtPsiBasedSymbolPointer
import org.jetbrains.kotlin.idea.frontend.api.symbols.pointers.KtSymbolPointer
import org.jetbrains.kotlin.idea.frontend.api.withValidityAssertion
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.idea.frontend.api.types.KtType
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
internal class KtFirSyntheticJavaPropertySymbol(
fir: FirSyntheticProperty,
resolveState: FirModuleResolveState,
override val token: ValidityToken,
private val builder: KtSymbolByFirBuilder
) : KtSyntheticJavaPropertySymbol(), KtFirSymbol<FirSyntheticProperty> {
override val firRef = firRef(fir, resolveState)
override val psi: PsiElement? by firRef.withFirAndCache { fir -> fir.findPsi(fir.session) }
override val isVal: Boolean get() = firRef.withFir { it.isVal }
override val name: Name get() = firRef.withFir { it.name }
override val annotatedType: KtTypeAndAnnotations by cached {
firRef.returnTypeAndAnnotations(FirResolvePhase.IMPLICIT_TYPES_BODY_RESOLVE, builder)
}
override val dispatchType: KtType? by cached {
firRef.dispatchReceiverTypeAndAnnotations(builder)
}
override val receiverType: KtTypeAndAnnotations? by cached {
firRef.receiverTypeAndAnnotations(builder)
}
override val isExtension: Boolean get() = firRef.withFir { it.receiverTypeRef != null }
override val initializer: KtConstantValue? by firRef.withFirAndCache(FirResolvePhase.BODY_RESOLVE) { fir -> fir.initializer?.convertConstantExpression() }
override val modality: KtCommonSymbolModality get() = getModality()
override val visibility: KtSymbolVisibility get() = getVisibility()
override val annotations: List<KtAnnotationCall> by cached { firRef.toAnnotationsList() }
override fun containsAnnotation(classId: ClassId): Boolean = firRef.containsAnnotation(classId)
override val annotationClassIds: Collection<ClassId> by cached { firRef.getAnnotationClassIds() }
override val callableIdIfNonLocal: FqName?
get() = firRef.withFir { fir ->
fir.symbol.callableId.takeUnless { fir.isLocal }?.asFqNameForDebugInfo()
}
override val getter: KtPropertyGetterSymbol by firRef.withFirAndCache(FirResolvePhase.RAW_FIR) { property ->
property.getter.let { builder.buildPropertyAccessorSymbol(it) } as KtPropertyGetterSymbol
}
override val setter: KtPropertySetterSymbol? by firRef.withFirAndCache(FirResolvePhase.RAW_FIR) { property ->
property.setter?.let { builder.buildPropertyAccessorSymbol(it) } as? KtPropertySetterSymbol
}
override val javaGetterName: Name get() = firRef.withFir { it.getter.delegate.name }
override val javaSetterName: Name? get() = firRef.withFir { it.setter?.delegate?.name }
override val isOverride: Boolean get() = firRef.withFir { it.isOverride }
override val hasSetter: Boolean get() = firRef.withFir { it.setter != null }
override val origin: KtSymbolOrigin get() = withValidityAssertion { KtSymbolOrigin.JAVA_SYNTHETIC_PROPERTY }
override fun createPointer(): KtSymbolPointer<KtPropertySymbol> {
KtPsiBasedSymbolPointer.createForSymbolFromSource(this)?.let { return it }
return when (symbolKind) {
KtSymbolKind.TOP_LEVEL -> TODO("Creating symbol for top level fun is not supported yet")
KtSymbolKind.NON_PROPERTY_PARAMETER -> TODO("Creating symbol for top level parameters is not supported yet")
KtSymbolKind.MEMBER -> KtFirMemberPropertySymbolPointer(
firRef.withFir { it.containingClass()?.classId ?: error("ClassId should not be null for member property") },
firRef.withFir { it.createSignature() }
)
KtSymbolKind.LOCAL -> throw CanNotCreateSymbolPointerForLocalLibraryDeclarationException(name.asString())
}
}
}
| apache-2.0 | ba1839c9975790ae61d891f238da3db1 | 54.92 | 158 | 0.777003 | 4.707071 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/hierarchy/calls/KotlinCallHierarchyBrowser.kt | 1 | 3044 | // 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.hierarchy.calls
import com.intellij.ide.hierarchy.CallHierarchyBrowserBase
import com.intellij.ide.hierarchy.HierarchyNodeDescriptor
import com.intellij.ide.hierarchy.HierarchyTreeStructure
import com.intellij.ide.hierarchy.JavaHierarchyUtil
import com.intellij.ide.util.treeView.NodeDescriptor
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.actionSystem.IdeActions
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.ui.PopupHandler
import org.jetbrains.kotlin.psi.KtElement
import javax.swing.JTree
class KotlinCallHierarchyBrowser(element: PsiElement) :
CallHierarchyBrowserBase(element.project, element) {
override fun createTrees(trees: MutableMap<in String, in JTree>) {
val baseOnThisMethodAction = BaseOnThisMethodAction()
val tree1 = createTree(false)
PopupHandler.installPopupMenu(
tree1,
IdeActions.GROUP_CALL_HIERARCHY_POPUP,
ActionPlaces.CALL_HIERARCHY_VIEW_POPUP
)
baseOnThisMethodAction.registerCustomShortcutSet(
ActionManager.getInstance().getAction(IdeActions.ACTION_CALL_HIERARCHY).shortcutSet,
tree1
)
trees[CALLEE_TYPE] = tree1
val tree2 = createTree(false)
PopupHandler.installPopupMenu(
tree2,
IdeActions.GROUP_CALL_HIERARCHY_POPUP,
ActionPlaces.CALL_HIERARCHY_VIEW_POPUP
)
baseOnThisMethodAction.registerCustomShortcutSet(
ActionManager.getInstance().getAction(IdeActions.ACTION_CALL_HIERARCHY).shortcutSet,
tree2
)
trees[CALLER_TYPE] = tree2
}
override fun getElementFromDescriptor(descriptor: HierarchyNodeDescriptor): PsiElement? {
return getTargetElement(descriptor)
}
override fun isApplicableElement(element: PsiElement): Boolean {
return if (element is PsiClass) false else isCallHierarchyElement(element) // PsiClass is not allowed at the hierarchy root
}
override fun createHierarchyTreeStructure(
type: String,
psiElement: PsiElement
): HierarchyTreeStructure? {
if (psiElement !is KtElement) return null
return when (type) {
CALLER_TYPE -> KotlinCallerTreeStructure(psiElement, currentScopeType)
CALLEE_TYPE -> KotlinCalleeTreeStructure(psiElement, currentScopeType)
else -> null
}
}
override fun getComparator(): Comparator<NodeDescriptor<*>> {
return JavaHierarchyUtil.getComparator(myProject)
}
companion object {
private fun getTargetElement(descriptor: HierarchyNodeDescriptor): PsiElement? {
return (descriptor as? KotlinCallHierarchyNodeDescriptor)?.psiElement
}
}
} | apache-2.0 | 4fdaab7d07bf0c4205384a96ed688680 | 38.545455 | 158 | 0.72339 | 5.115966 | false | false | false | false |
550609334/Twobbble | app/src/main/java/com/twobbble/view/activity/SearchActivity.kt | 1 | 3538 | package com.twobbble.view.activity
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.speech.RecognizerIntent
import android.support.v7.widget.PopupMenu
import android.transition.Fade
import android.transition.Slide
import android.view.View
import android.view.ViewAnimationUtils
import android.view.animation.AccelerateInterpolator
import com.twobbble.R
import com.twobbble.tools.Constant
import com.twobbble.tools.Parameters
import com.twobbble.tools.Utils
import com.twobbble.tools.startSpeak
import com.twobbble.view.adapter.ItemShotAdapter
import kotlinx.android.synthetic.main.activity_search.*
import kotlinx.android.synthetic.main.search_layout.*
class SearchActivity : BaseActivity() {
private var mSort: String? = null
private var mSortList: String? = null
private var mTimeFrame: String? = null
private var mPage: Int = 1
private var mListAdapter: ItemShotAdapter? = null
private var isLoading: Boolean = false
private val mSorts = listOf(null, Parameters.COMMENTS, Parameters.RECENT, Parameters.VIEWS)
private val mList = listOf(null, Parameters.ANIMATED, Parameters.ATTACHMENTS,
Parameters.DEBUTS, Parameters.DEBUTS, Parameters.PLAYOFFS, Parameters.REBOUNDS, Parameters.TEAMS)
companion object {
val KEY_KEYWORD: String = "keyword"
}
private var mKeyword: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_search)
initView()
}
private fun initView() {
mSortBtn.visibility = View.VISIBLE
mKeyword = intent.getStringExtra(KEY_KEYWORD)
mSearchEdit.setText(mKeyword)
mSortSpinner.dropDownVerticalOffset = Utils.dp2px(16).toInt()
mSortListSpinner.dropDownVerticalOffset = Utils.dp2px(16).toInt()
}
override fun onStart() {
super.onStart()
bindEvent()
}
private fun bindEvent() {
mBackBtn.setOnClickListener { finish() }
mVoiceBtn.setOnClickListener { startSpeak() }
mSortBtn.setOnClickListener {
val popupMenu = PopupMenu(this, mSortBtn)
popupMenu.setOnMenuItemClickListener { item ->
when (item.itemId) {
R.id.mNow -> timeFrameUpdate(null)
R.id.mWeek -> timeFrameUpdate(Parameters.WEEK)
R.id.mMonth -> timeFrameUpdate(Parameters.MONTH)
R.id.mYear -> timeFrameUpdate(Parameters.YEAR)
R.id.mAllTime -> timeFrameUpdate(Parameters.EVER)
}
true
}
val inflater = popupMenu.menuInflater
inflater.inflate(R.menu.sort_menu, popupMenu.menu)
popupMenu.show()
}
}
/**
* 更新时间线
* @param timeFrame 时间线,默认为null,代表Now,其它的值在Parameters这个单利对象中保存
*/
private fun timeFrameUpdate(timeFrame: String?) {
mListAdapter = null
mTimeFrame = timeFrame
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == Constant.VOICE_CODE && resultCode == Activity.RESULT_OK) {
val keywords = data?.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)
keywords?.forEach {
mSearchEdit.setText(it)
}
}
super.onActivityResult(requestCode, resultCode, data)
}
}
| apache-2.0 | 264ed87841a73e2bd127be12d7cc1c5e | 33.435644 | 109 | 0.674238 | 4.54047 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/groovy/src/org/jetbrains/kotlin/idea/groovy/inspections/DifferentKotlinGradleVersionInspection.kt | 1 | 3990 | // 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.groovy.inspections
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.idea.groovy.KotlinGroovyBundle
import org.jetbrains.kotlin.idea.inspections.PluginVersionDependentInspection
import org.jetbrains.kotlin.idea.inspections.gradle.KOTLIN_PLUGIN_CLASSPATH_MARKER
import org.jetbrains.kotlin.idea.inspections.gradle.KotlinGradleInspectionVisitor
import org.jetbrains.kotlin.idea.inspections.gradle.getResolvedKotlinGradleVersion
import org.jetbrains.kotlin.idea.versions.kotlinCompilerVersionShort
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.plugins.groovy.codeInspection.BaseInspection
import org.jetbrains.plugins.groovy.codeInspection.BaseInspectionVisitor
import org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrCallExpression
class DifferentKotlinGradleVersionInspection : BaseInspection(), PluginVersionDependentInspection {
override var testVersionMessage: String? = null
@TestOnly set
override fun buildVisitor(): BaseInspectionVisitor = MyVisitor()
override fun getGroupDisplayName() = getProbableBugs()
override fun buildErrorString(vararg args: Any): String =
KotlinGroovyBundle.message("error.text.different.kotlin.gradle.version", args[0], args[1])
private abstract class VersionFinder : KotlinGradleInspectionVisitor() {
protected abstract fun onFound(kotlinPluginVersion: String, kotlinPluginStatement: GrCallExpression)
override fun visitClosure(closure: GrClosableBlock) {
super.visitClosure(closure)
val dependenciesCall = closure.getStrictParentOfType<GrMethodCall>() ?: return
if (dependenciesCall.invokedExpression.text != "dependencies") return
val buildScriptCall = dependenciesCall.getStrictParentOfType<GrMethodCall>() ?: return
if (buildScriptCall.invokedExpression.text != "buildscript") return
val kotlinPluginStatement = GradleHeuristicHelper.findStatementWithPrefix(closure, "classpath").firstOrNull {
it.text.contains(KOTLIN_PLUGIN_CLASSPATH_MARKER)
} ?: return
val kotlinPluginVersion =
GradleHeuristicHelper.getHeuristicVersionInBuildScriptDependency(kotlinPluginStatement) ?: getResolvedKotlinGradleVersion(
closure.containingFile
) ?: return
onFound(kotlinPluginVersion, kotlinPluginStatement)
}
}
private inner class MyVisitor : VersionFinder() {
private val idePluginVersion by lazy { kotlinCompilerVersionShort() }
override fun onFound(kotlinPluginVersion: String, kotlinPluginStatement: GrCallExpression) {
if (kotlinPluginVersion != idePluginVersion) {
registerError(kotlinPluginStatement, kotlinPluginVersion, testVersionMessage ?: idePluginVersion)
}
}
}
companion object {
fun getKotlinPluginVersion(gradleFile: GroovyFileBase): String? {
var version: String? = null
val visitor = object : VersionFinder() {
override fun visitElement(element: GroovyPsiElement) {
element.acceptChildren(this)
}
override fun onFound(kotlinPluginVersion: String, kotlinPluginStatement: GrCallExpression) {
version = kotlinPluginVersion
}
}
gradleFile.accept(visitor)
return version
}
}
} | apache-2.0 | 6b01189450fb1cf079129a2d8c5a08c7 | 47.084337 | 158 | 0.73584 | 5.362903 | false | false | false | false |
siosio/intellij-community | plugins/yaml/src/org/jetbrains/yaml/smart/YAMLInjectedElementEnterHandler.kt | 1 | 4517 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.yaml.smart
import com.intellij.codeInsight.editorActions.enter.EnterHandlerDelegate
import com.intellij.codeInsight.editorActions.enter.EnterHandlerDelegateAdapter
import com.intellij.injected.editor.InjectionMeta
import com.intellij.injected.editor.VirtualFileWindow
import com.intellij.lang.injection.InjectedLanguageManager
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.RangeMarker
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiManager
import com.intellij.psi.codeStyle.CodeStyleManager
import org.jetbrains.yaml.YAMLLanguage
import org.jetbrains.yaml.psi.YAMLFile
import java.util.*
private val INJECTION_RANGE_BEFORE_ENTER = Key.create<RangeMarker>("NEXT_ELEMENT")
private val INDENT_BEFORE_PROCESSING = Key.create<String>("INDENT_BEFORE_PROCESSING")
fun preserveIndentStateBeforeProcessing(file: PsiFile, dataContext: DataContext) {
val hostEditor = CommonDataKeys.HOST_EDITOR.getData(dataContext) as? EditorEx ?: return
val virtualFile = hostEditor.virtualFile
val hostFile = hostEditor.project?.let { PsiManager.getInstance(it).findFile(virtualFile) } ?: return
if (!hostFile.viewProvider.hasLanguage(YAMLLanguage.INSTANCE)) return
if (file.virtualFile !is VirtualFileWindow) return
val injectionHost = InjectedLanguageManager.getInstance(file.project).getInjectionHost(file) ?: return
val lineIndent = InjectionMeta.INJECTION_INDENT[injectionHost]
INDENT_BEFORE_PROCESSING[file] = lineIndent
INJECTION_RANGE_BEFORE_ENTER[file] = hostEditor.document.createRangeMarker(injectionHost.textRange)
}
class YAMLInjectedElementEnterHandler : EnterHandlerDelegateAdapter() {
override fun postProcessEnter(file: PsiFile, editor: Editor, dataContext: DataContext): EnterHandlerDelegate.Result {
val hostEditor = CommonDataKeys.HOST_EDITOR.getData(dataContext) as? EditorEx ?: return EnterHandlerDelegate.Result.Continue
val caretOffset = hostEditor.caretModel.offset
val injectionIndent = INDENT_BEFORE_PROCESSING[file] ?: ""
val pointer = INJECTION_RANGE_BEFORE_ENTER[file] ?: return EnterHandlerDelegate.Result.Continue
val document = hostEditor.document
val currentInjectionHost = InjectedLanguageManager.getInstance(file.project).getInjectionHost(file)
?: return EnterHandlerDelegate.Result.Continue
val currentHostRange = currentInjectionHost.textRange
val lines = document.linesBetween(currentHostRange.endOffset, pointer.endOffset)
pointer.dispose(); INJECTION_RANGE_BEFORE_ENTER[file] = null
val caretLine = document.getLineNumber(caretOffset)
lines.add(caretLine)
val linesToAdjustIndent = TreeSet<Int>()
for (line in lines) {
val lineStartOffset = document.getLineStartOffset(line)
val lineChars = document.charsSequence.subSequence(lineStartOffset, document.getLineEndOffset(line))
val commonPrefixLength = StringUtil.commonPrefixLength(lineChars, injectionIndent)
val fix = !lineChars.startsWith(injectionIndent)
if (fix) {
document.replaceString(lineStartOffset, lineStartOffset + commonPrefixLength, injectionIndent)
if (line == caretLine) {
hostEditor.caretModel.moveToOffset(lineStartOffset + injectionIndent.length)
}
}
if (fix || (lineChars.isBlank() && lines.last() != line))
linesToAdjustIndent.add(line)
}
for (line in linesToAdjustIndent) {
val lineStartOffset = document.getLineStartOffset(line)
val forward = StringUtil.skipWhitespaceForward(document.charsSequence, lineStartOffset)
CodeStyleManager.getInstance(file.project).adjustLineIndent(document, forward)
}
return EnterHandlerDelegate.Result.Continue
}
}
private fun Document.linesBetween(startOffset: Int, endOffSet: Int): TreeSet<Int> {
if (startOffset > textLength) return TreeSet<Int>()
val endLine = if (endOffSet <= textLength) getLineNumber(endOffSet) else (lineCount - 1)
return (getLineNumber(startOffset)..endLine).filterTo(TreeSet<Int>()) { line -> getLineStartOffset(line) >= startOffset }
} | apache-2.0 | a80fddb3f66f2dfb8c366dfde1c04452 | 49.764045 | 140 | 0.785034 | 4.637577 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/parameterInfo/LambdaImpicitHints.kt | 1 | 2623 | // 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.parameterInfo
import com.intellij.codeInsight.hints.InlayInfo
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiComment
import com.intellij.psi.TokenType
import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.idea.codeInsight.hints.InlayInfoDetails
import org.jetbrains.kotlin.idea.codeInsight.hints.TextInlayInfoDetail
import org.jetbrains.kotlin.psi.KtLambdaExpression
import org.jetbrains.kotlin.psi.psiUtil.siblings
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.typeUtil.isUnit
fun provideLambdaImplicitHints(lambda: KtLambdaExpression): List<InlayInfoDetails>? {
val lbrace = lambda.leftCurlyBrace
if (!lbrace.isFollowedByNewLine()) {
return null
}
val bindingContext = lambda.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL)
val functionDescriptor = bindingContext[BindingContext.FUNCTION, lambda.functionLiteral] ?: return null
val implicitReceiverHint = functionDescriptor.extensionReceiverParameter?.let { implicitReceiver ->
val type = implicitReceiver.type
val renderedType = HintsTypeRenderer.getInlayHintsTypeRenderer(bindingContext, lambda).renderTypeIntoInlayInfo(type)
InlayInfoDetails(InlayInfo("", lbrace.psi.textRange.endOffset), listOf(TextInlayInfoDetail("this: ")) + renderedType)
}
val singleParameter = functionDescriptor.valueParameters.singleOrNull()
val singleParameterHint = if (singleParameter != null && bindingContext[BindingContext.AUTO_CREATED_IT, singleParameter] == true) {
val type = singleParameter.type
if (type.isUnit()) null else {
val renderedType = HintsTypeRenderer.getInlayHintsTypeRenderer(bindingContext, lambda).renderTypeIntoInlayInfo(type)
InlayInfoDetails(InlayInfo("", lbrace.textRange.endOffset), listOf(TextInlayInfoDetail("it: ")) + renderedType)
}
} else null
return listOfNotNull(implicitReceiverHint, singleParameterHint)
}
private fun ASTNode.isFollowedByNewLine(): Boolean {
for (sibling in siblings()) {
if (sibling.elementType != TokenType.WHITE_SPACE && sibling.psi !is PsiComment) {
continue
}
if (sibling.elementType == TokenType.WHITE_SPACE && sibling.textContains('\n')) {
return true
}
}
return false
}
| apache-2.0 | b5a99bd4350b132cf30479f302716dac | 47.574074 | 158 | 0.763629 | 4.812844 | false | false | false | false |
dkrivoruchko/ScreenStream | mjpeg/src/main/kotlin/info/dvkr/screenstream/mjpeg/httpserver/HttpServer.kt | 1 | 6530 | package info.dvkr.screenstream.mjpeg.httpserver
import android.content.Context
import android.graphics.Bitmap
import com.elvishew.xlog.XLog
import info.dvkr.screenstream.common.AppError
import info.dvkr.screenstream.common.getLog
import info.dvkr.screenstream.mjpeg.*
import info.dvkr.screenstream.mjpeg.image.NotificationBitmap
import info.dvkr.screenstream.mjpeg.settings.MjpegSettings
import io.ktor.server.cio.*
import io.ktor.server.engine.*
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.net.BindException
import java.util.concurrent.atomic.AtomicReference
@OptIn(ExperimentalCoroutinesApi::class)
internal class HttpServer(
applicationContext: Context,
private val parentCoroutineScope: CoroutineScope,
private val mjpegSettings: MjpegSettings,
private val bitmapStateFlow: StateFlow<Bitmap>,
private val notificationBitmap: NotificationBitmap
) {
sealed class Event {
sealed class Action : Event() {
object StartStopRequest : Action()
}
sealed class Statistic : Event() {
class Clients(val clients: List<MjpegClient>) : Statistic()
class Traffic(val traffic: List<MjpegTrafficPoint>) : Statistic()
}
class Error(val error: AppError) : Event()
override fun toString(): String = javaClass.simpleName
}
private val _eventSharedFlow = MutableSharedFlow<Event>(extraBufferCapacity = 64)
val eventSharedFlow: SharedFlow<Event> = _eventSharedFlow.asSharedFlow()
private val httpServerFiles: HttpServerFiles = HttpServerFiles(applicationContext, mjpegSettings)
private val clientData: ClientData = ClientData(mjpegSettings) { sendEvent(it) }
private val stopDeferred: AtomicReference<CompletableDeferred<Unit>?> = AtomicReference(null)
private lateinit var blockedJPEG: ByteArray
private var ktorServer: CIOApplicationEngine? = null
init {
XLog.d(getLog("init"))
}
fun start(serverAddresses: List<NetInterface>) {
XLog.d(getLog("startServer"))
val coroutineExceptionHandler = CoroutineExceptionHandler { _, throwable ->
if (throwable is IOException && throwable !is BindException) return@CoroutineExceptionHandler
if (throwable is CancellationException) return@CoroutineExceptionHandler
XLog.d(getLog("onCoroutineException", "ktorServer: ${ktorServer?.hashCode()}: $throwable"))
XLog.e(getLog("onCoroutineException", throwable.toString()), throwable)
ktorServer?.stop(0, 250)
ktorServer = null
when (throwable) {
is BindException -> sendEvent(Event.Error(AddressInUseException))
else -> sendEvent(Event.Error(HttpServerException))
}
}
val coroutineScope = CoroutineScope(Job() + Dispatchers.Default + coroutineExceptionHandler)
runBlocking(coroutineScope.coroutineContext) {
blockedJPEG = ByteArrayOutputStream().apply {
notificationBitmap.getNotificationBitmap(NotificationBitmap.Type.ADDRESS_BLOCKED)
.compress(Bitmap.CompressFormat.JPEG, 100, this)
}.toByteArray()
}
val resultJpegStream = ByteArrayOutputStream()
val lastJPEG: AtomicReference<ByteArray> = AtomicReference(ByteArray(0))
val mjpegSharedFlow = bitmapStateFlow
.map { bitmap ->
resultJpegStream.reset()
bitmap.compress(Bitmap.CompressFormat.JPEG, mjpegSettings.jpegQualityFlow.first(), resultJpegStream)
resultJpegStream.toByteArray()
}
.flatMapLatest { jpeg ->
lastJPEG.set(jpeg)
flow<ByteArray> { // Send last image every second as keep-alive //TODO Add settings option for this
while (currentCoroutineContext().isActive) {
emit(jpeg)
delay(1000)
}
}
}
.conflate()
.shareIn(coroutineScope, SharingStarted.Eagerly, 1)
runBlocking(coroutineScope.coroutineContext) {
httpServerFiles.configure()
clientData.configure()
}
val environment = applicationEngineEnvironment {
parentCoroutineContext = coroutineScope.coroutineContext
watchPaths = emptyList() // Fix for java.lang.ClassNotFoundException: java.nio.file.FileSystems for API < 26
module { appModule(httpServerFiles, clientData, mjpegSharedFlow, lastJPEG, blockedJPEG, stopDeferred) { sendEvent(it) } }
serverAddresses.forEach { netInterface ->
connector {
host = netInterface.address.hostAddress!!
port = runBlocking(parentCoroutineContext) { mjpegSettings.serverPortFlow.first() }
}
}
}
ktorServer = embeddedServer(CIO, environment) {
connectionIdleTimeoutSeconds = 10
}
var exception: AppError? = null
try {
ktorServer?.start(false)
} catch (ignore: CancellationException) {
} catch (ex: BindException) {
XLog.w(getLog("startServer", ex.toString()))
exception = AddressInUseException
} catch (throwable: Throwable) {
XLog.e(getLog("startServer >>>"))
XLog.e(getLog("startServer"), throwable)
exception = HttpServerException
} finally {
exception?.let {
sendEvent(Event.Error(it))
ktorServer?.stop(0, 250)
ktorServer = null
}
}
}
fun stop(): CompletableDeferred<Unit> {
XLog.d(getLog("stopServer"))
return CompletableDeferred<Unit>().apply Deferred@{
ktorServer?.apply {
stopDeferred.set(this@Deferred)
stop(0, 250)
XLog.d([email protected]("stopServer", "Deferred: ktorServer: ${ktorServer.hashCode()}"))
ktorServer = null
} ?: complete(Unit)
XLog.d([email protected]("stopServer", "Deferred"))
}
}
fun destroy(): CompletableDeferred<Unit> {
XLog.d(getLog("destroy"))
clientData.destroy()
return stop()
}
private fun sendEvent(event: Event) {
parentCoroutineScope.launch { _eventSharedFlow.emit(event) }
}
} | mit | 83afe0a2b41414d48184d48cc1233c89 | 37.875 | 133 | 0.640582 | 5.149842 | false | false | false | false |
nimakro/tornadofx | src/test/kotlin/tornadofx/testapps/PojoTreeTableColumns.kt | 1 | 1976 | package tornadofx.testapps
import javafx.scene.control.TreeItem
import tornadofx.*
import tornadofx.tests.JavaPerson
class PojoTreeTableColumnsApp : App(PojoTreeTableColumns::class)
class PojoTreeTableColumns : View("Pojo Tree Table Columns") {
val people = listOf(
JavaPerson("Mary Hanes", "IT Administration", "[email protected]", "[email protected]", listOf(
JavaPerson("Jacob Mays", "IT Help Desk", "[email protected]", "[email protected]"),
JavaPerson("John Ramsy", "IT Help Desk", "[email protected]", "[email protected]"))),
JavaPerson("Erin James", "Human Resources", "[email protected]", "[email protected]", listOf(
JavaPerson("Erlick Foyes", "Customer Service", "[email protected]", "[email protected]"),
JavaPerson("Steve Folley", "Customer Service", "[email protected]", "[email protected]"),
JavaPerson("Larry Cable", "Customer Service", "[email protected]", "[email protected]")))
).observable()
// Create the root item that holds all top level employees
val rootItem = TreeItem(JavaPerson().apply { name = "Employees by Manager"; employees = people })
override val root = treetableview(rootItem) {
prefWidth = 800.0
column<JavaPerson, String>("Name", "name").contentWidth(50) // non type safe
column("Department", JavaPerson::getDepartment).remainingWidth()
nestedColumn("Email addresses") {
column("Primary Email", JavaPerson::getPrimaryEmail)
column("Secondary Email", JavaPerson::getSecondaryEmail)
}
// Always return employees under the current person
populate { it.value.employees }
// Expand the two first levels
root.isExpanded = true
root.children.withEach { isExpanded = true }
smartResize()
}
} | apache-2.0 | db634c1d0e08f409d8e2832c344a35ac | 46.071429 | 124 | 0.658401 | 3.714286 | false | false | false | false |
kotlinx/kotlinx.html | src/commonMain/kotlin/generated/gen-attributes.kt | 1 | 2584 | package kotlinx.html
import kotlinx.html.*
import kotlinx.html.attributes.*
/*******************************************************************************
DO NOT EDIT
This file was generated by module generate
*******************************************************************************/
internal val attributeStringString : Attribute<String> = StringAttribute()
internal val attributeSetStringStringSet : Attribute<Set<String>> = StringSetAttribute()
internal val attributeBooleanBoolean : Attribute<Boolean> = BooleanAttribute()
internal val attributeBooleanBooleanOnOff : Attribute<Boolean> = BooleanAttribute("on", "off")
internal val attributeBooleanTicker : Attribute<Boolean> = TickerAttribute()
internal val attributeButtonFormEncTypeEnumButtonFormEncTypeValues : Attribute<ButtonFormEncType> = EnumAttribute(buttonFormEncTypeValues)
internal val attributeButtonFormMethodEnumButtonFormMethodValues : Attribute<ButtonFormMethod> = EnumAttribute(buttonFormMethodValues)
internal val attributeButtonTypeEnumButtonTypeValues : Attribute<ButtonType> = EnumAttribute(buttonTypeValues)
internal val attributeCommandTypeEnumCommandTypeValues : Attribute<CommandType> = EnumAttribute(commandTypeValues)
internal val attributeDirEnumDirValues : Attribute<Dir> = EnumAttribute(dirValues)
internal val attributeDraggableEnumDraggableValues : Attribute<Draggable> = EnumAttribute(draggableValues)
internal val attributeFormEncTypeEnumFormEncTypeValues : Attribute<FormEncType> = EnumAttribute(formEncTypeValues)
internal val attributeFormMethodEnumFormMethodValues : Attribute<FormMethod> = EnumAttribute(formMethodValues)
internal val attributeIframeSandboxEnumIframeSandboxValues : Attribute<IframeSandbox> = EnumAttribute(iframeSandboxValues)
internal val attributeInputFormEncTypeEnumInputFormEncTypeValues : Attribute<InputFormEncType> = EnumAttribute(inputFormEncTypeValues)
internal val attributeInputFormMethodEnumInputFormMethodValues : Attribute<InputFormMethod> = EnumAttribute(inputFormMethodValues)
internal val attributeInputTypeEnumInputTypeValues : Attribute<InputType> = EnumAttribute(inputTypeValues)
internal val attributeKeyGenKeyTypeEnumKeyGenKeyTypeValues : Attribute<KeyGenKeyType> = EnumAttribute(keyGenKeyTypeValues)
internal val attributeRunAtEnumRunAtValues : Attribute<RunAt> = EnumAttribute(runAtValues)
internal val attributeTextAreaWrapEnumTextAreaWrapValues : Attribute<TextAreaWrap> = EnumAttribute(textAreaWrapValues)
internal val attributeThScopeEnumThScopeValues : Attribute<ThScope> = EnumAttribute(thScopeValues)
| apache-2.0 | 2a6899859e165b432f343dc6b213fd9e | 48.692308 | 138 | 0.806889 | 4.959693 | false | false | false | false |
jsocle/jsocle-form | src/main/kotlin/com/github/jsocle/form/fields/CheckboxField.kt | 2 | 845 | package com.github.jsocle.form.fields
import com.github.jsocle.form.Field
import com.github.jsocle.form.FieldMapper
import com.github.jsocle.html.elements.Ul
import kotlin.collections.forEach
import kotlin.collections.listOf
open class CheckboxField<T : Any>(var choices: List<Pair<T, String>> = listOf(), mapper: FieldMapper<T>, defaults: List<T> = listOf())
: Field<T, Ul>(mapper, defaults) {
override fun render(): Ul {
return Ul(class_ = "jsocle-form-field-checkbox") {
choices.forEach {
li {
label {
input(type = "checkbox", name = name, value = mapper.toString(it.first), checked = if (it.first in [email protected]) "checked" else null)
+it.second
}
}
}
}
}
} | mit | 7e230f6a594537d3cca99031e7284042 | 34.25 | 170 | 0.590533 | 3.858447 | false | false | false | false |
GunoH/intellij-community | platform/lang-impl/testSources/com/intellij/build/output/BuildOutputInstantReaderImplTest.kt | 7 | 7255 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.build.output
import com.intellij.build.BuildProgressListener
import com.intellij.build.events.MessageEvent
import com.intellij.build.events.MessageEvent.Kind.*
import com.intellij.build.events.impl.MessageEventImpl
import org.junit.Assert
import org.junit.Test
import java.util.*
import kotlin.collections.ArrayList
class BuildOutputInstantReaderImplTest {
@Test
fun `sanity test`() {
doTest(mutableListOf(
createParser("[info]", INFO),
createParser("[error]", ERROR),
createParser("[warning]", WARNING)))
}
@Test
fun `test reading with greedy parser`() {
val greedyParser = BuildOutputParser { _, reader, _ ->
var count = 0
while (count < pushBackBufferSize && reader.readLine() != null) {
count++
}
reader.pushBack(count)
return@BuildOutputParser false
}
doTest(mutableListOf(
createParser("[info]", INFO),
greedyParser,
createParser("[error]", ERROR),
createParser("[warning]", WARNING)))
}
@Test
fun `test reading lot of lines to merge`() {
val predicate: (String) -> Boolean = { it.startsWith("[warning]") }
val parser = BuildOutputParser { line, reader, c ->
var next: String? = line
var count = 0
while (next != null) {
if (predicate(next)) {
count++
next = reader.readLine()
}
else {
if (count != 0) {
c.accept(MessageEventImpl(Object(), WARNING, "test", "lines of warns:" + count, null))
reader.pushBack()
return@BuildOutputParser true
}
else {
return@BuildOutputParser false
}
}
}
return@BuildOutputParser false
}
val buildId = Object()
val messages = mutableListOf<String>()
val outputReader = BuildOutputInstantReaderImpl(buildId, buildId,
BuildProgressListener { _, event -> messages += event.message },
listOf(parser, createParser("[error]", ERROR)), pushBackBufferSize)
val inputData = buildString {
appendln("[warning] this is a warning\n".repeat(80))
appendln("[error] error1\n")
}
outputReader.append(inputData).closeAndGetFuture().get()
Assert.assertEquals("""
lines of warns:80
error1
""".trimIndent(), messages.joinToString("\n").trimEnd())
}
@Test
fun `test reading with too greedy parser`() {
val greedyParser = BuildOutputParser { _, reader, _ ->
var count = 0
while (count <= pushBackBufferSize && reader.readLine() != null) {
count++
}
reader.pushBack(count)
return@BuildOutputParser false
}
doTest(mutableListOf(
createParser("[info]", INFO),
greedyParser,
createParser("[error]", ERROR),
createParser("[warning]", WARNING)), false)
}
@Test
fun `test bad parser pushed back too many lines`() {
val badParser = BuildOutputParser { _, reader, _ ->
reader.pushBack(pushBackBufferSize * 2)
return@BuildOutputParser false
}
doTest(mutableListOf(
createParser("[info]", INFO),
badParser,
createParser("[error]", ERROR),
createParser("[warning]", WARNING)))
}
@Test
fun `test producer will wait for consumer`() {
fun line(i: Int) = "line #$i"
fun String?.appended() = "'$this' appended"
fun String?.parsed() = "'$this' parsed"
val eventLog = Collections.synchronizedList(ArrayList<String>())
val slowParser = BuildOutputParser { line, _, _ ->
Thread.sleep(100)
eventLog += line.parsed()
false
}
val lines = (0..5).map(::line)
val outputReader = BuildOutputInstantReaderImpl(Object(), Object(), BuildProgressListener { _, _ -> }, listOf(slowParser), 0, 1)
lines.forEach {
outputReader.appendln(it)
eventLog += it.appended()
}
outputReader.closeAndGetFuture().get()
val expected = listOf(
line(0).appended(), line(1).appended(), /* parser keeps each line as additional single line buffer */
line(0).parsed(),
line(2).appended(),
line(1).parsed(),
line(3).appended(),
line(2).parsed(),
line(4).appended(),
line(3).parsed(),
line(5).appended(),
line(4).parsed(), line(5).parsed()
)
Assert.assertEquals(expected, eventLog)
}
companion object {
private fun doTest(parsers: MutableList<BuildOutputParser>, assertUnparsedLines: Boolean = true) {
val messages = mutableListOf<String>()
val unparsedLines = mutableListOf<String>()
val parser = BuildOutputParser { line, _, _ ->
unparsedLines.add(line)
true
}
parsers.add(parser)
val buildId = Object()
val outputReader = BuildOutputInstantReaderImpl(buildId, buildId,
BuildProgressListener {
_,
event -> messages += event.message
},
parsers, pushBackBufferSize)
val trashOut = (0 until pushBackBufferSize).map { "trash" }
val infoLines = """
[info] info1
info2
info3
""".trimIndent()
val warnLines = """
[warning] warn1
warn2
""".trimIndent()
val errLines = """
[error] error1
""".trimIndent()
val inputData = buildString {
trashOut.joinTo(this, "\n", postfix = "\n")
appendln(errLines)
appendln()
appendln(infoLines)
appendln()
appendln(infoLines) /* checks that duplicate messages are not sent */
appendln()
trashOut.joinTo(this, "\n", postfix = "\n")
appendln(warnLines)
}
outputReader.append(inputData).closeAndGetFuture().get()
if (assertUnparsedLines) {
Assert.assertEquals(trashOut + trashOut, unparsedLines)
}
Assert.assertEquals("""
error1
info1
info2
info3
warn1
warn2
""".trimIndent().replace("\r?\n".toRegex(), "\n"), messages.joinToString("\n").trimEnd().replace("\r?\n".toRegex(), "\n"))
}
private const val pushBackBufferSize = 50
private fun createParser(prefix: String, kind: MessageEvent.Kind): BuildOutputParser {
return BuildOutputParser { line, reader, messageConsumer ->
if (line.startsWith(prefix)) {
val buf = StringBuilder()
var nextLine: String? = line.dropWhile { !it.isWhitespace() }.trimStart()
while (!nextLine.isNullOrBlank() && !nextLine.startsWith('[')) {
buf.appendln(nextLine)
nextLine = reader.readLine()
}
messageConsumer.accept(MessageEventImpl(reader.parentEventId, kind, null, buf.toString().dropLast(1), null))
return@BuildOutputParser true
}
return@BuildOutputParser false
}
}
}
}
| apache-2.0 | 025a5b33bc06c778fcd8d59d9b85f5ce | 30.543478 | 140 | 0.582081 | 4.701879 | false | true | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/LambdaToAnonymousFunctionIntention.kt | 1 | 7967 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.editor.Editor
import org.jetbrains.kotlin.builtins.isSuspendFunctionType
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
import org.jetbrains.kotlin.descriptors.impl.AnonymousFunctionDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.core.moveInsideParentheses
import org.jetbrains.kotlin.idea.core.replaced
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.BranchedFoldingUtils
import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.quoteIfNeeded
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.getTargetFunctionDescriptor
import org.jetbrains.kotlin.resolve.calls.callUtil.getParameterForArgument
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.ErrorType
import org.jetbrains.kotlin.types.isFlexible
import org.jetbrains.kotlin.types.typeUtil.isTypeParameter
import org.jetbrains.kotlin.types.typeUtil.isUnit
import org.jetbrains.kotlin.types.typeUtil.makeNotNullable
class LambdaToAnonymousFunctionIntention : SelfTargetingIntention<KtLambdaExpression>(
KtLambdaExpression::class.java,
KotlinBundle.lazyMessage("convert.to.anonymous.function"),
KotlinBundle.lazyMessage("convert.lambda.expression.to.anonymous.function")
), LowPriorityAction {
override fun isApplicableTo(element: KtLambdaExpression, caretOffset: Int): Boolean {
val argument = element.getStrictParentOfType<KtValueArgument>()
val call = argument?.getStrictParentOfType<KtCallElement>()
if (call?.getStrictParentOfType<KtFunction>()?.hasModifier(KtTokens.INLINE_KEYWORD) == true) return false
val context = element.analyze(BodyResolveMode.PARTIAL)
if (call?.getResolvedCall(context)?.getParameterForArgument(argument)?.type?.isSuspendFunctionType == true) return false
val descriptor = context[
BindingContext.DECLARATION_TO_DESCRIPTOR,
element.functionLiteral,
] as? AnonymousFunctionDescriptor ?: return false
if (descriptor.valueParameters.any { it.name.isSpecial || it.type is ErrorType }) return false
val lastElement = element.functionLiteral.arrow ?: element.functionLiteral.lBrace
return caretOffset <= lastElement.endOffset
}
override fun applyTo(element: KtLambdaExpression, editor: Editor?) {
val functionDescriptor = element.functionLiteral.descriptor as? AnonymousFunctionDescriptor ?: return
val resultingFunction = convertLambdaToFunction(element, functionDescriptor) ?: return
val argument = when (val parent = resultingFunction.parent) {
is KtLambdaArgument -> parent
is KtLabeledExpression -> parent.replace(resultingFunction).parent as? KtLambdaArgument
else -> null
} ?: return
argument.moveInsideParentheses(argument.analyze(BodyResolveMode.PARTIAL))
}
companion object {
fun convertLambdaToFunction(
lambda: KtLambdaExpression,
functionDescriptor: FunctionDescriptor,
functionName: String = "",
functionParameterName: (ValueParameterDescriptor, Int) -> String = { parameter, _ ->
parameter.name.asString().quoteIfNeeded()
},
typeParameters: Map<String, KtTypeReference> = emptyMap(),
replaceElement: (KtNamedFunction) -> KtExpression = { lambda.replaced(it) }
): KtExpression? {
val typeSourceCode = IdeDescriptorRenderers.SOURCE_CODE_TYPES
val functionLiteral = lambda.functionLiteral
val bodyExpression = functionLiteral.bodyExpression ?: return null
val context = bodyExpression.analyze(BodyResolveMode.PARTIAL)
val functionLiteralDescriptor by lazy { functionLiteral.descriptor }
bodyExpression.collectDescendantsOfType<KtReturnExpression>().forEach {
val targetDescriptor = it.getTargetFunctionDescriptor(context)
if (targetDescriptor == functionDescriptor || targetDescriptor == functionLiteralDescriptor) it.labeledExpression?.delete()
}
val psiFactory = KtPsiFactory(lambda)
val function = psiFactory.createFunction(
KtPsiFactory.CallableBuilder(KtPsiFactory.CallableBuilder.Target.FUNCTION).apply {
typeParams()
functionDescriptor.extensionReceiverParameter?.type?.let {
receiver(typeSourceCode.renderType(it))
}
name(functionName)
for ((index, parameter) in functionDescriptor.valueParameters.withIndex()) {
val type = parameter.type.let { if (it.isFlexible()) it.makeNotNullable() else it }
val renderType = typeSourceCode.renderType(type)
val parameterName = functionParameterName(parameter, index)
if (type.isTypeParameter()) {
param(parameterName, typeParameters[renderType]?.text ?: renderType)
} else {
param(parameterName, renderType)
}
}
functionDescriptor.returnType?.takeIf { !it.isUnit() }?.let {
val lastStatement = bodyExpression.statements.lastOrNull()
if (lastStatement != null && lastStatement !is KtReturnExpression) {
val foldableReturns = BranchedFoldingUtils.getFoldableReturns(lastStatement)
if (foldableReturns == null || foldableReturns.isEmpty()) {
lastStatement.replace(psiFactory.createExpressionByPattern("return $0", lastStatement))
}
}
val renderType = typeSourceCode.renderType(it)
if (it.isTypeParameter()) {
returnType(typeParameters[renderType]?.text ?: renderType)
} else {
returnType(renderType)
}
} ?: noReturnType()
blockBody(" " + bodyExpression.text)
}.asString()
)
val result = wrapInParenthesisIfNeeded(replaceElement(function), psiFactory)
ShortenReferences.DEFAULT.process(result)
return result
}
private fun wrapInParenthesisIfNeeded(expression: KtExpression, psiFactory: KtPsiFactory): KtExpression {
val parent = expression.parent ?: return expression
val grandParent = parent.parent ?: return expression
if (parent is KtCallExpression && grandParent !is KtParenthesizedExpression && grandParent !is KtDeclaration) {
return expression.replaced(psiFactory.createExpressionByPattern("($0)", expression))
}
return expression
}
}
}
| apache-2.0 | 9f9a979c473dc6e6a7de7c94be4ba9f6 | 52.469799 | 158 | 0.681938 | 5.963323 | false | false | false | false |
JetBrains/kotlin-native | backend.native/tests/codegen/controlflow/for_loops_nested.kt | 4 | 1264 | /*
* 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 codegen.controlflow.for_loops_nested
import kotlin.test.*
@Test fun runTest() {
// Simple
for (i in 0..2) {
for (j in 0..2) {
print("$i$j ")
}
}
println()
// Break
l1@for (i in 0..2) {
l2@for (j in 0..2) {
print("$i$j ")
if (j == 1) break
}
}
println()
l1@for (i in 0..2) {
l2@for (j in 0..2) {
print("$i$j ")
if (j == 1) break@l2
}
}
println()
l1@for (i in 0..2) {
l2@for (j in 0..2) {
print("$i$j ")
if (j == 1) break@l1
}
}
println()
// Continue
l1@for (i in 0..2) {
l2@for (j in 0..2) {
if (j == 1) continue
print("$i$j ")
}
}
println()
l1@for (i in 0..2) {
l2@for (j in 0..2) {
if (j == 1) continue@l2
print("$i$j ")
}
}
println()
l1@for (i in 0..2) {
l2@for (j in 0..2) {
if (j == 1) continue@l1
print("$i$j ")
}
}
println()
} | apache-2.0 | 77ebf4dcc056f11533297c2a47230f94 | 17.602941 | 101 | 0.396361 | 3.05314 | false | false | false | false |
GoogleContainerTools/google-container-tools-intellij | core/src/main/kotlin/com/google/container/tools/core/analytics/UsageTrackerProvider.kt | 1 | 2900 | /*
* Copyright 2018 Google Inc. All Rights Reserved.
*
* 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.container.tools.core.analytics
import com.google.cloud.tools.ide.analytics.UsageTracker
import com.google.cloud.tools.ide.analytics.UsageTrackerManager
import com.google.cloud.tools.ide.analytics.UsageTrackerSettings
import com.google.common.annotations.VisibleForTesting
import com.google.container.tools.core.PluginInfo
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.application.PermanentInstallationID
import com.intellij.openapi.components.ServiceManager
/**
* Application service that initializes the [UsageTracker] for analytics. Sets up core components
* of analytics collection such as the analytics ID, user agent, client ID etc.
*
* Example usage:
* ```
* UsageTrackerProvider.instance.usageTracker.trackEvent("event-name").ping()
* ```
*/
class UsageTrackerProvider {
@VisibleForTesting
var usageTrackerSettings: UsageTrackerSettings
init {
val usageTrackerManagerService: UsageTrackerManagerService =
UsageTrackerManagerService.instance
usageTrackerSettings = UsageTrackerSettings.Builder()
.manager { usageTrackerManagerService.isUsageTrackingEnabled() }
.analyticsId(usageTrackerManagerService.getAnalyticsId())
.pageHost(PAGE_HOST)
.platformName(PluginInfo.instance.platformPrefix)
.platformVersion(ApplicationInfo.getInstance().strictVersion)
.pluginName(PluginInfo.PLUGIN_NAME_EXTERNAL)
.pluginVersion(PluginInfo.instance.pluginVersion)
.clientId(PermanentInstallationID.get())
.userAgent(PluginInfo.PLUGIN_USER_AGENT)
.build()
}
/**
* Returns the appropriate implementation of [UsageTracker]. The implementation will change -
* from either a noop version, or the real version - depending on the value returned by the
* [UsageTrackerManager] callback which will depend on the current user selected tracking
* preference.
*/
val usageTracker: UsageTracker get() = UsageTracker.create(usageTrackerSettings)
companion object {
private const val PAGE_HOST = "virtual.intellij"
val instance
get() = ServiceManager.getService(UsageTrackerProvider::class.java)!!
}
}
| apache-2.0 | 23fd4d65b1ebeddf40197e52039e1390 | 38.726027 | 97 | 0.738621 | 4.809287 | false | false | false | false |
hsz/idea-gitignore | src/main/kotlin/mobi/hsz/idea/gitignore/IgnoreBundle.kt | 1 | 6391 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package mobi.hsz.idea.gitignore
import com.intellij.AbstractBundle
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.VirtualFile
import mobi.hsz.idea.gitignore.file.type.IgnoreFileType
import mobi.hsz.idea.gitignore.lang.IgnoreLanguage
import mobi.hsz.idea.gitignore.lang.kind.BazaarLanguage
import mobi.hsz.idea.gitignore.lang.kind.ChefLanguage
import mobi.hsz.idea.gitignore.lang.kind.CloudFoundryLanguage
import mobi.hsz.idea.gitignore.lang.kind.CvsLanguage
import mobi.hsz.idea.gitignore.lang.kind.DarcsLanguage
import mobi.hsz.idea.gitignore.lang.kind.DockerLanguage
import mobi.hsz.idea.gitignore.lang.kind.ESLintLanguage
import mobi.hsz.idea.gitignore.lang.kind.ElasticBeanstalkLanguage
import mobi.hsz.idea.gitignore.lang.kind.FloobitsLanguage
import mobi.hsz.idea.gitignore.lang.kind.FossilLanguage
import mobi.hsz.idea.gitignore.lang.kind.GitLanguage
import mobi.hsz.idea.gitignore.lang.kind.GoogleCloudLanguage
import mobi.hsz.idea.gitignore.lang.kind.HelmLanguage
import mobi.hsz.idea.gitignore.lang.kind.JSHintLanguage
import mobi.hsz.idea.gitignore.lang.kind.JetpackLanguage
import mobi.hsz.idea.gitignore.lang.kind.MercurialLanguage
import mobi.hsz.idea.gitignore.lang.kind.MonotoneLanguage
import mobi.hsz.idea.gitignore.lang.kind.NodemonLanguage
import mobi.hsz.idea.gitignore.lang.kind.NpmLanguage
import mobi.hsz.idea.gitignore.lang.kind.NuxtJSLanguage
import mobi.hsz.idea.gitignore.lang.kind.PerforceLanguage
import mobi.hsz.idea.gitignore.lang.kind.PrettierLanguage
import mobi.hsz.idea.gitignore.lang.kind.StyleLintLanguage
import mobi.hsz.idea.gitignore.lang.kind.StylintLanguage
import mobi.hsz.idea.gitignore.lang.kind.SwaggerCodegenLanguage
import mobi.hsz.idea.gitignore.lang.kind.TFLanguage
import mobi.hsz.idea.gitignore.lang.kind.UpLanguage
import mobi.hsz.idea.gitignore.util.CachedConcurrentMap
import org.jetbrains.annotations.NonNls
import org.jetbrains.annotations.PropertyKey
import java.util.ArrayList
import java.util.ResourceBundle
/**
* [ResourceBundle]/localization utils for the .ignore support plugin.
*/
object IgnoreBundle : AbstractBundle("messages.IgnoreBundle") {
@NonNls
const val BUNDLE_NAME = "messages.IgnoreBundle"
private val BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME)
val LANGUAGES = IgnoreLanguages(
listOf(
BazaarLanguage.INSTANCE,
CloudFoundryLanguage.INSTANCE,
ChefLanguage.INSTANCE,
CvsLanguage.INSTANCE,
DarcsLanguage.INSTANCE,
DockerLanguage.INSTANCE,
ElasticBeanstalkLanguage.INSTANCE,
ESLintLanguage.INSTANCE,
FloobitsLanguage.INSTANCE,
FossilLanguage.INSTANCE,
GitLanguage.INSTANCE,
GoogleCloudLanguage.INSTANCE,
HelmLanguage.INSTANCE,
JetpackLanguage.INSTANCE,
JSHintLanguage.INSTANCE,
MercurialLanguage.INSTANCE,
MonotoneLanguage.INSTANCE,
NodemonLanguage.INSTANCE,
NpmLanguage.INSTANCE,
NuxtJSLanguage.INSTANCE,
PerforceLanguage.INSTANCE,
PrettierLanguage.INSTANCE,
StyleLintLanguage.INSTANCE,
StylintLanguage.INSTANCE,
SwaggerCodegenLanguage.INSTANCE,
TFLanguage.INSTANCE,
UpLanguage.INSTANCE
)
)
/**Highlighting for the mentioned languages already provided by IDEA core */
private val IGNORE_LANGUAGES_HIGHLIGHTING_EXCLUDED = arrayOf(
GitLanguage.INSTANCE,
MercurialLanguage.INSTANCE,
PerforceLanguage.INSTANCE
)
/** Available IgnoreFileType instances filtered with [IgnoreLanguage.isVCS] condition. */
val VCS_LANGUAGES = IgnoreLanguages(
LANGUAGES.filter(IgnoreLanguage::isVCS)
)
/** Contains information about enabled/disabled languages. */
val ENABLED_LANGUAGES = CachedConcurrentMap.create<IgnoreFileType, Boolean> { key -> key.ignoreLanguage.isEnabled }
/**
* Loads a [String] from the [.BUNDLE] [ResourceBundle].
*
* @param key the key of the resource
* @param params the optional parameters for the specific resource
* @return the [String] value or `null` if no resource found for the key
*/
fun message(@PropertyKey(resourceBundle = BUNDLE_NAME) key: String, vararg params: Any?) = message(BUNDLE, key, *params)
/**
* Loads a [String] from the [.BUNDLE] [ResourceBundle].
*
* @param key the key of the resource
* @param params the optional parameters for the specific resource
* @return the [String] value or `null` if no resource found for the key
*/
fun messagePointer(@PropertyKey(resourceBundle = BUNDLE_NAME) key: String, vararg params: Any?) = getLazyMessage(key, *params)
/**
* Returns [IgnoreLanguage] matching to the given [VirtualFile].
*
* @param file to obtain
* @return matching language
*/
fun obtainLanguage(file: VirtualFile) = LANGUAGES.find { it.filename == file.name }
fun isExcludedFromHighlighting(language: IgnoreLanguage) = IGNORE_LANGUAGES_HIGHLIGHTING_EXCLUDED.contains(language)
/** Available syntax list. */
enum class Syntax {
GLOB, REGEXP;
override fun toString() = super.toString().toLowerCase()
/**
* Returns [mobi.hsz.idea.gitignore.psi.IgnoreTypes.SYNTAX] element presentation.
*
* @return element presentation
*/
val presentation
get() = StringUtil.join(KEY, " ", toString())
companion object {
@NonNls
private val KEY = "syntax:"
fun find(name: String?) = when (name) {
null -> null
else ->
try {
valueOf(name.toUpperCase())
} catch (iae: IllegalArgumentException) {
null
}
}
}
}
/**
* Simple [ArrayList] with method to find [IgnoreLanguage] by its name.
*/
class IgnoreLanguages(languages: List<IgnoreLanguage>) : ArrayList<IgnoreLanguage>(languages) {
operator fun get(id: String) = find { id == it.id }
}
}
| mit | 1cc55ea1d0a36709a1b171e84d74a1eb | 37.969512 | 140 | 0.69723 | 4.318243 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/utils/ColorPickerFactory.kt | 1 | 3462 | package ch.rmy.android.http_shortcuts.utils
import android.app.Dialog
import android.graphics.Color
import android.text.InputFilter
import android.view.LayoutInflater
import androidx.annotation.ColorInt
import androidx.core.widget.addTextChangedListener
import ch.rmy.android.framework.extensions.runIfNotNull
import ch.rmy.android.framework.utils.localization.Localizable
import ch.rmy.android.http_shortcuts.R
import ch.rmy.android.http_shortcuts.databinding.DialogColorPickerBinding
import ch.rmy.android.http_shortcuts.utils.ColorUtil.colorIntToHexString
import ch.rmy.android.http_shortcuts.utils.ColorUtil.hexStringToColorInt
import com.skydoves.colorpickerview.listeners.ColorListener
import javax.inject.Inject
class ColorPickerFactory
@Inject
constructor(
private val activityProvider: ActivityProvider,
) {
fun createColorPicker(
onColorPicked: (Int) -> Unit,
onDismissed: () -> Unit,
title: Localizable = Localizable.EMPTY,
@ColorInt initialColor: Int? = null,
): Dialog {
val activity = activityProvider.getActivity()
val binding = DialogColorPickerBinding.inflate(LayoutInflater.from(activity))
binding.colorPickerView.attachBrightnessSlider(binding.brightnessSlideBar)
var suppressTextWatcher = false
var selectedColor = initialColor ?: Color.BLACK
binding.colorPickerView.setInitialColor(selectedColor)
fun updateColorInputView() {
suppressTextWatcher = true
val selectionStart = binding.inputColor.selectionStart
val selectionEnd = binding.inputColor.selectionEnd
binding.inputColor.setText(selectedColor.colorIntToHexString())
suppressTextWatcher = false
if (selectionStart != -1 && selectionEnd != -1) {
binding.inputColor.setSelection(selectionStart, selectionEnd)
} else {
binding.inputColor.setSelection(6)
}
binding.inputColorBackdrop.setBackgroundColor(selectedColor)
}
binding.inputColor.filters = arrayOf(
InputFilter { source, _, _, _, _, _ -> source.replace("[^A-Fa-f0-9]".toRegex(), "").uppercase() },
InputFilter.LengthFilter(6),
)
binding.inputColor.addTextChangedListener { text ->
binding.inputColorBackdrop.text = "#$text "
if (!suppressTextWatcher) {
val color = text?.toString()
?.takeIf { it.length == 6 }
?.hexStringToColorInt()
if (color != null) {
selectedColor = color
binding.colorPickerView.selectByHsvColor(color)
updateColorInputView()
}
}
}
binding.colorPickerView.setColorListener(object : ColorListener {
override fun onColorSelected(color: Int, fromUser: Boolean) {
selectedColor = color
updateColorInputView()
}
})
updateColorInputView()
return DialogBuilder(activity)
.runIfNotNull(title) {
title(it)
}
.view(binding.root)
.positive(R.string.dialog_ok) {
onColorPicked(selectedColor)
}
.negative(R.string.dialog_cancel)
.dismissListener {
onDismissed()
}
.build()
}
}
| mit | 2d0f029c4a1c741e2b37fb91218e407a | 36.630435 | 110 | 0.635471 | 5.159463 | false | false | false | false |
glorantq/KalanyosiRamszesz | src/glorantq/ramszesz/commands/ExecCommand.kt | 1 | 1919 | package glorantq.ramszesz.commands
import glorantq.ramszesz.Ramszesz
import glorantq.ramszesz.utils.BotUtils
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent
import sx.blah.discord.handle.obj.IMessage
import java.net.URL
class ExecCommand : ICommand {
override val commandName: String
get() = "exec"
override val description: String
get() = "Execute scripts"
override val permission: Permission
get() = Permission.BOT_OWNER
override val undocumented: Boolean
get() = true
override val usage: String
get() = "[script] (can be an attachment)"
override val availableInDM: Boolean
get() = true
override fun execute(event: MessageReceivedEvent, args: List<String>) {
val rawCode: String
when {
event.message.attachments.isNotEmpty() -> {
val attachment: IMessage.Attachment = event.message.attachments[0]
try {
val url = URL(attachment.url)
val request: Request = Request.Builder().url(url).get().build()
val response: Response = OkHttpClient.Builder().build().newCall(request).execute()
rawCode = response.body()!!.string()
} catch (e: Exception) {
BotUtils.sendMessage(BotUtils.createSimpleEmbed("Script Execution", "Failed to process attachment!", event.author), event.channel)
return
}
}
args.isNotEmpty() -> rawCode = args.joinToString(" ")
else -> {
BotUtils.sendUsageEmbed("No code supplied!", "Script Execution", event.author, event, this)
return
}
}
Ramszesz.instance.scriptingContext.runCode(rawCode, event)
}
} | gpl-3.0 | a05580fa3cc967f690c5b2bcd2b75fa8 | 37.4 | 150 | 0.619072 | 4.809524 | false | false | false | false |
mikepenz/MaterialDrawer | app/src/main/java/com/mikepenz/materialdrawer/app/MultiDrawerActivity.kt | 1 | 6208 | package com.mikepenz.materialdrawer.app
import android.os.Bundle
import android.view.MenuItem
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.mikepenz.iconics.typeface.library.fontawesome.FontAwesome
import com.mikepenz.iconics.typeface.library.fontawesome.FontAwesomeBrand
import com.mikepenz.materialdrawer.app.databinding.ActivityMultiSampleBinding
import com.mikepenz.materialdrawer.app.drawerItems.GmailDrawerItem
import com.mikepenz.materialdrawer.iconics.withIcon
import com.mikepenz.materialdrawer.model.PrimaryDrawerItem
import com.mikepenz.materialdrawer.model.SecondaryDrawerItem
import com.mikepenz.materialdrawer.model.SectionDrawerItem
import com.mikepenz.materialdrawer.model.interfaces.*
import com.mikepenz.materialdrawer.util.updateItem
class MultiDrawerActivity : AppCompatActivity() {
private lateinit var binding: ActivityMultiSampleBinding
override fun onCreate(savedInstanceState: Bundle?) {
//supportRequestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
super.onCreate(savedInstanceState)
binding = ActivityMultiSampleBinding.inflate(layoutInflater).also {
setContentView(it.root)
}
// Handle Toolbar
setSupportActionBar(binding.toolbar)
supportActionBar?.setTitle(R.string.drawer_item_multi_drawer)
binding.slider.apply {
itemAdapter.add(
GmailDrawerItem().withName(R.string.drawer_item_home).withIcon(FontAwesome.Icon.faw_home).withIdentifier(1),
GmailDrawerItem().withName(R.string.drawer_item_free_play).withIcon(FontAwesome.Icon.faw_gamepad),
GmailDrawerItem().withName(R.string.drawer_item_custom).withIcon(FontAwesome.Icon.faw_eye).withIdentifier(5),
SectionDrawerItem().withName(R.string.drawer_item_section_header),
SecondaryDrawerItem().withName(R.string.drawer_item_settings).withIcon(FontAwesome.Icon.faw_cog),
SecondaryDrawerItem().withName(R.string.drawer_item_help).withIcon(FontAwesome.Icon.faw_question).withEnabled(false),
SecondaryDrawerItem().withName(R.string.drawer_item_open_source).withIcon(FontAwesomeBrand.Icon.fab_github),
SecondaryDrawerItem().withName(R.string.drawer_item_contact).withIcon(FontAwesome.Icon.faw_bullhorn)
)
adapter.onClickListener = { v, adapter, drawerItem, position ->
if (drawerItem is Badgeable) {
if (drawerItem.badge != null) {
//note don't do this if your badge contains a "+"
//only use toString() if you set the test as String
val badge = Integer.valueOf(drawerItem.badge?.toString() ?: "0")
if (badge > 0) {
drawerItem.withBadge((badge - 1).toString())
binding.slider.updateItem(drawerItem)
}
}
}
if (drawerItem is Nameable) {
Toast.makeText(this@MultiDrawerActivity, drawerItem.name?.getText(this@MultiDrawerActivity), Toast.LENGTH_SHORT).show()
}
false
}
setSavedInstance(savedInstanceState)
setSelectionAtPosition(0)
}
binding.sliderEnd.apply {
stickyHeaderView = layoutInflater.inflate(R.layout.header, null)
itemAdapter.add(
PrimaryDrawerItem().withName(R.string.drawer_item_home).withIcon(FontAwesome.Icon.faw_home).withIdentifier(1),
PrimaryDrawerItem().withName(R.string.drawer_item_free_play).withIcon(FontAwesome.Icon.faw_gamepad),
PrimaryDrawerItem().withName(R.string.drawer_item_custom).withIcon(FontAwesome.Icon.faw_eye).withIdentifier(5),
SectionDrawerItem().withName(R.string.drawer_item_section_header),
SecondaryDrawerItem().withName(R.string.drawer_item_settings).withIcon(FontAwesome.Icon.faw_cog),
SecondaryDrawerItem().withName(R.string.drawer_item_help).withIcon(FontAwesome.Icon.faw_question).withEnabled(false),
SecondaryDrawerItem().withName(R.string.drawer_item_open_source).withIcon(FontAwesomeBrand.Icon.fab_github),
SecondaryDrawerItem().withName(R.string.drawer_item_contact).withIcon(FontAwesome.Icon.faw_bullhorn)
)
adapter.onClickListener = { v, adapter, drawerItem, position ->
if (drawerItem is Nameable) {
Toast.makeText(this@MultiDrawerActivity, drawerItem.name?.getText(this@MultiDrawerActivity), Toast.LENGTH_SHORT).show()
}
false
}
savedInstanceKey = "end"
setSavedInstance(savedInstanceState)
}
//set the back arrow in the toolbar
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setHomeButtonEnabled(false)
}
override fun onSaveInstanceState(_outState: Bundle) {
var outState = _outState
//add the values which need to be saved from the drawer to the bundle
outState = binding.slider.saveInstanceState(outState)
//add the values which need to be saved from the drawer to the bundle
outState = binding.sliderEnd.saveInstanceState(outState)
super.onSaveInstanceState(outState)
}
override fun onBackPressed() {
//handle the back press :D close the drawer first and if the drawer is closed close the activity
when {
binding.root.isDrawerOpen(binding.slider) -> binding.root.closeDrawer(binding.slider)
binding.root.isDrawerOpen(binding.sliderEnd) -> binding.root.closeDrawer(binding.sliderEnd)
else -> super.onBackPressed()
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
//handle the click on the back arrow click
return when (item.itemId) {
android.R.id.home -> {
onBackPressed()
true
}
else -> super.onOptionsItemSelected(item)
}
}
}
| apache-2.0 | d3eccb9ed616546ee063c3da091a25ea | 49.885246 | 139 | 0.664304 | 4.970376 | false | false | false | false |
flicus/vertx-telegram-bot-api | kotlin/src/main/kotlin/kt/schors/vertx/telegram/bot/api/types/payments/Invoice.kt | 1 | 585 | package kt.schors.vertx.telegram.bot.api.types.payments
import com.fasterxml.jackson.annotation.JsonCreator
import com.fasterxml.jackson.annotation.JsonProperty
data class Invoice
@JsonCreator constructor(
@JsonProperty("title")
var title: String? = null,
@JsonProperty("description")
var description: String? = null,
@JsonProperty("start_parameter")
var startParameter: String? = null,
@JsonProperty("currency")
var currency: String? = null,
@JsonProperty("total_amount")
var totalAmount: Int? = null
) | mit | 6a757f1cd431f3c0b4690d6d2a9474a6 | 31.555556 | 55 | 0.680342 | 4.5 | false | false | false | false |
seventhroot/elysium | bukkit/rpk-chat-bukkit/src/main/kotlin/com/rpkit/chat/bukkit/irc/listener/IRCChannelJoinListener.kt | 1 | 2976 | /*
* Copyright 2016 Ross Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.chat.bukkit.irc.listener
import com.rpkit.chat.bukkit.RPKChatBukkit
import com.rpkit.chat.bukkit.chatchannel.RPKChatChannelProvider
import com.rpkit.chat.bukkit.chatchannel.undirected.IRCComponent
import com.rpkit.chat.bukkit.irc.RPKIRCProvider
import org.pircbotx.PircBotX
import org.pircbotx.hooks.ListenerAdapter
import org.pircbotx.hooks.events.JoinEvent
/**
* IRC channel join listener.
* Prevents unauthorised users joining whitelisted channels.
*/
class IRCChannelJoinListener(private val plugin: RPKChatBukkit): ListenerAdapter() {
override fun onJoin(event: JoinEvent) {
val ircProvider = plugin.core.serviceManager.getServiceProvider(RPKIRCProvider::class)
val user = event.user
if (user != null) {
ircProvider.addIRCUser(user)
val verified = user.isVerified
val chatChannelProvider = plugin.core.serviceManager.getServiceProvider(RPKChatChannelProvider::class)
val chatChannel = chatChannelProvider.getChatChannelFromIRCChannel(event.channel.name)
if (chatChannel != null) {
if (chatChannel.undirectedPipeline
.mapNotNull { component -> component as? IRCComponent }
.firstOrNull()
?.isIRCWhitelisted == true) {
if (!verified) {
event.getBot<PircBotX>().sendIRC().message(event.channel.name, "/kick " + event.channel.name + " " + user.nick + " Only registered/identified users may join this channel.")
event.channel.send().message(user.nick + " attempted to join, but was not registered.")
} else if (!(user.channelsVoiceIn.contains(event.channel) || user.channelsHalfOpIn.contains(event.channel) || user.channelsOpIn.contains(event.channel))) {
//TODO: Once permissions is part of RPK, we can make this check permission via account link instead, where available.
event.getBot<PircBotX>().sendIRC().message(event.channel.name, "/kick " + event.channel.name + " " + user.nick + " Only authorised users may join this channel.")
event.channel.send().message(user.nick + " attempted to join, but was not authorised.")
}
}
}
}
}
} | apache-2.0 | bde4dcf3ff926f2866fb8c4334525628 | 49.457627 | 196 | 0.66297 | 4.642746 | false | false | false | false |
diareuse/mCache | mcache/src/main/java/wiki/depasquale/mcache/Cache.kt | 1 | 2675 | package wiki.depasquale.mcache
import android.app.Application
import android.content.Context
import com.google.gson.Gson
import com.orhanobut.logger.AndroidLogAdapter
import com.orhanobut.logger.Logger
import com.orhanobut.logger.PrettyFormatStrategy
import java.lang.ref.WeakReference
/**
* Automagical object for pleasuring your senses.
*/
object Cache {
private var contextReference: WeakReference<Context>? = null
@JvmStatic
fun withGlobalMode(mode: CacheMode): Cache {
this.mode = mode
return this
}
@JvmStatic
fun withGson(gson: Gson): Cache {
this.gson = gson
return this
}
@JvmStatic
fun with(context: Application) {
with(context as Context)
}
@JvmStatic
fun with(context: Context) {
contextReference = WeakReference(context)
if (BuildConfig.DEBUG) {
Logger.clearLogAdapters()
Logger.addLogAdapter(AndroidLogAdapter())
}
}
internal var mode: CacheMode = CacheMode.CACHE
private set
internal var gson: Gson = Gson()
private set
internal val context: Context
get() {
return contextReference?.get() ?: contextRationale()
}
@Throws(RuntimeException::class)
private fun contextRationale(): Context {
Logger.clearLogAdapters()
Logger.addLogAdapter(
AndroidLogAdapter(
PrettyFormatStrategy.newBuilder()
.showThreadInfo(true)
.tag("diareuse/mCache")
.build()
)
)
Logger.e(
"You may have forgotten to initialize the library. Please visit my GitHub\n" +
"[https://github.com/diareuse/mCache] for latest instructions on how to set it up.\n" +
"Exception is thrown immediately after this message. You may have error you code as well as I can.\n" +
"Post issues with description as accurate as possible. More info I have more code I can fix :)"
)
throw RuntimeException("Context must not be null.")
}
/**
* Initializes [FilePresenterBuilder] so it fetches file(s) defined further on.
*/
@JvmStatic
fun <T : Any> obtain(cls: Class<T>): FilePresenterBuilder<T> {
return FilePresenterBuilder<T>()
.ofClass(cls)
}
/**
* Initializes [FilePresenterBuilder] so it saves file defined further on.
*/
@JvmStatic
fun <T : Any> give(file: T): FilePresenterBuilder<T> {
return FilePresenterBuilder<T>()
.ofClass(file.javaClass)
.ofFile(file)
}
}
| apache-2.0 | abd0d78ab891d0b06b1209ced28b6916 | 27.763441 | 123 | 0.614953 | 4.480737 | false | false | false | false |
arcao/Geocaching4Locus | app/src/main/java/com/arcao/geocaching4locus/live_map/LiveMapService.kt | 1 | 3999 | package com.arcao.geocaching4locus.live_map
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import androidx.lifecycle.LifecycleService
import com.arcao.geocaching4locus.base.ProgressState
import com.arcao.geocaching4locus.base.constants.AppConstants
import com.arcao.geocaching4locus.base.util.ServiceUtil
import com.arcao.geocaching4locus.base.util.exhaustive
import com.arcao.geocaching4locus.base.util.withObserve
import com.arcao.geocaching4locus.live_map.util.LiveMapNotificationManager
import org.koin.android.ext.android.inject
class LiveMapService : LifecycleService() {
private val notificationManager by inject<LiveMapNotificationManager>()
private val viewModel by inject<LiveMapViewModel>()
private val onCompleteCallback: (Intent) -> Unit = { ServiceUtil.completeWakefulIntent(it) }
override fun onCreate() {
super.onCreate()
viewModel.progress.withObserve(this, ::handleProgress)
lifecycle.addObserver(viewModel)
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
// in case the service is already running, this must be called after each startForegroundService
startForeground(
AppConstants.NOTIFICATION_ID_LIVEMAP,
notificationManager.createNotification().build()
)
if (intent != null) {
if (ACTION_START == intent.action) {
viewModel.addTask(intent, onCompleteCallback)
} else if (ACTION_STOP == intent.action) {
cancelTasks()
stopSelf(startId)
}
}
return super.onStartCommand(intent, flags, startId)
}
private fun cancelTasks() {
viewModel.cancelTasks()
ServiceUtil.releaseAllWakeLocks(ComponentName(this, LiveMapService::class.java))
stopForeground(true)
}
override fun onDestroy() {
cancelTasks()
super.onDestroy()
}
private fun handleProgress(state: ProgressState) {
when (state) {
is ProgressState.ShowProgress -> {
notificationManager.setDownloadingProgress(state.progress, state.maxProgress)
}
is ProgressState.HideProgress -> {
notificationManager.setDownloadingProgress(Int.MAX_VALUE, Int.MAX_VALUE)
}
}.exhaustive
}
companion object {
const val PARAM_LATITUDE = "LATITUDE"
const val PARAM_LONGITUDE = "LONGITUDE"
const val PARAM_TOP_LEFT_LATITUDE = "TOP_LEFT_LATITUDE"
const val PARAM_TOP_LEFT_LONGITUDE = "TOP_LEFT_LONGITUDE"
const val PARAM_BOTTOM_RIGHT_LATITUDE = "BOTTOM_RIGHT_LATITUDE"
const val PARAM_BOTTOM_RIGHT_LONGITUDE = "BOTTOM_RIGHT_LONGITUDE"
private val ACTION_START = LiveMapService::class.java.canonicalName!! + ".START"
private val ACTION_STOP = LiveMapService::class.java.canonicalName!! + ".STOP"
fun stop(context: Context) {
context.stopService(Intent(context, LiveMapService::class.java).setAction(ACTION_STOP))
}
fun start(
context: Context,
centerLatitude: Double,
centerLongitude: Double,
topLeftLatitude: Double,
topLeftLongitude: Double,
bottomRightLatitude: Double,
bottomRightLongitude: Double
) = ServiceUtil.startWakefulForegroundService(context,
Intent(context, LiveMapService::class.java).apply {
action = ACTION_START
putExtra(PARAM_LATITUDE, centerLatitude)
putExtra(PARAM_LONGITUDE, centerLongitude)
putExtra(PARAM_TOP_LEFT_LATITUDE, topLeftLatitude)
putExtra(PARAM_TOP_LEFT_LONGITUDE, topLeftLongitude)
putExtra(PARAM_BOTTOM_RIGHT_LATITUDE, bottomRightLatitude)
putExtra(PARAM_BOTTOM_RIGHT_LONGITUDE, bottomRightLongitude)
}
)
}
}
| gpl-3.0 | d5c3e0a0abb3f9cf4009d2462414c67d | 37.825243 | 104 | 0.666667 | 4.783493 | false | false | false | false |
Juuxel/ChatTime | api/src/main/kotlin/chattime/api/features/Permissions.kt | 1 | 2955 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package chattime.api.features
import chattime.api.User
import chattime.api.plugin.LoadOrder
import chattime.api.plugin.LoadOrder.After
import chattime.api.plugin.Plugin
/**
* Permissions is a feature plugin for forbidding and allowing
* the use of different user actions, such as commands.
*
* The server's console user ([chattime.api.Server.serverUser]) has
* all permissions by default, and they're non-removable.
*
* ## The `!permissions` command
*
* - Permission adds a new command, `permissions`.
* - By default the use of `add` and `reset` is forbidden
* - Allowed for the server user
* - `list` is allowed by default
* - Usage: `!permissions <subcommand: list, add, remove>`
* - `list <user id>`: Lists the permission of `<user id>`
* - `add <user id> <command name> <type>`: Adds a new permission of `<type>`
* to `<user id>` for using `<command name>`
* - Type is either `Allow` or `Forbid` (case ignored)
* - Replaces any previous permissions for `<command name>`
* - The user can give only permissions that they have themselves
* - `reset <user id> [<command name>]`: Resets all permissions
* for `<command name>` from `<user id>`
* - If `<command name>` is not set, resets all permissions
*
* ## Command permissions
*
* The names of command permissions are `command.{command name}`.
* For subcommands this pattern is used: `command.{command name}.{subcommand}`.
*/
interface Permissions : Plugin
{
override val id: String
get() = "Permissions"
// Commands is required providing !permissions
override val loadOrder: List<LoadOrder>
get() = listOf(After("Commands", isRequired = true))
/**
* Makes [permission] the default permission for its action.
*
* If no global permission is set for an action,
* it will be allowed.
*
* @param permission the permission
*/
fun addGlobalPermission(permission: Permission)
/**
* Checks if [user] has the permission to use [action],
* or a matching global permission for it.
*
* @param user the user
* @param action the action
* @return true if [user] can use [action], false otherwise
*/
fun hasPermission(user: User, action: String): Boolean
/**
* A permission applying to [action].
*
* @constructor The primary constructor.
*
* @property action the action
* @property isAllowed true if the action is allowed
*/
data class Permission(
val action: String,
val isAllowed: Boolean)
{
override fun equals(other: Any?): Boolean
= other is Permission && other.action == action
override fun hashCode(): Int = action.hashCode()
}
}
| mpl-2.0 | 55523d08693bbc9cb58505a13f1e40ba | 33.360465 | 79 | 0.655499 | 4.081492 | false | false | false | false |
android/user-interface-samples | AppWidget/app/src/main/java/com/example/android/appwidget/glance/buttons/ButtonsGlanceWidget.kt | 1 | 6766 | /*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.appwidget.glance.buttons
import android.annotation.SuppressLint
import android.content.Context
import android.os.Build
import android.widget.RemoteViews
import androidx.compose.runtime.Composable
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.glance.Button
import androidx.glance.GlanceId
import androidx.glance.GlanceModifier
import androidx.glance.LocalContext
import androidx.glance.action.ActionParameters
import androidx.glance.action.actionParametersOf
import androidx.glance.action.actionStartActivity
import androidx.glance.appwidget.AndroidRemoteViews
import androidx.glance.appwidget.CheckBox
import androidx.glance.appwidget.GlanceAppWidget
import androidx.glance.appwidget.GlanceAppWidgetReceiver
import androidx.glance.appwidget.Switch
import androidx.glance.appwidget.action.ActionCallback
import androidx.glance.appwidget.action.ToggleableStateKey
import androidx.glance.appwidget.action.actionRunCallback
import androidx.glance.appwidget.appWidgetBackground
import androidx.glance.appwidget.lazy.LazyColumn
import androidx.glance.appwidget.state.updateAppWidgetState
import androidx.glance.background
import androidx.glance.currentState
import androidx.glance.layout.Column
import androidx.glance.layout.fillMaxSize
import androidx.glance.layout.fillMaxWidth
import androidx.glance.layout.padding
import androidx.glance.text.FontWeight
import androidx.glance.text.Text
import androidx.glance.text.TextStyle
import com.example.android.appwidget.MainActivity
import com.example.android.appwidget.R
import com.example.android.appwidget.glance.GlanceTheme
import com.example.android.appwidget.glance.appWidgetBackgroundCornerRadius
/**
* Glance widget that showcases how to use:
* - Actions
* - Compound buttons
* - Buttons
* - AndroidRemoteView
*/
class ButtonsGlanceWidget : GlanceAppWidget() {
@SuppressLint("RemoteViewLayout")
@Composable
override fun Content() {
GlanceTheme {
Column(
modifier = GlanceModifier
.fillMaxSize()
.padding(16.dp)
.appWidgetBackground()
.background(GlanceTheme.colors.background)
.appWidgetBackgroundCornerRadius()
) {
Text(
text = LocalContext.current.getString(R.string.buttons_title),
modifier = GlanceModifier
.fillMaxWidth()
.padding(8.dp),
style = TextStyle(
fontWeight = FontWeight.Bold,
fontSize = 18.sp,
color = GlanceTheme.colors.primary
),
)
LazyColumn {
item {
Button(
text = "Button",
modifier = GlanceModifier.fillMaxWidth(),
onClick = actionStartActivity<MainActivity>()
)
}
item {
CheckBox(
text = "Checkbox",
checked = currentState(key = CheckboxKey) ?: false,
onCheckedChange = actionRunCallback<CompoundButtonAction>(
actionParametersOf(SelectedKey to CheckboxKey.name)
)
)
}
item {
Switch(
text = "Switch",
checked = currentState(key = SwitchKey) ?: false,
onCheckedChange = actionRunCallback<CompoundButtonAction>(
actionParametersOf(SelectedKey to SwitchKey.name)
)
)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
item {
// Radio buttons are not implemented yet in Glance, using the interop
// composable to use the RemoteView + XML
AndroidRemoteViews(
remoteViews = RemoteViews(
LocalContext.current.packageName,
R.layout.item_radio_buttons
).apply {
// This code will check the item_radio_button2 in the
// item_radio_group RadioGroup
setRadioGroupChecked(
R.id.item_radio_group,
R.id.item_radio_button2
)
}
)
}
}
}
}
}
}
}
private val CheckboxKey = booleanPreferencesKey("checkbox")
private val SwitchKey = booleanPreferencesKey("switch")
private val SelectedKey = ActionParameters.Key<String>("key")
class CompoundButtonAction : ActionCallback {
override suspend fun onAction(context: Context, glanceId: GlanceId, parameters: ActionParameters) {
// The framework automatically sets the value of the toggled action (true/false)
// Retrieve it using the ToggleableStateKey
val toggled = parameters[ToggleableStateKey] ?: false
updateAppWidgetState(context, glanceId) { prefs ->
// Get which button the action came from
val key = booleanPreferencesKey(parameters[SelectedKey] ?: return@updateAppWidgetState)
// Update the state
prefs[key] = toggled
}
ButtonsGlanceWidget().update(context, glanceId)
}
}
class ButtonsGlanceWidgetReceiver : GlanceAppWidgetReceiver() {
override val glanceAppWidget: GlanceAppWidget = ButtonsGlanceWidget()
}
| apache-2.0 | fc1b0855d46d4d0f306f8995eafe1052 | 40.509202 | 103 | 0.595034 | 5.671417 | false | false | false | false |
MaibornWolff/codecharta | analysis/import/GitLogParser/src/main/kotlin/de/maibornwolff/codecharta/importer/gitlogparser/input/metrics/MedianCoupledFiles.kt | 1 | 1163 | package de.maibornwolff.codecharta.importer.gitlogparser.input.metrics
import de.maibornwolff.codecharta.importer.gitlogparser.input.Commit
import de.maibornwolff.codecharta.model.AttributeType
class MedianCoupledFiles : Metric {
private val numberCommitedFiles = mutableListOf<Int>()
private fun Iterable<Double>.median(): Double {
val list = this.sorted()
val len = list.size
if (len == 0) {
return 0.0
} else if (len % 2 == 0) {
return (list[len / 2 - 1] + list[len / 2]) / 2.0
}
return list[len / 2]
}
override fun description(): String {
return "Median Coupled Files: Median of number of other files that where commited with this file."
}
override fun metricName(): String {
return "median_coupled_files"
}
override fun value(): Number {
return numberCommitedFiles.map { v -> v.toDouble() }.median()
}
override fun registerCommit(commit: Commit) {
numberCommitedFiles.add(commit.modifications.size - 1)
}
override fun attributeType(): AttributeType {
return AttributeType.relative
}
}
| bsd-3-clause | 80640e091574e19fd7f4720829dcee5d | 28.075 | 106 | 0.643164 | 4.229091 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/economy/DailyCommand.kt | 1 | 2454 | package net.perfectdreams.loritta.morenitta.commands.vanilla.economy
import net.perfectdreams.loritta.morenitta.commands.AbstractCommand
import net.perfectdreams.loritta.morenitta.commands.CommandContext
import net.perfectdreams.loritta.morenitta.utils.Constants
import net.perfectdreams.loritta.morenitta.utils.DateUtils
import net.perfectdreams.loritta.morenitta.messages.LorittaReply
import net.perfectdreams.loritta.common.locale.BaseLocale
import net.perfectdreams.loritta.common.locale.LocaleKeyData
import net.perfectdreams.loritta.common.utils.Emotes
import net.perfectdreams.loritta.morenitta.utils.OutdatedCommandUtils
import net.perfectdreams.loritta.morenitta.LorittaBot
class DailyCommand(loritta: LorittaBot) : AbstractCommand(loritta, "daily", listOf("diário", "bolsafamilia", "bolsafamília"), net.perfectdreams.loritta.common.commands.CommandCategory.ECONOMY) {
override fun getDescriptionKey() = LocaleKeyData("commands.command.daily.description")
override suspend fun run(context: CommandContext, locale: BaseLocale) {
OutdatedCommandUtils.sendOutdatedCommandMessage(context, locale, "daily")
// 1. Pegue quando o daily foi pego da última vez
// 2. Pegue o tempo de quando seria amanhã
// 3. Compare se o tempo atual é maior que o tempo de amanhã
val (canGetDaily, tomorrow) = context.lorittaUser.profile.canGetDaily(loritta)
if (!canGetDaily) {
context.reply(
LorittaReply(
locale["commands.command.daily.pleaseWait", DateUtils.formatDateDiff(tomorrow, locale)],
Constants.ERROR
),
LorittaReply(
locale["commands.command.daily.pleaseWaitBuySonhos", "<${loritta.config.loritta.website.url}user/@me/dashboard/bundles>"],
"\uD83D\uDCB3"
)
)
return
}
val url = if (context.isPrivateChannel)
"${loritta.config.loritta.website.url}daily"
else // Used for daily multiplier priority
"${loritta.config.loritta.website.url}daily?guild=${context.guild.idLong}"
context.reply(
LorittaReply(
locale["commands.command.daily.dailyLink", url],
Emotes.LORI_RICH
),
LorittaReply(
context.locale["commands.command.daily.dailyWarning", "${loritta.config.loritta.website.url}guidelines"],
Emotes.LORI_BAN_HAMMER,
mentionUser = false
),
LorittaReply(
locale["commands.command.daily.dailyLinkBuySonhos", "<${loritta.config.loritta.website.url}user/@me/dashboard/bundles>"],
"\uD83D\uDCB3",
mentionUser = false
)
)
}
} | agpl-3.0 | b80d58216e829e837493035bd0957ccf | 39.147541 | 194 | 0.768382 | 3.766154 | false | true | false | false |
Lennoard/HEBF | app/src/main/java/com/androidvip/hebf/utils/gb/GameBoosterImpl.kt | 1 | 12402 | package com.androidvip.hebf.utils.gb
import android.app.ActivityManager
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import com.androidvip.hebf.R
import com.androidvip.hebf.percentOf
import com.androidvip.hebf.receivers.NotificationButtonReceiver
import com.androidvip.hebf.toast
import com.androidvip.hebf.utils.*
import com.androidvip.hebf.utils.vip.VipBatterySaverImpl
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
import java.util.*
/**
* Game Booster implementation for rooted devices
*/
class GameBoosterImpl(private val context: Context?) : IGameBooster, KoinComponent {
private val gbPrefs: GbPrefs by inject()
private val vipPrefs: VipPrefs by inject()
private val prefs: Prefs by inject()
private val userPrefs: UserPrefs by inject()
override suspend fun enable() = withContext(Dispatchers.Default) {
if (context == null) return@withContext
val notificationManager = context.getSystemService(
Context.NOTIFICATION_SERVICE
) as NotificationManager
val forceStop = gbPrefs.getBoolean(K.PREF.GB_FORCE_STOP, false)
val clearCaches = gbPrefs.getBoolean(K.PREF.GB_CLEAR_CACHES, true)
val dndMode = gbPrefs.getBoolean(K.PREF.GB_DND, false)
val changeLmkParams = gbPrefs.getBoolean(K.PREF.GB_CHANGE_LMK, false)
val changeBrightness = gbPrefs.getBoolean(K.PREF.GB_CHANGE_BRIGHTNESS, false)
val changeGov = gbPrefs.getBoolean(K.PREF.GB_CHANGE_GOV, false)
val gov = gbPrefs.getString(K.PREF.GB_GOV, "performance")
val customLmkParams = gbPrefs.getString(K.PREF.GB_CUSTOM_LMK_PARAMS, "")
val shouldUseCustomLmkParams = gbPrefs.getInt(K.PREF.GB_LMK_PROFILE_SELECTION, 0) == 1
val gameLmkParams = getLmkParams(context).first
val commands = mutableListOf<String>()
val isVipEnabled = vipPrefs.getBoolean(K.PREF.VIP_ENABLED, false)
if (isVipEnabled) {
VipBatterySaverImpl(context).disable()
}
commands.add("setprop hebf.gb_enabled 1")
if (clearCaches) {
commands.add("sync && echo 3 > /proc/sys/vm/drop_caches")
}
if (changeLmkParams) {
if (shouldUseCustomLmkParams && customLmkParams.isNotEmpty()) {
commands.add("echo $customLmkParams > /sys/module/lowmemorykiller/parameters/minfree")
prefs.putInt("PerfisLMK", 0)
} else {
val newParams = buildString {
for (i in 0..5) {
val lastChar = if (i == 5) "" else ","
append("${gameLmkParams[i].toPages()}$lastChar")
}
}
if (newParams.isEmpty() || newParams.contains(",0,")) {
Logger.logError("[LMK] Failed to set value: $newParams is invalid", context)
} else {
commands.add("echo '$newParams' > /sys/module/lowmemorykiller/parameters/minfree")
prefs.putInt("PerfisLMK", 4)
}
}
}
if (forceStop) {
forceStopApps(context)
}
if (dndMode) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && notificationManager.isNotificationPolicyAccessGranted) {
notificationManager.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_ALARMS)
}
}
if (changeGov) {
for (i in 0 until CpuManager.cpuCount) {
commands.add("chmod +w ${CpuManager.CPU_DIR}/cpu$i/cpufreq/scaling_governor")
commands.add("echo '$gov' > ${CpuManager.CPU_DIR}/cpu$i/cpufreq/scaling_governor")
}
}
if (changeBrightness) {
val brightnessValue = gbPrefs.getInt(K.PREF.GB_BRIGHTNESS_LEVEL_ENABLED, 240)
SettingsUtils(context).changeBrightness(brightnessValue)
}
RootUtils.executeSync(*commands.toTypedArray())
gbPrefs.putBoolean(K.PREF.GB_ENABLED, true)
notify(context, false)
}
override suspend fun disable() = withContext(Dispatchers.Default) {
if (context == null) return@withContext
val notificationManager = context.getSystemService(
Context.NOTIFICATION_SERVICE
) as NotificationManager
val dndMode = gbPrefs.getBoolean(K.PREF.GB_DND, false)
val changeBrightness = gbPrefs.getBoolean(K.PREF.GB_CHANGE_BRIGHTNESS, false)
val changeLmkParams = gbPrefs.getBoolean(K.PREF.GB_CHANGE_LMK, false)
val changeGov = gbPrefs.getBoolean(K.PREF.GB_CHANGE_GOV, false)
val moderateLmkParams = getLmkParams(context).second
val commands = mutableListOf<String>()
commands.add("setprop hebf.gb_enabled 0")
if (changeLmkParams) {
val newParams = buildString {
for (i in 0..5) {
val lastChar = if (i == 5) "" else ","
append("${moderateLmkParams[i].toPages()}$lastChar")
}
}
if (newParams.isEmpty() || newParams.contains(",0,")) {
Logger.logError("[LMK] Failed to set value: $newParams is invalid", context)
} else {
commands.add("echo '$newParams' > /sys/module/lowmemorykiller/parameters/minfree")
}
prefs.putInt("PerfisLMK", 1)
}
if (dndMode) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && notificationManager.isNotificationPolicyAccessGranted) {
notificationManager.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_ALL)
}
}
if (changeGov) {
val cpuManager = CpuManager()
val policy = cpuManager.policies?.firstOrNull()
val availableGovs = policy?.availableGovs
?: CpuManager.DEFAULT_GOVERNORS.split(" ").toTypedArray()
val easHint = availableGovs.firstOrNull {
it in CpuManager.EAS_GOVS.split(" ")
} != null
val gov = when {
easHint -> "schedutil"
Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT -> "ondemand"
else -> "interactive"
}
for (i in 0 until CpuManager.cpuCount) {
commands.add("chmod +w ${CpuManager.CPU_DIR}/cpu$i/cpufreq/scaling_governor")
commands.add("echo '$gov' > ${CpuManager.CPU_DIR}/cpu$i/cpufreq/scaling_governor")
}
}
if (changeBrightness) {
val brightnessValue = prefs.getInt(K.PREF.GB_BRIGHTNESS_LEVEL_DISABLED, 140)
SettingsUtils(context).changeBrightness(brightnessValue)
}
RootUtils.executeSync(*commands.toTypedArray())
gbPrefs.putBoolean(K.PREF.GB_ENABLED, false)
notify(context, true)
}
override suspend fun forceStopApps(context: Context) {
val packagesSet: MutableSet<String> = userPrefs.getStringSet(
K.PREF.FORCE_STOP_APPS_SET, HashSet()
)
val commands = mutableListOf<String>()
packagesSet.forEach {
if (it != "android" && it != "com.android.chrome" && it.isNotEmpty()) {
commands.add("am force-stop $it")
commands.add("am set-inactive $it true")
}
}
RootUtils.executeSync(*commands.toTypedArray())
}
override suspend fun notify(
context: Context,
dismissNotification: Boolean
) = withContext(Dispatchers.Main) {
val disableIntent = Intent(context, NotificationButtonReceiver::class.java).apply {
putExtra(K.EXTRA_NOTIF_ID, K.NOTIF_GB_ID)
putExtra(K.EXTRA_NOTIF_ACTION_ID, K.NOTIF_ACTION_STOP_GB_ID)
}
val disablePendingIntent = PendingIntent.getBroadcast(
context, 0, disableIntent, PendingIntent.FLAG_ONE_SHOT
)
val boostIntent = Intent(context, NotificationButtonReceiver::class.java).apply {
putExtra(K.EXTRA_NOTIF_ID, K.NOTIF_GB_ID)
putExtra(K.EXTRA_NOTIF_ACTION_ID, K.NOTIF_ACTION_BOOST_ID)
}
val boostPendingIntent = PendingIntent.getBroadcast(context, 1, boostIntent, 0)
val notifBuilder = NotificationCompat.Builder(context, K.NOTIF_CHANNEL_ID_LOW_PRIORITY)
.setSmallIcon(R.drawable.ic_notif_game_booster)
.setContentTitle(context.getString(R.string.game_on))
.setContentText("Set to max performance mode. This option may heat up your device.")
.setSubText(context.getString(R.string.game_booster))
.setPriority(NotificationCompat.PRIORITY_LOW)
.setCategory(NotificationCompat.CATEGORY_STATUS)
.setColor(ContextCompat.getColor(context, R.color.colorPrimary))
.setStyle(
NotificationCompat.BigTextStyle()
.bigText("Set to max performance mode. This option may heat up your device.")
)
.setOngoing(true)
.setColorized(true)
.addAction(NotificationCompat.Action(null, "Boost", boostPendingIntent))
.addAction(NotificationCompat.Action(null, context.getString(R.string.disable), disablePendingIntent))
if (dismissNotification) {
NotificationManagerCompat.from(context).cancel(K.NOTIF_GB_ID)
context.toast(R.string.game_off)
} else {
NotificationManagerCompat.from(context).notify(K.NOTIF_GB_ID, notifBuilder.build())
context.toast(R.string.game_on)
}
}
private fun getLmkParams(context: Context): Pair<List<Int>, List<Int>> {
val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
val memoryInfo = ActivityManager.MemoryInfo()
am.getMemoryInfo(memoryInfo)
val referenceParams = when (val memory = memoryInfo.totalMem / 1048567) {
in 0..512 -> listOf(
6 percentOf memory,
12 percentOf memory,
18 percentOf memory,
24 percentOf memory,
30 percentOf memory,
36 percentOf memory
)
in 513..768 -> listOf(
7.2 percentOf memory,
10 percentOf memory,
14 percentOf memory,
20 percentOf memory,
24 percentOf memory,
27 percentOf memory
)
in 769..1024 -> listOf(
2.6 percentOf memory,
5 percentOf memory,
10 percentOf memory,
16 percentOf memory,
20 percentOf memory,
30 percentOf memory
)
in 1025..2048 -> listOf(
2.5 percentOf memory,
3.5 percentOf memory,
5 percentOf memory,
10.5 percentOf memory,
14 percentOf memory,
15 percentOf memory
)
in 2049..4096 -> listOf(
3 percentOf memory,
4.5 percentOf memory,
6 percentOf memory,
11.5 percentOf memory,
14 percentOf memory,
15.5 percentOf memory
)
else -> listOf(
4.5 percentOf memory,
5.5 percentOf memory,
7.5 percentOf memory,
12.7 percentOf memory,
15 percentOf memory,
16.5 percentOf memory
)
}
return referenceParams.map { it.toInt() } to listOf(
((referenceParams[0] * 90.1) / 100).toInt(),
((referenceParams[1] * 90.5) / 100).toInt(),
((referenceParams[2] * 91.3) / 100).toInt(),
((referenceParams[3] * 54.33) / 100).toInt(),
((referenceParams[4] * 46.7) / 100).toInt(),
((referenceParams[5] * 56.06) / 100).toInt()
)
}
private fun Int.toPages() = (this * 1024) / 4
} | apache-2.0 | 704e662ed6cfcfe72e299efa30903260 | 39.53268 | 122 | 0.597162 | 4.422967 | false | false | false | false |
cketti/okhttp | okhttp-testing-support/src/main/kotlin/okhttp3/TestUtil.kt | 1 | 3295 | /*
* Copyright (C) 2018 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3
import java.io.File
import java.net.InetAddress
import java.net.InetSocketAddress
import java.net.UnknownHostException
import java.util.Arrays
import okhttp3.internal.http2.Header
import okio.Buffer
import org.junit.Assume.assumeFalse
import org.junit.Assume.assumeNoException
object TestUtil {
@JvmField
val UNREACHABLE_ADDRESS = InetSocketAddress("198.51.100.1", 8080)
@JvmStatic
fun headerEntries(vararg elements: String?): List<Header> {
return List(elements.size / 2) { Header(elements[it * 2]!!, elements[it * 2 + 1]!!) }
}
@JvmStatic
fun repeat(
c: Char,
count: Int
): String {
val array = CharArray(count)
Arrays.fill(array, c)
return String(array)
}
/**
* Okio buffers are internally implemented as a linked list of arrays. Usually this implementation
* detail is invisible to the caller, but subtle use of certain APIs may depend on these internal
* structures.
*
* We make such subtle calls in [okhttp3.internal.ws.MessageInflater] because we try to read a
* compressed stream that is terminated in a web socket frame even though the DEFLATE stream is
* not terminated.
*
* Use this method to create a degenerate Okio Buffer where each byte is in a separate segment of
* the internal list.
*/
@JvmStatic
fun fragmentBuffer(buffer: Buffer): Buffer {
// Write each byte into a new buffer, then clone it so that the segments are shared.
// Shared segments cannot be compacted so we'll get a long chain of short segments.
val result = Buffer()
while (!buffer.exhausted()) {
val box = Buffer()
box.write(buffer, 1)
result.write(box.copy(), 1)
}
return result
}
tailrec fun File.isDescendentOf(directory: File): Boolean {
val parentFile = parentFile ?: return false
if (parentFile == directory) return true
return parentFile.isDescendentOf(directory)
}
/**
* See FinalizationTester for discussion on how to best trigger GC in tests.
* https://android.googlesource.com/platform/libcore/+/master/support/src/test/java/libcore/
* java/lang/ref/FinalizationTester.java
*/
@Throws(Exception::class)
@JvmStatic
fun awaitGarbageCollection() {
Runtime.getRuntime().gc()
Thread.sleep(100)
System.runFinalization()
}
@JvmStatic
fun assumeNetwork() {
try {
InetAddress.getByName("www.google.com")
} catch (uhe: UnknownHostException) {
assumeNoException(uhe)
}
}
@JvmStatic
fun assumeNotWindows() {
assumeFalse("This test fails on Windows.", windows)
}
@JvmStatic
val windows: Boolean
get() = System.getProperty("os.name", "?").startsWith("Windows")
}
| apache-2.0 | e01c628a96b994158e46b2eb1cc2e766 | 29.509259 | 100 | 0.705918 | 4.083024 | false | true | false | false |
vanniktech/Emoji | emoji/src/androidMain/kotlin/com/vanniktech/emoji/variant/VariantEmojiManager.kt | 1 | 2807 | /*
* Copyright (C) 2016 - Niklas Baudy, Ruben Gees, Mario Đanić and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.vanniktech.emoji.variant
import android.content.Context
import com.vanniktech.emoji.Emoji
import com.vanniktech.emoji.EmojiManager
class VariantEmojiManager(
context: Context,
) : VariantEmoji {
private val preferences = context.applicationContext.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE)
private var variantsList = mutableListOf<Emoji>()
override fun getVariant(desiredEmoji: Emoji): Emoji {
if (variantsList.isEmpty()) {
initFromSharedPreferences()
}
val baseEmoji = desiredEmoji.base
return variantsList.firstOrNull { it.base == baseEmoji } ?: desiredEmoji
}
override fun addVariant(newVariant: Emoji) {
val newVariantBase = newVariant.base
for (i in variantsList.indices) {
val variant = variantsList[i]
if (variant.base == newVariantBase) {
if (variant == newVariant) {
return // Same skin-tone was used.
} else {
variantsList.removeAt(i)
variantsList.add(newVariant)
return
}
}
}
variantsList.add(newVariant)
}
override fun persist() {
if (variantsList.size > 0) {
val stringBuilder = StringBuilder(variantsList.size * EMOJI_GUESS_SIZE)
for (i in variantsList.indices) {
stringBuilder.append(variantsList[i].unicode).append(EMOJI_DELIMITER)
}
stringBuilder.setLength(stringBuilder.length - EMOJI_DELIMITER.length)
preferences.edit().putString(VARIANT_EMOJIS, stringBuilder.toString()).apply()
} else {
preferences.edit().remove(VARIANT_EMOJIS).apply()
}
}
private fun initFromSharedPreferences() {
val savedRecentVariants = preferences.getString(VARIANT_EMOJIS, "").orEmpty()
if (savedRecentVariants.isNotEmpty()) {
variantsList = savedRecentVariants.split(EMOJI_DELIMITER)
.mapNotNull { EmojiManager.findEmoji(it) }
.toMutableList()
}
}
internal companion object {
private const val PREFERENCE_NAME = "variant-emoji-manager"
private const val EMOJI_DELIMITER = "~"
private const val VARIANT_EMOJIS = "variant-emojis"
private const val EMOJI_GUESS_SIZE = 5
}
}
| apache-2.0 | d0fe21b29e8f97258f25179b13828c33 | 32 | 114 | 0.701961 | 4.282443 | false | false | false | false |
jitsi/jitsi-videobridge | rtp/src/main/kotlin/org/jitsi/rtp/rtcp/CompoundRtcpPacket.kt | 1 | 4313 | /*
* Copyright @ 2018 - present 8x8, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.rtp.rtcp
import org.jitsi.rtp.extensions.bytearray.toHex
import org.jitsi.rtp.util.BufferPool
class CompoundRtcpPacket(
buffer: ByteArray,
offset: Int,
length: Int
) : RtcpPacket(buffer, offset, length) {
val packets: List<RtcpPacket> by lazy { parse(buffer, offset, length) }
companion object {
fun parse(buffer: ByteArray, offset: Int, length: Int): List<RtcpPacket> {
var bytesRemaining = length
var currOffset = offset
val rtcpPackets = mutableListOf<RtcpPacket>()
while (bytesRemaining >= RtcpHeader.SIZE_BYTES) {
val rtcpPacket = try {
RtcpPacket.parse(buffer, currOffset, bytesRemaining)
} catch (e: InvalidRtcpException) {
throw CompoundRtcpContainedInvalidDataException(buffer, offset, length, currOffset, e.reason)
}
rtcpPackets.add(rtcpPacket)
currOffset += rtcpPacket.length
bytesRemaining -= rtcpPacket.length
}
return rtcpPackets
}
operator fun invoke(packets: List<RtcpPacket>): CompoundRtcpPacket {
val totalLength = packets.map { it.length }.sum()
val buf = BufferPool.getArray(totalLength + BYTES_TO_LEAVE_AT_END_OF_PACKET)
var off = 0
packets.forEach {
System.arraycopy(it.buffer, it.offset, buf, off, it.length)
off += it.length
}
return CompoundRtcpPacket(buf, 0, totalLength)
}
/**
* Create one or more compound RTCP packets from [packets], with each compound packet being
* no more than [mtu] bytes in size (unless an individual packet is bigger than that, in which
* case it will be in a compound packet on its own).
*/
fun createWithMtu(packets: List<RtcpPacket>, mtu: Int = 1500): List<CompoundRtcpPacket> {
return packets.chunkMaxSize(mtu) { it.length }.map { CompoundRtcpPacket(it) }
}
}
override fun clone(): RtcpPacket = CompoundRtcpPacket(cloneBuffer(0), 0, length)
}
/**
* Return a List of Lists, where sub-list is made up of an ordered list
* of values pulled from [this], such that the total size of each sub-list
* is not more than maxSize. (Sizes are evaluated by [evaluate]. If an
* individual element's size is more than [maxSize] it will be returned
* in a sub-list on its own.)
*/
private fun <T : Any> List<T>.chunkMaxSize(maxSize: Int, evaluate: (T) -> Int): List<List<T>> {
val chunks = mutableListOf<List<T>>()
if (this.isEmpty()) {
return chunks
}
var currentChunk = mutableListOf(first())
chunks.add(currentChunk)
var chunkSize = evaluate(currentChunk.first())
// Ignore the first value which we already put in the current chunk
drop(1).forEach {
val size = evaluate(it)
if (chunkSize + size > maxSize) {
currentChunk = mutableListOf(it)
chunks.add(currentChunk)
chunkSize = size
} else {
currentChunk.add(it)
chunkSize += size
}
}
return chunks
}
class CompoundRtcpContainedInvalidDataException(
compoundRtcpBuf: ByteArray,
compoundRtcpOffset: Int,
compoundRtcpLength: Int,
invalidDataOffset: Int,
invalidDataReason: String
) : Exception(
"Compound RTCP contained invalid data. Compound RTCP packet data is: " +
"${compoundRtcpBuf.toHex(compoundRtcpOffset, compoundRtcpLength)} Invalid data " +
"started at offset ${invalidDataOffset - compoundRtcpOffset} and failed due to '$invalidDataReason'"
)
| apache-2.0 | ab2ecc2657f70eed38a6a39d1edfd944 | 36.504348 | 113 | 0.644331 | 4.191448 | false | false | false | false |
vindkaldr/replicator | libreplicator-core/src/main/kotlin/org/libreplicator/core/locator/DefaultNodeLocator.kt | 2 | 3845 | /*
* Copyright (C) 2016 Mihály Szabó
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.libreplicator.core.locator
import org.libreplicator.api.LocalNode
import org.libreplicator.api.RemoteNode
import org.libreplicator.core.locator.api.NodeLocator
import org.libreplicator.core.locator.api.NodeLocatorSettings
import org.libreplicator.json.api.JsonMapper
import java.net.MulticastSocket
import java.util.Timer
import javax.inject.Inject
import kotlin.concurrent.fixedRateTimer
import kotlin.concurrent.thread
class DefaultNodeLocator @Inject constructor(
private val localNode: LocalNode,
private val settings: NodeLocatorSettings,
private val jsonMapper: JsonMapper
): NodeLocator {
private val remoteNodes = mutableMapOf<String, RemoteNode>()
private var multicastSocket: MulticastSocket? = null
private var multicastTimer: Timer? = null
override fun acquire(): NodeLocator = apply {
check(multicastSocket == null, { "Object already acquired!" })
multicastSocket = createMulticastSocket(settings.multicastPort)
listenOnMulticastSocket()
schedulePeriodicMulticast()
}
private fun listenOnMulticastSocket() = thread {
generateSequence { receiveMessage(multicastSocket, settings.bufferSizeInBytes) }
.takeWhile { it.isNotBlank() }
.map { readMessage(it) }
.forEach { updateRemoteNodes(it) }
}
private fun readMessage(message: String) = jsonMapper.read(message, NodeSyncMessage::class)
private fun updateRemoteNodes(nodeSyncMessage: NodeSyncMessage) {
nodeSyncMessage.removedNodeIds.forEach { remoteNodes.remove(it) }
nodeSyncMessage.addedNodes.forEach { remoteNodes[it.nodeId] = it }
}
private fun schedulePeriodicMulticast() {
multicastTimer = fixedRateTimer(period = settings.multicastPeriodInMilliseconds) {
multicast(writeMessage(createMessage(localNode)))
}
}
private fun createMessage(localNode: LocalNode) =
NodeSyncMessage(addedNodes = listOf(RemoteNode(localNode.nodeId, localNode.hostname, localNode.port)))
private fun writeMessage(nodeSyncMessage: NodeSyncMessage) = jsonMapper.write(nodeSyncMessage)
override fun release() {
check(multicastSocket != null, { "Object not yet acquired!" })
multicast(writeMessage(createMessage(localNode.nodeId)))
cancelPeriodicMulticast()
closeSocket()
removeNodes()
}
private fun multicast(message: String) {
sendMessage(multicastSocket, settings.multicastAddress, settings.multicastPort, message)
}
private fun cancelPeriodicMulticast() {
multicastTimer?.cancel()
multicastTimer = null
}
private fun closeSocket() {
closeMulticastSocket(multicastSocket)
multicastSocket = null
}
private fun removeNodes() {
remoteNodes.clear()
}
private fun createMessage(nodeId: String) = NodeSyncMessage(removedNodeIds = listOf(nodeId))
override fun getNode(nodeId: String): RemoteNode? {
check(multicastSocket != null, { "Object not yet acquired!" })
return remoteNodes[nodeId]
}
}
| gpl-3.0 | 6d55d2ac0afa70177c693ba29b714967 | 35.951923 | 110 | 0.714806 | 4.515864 | false | false | false | false |
vhromada/Catalog-Spring | src/test/kotlin/cz/vhromada/catalog/web/mapper/TimeMapperTest.kt | 1 | 1256 | package cz.vhromada.catalog.web.mapper
import cz.vhromada.catalog.web.CatalogMapperTestConfiguration
import cz.vhromada.catalog.web.common.TimeUtils
import cz.vhromada.catalog.web.fo.TimeFO
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.test.context.ContextConfiguration
import org.springframework.test.context.junit.jupiter.SpringExtension
/**
* A class represents test for mapper between [Integer] and [TimeFO].
*
* @author Vladimir Hromada
*/
@ExtendWith(SpringExtension::class)
@ContextConfiguration(classes = [CatalogMapperTestConfiguration::class])
class TimeMapperTest {
/**
* Mapper for time
*/
@Autowired
private lateinit var mapper: TimeMapper
/**
* Test method for [TimeMapper.map].
*/
@Test
fun map() {
val length = 100
val time = mapper.map(length)
TimeUtils.assertTimeDeepEquals(time, length)
}
/**
* Test method for [TimeMapper.mapBack].
*/
@Test
fun mapBack() {
val time = TimeUtils.getTimeFO()
val length = mapper.mapBack(time)
TimeUtils.assertTimeDeepEquals(time, length)
}
}
| mit | 6ae5cd8f572453a9b27b2f289a2141ee | 23.627451 | 72 | 0.708599 | 4.145215 | false | true | false | false |
FrancYescO/PokemonGoBot | src/main/kotlin/ink/abb/pogo/scraper/util/PokemonGo.kt | 1 | 1116 | /**
* Pokemon Go Bot Copyright (C) 2016 PokemonGoBot-authors (see authors.md for more information)
* This program comes with ABSOLUTELY NO WARRANTY;
* This is free software, and you are welcome to redistribute it under certain conditions.
*
* For more information, refer to the LICENSE file in this repositories root directory
*/
package ink.abb.pogo.scraper.util
import com.pokegoapi.api.PokemonGo
import com.pokegoapi.api.inventory.Inventories
private var _inventories: Inventories? = null
var PokemonGo.cachedInventories: Inventories
get() {
val inventories = inventories
val copyInventories = _inventories
if (copyInventories == null) {
_inventories = inventories
} else {
if (inventories.incubators.isEmpty()) {
// apparently currently fetching; return cache; always contains infinite incubator
return copyInventories
} else {
_inventories = inventories
}
}
return _inventories!!
}
set(inventories) {
_inventories = inventories
}
| gpl-3.0 | 460c3371a0d3b8e92b589a44bb6cb5a4 | 30.885714 | 98 | 0.658602 | 4.769231 | false | false | false | false |
Jonatino/Xena | src/main/java/org/xena/cs/Me.kt | 1 | 4911 | /*
* Copyright 2016 Jonathan Beaudoin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.xena.cs
import org.xena.Settings
import org.xena.offsets.OffsetManager.clientModule
import org.xena.offsets.OffsetManager.process
import org.xena.offsets.offsets.ClientOffsets.dwEntityList
import org.xena.offsets.offsets.ClientOffsets.dwLocalPlayer
import org.xena.offsets.offsets.ClientOffsets.dwMouseEnable
import org.xena.offsets.offsets.ClientOffsets.dwMouseEnablePtr
import org.xena.offsets.offsets.EngineOffsets.m_bCanReload
import org.xena.offsets.offsets.NetVarOffsets.fFlags
import org.xena.offsets.offsets.NetVarOffsets.hActiveWeapon
import org.xena.offsets.offsets.NetVarOffsets.hMyWeapons
import org.xena.offsets.offsets.NetVarOffsets.iClip1
import org.xena.offsets.offsets.NetVarOffsets.iClip2
import org.xena.offsets.offsets.NetVarOffsets.iCrossHairID
import org.xena.offsets.offsets.NetVarOffsets.iShotsFired
import org.xena.plugin.utils.AngleUtils
import org.xena.plugin.utils.Vector
class Me : Player() {
var activeWeapon = Weapon()
private set
var target: Player? = null
private set
var shotsFired: Long = 0
private set
var cursorEnabled: Boolean = true
private set
var flags: Int = 0
private set
var onGround: Boolean = false
private set
override fun update() {
setAddress(clientModule().readUnsignedInt(dwLocalPlayer.toLong()))
super.update()
val activeWeaponIndex = process().readUnsignedInt(address() + hActiveWeapon) and 0xFFF
for (i in 0 until weaponIds.size) {
val currentWeaponIndex = process().readUnsignedInt(address() + hMyWeapons.toLong() + ((i - 1) * 0x04).toLong()) and 0xFFF
val weaponAddress = clientModule().readUnsignedInt(dwEntityList + (currentWeaponIndex - 1) * 0x10)
if (weaponAddress > 0 && activeWeaponIndex == currentWeaponIndex) {
processWeapon(weaponAddress, i, true)
}
}
target = null
val crosshair = process().readUnsignedInt(address() + iCrossHairID) - 1
if (crosshair > -1 && crosshair <= 1024) {
val entity = entities[clientModule().readUnsignedInt(dwEntityList + crosshair * 0x10)]
if (entity != null) {
target = entity as Player
}
}
shotsFired = process().readUnsignedInt(address() + iShotsFired)
val cursorEnablePtr = clientModule().address() + dwMouseEnablePtr
cursorEnabled = clientModule().readInt(dwMouseEnable.toLong()) xor cursorEnablePtr.toInt() != 1
flags = process().readInt(address() + fFlags)
onGround = flags and 1 == 1
}
override fun processWeapon(weaponAddress: Long, index: Int, active: Boolean): Int {
val weaponId = super.processWeapon(weaponAddress, index, active)
if (active) {
activeWeapon.setAddress(weaponAddress)
activeWeapon.weaponID = weaponId.toLong()
activeWeapon.canReload = process().readBoolean(weaponAddress + m_bCanReload)
activeWeapon.clip1 = process().readUnsignedInt(weaponAddress + iClip1)
activeWeapon.clip2 = process().readUnsignedInt(weaponAddress + iClip2)
}
return weaponId
}
private val closestTargetVector by lazy { Vector() }
fun getClosestTarget(aimHelper: AngleUtils, fov: Int = Settings.FORCE_AIM_FOV): Player? {
if (target != null) {
return target
}
var closestDelta = Double.MAX_VALUE
var closestPlayer: Player? = null
val angle = clientState.angle()
var lastIdx = 0
while (lastIdx + 1 <= entities.size()) {
val entity = entities.get(lastIdx++)
try {
if (/*aimHelper.delta(viewOrigin, entity.bones) > 3000 || */!aimHelper.canShoot(me, entity)) {
continue
}
val eyePos = entity.bones
val distance = distanceTo(viewOrigin, eyePos)
aimHelper.calculateAngle(me, eyePos, closestTargetVector)
val pitchDiff = Math.abs(angle.x - closestTargetVector.x).toDouble()
val yawDiff = Math.abs(angle.y - closestTargetVector.y).toDouble()
val delta = Math.abs(Math.sin(Math.toRadians(yawDiff)) * distance)
val fovDelta = Math.abs((Math.sin(Math.toRadians(pitchDiff)) + Math.sin(Math.toRadians(yawDiff))) * distance)
if (fovDelta <= fov && delta < closestDelta && closestDelta >= 0) {
closestDelta = delta
closestPlayer = entity as Player?
}
} catch (e: Throwable) {
e.printStackTrace()
}
}
if (closestDelta == Double.MAX_VALUE || closestDelta < 0) {
return null
}
return closestPlayer
}
} | apache-2.0 | 3956f35258f600e17b2350e2b31e98e6 | 31.966443 | 124 | 0.72246 | 3.589912 | false | false | false | false |
android/camera-samples | CameraXBasic/app/src/main/java/com/android/example/cameraxbasic/fragments/GalleryFragment.kt | 1 | 7581 | /*
* 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
*
* 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.android.example.cameraxbasic.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import java.io.File
import android.content.Intent
import android.media.MediaScannerConnection
import android.os.Build
import android.webkit.MimeTypeMap
import androidx.core.content.FileProvider
import com.android.example.cameraxbasic.BuildConfig
import com.android.example.cameraxbasic.utils.padWithDisplayCutout
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.navigation.Navigation
import androidx.navigation.fragment.navArgs
import com.android.example.cameraxbasic.utils.showImmersive
import com.android.example.cameraxbasic.R
import com.android.example.cameraxbasic.databinding.FragmentGalleryBinding
import java.util.Locale
val EXTENSION_WHITELIST = arrayOf("JPG")
/** Fragment used to present the user with a gallery of photos taken */
class GalleryFragment internal constructor() : Fragment() {
/** Android ViewBinding */
private var _fragmentGalleryBinding: FragmentGalleryBinding? = null
private val fragmentGalleryBinding get() = _fragmentGalleryBinding!!
/** AndroidX navigation arguments */
private val args: GalleryFragmentArgs by navArgs()
private lateinit var mediaList: MutableList<File>
/** Adapter class used to present a fragment containing one photo or video as a page */
inner class MediaPagerAdapter(fm: FragmentManager) : FragmentStatePagerAdapter(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
override fun getCount(): Int = mediaList.size
override fun getItem(position: Int): Fragment = PhotoFragment.create(mediaList[position])
override fun getItemPosition(obj: Any): Int = POSITION_NONE
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Mark this as a retain fragment, so the lifecycle does not get restarted on config change
retainInstance = true
// Get root directory of media from navigation arguments
val rootDirectory = File(args.rootDirectory)
// Walk through all files in the root directory
// We reverse the order of the list to present the last photos first
mediaList = rootDirectory.listFiles { file ->
EXTENSION_WHITELIST.contains(file.extension.toUpperCase(Locale.ROOT))
}?.sortedDescending()?.toMutableList() ?: mutableListOf()
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_fragmentGalleryBinding = FragmentGalleryBinding.inflate(inflater, container, false)
return fragmentGalleryBinding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
//Checking media files list
if (mediaList.isEmpty()) {
fragmentGalleryBinding.deleteButton.isEnabled = false
fragmentGalleryBinding.shareButton.isEnabled = false
}
// Populate the ViewPager and implement a cache of two media items
fragmentGalleryBinding.photoViewPager.apply {
offscreenPageLimit = 2
adapter = MediaPagerAdapter(childFragmentManager)
}
// Make sure that the cutout "safe area" avoids the screen notch if any
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
// Use extension method to pad "inside" view containing UI using display cutout's bounds
fragmentGalleryBinding.cutoutSafeArea.padWithDisplayCutout()
}
// Handle back button press
fragmentGalleryBinding.backButton.setOnClickListener {
Navigation.findNavController(requireActivity(), R.id.fragment_container).navigateUp()
}
// Handle share button press
fragmentGalleryBinding.shareButton.setOnClickListener {
mediaList.getOrNull(fragmentGalleryBinding.photoViewPager.currentItem)?.let { mediaFile ->
// Create a sharing intent
val intent = Intent().apply {
// Infer media type from file extension
val mediaType = MimeTypeMap.getSingleton()
.getMimeTypeFromExtension(mediaFile.extension)
// Get URI from our FileProvider implementation
val uri = FileProvider.getUriForFile(
view.context, BuildConfig.APPLICATION_ID + ".provider", mediaFile)
// Set the appropriate intent extra, type, action and flags
putExtra(Intent.EXTRA_STREAM, uri)
type = mediaType
action = Intent.ACTION_SEND
flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
}
// Launch the intent letting the user choose which app to share with
startActivity(Intent.createChooser(intent, getString(R.string.share_hint)))
}
}
// Handle delete button press
fragmentGalleryBinding.deleteButton.setOnClickListener {
mediaList.getOrNull(fragmentGalleryBinding.photoViewPager.currentItem)?.let { mediaFile ->
AlertDialog.Builder(view.context, android.R.style.Theme_Material_Dialog)
.setTitle(getString(R.string.delete_title))
.setMessage(getString(R.string.delete_dialog))
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.yes) { _, _ ->
// Delete current photo
mediaFile.delete()
// Send relevant broadcast to notify other apps of deletion
MediaScannerConnection.scanFile(
view.context, arrayOf(mediaFile.absolutePath), null, null)
// Notify our view pager
mediaList.removeAt(fragmentGalleryBinding.photoViewPager.currentItem)
fragmentGalleryBinding.photoViewPager.adapter?.notifyDataSetChanged()
// If all photos have been deleted, return to camera
if (mediaList.isEmpty()) {
Navigation.findNavController(requireActivity(), R.id.fragment_container).navigateUp()
}
}
.setNegativeButton(android.R.string.no, null)
.create().showImmersive()
}
}
}
override fun onDestroyView() {
_fragmentGalleryBinding = null
super.onDestroyView()
}
}
| apache-2.0 | 930318446e8515d1d0733fbe0f5fbfbe | 41.351955 | 127 | 0.659676 | 5.407275 | false | false | false | false |
meh/watch_doge | src/main/java/meh/watchdoge/ui/packet/Packet.kt | 1 | 641 | package meh.watchdoge.ui.packet;
import meh.watchdoge.util.*;
import android.os.Bundle;
import org.jetbrains.anko.*;
import java.util.Date;
class Packet<T>(packet: Bundle) : AnkoComponent<T> {
private val packet = packet;
override fun createView(ui: AnkoContext<T>) = with(ui) {
verticalLayout {
padding = dip(5);
textView("Packet Size: ${[email protected]}") {
textSize = 10f
}
}
}
private val size: Int
get() = packet.get("size") as Int
private val timestamp: Date
get() {
val secs = packet.get("secs") as Long;
val msecs = packet.get("msecs") as Long;
return Date(secs + (msecs / 1000));
}
}
| agpl-3.0 | 4c88b4ea059515ba172f1dab9c5fc88b | 18.424242 | 57 | 0.655226 | 2.967593 | false | false | false | false |
zensum/franz | src/main/kotlin/producer/mock/MockProducer.kt | 1 | 1734 | package franz.producer.mock
import franz.producer.ProduceResult
import franz.producer.ProduceResultF
import franz.producer.Producer
import org.apache.kafka.clients.producer.ProducerRecord
import java.util.concurrent.CompletableFuture
import java.util.concurrent.CompletableFuture.supplyAsync
class MockProducer<K, V>(
val doSendResult: ProduceResult = MockProduceResult(),
val sendAsyncResult: ProduceResult = MockProduceResult(),
val sendRawResult: ProduceResult = MockProduceResult(),
val onSend: (V) -> Unit = {},
val onSendAsync: (V) -> Unit = {},
val onSendRaw: (V) -> Unit = {}
): Producer<K, V> {
private val producedResults: MutableList<V> = mutableListOf()
private fun doSend(rec: ProducerRecord<K, V>): CompletableFuture<ProduceResult> {
producedResults.add(rec.value())
onSend.invoke(rec.value())
return supplyAsync { doSendResult }
}
override fun sendAsync(topic: String, key: K?, value: V): ProduceResultF {
producedResults.add(value)
onSendAsync.invoke(value)
return supplyAsync { sendAsyncResult }
}
override fun sendRaw(rec: ProducerRecord<K, V>): CompletableFuture<ProduceResult> {
producedResults.add(rec.value())
onSendRaw.invoke(rec.value())
return supplyAsync { sendRawResult }
}
override fun sendAsync(topic: String, key: K?, value: V, headers: Iterable<Pair<String, ByteArray>>): ProduceResultF {
producedResults.add(value)
onSendAsync.invoke(value)
return supplyAsync { sendAsyncResult }
}
override fun close() = Unit
fun createFactory() =
MockProducerFactory(this)
fun results(): List<V> =
producedResults.toList()
} | mit | e7a9afbe2ff6dfb604763c7fb2dd66ee | 33.019608 | 122 | 0.694925 | 4.198547 | false | false | false | false |
tinypass/piano-sdk-for-android | sample/src/main/java/io/piano/sample/MainActivity.kt | 1 | 6335 | package io.piano.sample
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.webkit.CookieManager
import android.webkit.CookieSyncManager
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.snackbar.Snackbar
import io.piano.android.composer.Composer
import io.piano.android.id.PianoId
import io.piano.android.id.PianoId.Companion.isPianoIdUri
import io.piano.android.id.PianoId.Companion.parsePianoIdToken
import io.piano.android.id.PianoIdAuthResultContract
import io.piano.android.id.models.PianoIdAuthFailureResult
import io.piano.android.id.models.PianoIdAuthSuccessResult
import io.piano.android.id.models.PianoIdToken
import io.piano.android.id.models.PianoUserInfo
import io.piano.sample.databinding.ActivityMainBinding
import timber.log.Timber
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var prefsStorage: PrefsStorage
private val isDeepLink: Boolean
get() {
val uri = intent.data ?: return false
if (uri.isPianoIdUri()) {
uri.parsePianoIdToken { r ->
r.onFailure {
Timber.e(it, "Auth unsuccessful")
}.onSuccess {
Timber.d("Auth successful")
setAccessToken(it)
}
}
} else {
Timber.d("App deep link")
}
return true
}
private val authResult = registerForActivityResult(PianoIdAuthResultContract()) { r ->
when (r) {
null -> showMessage("OAuth cancelled")
is PianoIdAuthSuccessResult -> {
Timber.d("Is Double opt-in enabled? %b", r.token?.emailConfirmationRequired)
Timber.d("Is this a new user registered? %b", r.isNewUser)
setAccessToken(r.token)
}
is PianoIdAuthFailureResult -> showError(r.exception)
}
}
@Suppress("DEPRECATION")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
prefsStorage = SimpleDependenciesProvider.getInstance(this).prefsStorage
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
if (isDeepLink) {
Timber.d("We processed deep link")
}
binding.apply {
buttonPianoIdLogin.setOnClickListener {
authResult.launch(PianoId.signIn())
}
buttonPianoIdLogout.setOnClickListener { signOut() }
buttonPianoIdRefreshToken.setOnClickListener {
prefsStorage.pianoIdToken?.run {
PianoId.refreshToken(refreshToken) { r ->
r.onSuccess {
setAccessToken(it)
}.onFailure {
showError(it)
}
}
} ?: showMessage("Can't refresh token, we aren't authorized yet")
}
buttonComposerExample.setOnClickListener {
startActivity(
Intent(
this@MainActivity,
ComposerActivity::class.java
)
)
}
buttonComposerScrollDepth.setOnClickListener {
startActivity(
Intent(
this@MainActivity,
ComposerScrollDepthActivity::class.java
)
)
}
buttonComposerClearStorage.setOnClickListener {
Composer.getInstance().clearStoredData()
}
buttonClearAccessToken.setOnClickListener {
signOut()
val cookieManager = CookieManager.getInstance()
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
val cookieSyncManager = CookieSyncManager.createInstance(this@MainActivity)
cookieSyncManager.startSync()
cookieManager.removeAllCookie()
cookieSyncManager.stopSync()
} else {
cookieManager.removeAllCookies(null)
}
}
}
}
private fun signOut() {
val token = prefsStorage.pianoIdToken
setAccessToken(null)
PianoId.signOut(token?.accessToken ?: "tmp") { r ->
r.onSuccess {
showMessage("Sign out success callback")
}.onFailure {
showError(it)
}
}
}
private fun setAccessToken(token: PianoIdToken?) {
prefsStorage.pianoIdToken = token
if (token == null)
return
val userFields = token.info.map { (key, value) -> "$key = $value" }.joinToString(prefix = "[", postfix = "]")
Timber.d("Token has these fields: %s", userFields)
PianoId.getUserInfo(token.accessToken) { r ->
val customFields = r.getOrNull()
?.customFields
?.joinToString(prefix = "[", postfix = "]") { "${it.fieldName} = ${it.value}" }
Timber.d("User custom fields = $customFields")
val newUserInfo = PianoUserInfo("new_form")
.customField("test0", listOf("value"))
.customField("test1", "test")
.customField("test2", true)
.customField("test3", 5)
PianoId.putUserInfo(token.accessToken, newUserInfo) { r2 ->
val newCustomFields = r2.getOrNull()
?.customFields
?.joinToString(prefix = "[", postfix = "]") { "${it.fieldName} = ${it.value}" }
Timber.d("Updated user custom fields = $newCustomFields")
}
}
Composer.getInstance().userToken(token.accessToken)
showMessage("accessToken = " + token.accessToken)
}
private fun showError(throwable: Throwable) {
Timber.e(throwable)
showMessage("We've got error: " + throwable.message)
}
private fun showMessage(message: String) {
Snackbar.make(binding.root, message, Snackbar.LENGTH_LONG).show()
}
}
| apache-2.0 | b967188928aecefcecd6bec935e0d3d1 | 38.104938 | 117 | 0.566535 | 5.231214 | false | false | false | false |
charlesmadere/smash-ranks-android | smash-ranks-android/app/src/main/java/com/garpr/android/features/deepLink/DeepLinkActivity.kt | 1 | 3892 | package com.garpr.android.features.deepLink
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import com.garpr.android.R
import com.garpr.android.features.common.activities.BaseActivity
import com.garpr.android.features.deepLink.DeepLinkViewModel.Breadcrumb
import com.garpr.android.features.home.HomeActivity
import com.garpr.android.features.player.PlayerActivity
import com.garpr.android.features.players.PlayersActivity
import com.garpr.android.features.rankings.RankingsActivity
import com.garpr.android.features.tournament.TournamentActivity
import com.garpr.android.features.tournaments.TournamentsActivity
import org.koin.androidx.viewmodel.ext.android.viewModel
class DeepLinkActivity : BaseActivity() {
private val viewModel: DeepLinkViewModel by viewModel()
companion object {
private const val TAG = "DeepLinkActivity"
}
override val activityName = TAG
private fun error() {
Toast.makeText(this, R.string.error_loading_deep_link_data, Toast.LENGTH_LONG).show()
startActivity(HomeActivity.getLaunchIntent(context = this))
supportFinishAfterTransition()
}
private fun fetchBreadcrumbs() {
viewModel.fetchBreadcrumbs()
}
private fun initListeners() {
viewModel.breadcrumbsLiveData.observe(this, Observer {
processBreadcrumbs(it)
})
viewModel.networkErrorLiveData.observe(this, Observer {
error()
})
viewModel.urlParseErrorLiveData.observe(this, Observer {
error()
})
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_deep_link)
viewModel.initialize(intent?.dataString)
initListeners()
fetchBreadcrumbs()
}
private fun processBreadcrumbs(breadcrumbs: List<Breadcrumb>) {
val intents = mutableListOf<Intent>()
breadcrumbs.forEach {
intents.add(when (it) {
is Breadcrumb.Home -> {
HomeActivity.getLaunchIntent(
context = this,
initialPosition = it.initialPosition
)
}
is Breadcrumb.Player -> {
PlayerActivity.getLaunchIntent(
context = this,
playerId = it.playerId,
region = it.region
)
}
is Breadcrumb.Players -> {
PlayersActivity.getLaunchIntent(
context = this,
region = it.region
)
}
is Breadcrumb.Rankings -> {
RankingsActivity.getLaunchIntent(
context = this,
region = it.region
)
}
is Breadcrumb.Tournament -> {
TournamentActivity.getLaunchIntent(
context = this,
tournamentId = it.tournamentId,
region = it.region
)
}
is Breadcrumb.Tournaments -> {
TournamentsActivity.getLaunchIntent(
context = this,
region = it.region
)
}
})
}
if (breadcrumbs.isEmpty()) {
startActivity(HomeActivity.getLaunchIntent(context = this))
} else {
ContextCompat.startActivities(this, intents.toTypedArray())
}
supportFinishAfterTransition()
}
}
| unlicense | 53462b7da1ac97ca6cbddc2befe07d95 | 31.165289 | 93 | 0.567061 | 5.791667 | false | false | false | false |
NordicSemiconductor/Android-nRF-Toolbox | profile_prx/src/main/java/no/nordicsemi/android/prx/view/PRXLinkLossView.kt | 1 | 3737 | /*
* Copyright (c) 2022, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package no.nordicsemi.android.prx.view
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.HighlightOff
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import no.nordicsemi.android.theme.ScreenSection
import no.nordicsemi.android.prx.R
@Composable
fun DeviceOutOfRangeView(navigateUp: () -> Unit) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
ScreenSection {
Icon(
imageVector = Icons.Default.HighlightOff,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSecondary,
modifier = Modifier
.background(
color = MaterialTheme.colorScheme.secondary,
shape = CircleShape
)
.padding(8.dp)
)
Spacer(modifier = Modifier.size(16.dp))
Text(
text = stringResource(id = R.string.prx_device_out_of_range),
style = MaterialTheme.typography.titleMedium
)
Spacer(modifier = Modifier.size(16.dp))
Text(
text = stringResource(id = R.string.prx_device_out_of_range_reason),
textAlign = TextAlign.Center,
style = MaterialTheme.typography.bodyMedium
)
}
Spacer(modifier = Modifier.size(16.dp))
Button(onClick = { navigateUp() }) {
Text(text = stringResource(id = R.string.disconnect))
}
}
}
| bsd-3-clause | 4c2069ce65b0b39a8723db558d9d3663 | 38.336842 | 89 | 0.695745 | 4.791026 | false | false | false | false |
googlecodelabs/fido2-codelab | android/app-start/src/main/java/com/example/android/fido2/api/AuthApi.kt | 1 | 20928 | /*
* Copyright 2019 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.fido2.api
import android.util.JsonReader
import android.util.JsonToken
import android.util.JsonWriter
import android.util.Log
import com.example.android.fido2.BuildConfig
import com.example.android.fido2.decodeBase64
import com.example.android.fido2.toBase64
import com.google.android.gms.fido.fido2.api.common.Attachment
import com.google.android.gms.fido.fido2.api.common.AuthenticatorAssertionResponse
import com.google.android.gms.fido.fido2.api.common.AuthenticatorAttestationResponse
import com.google.android.gms.fido.fido2.api.common.AuthenticatorSelectionCriteria
import com.google.android.gms.fido.fido2.api.common.PublicKeyCredential
import com.google.android.gms.fido.fido2.api.common.PublicKeyCredentialCreationOptions
import com.google.android.gms.fido.fido2.api.common.PublicKeyCredentialDescriptor
import com.google.android.gms.fido.fido2.api.common.PublicKeyCredentialParameters
import com.google.android.gms.fido.fido2.api.common.PublicKeyCredentialRequestOptions
import com.google.android.gms.fido.fido2.api.common.PublicKeyCredentialRpEntity
import com.google.android.gms.fido.fido2.api.common.PublicKeyCredentialType
import com.google.android.gms.fido.fido2.api.common.PublicKeyCredentialUserEntity
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import okhttp3.ResponseBody
import ru.gildor.coroutines.okhttp.await
import java.io.StringReader
import java.io.StringWriter
import javax.inject.Inject
/**
* Interacts with the server API.
*/
class AuthApi @Inject constructor(
private val client: OkHttpClient
) {
companion object {
private const val BASE_URL = BuildConfig.API_BASE_URL
private val JSON = "application/json".toMediaTypeOrNull()
private const val SessionIdKey = "connect.sid="
private const val TAG = "AuthApi"
}
/**
* @param username The username to be used for sign-in.
* @return The Session ID.
*/
suspend fun username(username: String): ApiResult<Unit> {
val call = client.newCall(
Request.Builder()
.url("$BASE_URL/username")
.method("POST", jsonRequestBody {
name("username").value(username)
})
.build()
)
val response = call.await()
return response.result("Error calling /username") { }
}
/**
* @param sessionId The session ID received on `username()`.
* @param password A password.
* @return An [ApiResult].
*/
suspend fun password(sessionId: String, password: String): ApiResult<Unit> {
val call = client.newCall(
Request.Builder()
.url("$BASE_URL/password")
.addHeader("Cookie", formatCookie(sessionId))
.method("POST", jsonRequestBody {
name("password").value(password)
})
.build()
)
val response = call.await()
return response.result("Error calling /password") { }
}
/**
* @param sessionId The session ID.
* @return A list of all the credentials registered on the server.
*/
suspend fun getKeys(sessionId: String): ApiResult<List<Credential>> {
val call = client.newCall(
Request.Builder()
.url("$BASE_URL/getKeys")
.addHeader("Cookie", formatCookie(sessionId))
.method("POST", jsonRequestBody {})
.build()
)
val response = call.await()
return response.result("Error calling /getKeys") {
parseUserCredentials(body ?: throw ApiException("Empty response from /getKeys"))
}
}
/**
* @param sessionId The session ID.
* @return A pair. The `first` element is an [PublicKeyCredentialCreationOptions] that can be
* used for a subsequent FIDO2 API call. The `second` element is a challenge string that should
* be sent back to the server in [registerResponse].
*/
suspend fun registerRequest(sessionId: String): ApiResult<PublicKeyCredentialCreationOptions> {
val call = client.newCall(
Request.Builder()
.url("$BASE_URL/registerRequest")
.addHeader("Cookie", formatCookie(sessionId))
.method("POST", jsonRequestBody {
name("attestation").value("none")
name("authenticatorSelection").objectValue {
name("authenticatorAttachment").value("platform")
name("userVerification").value("required")
}
})
.build()
)
val response = call.await()
return response.result("Error calling /registerRequest") {
parsePublicKeyCredentialCreationOptions(
body ?: throw ApiException("Empty response from /registerRequest")
)
}
}
/**
* @param sessionId The session ID.
* @param credential The FIDO2 PublicKeyCredential object.
* @return A list of all the credentials registered on the server, including the newly
* registered one.
*/
suspend fun registerResponse(
sessionId: String,
credential: PublicKeyCredential
): ApiResult<List<Credential>> {
val rawId = credential.rawId.toBase64()
val response = credential.response as AuthenticatorAttestationResponse
val call = client.newCall(
Request.Builder()
.url("$BASE_URL/registerResponse")
.addHeader("Cookie", formatCookie(sessionId))
.method("POST", jsonRequestBody {
name("id").value(rawId)
name("type").value(PublicKeyCredentialType.PUBLIC_KEY.toString())
name("rawId").value(rawId)
name("response").objectValue {
name("clientDataJSON").value(
response.clientDataJSON.toBase64()
)
name("attestationObject").value(
response.attestationObject.toBase64()
)
}
})
.build()
)
val apiResponse = call.await()
return apiResponse.result("Error calling /registerResponse") {
parseUserCredentials(
body ?: throw ApiException("Empty response from /registerResponse")
)
}
}
/**
* @param sessionId The session ID.
* @param credentialId The credential ID to be removed.
*/
suspend fun removeKey(sessionId: String, credentialId: String): ApiResult<Unit> {
val call = client.newCall(
Request.Builder()
.url("$BASE_URL/removeKey?credId=$credentialId")
.addHeader("Cookie", formatCookie(sessionId))
.method("POST", jsonRequestBody {})
.build()
)
val response = call.await()
return response.result("Error calling /removeKey") { }
}
/**
* @param sessionId The session ID to be used for the sign-in.
* @param credentialId The credential ID of this device.
* @return A pair. The `first` element is a [PublicKeyCredentialRequestOptions] that can be used
* for a subsequent FIDO2 API call. The `second` element is a challenge string that should
* be sent back to the server in [signinResponse].
*/
suspend fun signinRequest(
sessionId: String,
credentialId: String?
): ApiResult<PublicKeyCredentialRequestOptions> {
val call = client.newCall(
Request.Builder()
.url(
buildString {
append("$BASE_URL/signinRequest")
if (credentialId != null) {
append("?credId=$credentialId")
}
}
)
.addHeader("Cookie", formatCookie(sessionId))
.method("POST", jsonRequestBody {})
.build()
)
val response = call.await()
return response.result("Error calling /signinRequest") {
parsePublicKeyCredentialRequestOptions(
body ?: throw ApiException("Empty response from /signinRequest")
)
}
}
/**
* @param sessionId The session ID.
* @param credential The FIDO2 PublicKeyCredential object.
* @return A list of all the credentials registered on the server, including the newly
* registered one.
*/
suspend fun signinResponse(
sessionId: String,
credential: PublicKeyCredential
): ApiResult<List<Credential>> {
val rawId = credential.rawId.toBase64()
val response = credential.response as AuthenticatorAssertionResponse
val call = client.newCall(
Request.Builder()
.url("$BASE_URL/signinResponse")
.addHeader("Cookie", formatCookie(sessionId))
.method("POST", jsonRequestBody {
name("id").value(rawId)
name("type").value(PublicKeyCredentialType.PUBLIC_KEY.toString())
name("rawId").value(rawId)
name("response").objectValue {
name("clientDataJSON").value(
response.clientDataJSON.toBase64()
)
name("authenticatorData").value(
response.authenticatorData.toBase64()
)
name("signature").value(
response.signature.toBase64()
)
name("userHandle").value(
response.userHandle?.toBase64() ?: ""
)
}
})
.build()
)
val apiResponse = call.await()
return apiResponse.result("Error calling /signingResponse") {
parseUserCredentials(body ?: throw ApiException("Empty response from /signinResponse"))
}
}
private fun parsePublicKeyCredentialRequestOptions(
body: ResponseBody
): PublicKeyCredentialRequestOptions {
val builder = PublicKeyCredentialRequestOptions.Builder()
JsonReader(body.byteStream().bufferedReader()).use { reader ->
reader.beginObject()
while (reader.hasNext()) {
when (reader.nextName()) {
"challenge" -> builder.setChallenge(reader.nextString().decodeBase64())
"userVerification" -> reader.skipValue()
"allowCredentials" -> builder.setAllowList(parseCredentialDescriptors(reader))
"rpId" -> builder.setRpId(reader.nextString())
"timeout" -> builder.setTimeoutSeconds(reader.nextDouble())
else -> reader.skipValue()
}
}
reader.endObject()
}
return builder.build()
}
private fun parsePublicKeyCredentialCreationOptions(
body: ResponseBody
): PublicKeyCredentialCreationOptions {
val builder = PublicKeyCredentialCreationOptions.Builder()
JsonReader(body.byteStream().bufferedReader()).use { reader ->
reader.beginObject()
while (reader.hasNext()) {
when (reader.nextName()) {
"user" -> builder.setUser(parseUser(reader))
"challenge" -> builder.setChallenge(reader.nextString().decodeBase64())
"pubKeyCredParams" -> builder.setParameters(parseParameters(reader))
"timeout" -> builder.setTimeoutSeconds(reader.nextDouble())
"attestation" -> reader.skipValue() // Unused
"excludeCredentials" -> builder.setExcludeList(
parseCredentialDescriptors(reader)
)
"authenticatorSelection" -> builder.setAuthenticatorSelection(
parseSelection(reader)
)
"rp" -> builder.setRp(parseRp(reader))
}
}
reader.endObject()
}
return builder.build()
}
private fun parseRp(reader: JsonReader): PublicKeyCredentialRpEntity {
var id: String? = null
var name: String? = null
reader.beginObject()
while (reader.hasNext()) {
when (reader.nextName()) {
"id" -> id = reader.nextString()
"name" -> name = reader.nextString()
else -> reader.skipValue()
}
}
reader.endObject()
return PublicKeyCredentialRpEntity(id!!, name!!, /* icon */ null)
}
private fun parseSelection(reader: JsonReader): AuthenticatorSelectionCriteria {
val builder = AuthenticatorSelectionCriteria.Builder()
reader.beginObject()
while (reader.hasNext()) {
when (reader.nextName()) {
"authenticatorAttachment" -> builder.setAttachment(
Attachment.fromString(reader.nextString())
)
"userVerification" -> reader.skipValue()
else -> reader.skipValue()
}
}
reader.endObject()
return builder.build()
}
private fun parseCredentialDescriptors(
reader: JsonReader
): List<PublicKeyCredentialDescriptor> {
val list = mutableListOf<PublicKeyCredentialDescriptor>()
reader.beginArray()
while (reader.hasNext()) {
var id: String? = null
reader.beginObject()
while (reader.hasNext()) {
when (reader.nextName()) {
"id" -> id = reader.nextString()
"type" -> reader.skipValue()
"transports" -> reader.skipValue()
else -> reader.skipValue()
}
}
reader.endObject()
list.add(
PublicKeyCredentialDescriptor(
PublicKeyCredentialType.PUBLIC_KEY.toString(),
id!!.decodeBase64(),
/* transports */ null
)
)
}
reader.endArray()
return list
}
private fun parseUser(reader: JsonReader): PublicKeyCredentialUserEntity {
reader.beginObject()
var id: String? = null
var name: String? = null
var displayName = ""
while (reader.hasNext()) {
when (reader.nextName()) {
"id" -> id = reader.nextString()
"name" -> name = reader.nextString()
"displayName" -> displayName = reader.nextString()
else -> reader.skipValue()
}
}
reader.endObject()
return PublicKeyCredentialUserEntity(
id!!.decodeBase64(),
name!!,
null, // icon
displayName
)
}
private fun parseParameters(reader: JsonReader): List<PublicKeyCredentialParameters> {
val parameters = mutableListOf<PublicKeyCredentialParameters>()
reader.beginArray()
while (reader.hasNext()) {
reader.beginObject()
var type: String? = null
var alg = 0
while (reader.hasNext()) {
when (reader.nextName()) {
"type" -> type = reader.nextString()
"alg" -> alg = reader.nextInt()
else -> reader.skipValue()
}
}
reader.endObject()
parameters.add(PublicKeyCredentialParameters(type!!, alg))
}
reader.endArray()
return parameters
}
private fun jsonRequestBody(body: JsonWriter.() -> Unit): RequestBody {
val output = StringWriter()
JsonWriter(output).use { writer ->
writer.beginObject()
writer.body()
writer.endObject()
}
return output.toString().toRequestBody(JSON)
}
private fun parseUserCredentials(body: ResponseBody): List<Credential> {
fun readCredentials(reader: JsonReader): List<Credential> {
val credentials = mutableListOf<Credential>()
reader.beginArray()
while (reader.hasNext()) {
reader.beginObject()
var id: String? = null
var publicKey: String? = null
while (reader.hasNext()) {
when (reader.nextName()) {
"credId" -> id = reader.nextString()
"publicKey" -> publicKey = reader.nextString()
else -> reader.skipValue()
}
}
reader.endObject()
if (id != null && publicKey != null) {
credentials.add(Credential(id, publicKey))
}
}
reader.endArray()
return credentials
}
JsonReader(body.byteStream().bufferedReader()).use { reader ->
reader.beginObject()
while (reader.hasNext()) {
val name = reader.nextName()
if (name == "credentials") {
return readCredentials(reader)
} else {
reader.skipValue()
}
}
reader.endObject()
}
throw ApiException("Cannot parse credentials")
}
private fun throwResponseError(response: Response, message: String): Nothing {
val b = response.body
if (b != null) {
throw ApiException("$message; ${parseError(b)}")
} else {
throw ApiException(message)
}
}
private fun parseError(body: ResponseBody): String {
val errorString = body.string()
try {
JsonReader(StringReader(errorString)).use { reader ->
reader.beginObject()
while (reader.hasNext()) {
val name = reader.nextName()
if (name == "error") {
val token = reader.peek()
if (token == JsonToken.STRING) {
return reader.nextString()
}
return "Unknown"
} else {
reader.skipValue()
}
}
reader.endObject()
}
} catch (e: Exception) {
Log.e(TAG, "Cannot parse the error: $errorString", e)
// Don't throw; this method is called during throwing.
}
return ""
}
private fun JsonWriter.objectValue(body: JsonWriter.() -> Unit) {
beginObject()
body()
endObject()
}
private fun <T> Response.result(errorMessage: String, data: Response.() -> T): ApiResult<T> {
if (!isSuccessful) {
if (code == 401) { // Unauthorized
return ApiResult.SignedOutFromServer
}
// All other errors throw an exception.
throwResponseError(this, errorMessage)
}
val cookie = headers("set-cookie").find { it.startsWith(SessionIdKey) }
val sessionId = if (cookie != null) parseSessionId(cookie) else null
return ApiResult.Success(sessionId, data())
}
private fun parseSessionId(cookie: String): String {
val start = cookie.indexOf(SessionIdKey)
if (start < 0) {
throw ApiException("Cannot find $SessionIdKey")
}
val semicolon = cookie.indexOf(";", start + SessionIdKey.length)
val end = if (semicolon < 0) cookie.length else semicolon
return cookie.substring(start + SessionIdKey.length, end)
}
private fun formatCookie(sessionId: String): String {
return "$SessionIdKey$sessionId"
}
}
| apache-2.0 | 543ff63598986c5f31de04ce42b4cbf3 | 37.4 | 100 | 0.561688 | 5.178916 | false | false | false | false |
sangcomz/FishBun | FishBun/src/main/java/com/sangcomz/fishbun/ui/picker/PickerAdapter.kt | 1 | 6727 | package com.sangcomz.fishbun.ui.picker
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.recyclerview.widget.RecyclerView
import com.sangcomz.fishbun.R
import com.sangcomz.fishbun.adapter.image.ImageAdapter
import com.sangcomz.fishbun.ui.picker.listener.OnPickerActionListener
import com.sangcomz.fishbun.ui.picker.model.PickerListItem
import com.sangcomz.fishbun.util.RadioWithTextButton
class PickerAdapter(
private val imageAdapter: ImageAdapter,
private val onPickerActionListener: OnPickerActionListener,
private val hasCameraInPickerPage: Boolean
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private var pickerList: List<PickerListItem> = listOf()
init {
setHasStableIds(true)
}
override fun getItemId(position: Int): Long {
return pickerList[position].getItemId()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return when (viewType) {
TYPE_CAMERA -> {
ViewHolderCamera(
LayoutInflater.from(parent.context)
.inflate(R.layout.header_item, parent, false)
).apply {
itemView.setOnClickListener {
onPickerActionListener.takePicture()
}
}
}
else -> {
ViewHolderImage(
LayoutInflater.from(parent.context)
.inflate(R.layout.picker_item, parent, false),
imageAdapter,
onPickerActionListener
).apply {
btnThumbCount.setOnClickListener {
onPickerActionListener.onClickThumbCount(adapterPosition)
}
imgThumbImage.setOnClickListener {
onPickerActionListener.onClickImage(adapterPosition)
}
}
}
}
}
override fun onBindViewHolder(
holder: RecyclerView.ViewHolder,
position: Int,
payloads: MutableList<Any>
) {
if (payloads.contains(UPDATE_PAYLOAD)) {
(holder as? ViewHolderImage)?.update(pickerList[position])
} else {
super.onBindViewHolder(holder, position, payloads)
}
}
override fun onBindViewHolder(
holder: RecyclerView.ViewHolder,
position: Int
) {
(holder as? ViewHolderImage)?.bindData(pickerList[position])
}
override fun getItemCount(): Int {
return pickerList.size
}
override fun getItemViewType(position: Int): Int {
return if (position == 0 && hasCameraInPickerPage) {
TYPE_CAMERA
} else {
super.getItemViewType(position)
}
}
fun setPickerList(pickerList: List<PickerListItem>) {
this.pickerList = pickerList
notifyDataSetChanged()
}
fun updatePickerListItem(position: Int, image: PickerListItem.Image) {
this.pickerList = this.pickerList.toMutableList().apply {
set(position, image)
}
notifyItemChanged(position, UPDATE_PAYLOAD)
}
fun addImage(path: PickerListItem.Image) {
val addedIndex = if (hasCameraInPickerPage) 1 else 0
pickerList.toMutableList()
.apply { add(addedIndex, path) }
.also(this::setPickerList)
}
class ViewHolderImage(
itemView: View,
private val imageAdapter: ImageAdapter,
private val onPickerActionListener: OnPickerActionListener
) :
RecyclerView.ViewHolder(itemView) {
val imgThumbImage: ImageView = itemView.findViewById(R.id.img_thumb_image)
val btnThumbCount: RadioWithTextButton = itemView.findViewById(R.id.btn_thumb_count)
fun bindData(item: PickerListItem) {
if (item !is PickerListItem.Image) return
itemView.tag = item.imageUri
val viewData = item.viewData
btnThumbCount.run {
unselect()
setCircleColor(viewData.colorActionBar)
setTextColor(viewData.colorActionBarTitle)
setStrokeColor(viewData.colorSelectCircleStroke)
}
initState(item.selectedIndex, viewData.maxCount == 1)
imageAdapter.loadImage(imgThumbImage, item.imageUri)
}
private fun initState(selectedIndex: Int, isUseDrawable: Boolean) {
if (selectedIndex != -1) {
setScale(imgThumbImage, true)
setRadioButton(isUseDrawable, (selectedIndex + 1).toString())
} else {
setScale(imgThumbImage, false)
}
}
fun update(item: PickerListItem) {
if (item !is PickerListItem.Image) return
val selectedIndex = item.selectedIndex
animScale(imgThumbImage, selectedIndex != -1, true)
if (selectedIndex != -1) {
setRadioButton(item.viewData.maxCount == 1, (selectedIndex + 1).toString())
} else {
btnThumbCount.unselect()
}
}
private fun animScale(view: View, isSelected: Boolean, isAnimation: Boolean) {
var duration = 200
if (!isAnimation) duration = 0
val toScale: Float = if (isSelected) .8f else 1.0f
ViewCompat.animate(view)
.setDuration(duration.toLong())
.scaleX(toScale)
.scaleY(toScale)
.withEndAction { if (isAnimation && !isSelected) onPickerActionListener.onDeselect() }
.start()
}
private fun setScale(view: View, isSelected: Boolean) {
val toScale: Float = if (isSelected) .8f else 1.0f
view.scaleX = toScale
view.scaleY = toScale
}
private fun setRadioButton(isUseDrawable: Boolean, text: String) {
if (isUseDrawable) {
ContextCompat.getDrawable(
btnThumbCount.context,
R.drawable.ic_done_white_24dp
)?.let {
btnThumbCount.setDrawable(it)
}
} else {
btnThumbCount.setText(text)
}
}
}
class ViewHolderCamera(itemView: View) : RecyclerView.ViewHolder(itemView)
companion object {
private const val TYPE_CAMERA = Int.MIN_VALUE
private const val UPDATE_PAYLOAD = "payload_update"
}
} | apache-2.0 | 1070ec865e3cf939384468d14657a7d2 | 32.142857 | 102 | 0.594321 | 5.012668 | false | false | false | false |
square/moshi | moshi-kotlin-codegen/src/main/java/com/squareup/moshi/kotlin/codegen/api/TargetProperty.kt | 1 | 1292 | /*
* Copyright (C) 2018 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.moshi.kotlin.codegen.api
import com.squareup.kotlinpoet.KModifier
import com.squareup.kotlinpoet.PropertySpec
import com.squareup.kotlinpoet.TypeName
/** A property in user code that maps to JSON. */
@InternalMoshiCodegenApi
public data class TargetProperty(
val propertySpec: PropertySpec,
val parameter: TargetParameter?,
val visibility: KModifier,
val jsonName: String?,
val jsonIgnore: Boolean
) {
val name: String get() = propertySpec.name
val type: TypeName get() = propertySpec.type
val parameterIndex: Int get() = parameter?.index ?: -1
val hasDefault: Boolean get() = parameter?.hasDefault ?: true
override fun toString(): String = name
}
| apache-2.0 | 0461f54f49538b7b36e373530ec10645 | 33.918919 | 75 | 0.747678 | 4.154341 | false | false | false | false |
wleroux/fracturedskies | src/main/kotlin/com/fracturedskies/render/mainmenu/MainMenuRenderer.kt | 1 | 5239 | package com.fracturedskies.render.mainmenu
import com.fracturedskies.api.*
import com.fracturedskies.api.GameSize.NORMAL
import com.fracturedskies.engine.api.Cause
import com.fracturedskies.engine.collections.MultiTypeMap
import com.fracturedskies.engine.jeact.*
import com.fracturedskies.engine.math.Color4
import com.fracturedskies.render.common.components.TextRenderer.Companion.text
import com.fracturedskies.render.common.components.button.Button.Companion.button
import com.fracturedskies.render.common.components.layout.*
import com.fracturedskies.render.common.components.layout.ContentAlign.STRETCH
import com.fracturedskies.render.common.components.layout.Direction.COLUMN_REVERSE
import com.fracturedskies.render.common.components.layout.JustifyContent.CENTER
import com.fracturedskies.render.common.components.layout.Layout.Companion.layout
import com.fracturedskies.render.common.components.layout.Wrap.NO_WRAP
import com.fracturedskies.render.common.style.*
import com.fracturedskies.render.common.style.Border.*
import com.fracturedskies.render.mainmenu.MainMenuRenderer.MenuState
import com.fracturedskies.render.mainmenu.MainMenuRenderer.Mode.*
import javax.inject.Inject
class MainMenuRenderer : Component<MenuState>(MenuState()) {
companion object {
fun Node.Builder<*>.mainMenu(additionalContext: MultiTypeMap = MultiTypeMap(), block: Node.Builder<*>.() -> Unit = {}) {
nodes.add(Node(MainMenuRenderer::class, additionalContext, block))
}
}
@Inject
private lateinit var world: World
data class MenuState(
val mode: Mode = MAIN_MENU,
val gameSize: GameSize = NORMAL
)
enum class Mode {
MAIN_MENU,
NEW_GAME
}
private fun setMode(mode: Mode) {
nextState = currentState.copy(mode = mode)
}
private fun onSelectGameSize(gameSize: GameSize) {
nextState = currentState.copy(gameSize = gameSize)
}
private fun onQuit() {
world.requestShutdown(Cause.of(this))
}
private fun startGame() {
world.startGame(currentState.gameSize, Cause.of(this))
}
override fun render() = nodes {
val defaultMargin = Margin(4, 0, 4, 0)
val defaultPadding = Padding(4, 8, 4, 8)
val defaultBorder = Border(
color = Color4.WHITE,
width = BorderWidth(1, 1, 1, 1),
radius = BorderRadius(8, 8, 8, 8)
)
if (state.mode == MAIN_MENU) {
layout(justifyContent = CENTER, alignContent = ContentAlign.CENTER) {
layout(COLUMN_REVERSE, CENTER, ItemAlign.STRETCH, ContentAlign.STRETCH, NO_WRAP) {
button(
margin = defaultMargin,
padding = defaultPadding,
border = defaultBorder,
onClick = { _ -> [email protected](NEW_GAME) }
) { text("New Game") }
button(
margin = defaultMargin,
padding = defaultPadding,
border = defaultBorder,
onClick = { _ -> [email protected]() }
) { text("Quit Game")}
}
}
} else {
layout(COLUMN_REVERSE, alignItems = ItemAlign.STRETCH, alignContent = ContentAlign.CENTER, justifyContent = CENTER, wrap = NO_WRAP) {
layout(alignItems = ItemAlign.CENTER, alignContent = STRETCH) {
text("Game Size: ${state.gameSize.name}")
}
layout(COLUMN_REVERSE, alignItems = ItemAlign.STRETCH, alignContent = ContentAlign.CENTER, justifyContent = CENTER, wrap = NO_WRAP) {
// Button Group
GameSize.values().forEachIndexed { index, gameSize ->
val isTopButton = index == 0
val isBottomButton = index == GameSize.values().size - 1
val margin = defaultMargin.copy(
top = if (isTopButton) defaultMargin.top else 0,
bottom = if (isBottomButton) defaultMargin.bottom else 0
)
val border = defaultBorder.copy(
width = defaultBorder.width.copy(
bottom = if (isBottomButton) defaultBorder.width.bottom else 0
),
radius = defaultBorder.radius.copy(
topLeft = if (isTopButton) defaultBorder.radius.topLeft else 0,
topRight = if (isTopButton) defaultBorder.radius.topRight else 0,
bottomLeft = if (isBottomButton) defaultBorder.radius.bottomLeft else 0,
bottomRight = if (isBottomButton) defaultBorder.radius.bottomRight else 0
)
)
button(
margin = margin,
padding = defaultPadding,
border = border,
onClick = { _ -> [email protected](gameSize) }
) { text(gameSize.name) }
}
button(
margin = defaultMargin,
padding = defaultPadding,
border = defaultBorder,
onClick = { _ -> [email protected]() }
) { text("Start Game") }
button(
margin = defaultMargin,
padding = defaultPadding,
border = defaultBorder,
onClick = { _ -> [email protected](MAIN_MENU) }
) { text("Back") }
}
}
}
}
} | unlicense | 6aa3df8aae4c107e634926bb54f94c67 | 36.971014 | 141 | 0.64058 | 4.387772 | false | false | false | false |
pdvrieze/ProcessManager | darwin/src/jsMain/kotlin/uk/ac/bournemouth/darwin/util/domutil.kt | 1 | 3565 | /*
* Copyright (c) 2017.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
/**
* Utility methods for working on the DOM.
* Created by pdvrieze on 27/03/16.
*/
package uk.ac.bournemouth.darwin.util
import kotlinx.dom.clear
import kotlinx.html.TagConsumer
import org.w3c.dom.*
import kotlin.dom.clear
import kotlinx.html.dom.append as kotlinxAppend
const val BUTTON_DEFAULT: Short = 0
fun Element.childElements(): Iterable<Element> = object : Iterable<Element> {
override fun iterator() = object : Iterator<Element> {
private var current: Element? = [email protected]
override fun hasNext(): Boolean {
return current != null
}
override fun next(): Element {
return current?.also { current = it.nextElementSibling } ?: throw NoSuchElementException("End of iterator")
}
}
}
inline fun HTMLCollection.foreach(body: (Element?) -> Unit) {
length.let { l ->
for (i in 0 until l) {
body(this[i])
}
}
}
inline fun Element.removeChildElementIf(crossinline predicate: (Element) -> Boolean) {
childElements()
.asSequence()
.filter { predicate(it) }
.forEach { it.remove() }
}
external fun encodeURI(uri: dynamic): String? = definedExternally
inline fun Element.removeChildIf(predicate: (Node) -> Boolean) {
childNodes.forEach { childNode ->
if (predicate(childNode)) {
childNode.removeFromParent()
}
}
}
inline fun Node.removeFromParent() {
parentElement!!.removeChild(this)
}
inline fun NodeList.forEach(visitor: (Node) -> Unit) {
var i = 0
val len = this.length
while (i < len) {
visitor(this[i]!!)
i += 1
}
}
fun Element.setChildren(children: NodeList?, alternative: () -> Node? = { null }) {
this.clear()
val elem = this
if (children == null) {
alternative()?.let { elem.appendChild(it) }
} else {
while (children.length > 0) {
elem.appendChild(children.item(0)!!)
}
}
}
inline fun Node.appendHtml(crossinline block: TagConsumer<HTMLElement>.() -> Unit): List<HTMLElement> =
kotlinxAppend({ ConsumerExt(this).block() })
val HTMLElement.appendHtml: TagConsumer<HTMLElement>
get() = ConsumerExt(kotlinxAppend)
class ConsumerExt<out T>(val parent: TagConsumer<T>) : TagConsumer<T> by parent {
@Suppress("NOTHING_TO_INLINE")
inline operator fun CharSequence.unaryPlus() {
parent.onTagContent(this)
}
}
fun Element.visitDescendants(filter: (Node) -> Short = { _ -> NodeFilter.FILTER_ACCEPT }, visitor: (Node) -> Unit) {
val walker = ownerDocument!!.createTreeWalker(root = this, whatToShow = NodeFilter.SHOW_ALL, filter = filter)
while (walker.nextNode() != null) {
visitor(walker.currentNode)
}
}
@Suppress("NOTHING_TO_INLINE")
inline operator fun <T, C : TagConsumer<T>> C.plus(text: String) = this.onTagContent(text)
| lgpl-3.0 | 4d03a5f3cf84883e2616aeca34a36764 | 29.470085 | 119 | 0.666199 | 3.992161 | false | false | false | false |
fossasia/open-event-android | app/src/main/java/org/fossasia/openevent/general/attendees/Attendee.kt | 1 | 2353 | package org.fossasia.openevent.general.attendees
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.PrimaryKey
import com.fasterxml.jackson.databind.PropertyNamingStrategy
import com.fasterxml.jackson.databind.annotation.JsonNaming
import com.github.jasminb.jsonapi.IntegerIdHandler
import com.github.jasminb.jsonapi.annotations.Id
import com.github.jasminb.jsonapi.annotations.Relationship
import com.github.jasminb.jsonapi.annotations.Type
import org.fossasia.openevent.general.event.Event
import org.fossasia.openevent.general.event.EventId
import org.fossasia.openevent.general.ticket.Ticket
import org.fossasia.openevent.general.ticket.TicketId
@Type("attendee")
@JsonNaming(PropertyNamingStrategy.KebabCaseStrategy::class)
@Entity(foreignKeys = [
(ForeignKey(entity = Event::class, parentColumns = ["id"],
childColumns = ["event"], onDelete = ForeignKey.CASCADE)),
(ForeignKey(entity = Ticket::class, parentColumns = ["id"],
childColumns = ["ticket"], onDelete = ForeignKey.CASCADE))])
data class Attendee(
@Id(IntegerIdHandler::class)
@PrimaryKey
val id: Long,
val firstname: String? = null,
val lastname: String? = null,
val email: String? = null,
val address: String? = null,
val city: String? = null,
val state: String? = null,
val country: String? = null,
val jobTitle: String? = null,
val phone: String? = null,
val taxBusinessInfo: String? = null,
val billingAddress: String? = null,
val homeAddress: String? = null,
val shippingAddress: String? = null,
val company: String? = null,
val workAddress: String? = null,
val workPhone: String? = null,
val website: String? = null,
val blog: String? = null,
val github: String? = null,
val facebook: String? = null,
val twitter: String? = null,
val gender: String? = null,
val isCheckedIn: Boolean? = false,
val checkinTimes: String? = null,
val isCheckedOut: Boolean = false,
val pdfUrl: String? = null,
val ticketId: String? = null,
val checkedIn: String? = null,
val checkedOut: String? = null,
@ColumnInfo(index = true)
@Relationship("event")
var event: EventId? = null,
@ColumnInfo(index = true)
@Relationship("ticket")
var ticket: TicketId? = null
)
| apache-2.0 | bd0f081c6496f7b092f91cd89c234e7a | 35.765625 | 68 | 0.710582 | 3.921667 | false | false | false | false |
binaryfoo/emv-bertlv | src/main/java/io/github/binaryfoo/decoders/CardholderVerificationConditionCode.kt | 1 | 885 | package io.github.binaryfoo.decoders
/**
* When a given method for verifying a cardholder should be applied.
*/
enum class CardholderVerificationConditionCode(val code: Int, val description: String) {
Always(0, "Always"),
UnattendedCash(1, "If unattended cash"),
NotStuff(2, "If not (unattended cash, manual cash, purchase + cash)"),
TerminalSupports(3, "If terminal supports CVM"),
ManualCash(4, "If manual cash"),
PurchasePlusCash(5, "If purchase + cash"),
TxLessThanX(6, "If transaction in application currency and < X"),
TxMoreThanX(7, "If transaction in application currency and >= X"),
TxLessThanY(8, "If transaction in application currency and < Y"),
TxMoreThanY(9, "If transaction in application currency and >= Y");
companion object {
fun fromCode(code: Int): CardholderVerificationConditionCode? = values().firstOrNull { it.code == code }
}
}
| mit | fdc579ad6cd59bac484c7c69552cc792 | 41.142857 | 108 | 0.724294 | 3.798283 | false | false | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/provider/UsersNameColorsOrderProvider.kt | 1 | 1105 | package com.boardgamegeek.provider
import android.net.Uri
import com.boardgamegeek.provider.BggContract.Companion.PATH_COLORS
import com.boardgamegeek.provider.BggContract.Companion.PATH_USERS
import com.boardgamegeek.provider.BggContract.PlayerColors
import com.boardgamegeek.provider.BggContract.PlayerColors.Columns.PLAYER_COLOR_SORT_ORDER
import com.boardgamegeek.provider.BggContract.PlayerColors.Columns.PLAYER_NAME
import com.boardgamegeek.provider.BggContract.PlayerColors.Columns.PLAYER_TYPE
import com.boardgamegeek.provider.BggDatabase.Tables
class UsersNameColorsOrderProvider : BaseProvider() {
override fun getType(uri: Uri) = PlayerColors.CONTENT_ITEM_TYPE
override val path = "$PATH_USERS/*/$PATH_COLORS/#"
override fun buildSimpleSelection(uri: Uri): SelectionBuilder {
return SelectionBuilder().table(Tables.PLAYER_COLORS)
.where("$PLAYER_TYPE=?", PlayerColors.TYPE_USER.toString())
.where("$PLAYER_NAME=?", PlayerColors.getUsername(uri))
.where("$PLAYER_COLOR_SORT_ORDER=?", PlayerColors.getSortOrder(uri).toString())
}
}
| gpl-3.0 | c4c0746e94bc35cdbf2fc23eadb7dca1 | 47.043478 | 91 | 0.779186 | 4.40239 | false | false | false | false |
Kotlin/kotlinx.serialization | formats/json/jsMain/src/kotlinx/serialization/json/internal/DynamicEncoders.kt | 1 | 9491 | /*
* Copyright 2017-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
@file:OptIn(ExperimentalSerializationApi::class)
package kotlinx.serialization.json.internal
import kotlinx.serialization.*
import kotlinx.serialization.descriptors.*
import kotlinx.serialization.encoding.*
import kotlinx.serialization.json.*
import kotlinx.serialization.modules.*
import kotlin.math.*
/**
* Converts Kotlin data structures to plain Javascript objects
*
*
* Limitations:
* * Map keys must be of primitive or enum type
* * Enums are serialized as the value of `@SerialName` if present or their name, in that order.
* * Currently does not support polymorphism
*
* Example of usage:
* ```
* @Serializable
* open class DataWrapper(open val s: String, val d: String?)
*
* val wrapper = DataWrapper("foo", "bar")
* val plainJS: dynamic = DynamicObjectSerializer().serialize(DataWrapper.serializer(), wrapper)
* ```
*/
@JsName("encodeToDynamic")
@OptIn(ExperimentalSerializationApi::class)
internal fun <T> Json.encodeDynamic(serializer: SerializationStrategy<T>, value: T): dynamic {
if (serializer.descriptor.kind is PrimitiveKind || serializer.descriptor.kind is SerialKind.ENUM) {
val encoder = DynamicPrimitiveEncoder(this)
encoder.encodeSerializableValue(serializer, value)
return encoder.result
}
val encoder = DynamicObjectEncoder(this, false)
encoder.encodeSerializableValue(serializer, value)
return encoder.result
}
@OptIn(ExperimentalSerializationApi::class)
private class DynamicObjectEncoder(
override val json: Json,
private val encodeNullAsUndefined: Boolean
) : AbstractEncoder(), JsonEncoder {
override val serializersModule: SerializersModule
get() = json.serializersModule
var result: dynamic = NoOutputMark
private lateinit var current: Node
private var currentName: String? = null
private lateinit var currentDescriptor: SerialDescriptor
private var currentElementIsMapKey = false
/**
* Flag of usage polymorphism with discriminator attribute
*/
private var polymorphicDiscriminator: String? = null
private object NoOutputMark
class Node(val writeMode: WriteMode, val jsObject: dynamic) {
var index: Int = 0
lateinit var parent: Node
}
enum class WriteMode {
OBJ, MAP, LIST
}
override fun encodeElement(descriptor: SerialDescriptor, index: Int): Boolean {
current.index = index
currentDescriptor = descriptor
when {
current.writeMode == WriteMode.MAP -> currentElementIsMapKey = current.index % 2 == 0
current.writeMode == WriteMode.LIST && descriptor.kind is PolymorphicKind -> currentName = index.toString()
else -> currentName = descriptor.getElementName(index)
}
return true
}
override fun encodeValue(value: Any) {
if (currentElementIsMapKey) {
currentName = value.toString()
} else if (isNotStructured()) {
result = value
} else {
current.jsObject[currentName] = value
}
}
override fun encodeChar(value: Char) {
encodeValue(value.toString())
}
override fun encodeNull() {
if (currentElementIsMapKey) {
currentName = null
} else {
if (encodeNullAsUndefined) return // omit element
current.jsObject[currentName] = null
}
}
override fun encodeEnum(enumDescriptor: SerialDescriptor, index: Int) {
encodeValue(enumDescriptor.getElementName(index))
}
override fun encodeLong(value: Long) {
val asDouble = value.toDouble()
val conversionHasLossOfPrecision = abs(asDouble) > MAX_SAFE_INTEGER
// todo: shall it be driven by isLenient or another configuration key?
if (!json.configuration.isLenient && conversionHasLossOfPrecision) {
throw IllegalArgumentException(
"$value can't be serialized to number due to a potential precision loss. " +
"Use the JsonConfiguration option isLenient to serialize anyway"
)
}
if (currentElementIsMapKey && conversionHasLossOfPrecision) {
throw IllegalArgumentException(
"Long with value $value can't be used in json as map key, because its value is larger than Number.MAX_SAFE_INTEGER"
)
}
encodeValue(asDouble)
}
override fun encodeFloat(value: Float) {
encodeDouble(value.toDouble())
}
override fun encodeDouble(value: Double) {
if (currentElementIsMapKey) {
val hasNonZeroFractionalPart = floor(value) != value
if (!value.isFinite() || hasNonZeroFractionalPart) {
throw IllegalArgumentException(
"Double with value $value can't be used in json as map key, because its value is not an integer."
)
}
}
encodeValue(value)
}
override fun <T : Any> encodeNullableSerializableElement(
descriptor: SerialDescriptor,
index: Int,
serializer: SerializationStrategy<T>,
value: T?
) {
if (value != null || json.configuration.explicitNulls) {
super.encodeNullableSerializableElement(descriptor, index, serializer, value)
}
}
override fun encodeJsonElement(element: JsonElement) {
encodeSerializableValue(JsonElementSerializer, element)
}
override fun shouldEncodeElementDefault(descriptor: SerialDescriptor, index: Int) =
json.configuration.encodeDefaults
private fun enterNode(jsObject: dynamic, writeMode: WriteMode) {
val child = Node(writeMode, jsObject)
child.parent = current
current = child
}
private fun exitNode() {
current = current.parent
currentElementIsMapKey = false
}
private fun isNotStructured() = result === NoOutputMark
override fun <T> encodeSerializableValue(serializer: SerializationStrategy<T>, value: T) {
encodePolymorphically(serializer, value) {
polymorphicDiscriminator = it
}
}
override fun beginStructure(descriptor: SerialDescriptor): CompositeEncoder {
// we currently do not structures as map key
if (currentElementIsMapKey) {
throw IllegalArgumentException(
"Value of type ${descriptor.serialName} can't be used in json as map key. " +
"It should have either primitive or enum kind, but its kind is ${descriptor.kind}."
)
}
val newMode = selectMode(descriptor)
if (result === NoOutputMark) {
result = newChild(newMode)
current = Node(newMode, result)
current.parent = current
} else {
val child = newChild(newMode)
current.jsObject[currentName] = child
enterNode(child, newMode)
}
if (polymorphicDiscriminator != null) {
current.jsObject[polymorphicDiscriminator!!] = descriptor.serialName
polymorphicDiscriminator = null
}
current.index = 0
return this
}
private fun newChild(writeMode: WriteMode) = when (writeMode) {
WriteMode.OBJ, WriteMode.MAP -> js("{}")
WriteMode.LIST -> js("[]")
}
override fun endStructure(descriptor: SerialDescriptor) {
exitNode()
}
@OptIn(ExperimentalSerializationApi::class)
fun selectMode(desc: SerialDescriptor) = when (desc.kind) {
StructureKind.CLASS, StructureKind.OBJECT, SerialKind.CONTEXTUAL -> WriteMode.OBJ
StructureKind.LIST, is PolymorphicKind -> WriteMode.LIST
StructureKind.MAP -> WriteMode.MAP
is PrimitiveKind, SerialKind.ENUM -> {
// the two cases are handled in DynamicObjectSerializer. But compiler does not know
error("DynamicObjectSerializer does not support serialization of singular primitive values or enum types.")
}
}
}
private class DynamicPrimitiveEncoder(
override val json: Json,
) : AbstractEncoder(), JsonEncoder {
override val serializersModule: SerializersModule
get() = json.serializersModule
var result: dynamic = null
override fun encodeNull() {
result = null
}
override fun encodeLong(value: Long) {
val asDouble = value.toDouble()
// todo: shall it be driven by isLenient or another configuration key?
if (!json.configuration.isLenient && abs(value) > MAX_SAFE_INTEGER) {
throw IllegalArgumentException(
"$value can't be deserialized to number due to a potential precision loss. " +
"Use the JsonConfiguration option isLenient to serialize anyway"
)
}
encodeValue(asDouble)
}
override fun encodeChar(value: Char) {
encodeValue(value.toString())
}
override fun encodeValue(value: Any) {
result = value
}
@OptIn(ExperimentalSerializationApi::class)
override fun encodeEnum(enumDescriptor: SerialDescriptor, index: Int) {
encodeValue(enumDescriptor.getElementName(index))
}
override fun endStructure(descriptor: SerialDescriptor) {
}
override fun encodeJsonElement(element: JsonElement) {
encodeSerializableValue(JsonElementSerializer, element)
}
}
| apache-2.0 | c96d340f5f4d35cc4e46447024bf365e | 32.301754 | 131 | 0.655779 | 4.995263 | false | false | false | false |
ekager/focus-android | app/src/main/java/org/mozilla/focus/activity/SettingsActivity.kt | 2 | 3184 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.activity
import android.os.Bundle
import android.view.MenuItem
import kotlinx.android.synthetic.main.activity_settings.*
import org.mozilla.focus.R
import org.mozilla.focus.locale.LocaleAwareAppCompatActivity
import org.mozilla.focus.settings.BaseSettingsFragment
import org.mozilla.focus.settings.MozillaSettingsFragment
import org.mozilla.focus.settings.SettingsFragment
import org.mozilla.focus.settings.PrivacySecuritySettingsFragment
import org.mozilla.focus.settings.GeneralSettingsFragment
class SettingsActivity : LocaleAwareAppCompatActivity(), BaseSettingsFragment.ActionBarUpdater {
companion object {
@JvmField
val ACTIVITY_RESULT_LOCALE_CHANGED = 1
const val SHOULD_OPEN_PRIVACY_EXTRA = "shouldOpenPrivacy"
const val SHOULD_OPEN_MOZILLA_EXTRA = "shouldOpenMozilla"
const val SHOULD_OPEN_GENERAL_EXTRA = "shouldOpenGeneral"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_settings)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
if (intent.extras != null) {
if (intent?.extras?.getBoolean(SHOULD_OPEN_PRIVACY_EXTRA) == true) {
supportFragmentManager.beginTransaction()
.replace(R.id.container, PrivacySecuritySettingsFragment())
.commit()
} else if (intent?.extras?.getBoolean(SHOULD_OPEN_MOZILLA_EXTRA) == true) {
supportFragmentManager.beginTransaction()
.replace(R.id.container, MozillaSettingsFragment())
.commit()
} else if (intent?.extras?.getBoolean(SHOULD_OPEN_GENERAL_EXTRA) == true) {
supportFragmentManager.beginTransaction()
.replace(R.id.container, GeneralSettingsFragment())
.commit()
}
} else if (savedInstanceState == null) {
supportFragmentManager.beginTransaction()
.add(R.id.container, SettingsFragment.newInstance())
.commit()
}
// Ensure all locale specific Strings are initialised on first run, we don't set the title
// anywhere before now (the title can only be set via AndroidManifest, and ensuring
// that that loads the correct locale string is tricky).
applyLocale()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) {
android.R.id.home -> {
onBackPressed()
true
}
else -> super.onOptionsItemSelected(item)
}
override fun applyLocale() {
setTitle(R.string.menu_settings)
}
override fun updateTitle(titleResId: Int) {
setTitle(titleResId)
}
override fun updateIcon(iconResId: Int) {
supportActionBar?.setHomeAsUpIndicator(iconResId)
}
}
| mpl-2.0 | 40dbe6d91d96c4ce84f0f5c35a017df0 | 38.308642 | 98 | 0.667085 | 4.921175 | false | false | false | false |
wzhxyz/ACManager | src/main/java/com/zzkun/util/web/POJWebGetter.kt | 2 | 3206 | package com.zzkun.util.web
import com.zzkun.model.ExtOjPbInfo
import com.zzkun.model.OJType
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import java.util.*
import java.util.regex.Pattern
/**
* Created by kun on 2016/10/15.
*/
@Component
open class POJWebGetter {
companion object {
val logger = LoggerFactory.getLogger(POJWebGetter::class.java)
}
@Autowired lateinit var httpUtil: HttpUtil
fun userACPbs(pojName: String?, link: String): List<String> {
if(pojName == null)
return ArrayList()
val url = String.format(link, pojName)
// logger.info("开始获取poj用户${pojName}AC题目:$url")
val body = httpUtil.readJsoupURL(url).body().toString()
val patten = Pattern.compile("""p\(([\d]+)\)""")
val matcher = patten.matcher(body)
val res = sortedSetOf<String>()
while(matcher.find())
res.add(matcher.group(1))
logger.info("获取到poj用户${pojName}的${res.size}条纪录")
return res.toList()
}
fun pbInfomation(pbId: String, link: String): ExtOjPbInfo? {
try {
val url = String.format(link, pbId)
val body = httpUtil.readJsoupURL(url).body().toString()
val res = ExtOjPbInfo()
res.pid = pbId
res.num = pbId
res.ojName = OJType.POJ
var mattcher = Pattern.compile(""",([\d]+),'status""").matcher(body)
if(mattcher.find()) {
res.dacu = mattcher.group(1).toInt()
}
mattcher = Pattern.compile("""sa\[1\]\[\d+\]='([A-Za-z\s]+)';\ssa\[0\]\[\d+\]=([\d]+);""").matcher(body)
while(mattcher.find()) {
val name = mattcher.group(1)
val cnt = mattcher.group(2).toInt()
when(name) {
"Accepted" -> res.ac = cnt
"Presentation Error" -> res.pe = cnt
"Time Limit Exceeded" -> res.tle = cnt
"Memory Limit Exceeded" -> res.mle = cnt
"Wrong Answer" -> res.wa = cnt
"Runtime Error" -> res.re = cnt
"Output Limit Exceeded" -> res.ole = cnt
"Compile Error" -> res.ce = cnt
"System Error" -> res.sube = cnt
"Waiting" -> res.inq += cnt
"Compiling" -> res.inq += cnt
}
}
res.totSubmit = res.calcTotSubmits()
return if(res.totSubmit != 0) res else null
} catch(e: Exception) {
e.printStackTrace()
return null
}
}
fun allPbInfo(link: String): List<ExtOjPbInfo> {
logger.info("开始获取POJ所有题目数据...")
val res = arrayListOf<ExtOjPbInfo>()
for(i in 1000..999999) {
val info = pbInfomation(i.toString(), link)
if(info != null)
res.add(info)
else break
}
return res
}
}
| gpl-3.0 | 0608e37ba6aec7c21581986bf20ad414 | 34.229885 | 116 | 0.514594 | 3.820606 | false | false | false | false |
Team-Antimatter-Mod/AntiMatterMod | src/main/java/antimattermod/core/Energy/MultiBlock/TileMultiController.kt | 1 | 1736 | package antimattermod.core.Energy.MultiBlock
import c6h2cl2.YukariLib.Util.BlockPos
import net.minecraft.nbt.NBTTagCompound
import net.minecraft.tileentity.TileEntity
/**
* Created by kojin15.
*/
class TileMultiController : TileEntity() {
var blockMeta: Int = worldObj.getBlockMetadata(xCoord, yCoord, zCoord)
var page: Int = 0
var multiPlaceIndex: Int = -1
var isShowAssist: Boolean = false
var isDetails: Boolean = false
var coreBlockName: String = BlockMultiController().unlocalizedName
var thisTilePos: BlockPos? = BlockPos(xCoord, yCoord, zCoord)
var machineType: MachineType = MachineType.Controller
override fun readFromNBT(nbtTagCompound: NBTTagCompound?) {
if (nbtTagCompound != null) {
page = nbtTagCompound.getInteger("page")
isShowAssist = nbtTagCompound.getBoolean("isShowAssist")
isDetails = nbtTagCompound.getBoolean("isDetails")
coreBlockName = nbtTagCompound.getString("coreBlockName")
multiPlaceIndex = nbtTagCompound.getInteger("Index")
val machinetype = MachineType.values()
machineType = machinetype[nbtTagCompound.getInteger("MachineTypeIndex")]
}
}
override fun writeToNBT(nbtTagCompound: NBTTagCompound?) {
if (nbtTagCompound != null) {
nbtTagCompound.setInteger("page", page)
nbtTagCompound.setBoolean("isShowAssist", isShowAssist)
nbtTagCompound.setBoolean("isDetails", isDetails)
nbtTagCompound.setString("coreBlockName", coreBlockName)
nbtTagCompound.setInteger("Index", multiPlaceIndex)
nbtTagCompound.setInteger("MachineTypeIndex", machineType.ordinal)
}
}
} | gpl-3.0 | 370c05d4c693f63196cf0266ad6c2e40 | 35.1875 | 84 | 0.696429 | 4.666667 | false | false | false | false |
ratabb/Hishoot2i | app/src/main/java/org/illegaller/ratabb/hishoot2i/ui/crop/CropViewModel.kt | 1 | 1316 | package org.illegaller.ratabb.hishoot2i.ui.crop
import android.graphics.Bitmap
import androidx.core.net.toUri
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import common.FileConstants
import common.ext.graphics.saveTo
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import javax.inject.Inject
@HiltViewModel
class CropViewModel @Inject constructor(
fileConstants: FileConstants
) : ViewModel() {
private val fileCrop: () -> File = (fileConstants::bgCrop)
private val _uiState = MutableLiveData<CropView>()
internal val uiState: LiveData<CropView>
get() = _uiState
fun savingCrop(bitmap: Bitmap) {
viewModelScope.launch {
runCatching {
withContext(IO) { savingProcess(fileCrop(), bitmap) }
}.fold({ _uiState.value = Success(it) }, { _uiState.value = Fail(it) })
}
}
private fun savingProcess(file: File, bitmap: Bitmap): String {
if (file.exists()) file.delete()
file.createNewFile() //
bitmap.saveTo(file)
return file.toUri().toString()
}
}
| apache-2.0 | 01d50fe4f09ebf0d85472a224f03cfcf | 31.097561 | 83 | 0.716565 | 4.328947 | false | false | false | false |
ns2j/nos2jdbc-tutorial | nos2jdbc-tutorial-kotlin-spring/src/main/kotlin/nos2jdbc/tutorial/kotlinspring/entity/nonauto/MemberItem.kt | 1 | 557 | package nos2jdbc.tutorial.kotlinspring.entity.nonauto
import java.math.BigDecimal
import java.time.LocalDate
import javax.persistence.Entity
import javax.persistence.Id
import javax.persistence.ManyToOne
import javax.persistence.Transient
import nos2jdbc.annotation.NoFk
import nos2jdbc.annotation.NonAuto
@Entity @NonAuto
class MemberItem {
@Id
var lunchFeeId: Long? = null
var payOn: LocalDate? = null
var amount: BigDecimal = BigDecimal.ZERO
var count: Int = 0
@Transient @ManyToOne @NoFk
var ym: MemberYm? = null
}
| apache-2.0 | b3700a4e8f73de1b20495ecf5ecba3f3 | 22.208333 | 53 | 0.761221 | 3.738255 | false | false | false | false |
ageery/kwicket | kwicket-wicket-bootstrap-core/src/main/kotlin/org/kwicket/agilecoders/Components.kt | 1 | 2065 | package org.kwicket.agilecoders
import de.agilecoders.wicket.core.markup.html.bootstrap.form.InputBehavior
import org.apache.wicket.Component
import org.apache.wicket.behavior.Behavior
import org.apache.wicket.markup.html.form.FormComponent
import org.apache.wicket.model.IModel
import org.kwicket.agilecoders.wicket.core.ajax.markup.html.bootstrap.form.InputFormGroup
import org.kwicket.wicket.core.markup.html.form.KTextField
import kotlin.reflect.KClass
fun <T : Any> textField(
model: IModel<T?>? = null,
type: KClass<T>? = null,
required: Boolean? = null,
outputMarkupId: Boolean? = null,
outputMarkupPlaceholderTag: Boolean? = null,
label: IModel<String>? = null,
visible: Boolean? = null,
enabled: Boolean? = null,
behaviors: List<Behavior>? = null
): (String) -> FormComponent<T> = {
KTextField(
id = it,
model = model,
type = type,
label = label,
required = required,
outputMarkupPlaceholderTag = outputMarkupPlaceholderTag,
outputMarkupId = outputMarkupId,
visible = visible,
enabled = enabled,
behaviors = behaviors?.let { it + InputBehavior() } ?: listOf(InputBehavior())
)
}
fun inputFormGroup(field: (String) -> Component): (String) -> InputFormGroup<*> =
{ InputFormGroup(id = it, field = field) }
fun <T : Any> textFieldFormGroup(
model: IModel<T?>? = null,
type: KClass<T>? = null,
required: Boolean? = null,
outputMarkupId: Boolean? = null,
outputMarkupPlaceholderTag: Boolean? = null,
label: IModel<String>? = null,
visible: Boolean? = null,
enabled: Boolean? = null,
behaviors: List<Behavior>? = null
)
: (String) -> InputFormGroup<*> = inputFormGroup(
field = textField(
model = model,
type = type,
label = label,
required = required,
outputMarkupId = outputMarkupId,
outputMarkupPlaceholderTag = outputMarkupPlaceholderTag,
visible = visible,
enabled = enabled,
behaviors = behaviors
)
) | apache-2.0 | 36c6d61d0f2d6c6c6e090e169a00b2e7 | 31.793651 | 89 | 0.661501 | 4.180162 | false | false | false | false |
t-ray/malbec | src/main/kotlin/malbec/core/biz/ProjectsService.kt | 1 | 912 | package malbec.core.biz
import malbec.core.data.ProjectsDao
import malbec.core.domain.Project
import org.funktionale.either.Either
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
@Service
open class ProjectsService(
private val projectsDao: ProjectsDao) {
@Transactional(readOnly = true)
open fun find(id: Int): Either<ObjectNotFoundException, Project> = projectsDao.find(id)
@Transactional(readOnly = true)
open fun selectAll(): List<Project> = projectsDao.selectAll()
@Transactional
open fun insert(item: Project): Project = projectsDao.insert(item)
@Transactional
open fun update(item: Project): Either<ObjectNotFoundException, Project>
= projectsDao.update(item)
@Transactional
open fun delete(id: Int): Either<ObjectNotFoundException, Int> = projectsDao.delete(id)
} //END ProjectsService | mit | d576491bf41cbee8779b1c332aa54d3d | 31.607143 | 91 | 0.766447 | 4.183486 | false | false | false | false |
Geobert/radis | app/src/main/kotlin/fr/geobert/radis/tools/ToggleImageButton.kt | 1 | 3220 | /**
* From https://gist.github.com/akshaydashrath/9662072
*/
package fr.geobert.radis.tools
import android.content.Context
import android.os.Bundle
import android.os.Parcelable
import android.util.AttributeSet
import android.view.View
import android.widget.Checkable
import android.widget.ImageButton
import fr.geobert.radis.R
class ToggleImageButton : ImageButton, Checkable {
private var isChecked: Boolean = false
private var isBroadCasting: Boolean = false
private var onCheckedChangeListener: OnCheckedChangeListener? = null
constructor(context: Context) : super(context) {
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
}
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {
initAttr(context, attrs, defStyle)
}
private fun initAttr(context: Context, attrs: AttributeSet, defStyle: Int) {
val a = context.obtainStyledAttributes(
attrs, R.styleable.ToogleImageButton, defStyle, 0)
val checked = a.getBoolean(R.styleable.ToogleImageButton_checked, false)
setChecked(checked)
a.recycle()
}
override fun onFinishInflate() {
super.onFinishInflate()
}
override fun performClick(): Boolean {
toggle()
return super.performClick()
}
override fun isChecked(): Boolean {
return isChecked //To change body of implemented methods use File | Settings | File Templates.
}
override fun setChecked(checked: Boolean) {
if (isChecked == checked) {
return
}
isChecked = checked
refreshDrawableState()
if (isBroadCasting) {
return
}
isBroadCasting = true
if (onCheckedChangeListener != null) {
onCheckedChangeListener!!.onCheckedChanged(this, isChecked)
}
isBroadCasting = false
}
override fun onCreateDrawableState(extraSpace: Int): IntArray {
val drawableState = super.onCreateDrawableState(extraSpace + 1)
if (isChecked()) {
View.mergeDrawableStates(drawableState, CHECKED_STATE_SET)
}
return drawableState
}
fun setOnCheckedChangeListener(onCheckedChangeListener: OnCheckedChangeListener) {
this.onCheckedChangeListener = onCheckedChangeListener
}
override fun toggle() {
setChecked(!isChecked)
}
public override fun onSaveInstanceState(): Parcelable {
val bundle = Bundle()
bundle.putParcelable("instanceState", super.onSaveInstanceState())
bundle.putBoolean("state", isChecked)
return bundle
}
override fun onRestoreInstanceState(s: Parcelable) {
var state = s
if (state is Bundle) {
setChecked(state.getBoolean("state"))
state = state.getParcelable<Parcelable>("instanceState")
}
super.onRestoreInstanceState(state)
}
interface OnCheckedChangeListener {
fun onCheckedChanged(buttonView: ToggleImageButton, isChecked: Boolean)
}
companion object {
private val CHECKED_STATE_SET = intArrayOf(android.R.attr.state_checked)
}
}
| gpl-2.0 | c361214dd862bc4f93803d5d31a3bbd0 | 28.541284 | 105 | 0.668944 | 4.969136 | false | false | false | false |
Ray-Eldath/Avalon | src/main/kotlin/avalon/tool/system/Configs.kt | 1 | 3149 | package avalon.tool.system
import org.json.JSONArray
import org.json.JSONObject
import org.json.JSONTokener
import org.slf4j.LoggerFactory
import java.io.File
import java.io.FileReader
import java.io.IOException
/**
* Created by Eldath Ray on 2017/3/17.
*
* @author Eldath Ray
* @since v0.0.1 Beta
*/
object Configs : BaseConfigSystem {
private lateinit var root: JSONObject
private var allConfigs: Map<String, Any> = hashMapOf()
private var responderConfigs: Map<String, Any> = hashMapOf()
private var functionConfigs: Map<String, Any> = hashMapOf()
private val logger = LoggerFactory.getLogger(Configs::class.java)
init {
try {
val path = File("").canonicalPath // 这里不用常量池是因为初始化的问题。反正别改。
root = JSONTokener(FileReader(
File(path + File.separator + "config.json"))).nextValue() as JSONObject
allConfigs = jsonObjectToMap(root)
responderConfigs = jsonObjectToMap(root["responder_config"] as JSONObject)
functionConfigs = jsonObjectToMap(root["function_config"] as JSONObject)
} catch (e: IOException) {
logger.error("Exception thrown while init Configs: `${e.localizedMessage}`")
}
}
private fun jsonObjectToMap(obj: JSONObject): Map<String, Any> {
val result = hashMapOf<String, Any>()
val names = obj.names()
for (i in 0 until obj.length()) {
val key = names[i].toString()
if ("comment" in key)
continue
val thisObject = obj[key]
result[key] = thisObject
}
return result
}
override operator fun get(key: String): Any? = allConfigs[key]
override fun getString(key: String): String =
allConfigs[key] as? String ?: throw UnsupportedOperationException("value invalid: not a String")
fun has(key: String) = root.has(key)
fun getJSONObject(key: String): JSONObject = root.getJSONObject(key)
fun getConfigArray(key: String): Array<Any?> {
val array = allConfigs[key] as JSONArray
val result = arrayOfNulls<Any>(array.length())
for (i in 0 until array.length()) result[i] = array[i]
return result
}
fun getResponderConfig(responderName: String, key: String): Any? =
getObjectConfig(responderConfigs, responderName, key)
fun getResponderConfigArray(responderName: String, key: String): Array<Any> =
getObjectConfigArray(responderConfigs, responderName, key)
fun isPluginEnable(pluginName: String): Boolean =
getPluginConfig(pluginName, "enable") as Boolean
@Suppress("MemberVisibilityCanBePrivate")
fun getPluginConfig(pluginName: String, key: String): Any? =
getObjectConfig(functionConfigs, pluginName, key)
fun getPluginConfigArray(pluginName: String, key: String): Array<Any> =
getObjectConfigArray(functionConfigs, pluginName, key)
private fun getObjectConfig(`object`: Map<String, Any>, key1: String, key2: String): Any? {
val obj = `object`[key1] as JSONObject
return if (obj.has(key2)) obj[key2] else null
}
private fun getObjectConfigArray(`object`: Map<String, Any>, key1: String, key2: String): Array<Any> {
return (`object`[key1] as JSONObject).getJSONArray(key2).map { it }.toTypedArray()
}
object Companion {
@JvmStatic
fun instance(): Configs = Configs
}
} | agpl-3.0 | ae317f51dc5cc635cd53ba58843a45a1 | 31.354167 | 103 | 0.730435 | 3.520408 | false | true | false | false |
didi/DoraemonKit | Android/dokit-ft/src/main/java/com/didichuxing/doraemonkit/kit/filemanager/ability/DokitFtModuleProcessor.kt | 1 | 646 | package com.didichuxing.doraemonkit.kit.filemanager.ability
import com.didichuxing.doraemonkit.kit.core.DokitAbility
import com.google.auto.service.AutoService
/**
* ================================================
* 作 者:jint(金台)
* 版 本:1.0
* 创建日期:2021/6/7-19:50
* 描 述:
* 修订历史:
* ================================================
*/
class DokitFtModuleProcessor : DokitAbility.DokitModuleProcessor {
override fun values(): Map<String, Any> {
return mapOf()
}
override fun proceed(actions: Map<String, Any?>?): Map<String, Any> {
return mapOf()
}
} | apache-2.0 | 7e9846ff51ff37d9fbe9913b4a14b41a | 23.04 | 74 | 0.551667 | 3.97351 | false | false | false | false |
natanieljr/droidmate | project/pcComponents/exploration/src/main/kotlin/org/droidmate/exploration/modelFeatures/reporter/ApiActionTraceMF.kt | 1 | 3343 | // DroidMate, an automated execution generator for Android apps.
// Copyright (C) 2012-2018. Saarland University
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// Current Maintainers:
// Nataniel Borges Jr. <nataniel dot borges at cispa dot saarland>
// Jenny Hotzkow <jenny dot hotzkow at cispa dot saarland>
//
// Former Maintainers:
// Konrad Jamrozik <jamrozik at st dot cs dot uni-saarland dot de>
//
// web: www.droidmate.org
package org.droidmate.exploration.modelFeatures.reporter
import kotlinx.coroutines.CoroutineName
import org.droidmate.device.logcat.ApiLogcatMessage
import org.droidmate.deviceInterface.exploration.isLaunchApp
import org.droidmate.deviceInterface.exploration.isPressBack
import org.droidmate.exploration.ExplorationContext
import java.nio.file.Files
import java.nio.file.Path
import kotlin.coroutines.CoroutineContext
class ApiActionTraceMF(reportDir: Path,
resourceDir: Path,
private val fileName: String = "apiActionTrace.txt") : ApkReporterMF(reportDir, resourceDir) {
override val coroutineContext: CoroutineContext = CoroutineName("ApiActionTraceMF")
override suspend fun safeWriteApkReport(context: ExplorationContext<*, *, *>, apkReportDir: Path, resourceDir: Path) {
val sb = StringBuilder()
val header = "actionNr\tactivity\taction\tapi\tuniqueStr\n"
sb.append(header)
var lastActivity = ""
var currActivity = context.apk.launchableMainActivityName
context.explorationTrace.getActions().forEachIndexed { actionNr, record ->
if (record.actionType.isPressBack())
currActivity = lastActivity
else if (record.actionType.isLaunchApp())
currActivity = context.apk.launchableMainActivityName
val logs = record.deviceLogs
logs.forEach { ApiLogcatMessage.from(it).let { log ->
if (log.methodName.toLowerCase().startsWith("startactivit")) {
val intent = log.getIntents()
// format is: [ '[data=, component=<HERE>]', 'package ]
if (intent.isNotEmpty()) {
lastActivity = currActivity
currActivity = intent[0].substring(intent[0].indexOf("component=") + 10).replace("]", "")
}
}
sb.appendln("$actionNr\t$currActivity\t${record.actionType}\t${log.objectClass}->${log.methodName}\t${log.uniqueString}")
}}
}
val reportFile = apkReportDir.resolve(fileName)
Files.write(reportFile, sb.toString().toByteArray())
}
override fun reset() {
// Do nothing
// Nothing to reset here
}
}
| gpl-3.0 | c8d9c150a70fff379b8431b779d96554 | 39.768293 | 137 | 0.674245 | 4.54212 | false | false | false | false |
Light-Team/ModPE-IDE-Source | app/src/main/kotlin/com/brackeys/ui/feature/settings/fragments/EditorFragment.kt | 1 | 2083 | /*
* Copyright 2021 Brackeys IDE contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.brackeys.ui.feature.settings.fragments
import android.os.Bundle
import android.view.View
import androidx.navigation.NavController
import androidx.navigation.fragment.findNavController
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import com.brackeys.ui.R
import com.brackeys.ui.data.storage.keyvalue.SettingsManager
class EditorFragment : PreferenceFragmentCompat() {
companion object {
private const val KEY_FONT_TYPE = SettingsManager.KEY_FONT_TYPE
private const val KEY_KEYBOARD_PRESET = SettingsManager.KEY_KEYBOARD_PRESET
}
private lateinit var navController: NavController
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
navController = findNavController()
}
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.preference_editor, rootKey)
findPreference<Preference>(KEY_FONT_TYPE)?.setOnPreferenceClickListener {
val destination = EditorFragmentDirections.toFontsGraph()
navController.navigate(destination)
true
}
findPreference<Preference>(KEY_KEYBOARD_PRESET)?.setOnPreferenceClickListener {
val destination = EditorFragmentDirections.toPresetDialog()
navController.navigate(destination)
true
}
}
} | apache-2.0 | 0663070e07725e26a0152429fdb9c844 | 36.214286 | 87 | 0.743639 | 5.055825 | false | false | false | false |
arturbosch/detekt | detekt-api/src/main/kotlin/io/gitlab/arturbosch/detekt/api/Context.kt | 1 | 2285 | package io.gitlab.arturbosch.detekt.api
import io.gitlab.arturbosch.detekt.api.internal.isSuppressedBy
import org.jetbrains.kotlin.psi.KtFile
/**
* A context describes the storing and reporting mechanism of [Finding]'s inside a [Rule].
* Additionally it handles suppression and aliases management.
*
* The detekt engine retrieves the findings after each KtFile visit and resets the context
* before the next KtFile.
*/
interface Context {
val findings: List<Finding>
/**
* Reports a single new violation.
* By contract the implementation can check if
* this finding is already suppressed and should not get reported.
* An alias set can be given to additionally check if an alias was used when suppressing.
* Additionally suppression by rule set id is supported.
*/
fun report(finding: Finding, aliases: Set<String> = emptySet(), ruleSetId: RuleSetId? = null) {
// no-op
}
/**
* Same as [report] but reports a list of [findings].
*/
fun report(findings: List<Finding>, aliases: Set<String> = emptySet(), ruleSetId: RuleSetId? = null) {
findings.forEach { report(it, aliases, ruleSetId) }
}
/**
* Clears previous findings.
* Normally this is done on every new [KtFile] analyzed and should be called by clients.
*/
fun clearFindings()
}
/**
* Default [Context] implementation.
*/
@Deprecated("You should not use this class directly. Use or extend Context instead.")
open class DefaultContext : Context {
/**
* Returns a copy of violations for this rule.
*/
override val findings: List<Finding>
get() = _findings.toList()
private val _findings: MutableList<Finding> = mutableListOf()
/**
* Reports a single code smell finding.
*
* Before adding a finding, it is checked if it is not suppressed
* by @Suppress or @SuppressWarnings annotations.
*/
override fun report(finding: Finding, aliases: Set<String>, ruleSetId: RuleSetId?) {
val ktElement = finding.entity.ktElement
if (ktElement == null || !ktElement.isSuppressedBy(finding.id, aliases, ruleSetId)) {
_findings.add(finding)
}
}
final override fun clearFindings() {
_findings.clear()
}
}
| apache-2.0 | b7be91cf16337c5facb2f23392e794c5 | 30.736111 | 106 | 0.670022 | 4.402697 | false | false | false | false |
wiltonlazary/kotlin-native | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/llvm/StaticObjects.kt | 1 | 5253 | /*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package org.jetbrains.kotlin.backend.konan.llvm
import kotlinx.cinterop.cValuesOf
import llvm.*
import org.jetbrains.kotlin.backend.konan.ir.fqNameForIrSerialization
import org.jetbrains.kotlin.backend.konan.ir.llvmSymbolOrigin
import org.jetbrains.kotlin.ir.declarations.IrClass
import org.jetbrains.kotlin.ir.util.fqNameForIrSerialization
private fun ConstPointer.add(index: Int): ConstPointer {
return constPointer(LLVMConstGEP(llvm, cValuesOf(Int32(index).llvm), 1)!!)
}
// Must match OBJECT_TAG_PERMANENT_CONTAINER in C++.
private fun StaticData.permanentTag(typeInfo: ConstPointer): ConstPointer {
// Only pointer arithmetic via GEP works on constant pointers in LLVM.
return typeInfo.bitcast(int8TypePtr).add(1).bitcast(kTypeInfoPtr)
}
private fun StaticData.objHeader(typeInfo: ConstPointer): Struct {
return Struct(runtime.objHeaderType, permanentTag(typeInfo))
}
private fun StaticData.arrayHeader(typeInfo: ConstPointer, length: Int): Struct {
assert (length >= 0)
return Struct(runtime.arrayHeaderType, permanentTag(typeInfo), Int32(length))
}
internal fun StaticData.createKotlinStringLiteral(value: String): ConstPointer {
val elements = value.toCharArray().map(::Char16)
val objRef = createConstKotlinArray(context.ir.symbols.string.owner, elements)
return objRef
}
private fun StaticData.createRef(objHeaderPtr: ConstPointer) = objHeaderPtr.bitcast(kObjHeaderPtr)
internal fun StaticData.createConstKotlinArray(arrayClass: IrClass, elements: List<LLVMValueRef>) =
createConstKotlinArray(arrayClass, elements.map { constValue(it) }).llvm
internal fun StaticData.createConstKotlinArray(arrayClass: IrClass, elements: List<ConstValue>): ConstPointer {
val typeInfo = arrayClass.typeInfoPtr
val bodyElementType: LLVMTypeRef = elements.firstOrNull()?.llvmType ?: int8Type
// (use [0 x i8] as body if there are no elements)
val arrayBody = ConstArray(bodyElementType, elements)
val compositeType = structType(runtime.arrayHeaderType, arrayBody.llvmType)
val global = this.createGlobal(compositeType, "")
val objHeaderPtr = global.pointer.getElementPtr(0)
val arrayHeader = arrayHeader(typeInfo, elements.size)
global.setInitializer(Struct(compositeType, arrayHeader, arrayBody))
global.setConstant(true)
return createRef(objHeaderPtr)
}
internal fun StaticData.createConstKotlinObject(type: IrClass, vararg fields: ConstValue): ConstPointer {
val typeInfo = type.typeInfoPtr
val objHeader = objHeader(typeInfo)
val global = this.placeGlobal("", Struct(objHeader, *fields))
global.setConstant(true)
val objHeaderPtr = global.pointer.getElementPtr(0)
return createRef(objHeaderPtr)
}
internal fun StaticData.createInitializer(type: IrClass, vararg fields: ConstValue): ConstValue =
Struct(objHeader(type.typeInfoPtr), *fields)
/**
* Creates static instance of `kotlin.collections.ArrayList<elementType>` with given values of fields.
*
* @param array value for `array: Array<E>` field.
* @param length value for `length: Int` field.
*/
internal fun StaticData.createConstArrayList(array: ConstPointer, length: Int): ConstPointer {
val arrayListClass = context.ir.symbols.arrayList.owner
val arrayListFqName = arrayListClass.fqNameForIrSerialization
val arrayListFields = mapOf(
"$arrayListFqName.array" to array,
"$arrayListFqName.offset" to Int32(0),
"$arrayListFqName.length" to Int32(length),
"$arrayListFqName.backing" to NullPointer(kObjHeader))
// Now sort these values according to the order of fields returned by getFields()
// to match the sorting order of the real ArrayList().
val sorted = linkedMapOf<String, ConstValue>()
context.getLayoutBuilder(arrayListClass).fields.forEach {
val fqName = it.fqNameForIrSerialization.asString()
sorted.put(fqName, arrayListFields[fqName]!!)
}
return createConstKotlinObject(arrayListClass, *sorted.values.toTypedArray())
}
internal fun StaticData.createUniqueInstance(
kind: UniqueKind, bodyType: LLVMTypeRef, typeInfo: ConstPointer): ConstPointer {
assert (getStructElements(bodyType).size == 1) // ObjHeader only.
val objHeader = when (kind) {
UniqueKind.UNIT -> objHeader(typeInfo)
UniqueKind.EMPTY_ARRAY -> arrayHeader(typeInfo, 0)
}
val global = this.placeGlobal(kind.llvmName, objHeader, isExported = true)
global.setConstant(true)
return global.pointer
}
internal fun ContextUtils.unique(kind: UniqueKind): ConstPointer {
val descriptor = when (kind) {
UniqueKind.UNIT -> context.ir.symbols.unit.owner
UniqueKind.EMPTY_ARRAY -> context.ir.symbols.array.owner
}
return if (isExternal(descriptor)) {
constPointer(importGlobal(
kind.llvmName, context.llvm.runtime.objHeaderType, origin = descriptor.llvmSymbolOrigin
))
} else {
context.llvmDeclarations.forUnique(kind).pointer
}
}
internal val ContextUtils.theUnitInstanceRef: ConstPointer
get() = this.unique(UniqueKind.UNIT) | apache-2.0 | f09f20a8bbe00c8df681b109b279c910 | 38.208955 | 111 | 0.748144 | 4.188995 | false | false | false | false |
rsiebert/TVHClient | data/src/main/java/org/tvheadend/data/entity/EpgChannel.kt | 1 | 1481 | package org.tvheadend.data.entity
import androidx.room.ColumnInfo
data class EpgChannel(
@ColumnInfo(name = "id")
var id: Int = 0,
@ColumnInfo(name = "number")
var number: Int = 0,
@ColumnInfo(name = "number_minor")
var numberMinor: Int = 0,
@ColumnInfo(name = "name")
var name: String? = null,
@ColumnInfo(name = "icon")
var icon: String? = null,
@ColumnInfo(name = "display_number")
var displayNumber: String? = null
)
internal data class EpgChannelEntity(
@ColumnInfo(name = "id")
var id: Int = 0,
@ColumnInfo(name = "number")
var number: Int = 0,
@ColumnInfo(name = "number_minor")
var numberMinor: Int = 0,
@ColumnInfo(name = "name")
var name: String? = null,
@ColumnInfo(name = "icon")
var icon: String? = null,
@ColumnInfo(name = "display_number")
var displayNumber: String? = null
) {
companion object {
fun from(channel: EpgChannel): EpgChannelEntity {
return EpgChannelEntity(
channel.id,
channel.number,
channel.numberMinor,
channel.name,
channel.icon,
channel.displayNumber
)
}
}
fun toEpgChannel(): EpgChannel {
return EpgChannel(id, number, numberMinor, name, icon, displayNumber)
}
}
| gpl-3.0 | 54d99c4c01c73fb4454f0e788258c37e | 27.480769 | 77 | 0.53815 | 4.268012 | false | false | false | false |
material-components/material-components-android-examples | Reply/app/src/main/java/com/materialstudies/reply/util/ContentViewBindingDelegate.kt | 1 | 1641 | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.materialstudies.reply.util
import android.app.Activity
import androidx.annotation.LayoutRes
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import kotlin.reflect.KProperty
/**
* A delegate who lazily inflates a data binding layout, calls [Activity.setContentView], sets
* the lifecycle owner and returns the binding.
*/
class ContentViewBindingDelegate<in R : AppCompatActivity, out T : ViewDataBinding>(
@LayoutRes private val layoutRes: Int
) {
private var binding: T? = null
operator fun getValue(activity: R, property: KProperty<*>): T {
if (binding == null) {
binding = DataBindingUtil.setContentView<T>(activity, layoutRes).apply {
lifecycleOwner = activity
}
}
return binding!!
}
}
fun <R : AppCompatActivity, T : ViewDataBinding> contentView(
@LayoutRes layoutRes: Int
): ContentViewBindingDelegate<R, T> = ContentViewBindingDelegate(layoutRes) | apache-2.0 | 91f09bad7d8b4fc1036b3b8defdabde5 | 32.510204 | 94 | 0.731871 | 4.596639 | false | false | false | false |
soywiz/korge | korge/src/commonMain/kotlin/com/soywiz/korge/input/GamepadEvents.kt | 1 | 3976 | package com.soywiz.korge.input
import com.soywiz.kds.*
import com.soywiz.kds.iterators.*
import com.soywiz.korge.component.*
import com.soywiz.korge.view.*
import com.soywiz.korio.async.*
import com.soywiz.korev.*
class GamePadEvents(override val view: View) : GamepadComponent {
@PublishedApi
internal lateinit var views: Views
@PublishedApi
internal val coroutineContext get() = views.coroutineContext
val gamepads = GamePadUpdateEvent()
val updated = Signal<GamePadUpdateEvent>()
val stick = Signal<GamePadStickEvent>()
val button = Signal<GamePadButtonEvent>()
val connection = Signal<GamePadConnectionEvent>()
fun stick(playerId: Int, stick: GameStick, callback: suspend (x: Double, y: Double) -> Unit) {
stick { e -> if (e.gamepad == playerId && e.stick == stick) launchImmediately(coroutineContext) { callback(e.x, e.y) } }
}
fun stick(callback: suspend (playerId: Int, stick: GameStick, x: Double, y: Double) -> Unit) {
stick { e -> launchImmediately(coroutineContext) { callback(e.gamepad, e.stick, e.x, e.y) } }
}
fun button(callback: suspend (playerId: Int, pressed: Boolean, button: GameButton, value: Double) -> Unit) {
button { e ->
launchImmediately(coroutineContext) { callback(e.gamepad, e.type == GamePadButtonEvent.Type.DOWN, e.button, e.value) }
}
}
fun button(playerId: Int, callback: suspend (pressed: Boolean, button: GameButton, value: Double) -> Unit) {
button { e ->
if (e.gamepad == playerId) launchImmediately(coroutineContext) { callback(e.type == GamePadButtonEvent.Type.DOWN, e.button, e.value) }
}
}
fun down(playerId: Int, button: GameButton, callback: suspend () -> Unit) {
button { e ->
if (e.gamepad == playerId && e.button == button && e.type == GamePadButtonEvent.Type.DOWN) launchImmediately(coroutineContext) { callback() }
}
}
fun up(playerId: Int, button: GameButton, callback: suspend () -> Unit) {
button { e ->
if (e.gamepad == playerId && e.button == button && e.type == GamePadButtonEvent.Type.UP) launchImmediately(coroutineContext) { callback() }
}
}
fun connected(callback: suspend (playerId: Int) -> Unit) {
connection { e ->
if (e.type == GamePadConnectionEvent.Type.CONNECTED) launchImmediately(coroutineContext) { callback(e.gamepad) }
}
}
fun disconnected(callback: suspend (playerId: Int) -> Unit) {
connection { e ->
if (e.type == GamePadConnectionEvent.Type.DISCONNECTED) launchImmediately(coroutineContext) { callback(e.gamepad) }
}
}
private val oldGamepads = GamePadUpdateEvent()
private val stickEvent = GamePadStickEvent()
private val buttonEvent = GamePadButtonEvent()
override fun onGamepadEvent(views: Views, event: GamePadUpdateEvent) {
this.views = views
gamepads.copyFrom(event)
// Compute diff
for (gamepadIndex in 0 until event.gamepadsLength) {
val gamepad = event.gamepads[gamepadIndex]
val oldGamepad = this.oldGamepads.gamepads[gamepadIndex]
GameButton.BUTTONS.fastForEach { button ->
if (gamepad[button] != oldGamepad[button]) {
button(buttonEvent.apply {
this.gamepad = gamepad.index
this.type = if (gamepad[button] != 0.0) GamePadButtonEvent.Type.DOWN else GamePadButtonEvent.Type.UP
this.button = button
this.value = gamepad[button]
})
}
}
GameStick.STICKS.fastForEach { stick ->
val vector = gamepad[stick]
if (vector != oldGamepad[stick]) {
stick(stickEvent.apply {
this.gamepad = gamepad.index
this.stick = stick
this.x = vector.x
this.y = vector.y
})
}
}
}
oldGamepads.copyFrom(event)
updated(event)
}
override fun onGamepadEvent(views: Views, event: GamePadConnectionEvent) {
this.views = views
connection(event)
}
}
val View.gamepad by Extra.PropertyThis<View, GamePadEvents> { this.getOrCreateComponentGamepad<GamePadEvents> { GamePadEvents(this) } }
inline fun <T> View.gamepad(callback: GamePadEvents.() -> T): T = gamepad.run(callback)
| apache-2.0 | 58f79d9bf044fc28c165b17927ce2937 | 34.81982 | 144 | 0.700201 | 3.469459 | false | false | false | false |
oboehm/jfachwert | src/main/kotlin/de/jfachwert/math/Primzahl.kt | 1 | 6852 | /*
* Copyright (c) 2018-2020 by Oliver Boehm
*
* 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.
*
* (c)reated 04.04.2018 by oboehm ([email protected])
*/
package de.jfachwert.math
import de.jfachwert.KFachwert
import java.lang.ref.SoftReference
import java.math.BigInteger
import java.util.concurrent.CopyOnWriteArrayList
/**
* Eine Primzahl ist eine natuerliche Zahl, die nur durch 1 und durch sich
* selbst teilbar ist. Die kleinste Primzahl ist 2.
*
* Intern wird 'int' zur Speicherung der Primzahl verwendet, da dies fuer den
* Standard-Fall ausreichend ist. So benoetigt bereits die Ermittlung einer
* 8-stelligen Primzahl (> 10 Mio.) ca. 3 Minuten. Die Emittlung einer
* 10-stelligen Primzahl (< 2 Mrd.) dürfte damit im Stunden, wenn nicht gar
* Tage-Bereich liegen.
*
* Die groesste Primzahl, die mit einem long dargestellt werden kann, ist
* 9223372036854775783.
*
* @author oboehm
* @since 0.6.1 (04.04.2018)
*/
open class Primzahl private constructor(private val value: Int) : Number(), KFachwert, Comparable<Primzahl> {
/**
* Liefert den numerischen Wert der Primzahl. Der Name der Methode
* orientiert sich dabei an die Number-Klasse aus Java.
*
* @return numerischer Wert
*/
override fun toLong(): Long {
return value.toLong()
}
/**
* Liefert den numerischen Wert der Primzahl. Der Name der Methode
* orientiert sich dabei an die Number-Klasse aus Java.
*
* @return numerischer Wert
*/
override fun toInt(): Int {
return value
}
/**
* Liefert die Zahl als ein `float` zurueck.
*
* @return den numerischen Wert als `float`
* @since 0.6.2
*/
override fun toFloat(): Float {
return toBigInteger().toFloat()
}
/**
* Liefert die Zahl als ein `double` zurueck.
*
* @return den numerischen Wert als `double`
* @since 0.6.2
*/
override fun toDouble(): Double {
return toBigInteger().toDouble()
}
override fun toShort(): Short {
return toBigInteger().toShort()
}
override fun toByte(): Byte {
return toBigInteger().toByte()
}
override fun toChar(): Char {
return toBigInteger().toChar()
}
/**
* Liefert den numerischen Wert der Primzahl als [BigInteger]. Der
* Name der Methode orientiert sich dabei an die BigDecimal-Klasse aus
* Java.
*
* @return numerischer Wert
*/
fun toBigInteger(): BigInteger {
return BigInteger.valueOf(toLong())
}
/**
* Liefert die naechste Primzahl.
*
* @return naechste Primzahl
*/
operator fun next(): Primzahl {
return after(toInt())
}
/**
* Dient zum Vergleich zweier Primzahlen.
*
* @param other die andere Primzahl
* @return Abstand zur anderen Primzahl
* @since 3.0
*/
override fun compareTo(other: Primzahl): Int {
return value - other.value
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || javaClass != other.javaClass) return false
val primzahl = other as Primzahl
return value == primzahl.value
}
override fun hashCode(): Int {
return value
}
/**
* Als Ausgabe nehmen wir die Zahl selbst.
*
* @return die Zahl selbst
*/
override fun toString(): String {
return Integer.toString(value)
}
companion object {
/** Zwei ist die kleinste Primzahl. */
@JvmField
val ZWEI = Primzahl(2)
/** Drei ist die naechste Primzahl. */
@JvmField
val DREI = Primzahl(3)
private var refPrimzahlen = SoftReference(initPrimzahlen())
private fun initPrimzahlen(): MutableList<Primzahl> {
val primzahlen: MutableList<Primzahl> = CopyOnWriteArrayList()
primzahlen.add(DREI)
return primzahlen
}
/**
* Liefert die erste Primzahl.
*
* @return #ZWEI
*/
fun first(): Primzahl {
return ZWEI
}
/**
* Liefert die naechste Primzahl nach der angegebenen Zahl.
*
* @param zahl Zahl
* @return naechste Primzahl > zahl
*/
@JvmStatic
fun after(zahl: Int): Primzahl {
val primzahlen = primzahlen
for (p in primzahlen!!) {
if (zahl < p.toInt()) {
return p
}
}
run {
var n = primzahlen[primzahlen.size - 1].toInt() + 2
while (n <= zahl) {
if (!hasTeiler(n)) {
primzahlen.add(Primzahl(n))
}
n += 2
}
}
var n = primzahlen[primzahlen.size - 1].toInt() + 2
while (hasTeiler(n)) {
n += 2
}
val nextPrimzahl = Primzahl(n)
primzahlen.add(nextPrimzahl)
return nextPrimzahl
}
/**
* Ermittelt, ob die uebergebene Zahl einen Teiler hat.
* Alternative Implementierung mit Streams zeigten ein deutlich
* schlechteres Zeitverhalten (ca. Faktor 10 langsamer). Eine weitere
* Implementierung mit ParallelStreams war noch langsamer - vermutlich
* ist der Overhaed einfach zu gross.
*
* @param n Zahl, die nach einem Teiler untersucht wird
* @return true, falls Zahl einen Teiler hat (d.h. keine Primzahl ist)
*/
private fun hasTeiler(n: Int): Boolean {
for (p in primzahlen!!) {
val teiler = p.toInt()
if (n % teiler == 0) {
return true
}
if (teiler * teiler > n) {
break
}
}
return false
}
private val primzahlen: MutableList<Primzahl>?
get() {
var primzahlen = refPrimzahlen.get()
if (primzahlen == null) {
primzahlen = initPrimzahlen()
refPrimzahlen = SoftReference(primzahlen)
}
return primzahlen
}
}
} | apache-2.0 | f9c536f0fdf8dc98eeac1c2f48299bc4 | 27.431535 | 109 | 0.569114 | 3.853206 | false | false | false | false |
ArdentDiscord/ArdentKotlin | src/main/kotlin/utils/discord/UserData.kt | 1 | 8127 | package utils.discord
import main.conn
import main.r
import net.dv8tion.jda.api.entities.TextChannel
import net.dv8tion.jda.api.entities.User
import translation.tr
import utils.functionality.*
import utils.music.DatabaseMusicLibrary
import utils.music.DatabaseMusicPlaylist
import java.util.concurrent.TimeUnit
fun User.isAdministrator(channel: TextChannel, complain: Boolean = false): Boolean {
if (getStaffLevel(id) == StaffRole.ADMINISTRATOR)
if (complain) channel.send("${Emoji.HEAVY_MULTIPLICATION_X} " + "You need to be an **Ardent Administrator** to use this command!".tr(channel))
return false
}
fun TextChannel.requires(user: User, requiredLevel: PatronLevel, failQuietly: Boolean = false): Boolean {
if (guild.isPatronGuild()) return true
else send("${Emoji.CROSS_MARK} " + "{0}, This command requires that you or the owner of this server have a donation level of **{0}** to be able to use it".tr(guild, user.asMention, requiredLevel.readable))
return false
}
fun User.hasPatronPermission(channel: TextChannel, donationLevel: PatronLevel, failQuietly: Boolean = false): Boolean {
val patronLevel = getPatronLevel(id)
return if (patronLevel != null && patronLevel.level >= donationLevel.level) true
else channel.requires(this, donationLevel, failQuietly)
}
fun User.getData(): UserData {
var data = asPojo(r.table("users").get(id).run(conn), UserData::class.java)
if (data != null) return data
data = UserData(id, 25.0, 0L, null, UserData.Gender.UNDEFINED, mutableListOf("English"), connectedAccounts = ConnectedAccounts())
data.insert("users")
return data
}
data class ConnectedAccounts(var spotifyId: String? = null)
class UserData(val id: String, var gold: Double = 50.0, var collected: Long = 0, var selfDescription: String?,
var gender: Gender, val languagesSpoken: MutableList<String>, val reminders: MutableList<Reminder> = mutableListOf(),
val connectedAccounts: ConnectedAccounts) {
fun canCollect(): Boolean {
return ((System.currentTimeMillis() - collected) / 1000) > 86399
}
fun collectionTime(): String {
return (collected + TimeUnit.DAYS.toMillis(1)).readableDate()
}
fun collect(): Int {
val amount = random.nextInt(500) + 1
gold += amount
collected = System.currentTimeMillis() + (1000 * 60 * 24)
update()
return amount
}
fun update(blocking: Boolean = false) {
if (!blocking) r.table("users").get(id).update(r.json(gson.toJson(this))).runNoReply(conn)
else r.table("users").get(id).update(r.json(gson.toJson(this))).run<Any>(conn)
}
enum class Gender(val display: String) { MALE("♂"), FEMALE("♀"), UNDEFINED("Not Specified") }
}
fun getMusicLibrary(id: String): DatabaseMusicLibrary {
var library = asPojo(r.table("musicLibraries").get(id).run(conn), DatabaseMusicLibrary::class.java)
if (library == null) {
library = DatabaseMusicLibrary(id, mutableListOf())
library.update("musicLibraries", id)
}
return library
}
fun getPlaylists(id: String): List<DatabaseMusicPlaylist> {
val playlists = mutableListOf<DatabaseMusicPlaylist>()
r.table("musicPlaylists").filter { r.hashMap("owner", id) }.run<Any>(conn).queryAsArrayList(DatabaseMusicPlaylist::class.java)
.forEach { if (it != null) playlists.add(it) }
return playlists
}
data class StaffMember(val id: String, var role: StaffRole)
enum class StaffRole(val readable: String, val level: Int) {
TRANSLATOR("Translator", 0), STAFF("Moderator", 1), ADMINISTRATOR("Administrator", 2);
fun hasPermission(role: StaffRole): Boolean {
return level >= role.level
}
}
fun getStaffLevel(id: String): StaffRole? {
return asPojo(r.table("staff").filter(r.hashMap("id", id)).run(conn), StaffMember::class.java)?.role
}
fun getPatronLevel(id: String): PatronLevel? {
return asPojo(r.table("patrons").filter(r.hashMap("id", id)).run(conn), Patron::class.java)?.level
}
fun User.hasStaffLevel(role: StaffRole, channel: TextChannel? = null, complain: Boolean = true): Boolean {
return if (getStaffLevel(id) == role) true
else {
if (complain) channel?.send("You need the `{0}` staff role to be able to use this command!".tr(channel, role.readable))
false
}
}
enum class PatronLevel(val readable: String, val level: Int) { SUPPORTER("Supporter", 1), PREMIUM("Premium", 3), SPONSOR("Sponsor", 7) }
data class Patron(val id: String, val level: PatronLevel)
/*
fun UserData.getBlackjackData(): BlackjackPlayerData {
val data = BlackjackPlayerData()
r.table("BlackjackData").run<Any>(conn).queryAsArrayList(GameDataBlackjack::class.java).forEach { game ->
if (game != null && game.creator == id) {
game.rounds.forEach { round ->
when (round.won) {
BlackjackGame.Result.TIED -> data.ties++
BlackjackGame.Result.WON -> data.wins++
BlackjackGame.Result.LOST -> data.losses++
}
}
}
}
return data
}
fun UserData.getConnect4Data(): Connect4PlayerData {
val data = Connect4PlayerData()
r.table("Connect_4Data").run<Any>(conn).queryAsArrayList(GameDataConnect4::class.java).forEach { game ->
if (game != null && (game.loser == id || game.winner == id)) {
if (game.winner == id) data.wins++
else data.losses++
}
}
return data
}
fun UserData.getTicTacToeData(): TicTacToePlayerData {
val data = TicTacToePlayerData()
r.table("Tic_Tac_ToeData").run<Any>(conn).queryAsArrayList(GameDataTicTacToe::class.java).forEach { game ->
if (game != null && (game.playerOne == id || game.playerTwo == id)) {
if (game.winner == null) data.ties++
else {
if (game.winner == id) data.wins++
else data.losses++
}
}
}
return data
}
fun UserData.getBettingData(): BettingPlayerData {
val data = BettingPlayerData()
r.table("BettingData").run<Any>(conn).queryAsArrayList(GameDataBetting::class.java).forEach { game ->
if (game != null && game.creator == id) {
game.rounds.forEach { round ->
if (round.won) {
data.wins++
data.netWinnings += round.betAmount
} else {
data.losses++
data.netWinnings -= round.betAmount
}
}
}
}
return data
}
fun UserData.getTriviaData(): TriviaPlayerData {
val correctByCategory = hashMapOf<String, Pair<Int, Int>>()
val data = TriviaPlayerData()
r.table("TriviaData").run<Any>(conn).queryAsArrayList(GameDataTrivia::class.java).forEach { game ->
if (game != null && (game.winner == id || game.losers.contains(id))) {
if (game.winner == id) data.wins++
else data.losses++
game.rounds.forEach { round ->
val currentQuestion = round.question
if (!correctByCategory.containsKey(currentQuestion.category)) correctByCategory.put(currentQuestion.category, Pair(0, 0))
if (round.winners.contains(id)) {
data.questionsCorrect++
correctByCategory.replace(currentQuestion.category, Pair(correctByCategory[currentQuestion.category]!!.first + 1, correctByCategory[currentQuestion.category]!!.second))
} else {
data.questionsWrong++
correctByCategory.replace(currentQuestion.category, Pair(correctByCategory[currentQuestion.category]!!.first, correctByCategory[currentQuestion.category]!!.second + 1))
}
}
}
}
correctByCategory.forEach { category, (first, second) -> data.percentageCorrect.put(category, first.toDouble() / (first + second).toDouble() * 100) }
data.overallCorrectPercent = (data.questionsCorrect.toDouble() / (data.questionsCorrect + data.questionsWrong).toDouble()) * 100.0
return data
}
*/ | apache-2.0 | 917209ade25e254ccb5d7cf22e564769 | 39.62 | 209 | 0.646436 | 3.914699 | false | false | false | false |
yiyocx/GitlabAndroid | app/src/main/kotlin/yiyo/gitlabandroid/ui/activities/MainActivity.kt | 2 | 3681 | package yiyo.gitlabandroid.ui.activities
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.view.Menu
import android.view.MenuItem
import kotlinx.android.synthetic.main.activity_main.*
import yiyo.gitlabandroid.R
import yiyo.gitlabandroid.ui.fragments.HomeFragment
import yiyo.gitlabandroid.ui.fragments.NavigationViewFragment
import yiyo.gitlabandroid.utils.Configuration
import yiyo.gitlabandroid.utils.toast
import kotlin.properties.Delegates
class MainActivity : AppCompatActivity(), NavigationViewFragment.NavigationDrawerCallbacks {
private val mNavigationViewFragment by lazy(LazyThreadSafetyMode.NONE) {
getFragmentManager().findFragmentById(R.id.navigation_fragment) as NavigationViewFragment }
private val configuration: Configuration by lazy(LazyThreadSafetyMode.NONE) { Configuration(this@MainActivity) }
private var mToolbar: Toolbar by Delegates.notNull()
private var mCurrentFragment: Fragment by Delegates.notNull()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mToolbar = findViewById(R.id.toolbar) as Toolbar
if (!configuration.isLoggedIn()) {
logoutUser()
}
setupToolbar()
setupNavigationView()
}
private fun setupToolbar() {
setSupportActionBar(mToolbar)
// Show menu icon
val ab = getSupportActionBar()
ab?.setHomeAsUpIndicator(R.drawable.ic_menu)
ab?.setDisplayHomeAsUpEnabled(true)
}
fun setupNavigationView() {
mNavigationViewFragment.setUp(R.id.navigation_fragment, drawer_layout)
}
private fun logoutUser() {
configuration.closeSession()
val intent = Intent(this, LoginActivity::class.java)
startActivity(intent)
finish()
}
/**
* Para que al presionar el boton back el drawer se oculte
*/
override fun onBackPressed() {
if (mNavigationViewFragment.isDrawerOpen()) {
mNavigationViewFragment.closeDrawer()
} else {
super.onBackPressed()
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.getItemId()) {
android.R.id.home -> {
mNavigationViewFragment.openDrawer()
true
}
R.id.action_logout -> {
logoutUser()
true
}
else -> super.onOptionsItemSelected(item)
}
}
/** Pasando la opción del menú elegida para mostrar el Fragment Correspondiente */
override fun onNavigationDrawerItemSelected(menuItem: MenuItem) {
setTitle(menuItem.getTitle())
// Actualizar el contenido principal reemplazando los fragments
when (menuItem.getItemId()) {
R.id.navigation_item_1 -> {
mCurrentFragment = HomeFragment()
setTitle(R.string.app_name)
}
R.id.navigation_item_2, R.id.navigation_item_3 -> toast(menuItem.getTitle())
else -> mCurrentFragment = HomeFragment()
}
val fragmentManager = getSupportFragmentManager()
fragmentManager.beginTransaction().replace(R.id.main_content, mCurrentFragment).commit()
}
}
| gpl-2.0 | 42d13a92992df377143f27abb4537bf9 | 33.383178 | 116 | 0.674096 | 4.847167 | false | true | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/view/ContainerView.kt | 1 | 3471 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.view
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.FrameLayout
open class ContainerView(context: Context, attrs: AttributeSet? = null) : FrameLayout(context, attrs) {
private var attachedToWindow: Boolean = false
var viewController: ViewController? = null
set(value) {
field?.let { oldVc ->
if (oldVc.attached) {
oldVc.attached = false
oldVc.onDetached()
}
val view = oldVc.view
oldVc.onDestroyView(view)
this.removeView(view)
oldVc.onDestroy()
}
field = value
if (value != null) {
if (value.attached) {
throw IllegalStateException("ViewController has already attached")
}
value.context = context
val view = value.onCreateView(this)
this.addView(view)
value.view = view
value.onCreate()
value.onViewCreated(view)
if (attachedToWindow) {
value.attached = true
value.onAttached()
}
}
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
attachedToWindow = true
viewController?.let { vc ->
if (!vc.windowAttached) {
vc.windowAttached = true
vc.onWindowAttached()
}
}
}
override fun onDetachedFromWindow() {
attachedToWindow = false
viewController?.let { vc ->
if (vc.attached) {
vc.windowAttached = false
vc.onWindowDetached()
}
}
super.onDetachedFromWindow()
}
abstract class ViewController {
lateinit var context: Context
internal set
lateinit var view: View
internal set
var attached: Boolean = false
internal set
var windowAttached: Boolean = false
internal set
open fun onCreate() {}
open fun onDestroy() {}
open fun onAttached() {}
open fun onDetached() {}
open fun onWindowAttached() {}
open fun onWindowDetached() {}
abstract fun onCreateView(parent: ContainerView): View
open fun onDestroyView(view: View) {}
open fun onViewCreated(view: View) {}
}
} | gpl-3.0 | ae78d65da80d8a6465de0a2c8ffa4b55 | 29.191304 | 103 | 0.579084 | 4.965665 | false | false | false | false |
robohorse/gpversionchecker | gpversionchecker/src/main/kotlin/com/robohorse/gpversionchecker/executor/SyncExecutor.kt | 1 | 1706 | package com.robohorse.gpversionchecker.executor
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.os.Message
import com.robohorse.gpversionchecker.GPVersionChecker
import com.robohorse.gpversionchecker.R
import com.robohorse.gpversionchecker.debug.ALog
import com.robohorse.gpversionchecker.domain.ProjectModel
import com.robohorse.gpversionchecker.domain.Version
import com.robohorse.gpversionchecker.provider.VersionDataProvider
class SyncExecutor {
private val handler = object : Handler(Looper.getMainLooper()) {
override fun handleMessage(msg: Message) {
super.handleMessage(msg)
if (msg.arg1 == MESSAGE_CODE) {
GPVersionChecker.onResponseReceived(msg.obj as? Version?, null)
}
}
}
fun startSync(context: Context) {
val projectModel = ProjectModel(
packageName = context.packageName,
storeUrl = context.getString(R.string.gpvch_google_play_url),
currentVersion = context.applicationContext
.packageManager
.getPackageInfo(
context.applicationContext.packageName, DEFAULT_FLAG
).versionName
)
Thread(Runnable {
VersionDataProvider().obtainDataFromGooglePlay(projectModel)?.let {
ALog.d("Response received: $it")
handler.sendMessage(Message().apply {
arg1 = MESSAGE_CODE
obj = it
})
}
}).start()
}
}
private const val MESSAGE_CODE = 233
private const val DEFAULT_FLAG = 0
| mit | 515c30311e5f6f003a1ab7a0174a7dc3 | 35.297872 | 84 | 0.632474 | 5.092537 | false | false | false | false |
MaximumSquotting/chopin | app/src/main/java/com/chopin/chopin/fragments/MyOfferList.kt | 1 | 2102 | package com.chopin.chopin.fragments
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import bindView
import butterknife.ButterKnife
import com.chopin.chopin.ConnectionHandler
import com.chopin.chopin.R
import com.chopin.chopin.adapters.RVAdapter
import com.chopin.chopin.models.Offer
import java.util.*
class MyOfferList : Fragment() {
private var offers: ArrayList<Offer>? = null
private var adapter: RVAdapter? = null
internal val mRecyclerView: RecyclerView by bindView(R.id.list)
val swipe : SwipeRefreshLayout by bindView(R.id.swipe)
private var connectionHandler: ConnectionHandler = ConnectionHandler()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
offers = ArrayList<Offer>()
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val v = inflater!!.inflate(R.layout.fragment_list, container, false)
ButterKnife.bind(this, v)
return v
}
override fun onStart() {
super.onStart()
mRecyclerView?.setHasFixedSize(true)
// use a linear layout manager
val mLayoutManager = LinearLayoutManager(this.context)
mRecyclerView?.layoutManager = mLayoutManager
offers = connectionHandler.myOfferFromServer
adapter = RVAdapter(offers, activity)
mRecyclerView!!.adapter = adapter
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
swipe?.setOnRefreshListener {
Log.d("onRefresh", "calling get()")
offers = connectionHandler.myOfferFromServer
adapter!!.notifyDataSetChanged()
swipe!!.isRefreshing = false
}
}
}// Required empty public constructor
| mit | d99af4f184e7d980c05ed7567aec1ffb | 33.459016 | 79 | 0.715509 | 4.76644 | false | false | false | false |
Undin/intellij-rust | src/test/kotlin/org/rust/ide/intentions/AddDeriveIntentionTest.kt | 3 | 1474 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.intentions
class AddDeriveIntentionTest : RsIntentionTestBase(AddDeriveIntention::class) {
fun `test availability range in struct`() = checkAvailableInSelectionOnly("""
<selection>struct Test {
field: i32
}</selection>
""")
fun `test availability range in tuple struct`() = checkAvailableInSelectionOnly("""
<selection>struct Test (i32);</selection>
""")
fun `test availability range in enum`() = checkAvailableInSelectionOnly("""
<selection>enum Test {
Something
}</selection>
""")
fun `test add derive struct`() = doAvailableTest("""
struct Test/*caret*/ {}
""", """
#[derive(/*caret*/)]
struct Test {}
""")
fun `test add derive pub struct`() = doAvailableTest("""
pub struct Test/*caret*/ {}
""", """
#[derive(/*caret*/)]
pub struct Test {}
""")
fun `test add derive enum`() = doAvailableTest("""
enum Test /*caret*/{
Something
}
""", """
#[derive(/*caret*/)]
enum Test {
Something
}
""")
fun `test add derive existing attr`() = doAvailableTest("""
#[derive(Something)]
struct Test/*caret*/ {}
""", """
#[derive(Something/*caret*/)]
struct Test {}
""")
}
| mit | ba63e2dd30cbbc1bb014984ee3176757 | 24.859649 | 87 | 0.543419 | 4.913333 | false | true | false | false |
Undin/intellij-rust | src/test/kotlin/org/rust/ide/inspections/RsMissingElseInspectionTest.kt | 4 | 2764 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.inspections
/**
* Tests for Missing Else inspection.
*/
class RsMissingElseInspectionTest : RsInspectionsTestBase(RsMissingElseInspection::class) {
fun testSimple() = checkByText("""
fn main() {
if true {
}<warning descr="Suspicious if. Did you mean `else if`?"> if </warning>true {
}
}
""")
fun testNoSpaces() = checkByText("""
fn main() {
let a = 10;
if true {
}<warning descr="Suspicious if. Did you mean `else if`?">if</warning>(a > 10){
}
}
""")
fun testWideSpaces() = checkByText("""
fn main() {
let a = 10;
if true {
}<warning descr="Suspicious if. Did you mean `else if`?"> if </warning>(a > 10) {
}
}
""")
fun testComments() = checkByText("""
fn main() {
let a = 10;
if true {
}<warning descr="Suspicious if. Did you mean `else if`?"> /* commented */ /* else */ if </warning>a > 10 {
}
}
""")
fun testNotLastExpr() = checkByText("""
fn main() {
let a = 10;
if a > 5 {
}<warning descr="Suspicious if. Did you mean `else if`?"> if </warning>a > 10{
}
let b = 20;
}
""")
fun testHandlesBlocksWithNoSiblingsCorrectly() = checkByText("""
fn main() {if true {}}
""")
fun testNotAppliedWhenLineBreakExists() = checkByText("""
fn main() {
if true {}
if true {}
}
""")
fun testNotAppliedWhenTheresNoSecondIf() = checkByText("""
fn main() {
if {
92;
}
{}
}
""")
fun testFix() = checkFixByText("Change to `else if`", """
fn main() {
let a = 10;
if a > 7 {
}<warning descr="Suspicious if. Did you mean `else if`?"> i<caret>f </warning>a > 14 {
}
}
""", """
fn main() {
let a = 10;
if a > 7 {
} else if a > 14 {
}
}
""")
fun testFixPreservesComments() = checkFixByText("Change to `else if`", """
fn main() {
let a = 10;
if a > 7 {
}<warning descr="Suspicious if. Did you mean `else if`?"> /* comment */<caret> if /* ! */ </warning>a > 14 {
}
}
""", """
fn main() {
let a = 10;
if a > 7 {
} /* comment */ else if /* ! */ a > 14 {
}
}
""")
}
| mit | 9cac77f55576e7a15823f6c52c500422 | 24.357798 | 120 | 0.433792 | 4.387302 | false | true | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/inspections/lints/RsDoubleMustUseInspection.kt | 2 | 1891 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.inspections.lints
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.rust.RsBundle
import org.rust.ide.inspections.RsProblemsHolder
import org.rust.lang.core.psi.RsFunction
import org.rust.lang.core.psi.RsVisitor
import org.rust.lang.core.psi.ext.findFirstMetaItem
import org.rust.lang.core.psi.ext.normReturnType
import org.rust.lang.core.types.ty.TyAdt
private class FixRemoveMustUseAttr : LocalQuickFix {
override fun getFamilyName() = RsBundle.message("inspection.DoubleMustUse.FixRemoveMustUseAttr.name")
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
descriptor.psiElement?.delete()
}
}
/** Analogue of Clippy's double_must_use. */
class RsDoubleMustUseInspection : RsLintInspection() {
override fun getLint(element: PsiElement): RsLint = RsLint.DoubleMustUse
override fun buildVisitor(holder: RsProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() {
override fun visitFunction(o: RsFunction) {
super.visitFunction(o)
val mustUseAttrName = "must_use"
val attrFunc = o.findFirstMetaItem(mustUseAttrName)
val type = o.normReturnType as? TyAdt
val attrType = type?.item?.findFirstMetaItem(mustUseAttrName)
if (attrFunc != null && attrType != null) {
val description = RsBundle.message("inspection.DoubleMustUse.description")
val highlighting = RsLintHighlightingType.WEAK_WARNING
holder.registerLintProblem(attrFunc.parent, description, highlighting, fixes = listOf(FixRemoveMustUseAttr()))
}
}
}
}
| mit | 012e3575ccd360f5dc10ff3026152d01 | 39.234043 | 126 | 0.729244 | 4.192905 | false | false | false | false |
Guardiola31337/uiagesturegen | uiagesturegen/src/main/kotlin/com/pguardiola/uigesturegen/dsl/interpreter.kt | 1 | 6658 | /*
* Copyright (C) 2017 Pablo Guardiola Sánchez.
*
* 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.pguardiola.uigesturegen.dsl
import android.support.test.uiautomator.Configurator
import android.support.test.uiautomator.UiObject
import kategory.*
@Suppress("UNCHECKED_CAST")
fun safeInterpreter(view: UiObject): FunctionK<GesturesDSLHK, ValidatedKindPartial<NonEmptyList<GestureError>>> =
object : FunctionK<GesturesDSLHK, ValidatedKindPartial<NonEmptyList<GestureError>>> {
override fun <A> invoke(fa: GesturesDSLKind<A>): ValidatedKind<NonEmptyList<GestureError>, A> {
val g = fa.ev()
return when (g) {
is GesturesDSL.WithView -> Try { g.f(view) }.fold(
{ GestureError.UnknownError(it).invalidNel<GestureError, A>() },
{ it.validNel() }
)
is GesturesDSL.Combine -> {
val aResult = g.a.validate(view).map { _ -> Unit }
val bResult = g.b.validate(view).map { _ -> Unit }
aResult.combineK(bResult, NonEmptyList.semigroup<GestureError>())
}
is GesturesDSL.Click -> view.click().validate({ GestureError.ClickError(view) })
is GesturesDSL.DoubleTap -> Try {
doubleTapImpl(view)
}.fold(
{ GestureError.DoubleTapError(view).invalidNel<GestureError, Unit>() },
{ it.validNel() }
)
is GesturesDSL.PinchIn -> view.pinchIn(g.percent, g.steps).validate({ GestureError.PinchInError(view) })
is GesturesDSL.PinchOut -> view.pinchOut(g.percent, g.steps).validate({ GestureError.PinchOutError(view) })
is GesturesDSL.SwipeLeft -> view.swipeLeft(g.steps).validate({ GestureError.SwipeLeftError(view) })
is GesturesDSL.SwipeRight -> view.swipeRight(g.steps).validate({ GestureError.SwipeRightError(view) })
is GesturesDSL.SwipeUp -> view.swipeUp(g.steps).validate({ GestureError.SwipeUpError(view) })
is GesturesDSL.SwipeDown -> view.swipeDown(g.steps).validate({ GestureError.SwipeDownError(view) })
is GesturesDSL.MultiTouch -> view.performMultiPointerGesture(*(g.touches.toTypedArray())).validate({ GestureError.MultiTouchError(view) })
is GesturesDSL.TwoPointer -> view.performTwoPointerGesture(g.firstStart, g.secondStart, g.firstEnd, g.secondEnd, g.steps).validate({ GestureError.TwoPointerError(view) })
} as ValidatedKind<NonEmptyList<GestureError>, A>
}
}
private fun doubleTapImpl(view: UiObject) {
val configurator = Configurator.getInstance()
configurator.actionAcknowledgmentTimeout = 40
view.click()
view.click()
configurator.actionAcknowledgmentTimeout = 3000
}
@Suppress("UNCHECKED_CAST")
fun safeInterpreterEither(view: UiObject): FunctionK<GesturesDSLHK, EitherKindPartial<GestureError>> =
object : FunctionK<GesturesDSLHK, EitherKindPartial<GestureError>> {
override fun <A> invoke(fa: GesturesDSLKind<A>): EitherKind<GestureError, A> {
val g = fa.ev()
return when (g) {
is GesturesDSL.WithView -> {
Either.monadError<GestureError>().catch({ g.f(view) }, { GestureError.UnknownError(it) })
}
is GesturesDSL.Combine -> {
val aResult = g.a.failFast(view).map { _ -> Unit }
val bResult = g.b.failFast(view).map { _ -> Unit }
aResult.combineK(bResult)
}
is GesturesDSL.Click -> view.click().either({ GestureError.ClickError(view) })
is GesturesDSL.DoubleTap -> Either.monadError<GestureError>().catch({
doubleTapImpl(view)
}, { GestureError.DoubleTapError(view) }
)
is GesturesDSL.PinchIn -> view.pinchIn(g.percent, g.steps).either({ GestureError.PinchInError(view) })
is GesturesDSL.PinchOut -> view.pinchOut(g.percent, g.steps).either({ GestureError.PinchOutError(view) })
is GesturesDSL.SwipeLeft -> view.swipeLeft(g.steps).either({ GestureError.SwipeLeftError(view) })
is GesturesDSL.SwipeRight -> view.swipeRight(g.steps).either({ GestureError.SwipeRightError(view) })
is GesturesDSL.SwipeUp -> view.swipeUp(g.steps).either({ GestureError.SwipeUpError(view) })
is GesturesDSL.SwipeDown -> view.swipeDown(g.steps).either({ GestureError.SwipeDownError(view) })
is GesturesDSL.MultiTouch -> view.performMultiPointerGesture(*(g.touches.toTypedArray())).either({ GestureError.MultiTouchError(view) })
is GesturesDSL.TwoPointer -> view.performTwoPointerGesture(g.firstStart, g.secondStart, g.firstEnd, g.secondEnd, g.steps).either({ GestureError.TwoPointerError(view) })
} as EitherKind<GestureError, A>
}
}
@Suppress("UNCHECKED_CAST")
fun loggingInterpreter(view: UiObject): FunctionK<GesturesDSLHK, EitherKindPartial<GestureError>> =
object : FunctionK<GesturesDSLHK, EitherKindPartial<GestureError>> {
override fun <A> invoke(fa: GesturesDSLKind<A>): EitherKind<GestureError, A> {
println(fa)
return safeInterpreterEither(view) as EitherKind<GestureError, A>
}
}
fun Boolean.validate(ifInvalid: () -> GestureError): ValidatedNel<GestureError, Unit> =
if (true) Unit.validNel()
else ifInvalid().invalidNel()
fun Boolean.invalidate(ifInvalid: () -> GestureError): ValidatedNel<GestureError, Unit> =
ifInvalid().invalidNel()
fun Boolean.either(ifInvalid: () -> GestureError): Either<GestureError, Unit> =
if (true) Unit.right()
else ifInvalid().left()
| apache-2.0 | fd8699b0dfdebb822cd915064c5f1319 | 56.387931 | 190 | 0.619198 | 4.281029 | false | false | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/stories/my/MyStoriesViewModel.kt | 2 | 1226 | package org.thoughtcrime.securesms.stories.my
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import io.reactivex.rxjava3.core.Completable
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.kotlin.plusAssign
import org.thoughtcrime.securesms.database.model.MessageRecord
import org.thoughtcrime.securesms.util.livedata.Store
class MyStoriesViewModel(private val repository: MyStoriesRepository) : ViewModel() {
private val store = Store(MyStoriesState())
private val disposables = CompositeDisposable()
val state: LiveData<MyStoriesState> = store.stateLiveData
init {
disposables += repository.getMyStories().subscribe { distributionSets ->
store.update { it.copy(distributionSets = distributionSets) }
}
}
override fun onCleared() {
disposables.clear()
}
fun resend(story: MessageRecord): Completable {
return repository.resend(story)
}
class Factory(private val repository: MyStoriesRepository) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return modelClass.cast(MyStoriesViewModel(repository)) as T
}
}
}
| gpl-3.0 | 6f80caac276421430aa3bd8bf4fdf3a3 | 31.263158 | 90 | 0.77814 | 4.540741 | false | false | false | false |
androidx/androidx | paging/integration-tests/testapp/src/main/java/androidx/paging/integration/testapp/custom/ItemDataSource.kt | 3 | 3006 | /*
* Copyright 2018 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.paging.integration.testapp.custom
import android.graphics.Color
import androidx.annotation.ColorInt
import androidx.paging.PagingSource
import androidx.paging.PagingState
import kotlinx.coroutines.delay
import java.util.concurrent.atomic.AtomicBoolean
val dataSourceError = AtomicBoolean(false)
/**
* Sample position-based PagingSource with artificial data.
*/
internal class ItemDataSource : PagingSource<Int, Item>() {
class RetryableItemError : Exception()
private val generationId = sGenerationId++
override fun getRefreshKey(state: PagingState<Int, Item>): Int? = state.anchorPosition
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Item> =
when (params) {
is LoadParams.Refresh ->
loadInternal(
position = ((params.key ?: 0) - params.loadSize / 2).coerceAtLeast(0),
loadSize = params.loadSize
)
is LoadParams.Prepend -> {
val loadSize = minOf(params.key, params.loadSize)
loadInternal(
position = params.key - loadSize,
loadSize = loadSize
)
}
is LoadParams.Append ->
loadInternal(
position = params.key,
loadSize = params.loadSize
)
}
private suspend fun loadInternal(
position: Int,
loadSize: Int
): LoadResult<Int, Item> {
delay(1000)
if (dataSourceError.compareAndSet(true, false)) {
return LoadResult.Error(RetryableItemError())
} else {
val bgColor = COLORS[generationId % COLORS.size]
val endExclusive = (position + loadSize).coerceAtMost(COUNT)
val data = (position until endExclusive).map {
Item(it, "item $it", bgColor)
}
return LoadResult.Page(
data = data,
prevKey = position,
nextKey = endExclusive,
itemsBefore = position,
itemsAfter = COUNT - endExclusive
)
}
}
companion object {
private const val COUNT = 60
@ColorInt
private val COLORS = intArrayOf(Color.RED, Color.BLUE, Color.BLACK)
private var sGenerationId: Int = 0
}
}
| apache-2.0 | d459baf74b87bf6efc031e29ff5b5d6d | 32.4 | 90 | 0.612109 | 4.968595 | false | false | false | false |
googlecodelabs/complications-data-source | complete/src/main/java/com/example/android/wearable/complicationsdatasource/ComplicationTapBroadcastReceiver.kt | 1 | 4548 | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.wearable.complicationsdatasource
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import androidx.datastore.preferences.core.edit
import androidx.wear.watchface.complications.datasource.ComplicationDataSourceUpdateRequester
import com.example.android.wearable.complicationsdatasource.data.TAP_COUNTER_PREF_KEY
import com.example.android.wearable.complicationsdatasource.data.dataStore
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
/**
* Simple [BroadcastReceiver] subclass for asynchronously incrementing an integer for any
* complication id triggered via TapAction on complication. Also, provides static method to create
* a [PendingIntent] that triggers this receiver.
*/
class ComplicationTapBroadcastReceiver : BroadcastReceiver() {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
override fun onReceive(context: Context, intent: Intent) {
// Retrieve complication values from Intent's extras.
val extras = intent.extras ?: return
val dataSource = extras.getParcelable<ComponentName>(EXTRA_DATA_SOURCE_COMPONENT) ?: return
val complicationId = extras.getInt(EXTRA_COMPLICATION_ID)
// Required when using async code in onReceive().
val result = goAsync()
// Launches coroutine to update the DataStore counter value.
scope.launch {
try {
context.dataStore.edit { preferences ->
val currentValue = preferences[TAP_COUNTER_PREF_KEY] ?: 0
// Update data for complication.
val newValue = (currentValue + 1) % MAX_NUMBER
preferences[TAP_COUNTER_PREF_KEY] = newValue
}
// Request an update for the complication that has just been tapped, that is,
// the system call onComplicationUpdate on the specified complication data
// source.
val complicationDataSourceUpdateRequester =
ComplicationDataSourceUpdateRequester.create(
context = context,
complicationDataSourceComponent = dataSource
)
complicationDataSourceUpdateRequester.requestUpdate(complicationId)
} finally {
// Always call finish, even if cancelled
result.finish()
}
}
}
companion object {
private const val EXTRA_DATA_SOURCE_COMPONENT =
"com.example.android.wearable.complicationsdatasource.action.DATA_SOURCE_COMPONENT"
private const val EXTRA_COMPLICATION_ID =
"com.example.android.wearable.complicationsdatasource.action.COMPLICATION_ID"
const val MAX_NUMBER = 20
/**
* Returns a pending intent, suitable for use as a tap intent, that causes a complication to be
* toggled and updated.
*/
fun getToggleIntent(
context: Context,
dataSource: ComponentName,
complicationId: Int
): PendingIntent {
val intent = Intent(context, ComplicationTapBroadcastReceiver::class.java)
intent.putExtra(EXTRA_DATA_SOURCE_COMPONENT, dataSource)
intent.putExtra(EXTRA_COMPLICATION_ID, complicationId)
// Pass complicationId as the requestCode to ensure that different complications get
// different intents.
return PendingIntent.getBroadcast(
context,
complicationId,
intent,
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
)
}
}
}
| apache-2.0 | 17f0727bb19917659f118899a0e88448 | 41.111111 | 103 | 0.676121 | 5.338028 | false | false | false | false |
initrc/android-bootstrap | app/src/main/java/io/github/initrc/bootstrap/view/HomeView.kt | 1 | 6676 | package io.github.initrc.bootstrap.view
import android.app.Activity
import android.content.Context
import android.support.v7.widget.StaggeredGridLayoutManager
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.ScaleGestureDetector
import android.view.ScaleGestureDetector.SimpleOnScaleGestureListener
import android.view.View
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.widget.FrameLayout
import io.github.initrc.bootstrap.R
import io.github.initrc.bootstrap.presenter.ColumnCountType
import io.github.initrc.bootstrap.presenter.ColumnPresenter
import io.github.initrc.bootstrap.presenter.HomePresenter
import io.github.initrc.bootstrap.view.decoration.HorizontalEqualSpaceItemDecoration
import io.github.initrc.bootstrap.view.listener.InfiniteGridScrollListener
import io.github.initrc.bootstrap.view.listener.VerticalScrollListener
import kotlinx.android.synthetic.main.view_home.view.*
import util.AnimationUtils
import util.inflate
/**
* Home view.
*/
class HomeView : FrameLayout {
private val presenter: HomePresenter
private val columnPresenter: ColumnPresenter
private val scaleGestureDetector: ScaleGestureDetector
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
init {
inflate(R.layout.view_home, true)
// dynamic columns
columnPresenter = ColumnPresenter(context as Activity)
val gridColumnCount = columnPresenter.getDynamicGridColumnCount()
presenter = HomePresenter(feedList, columnPresenter.getGridColumnWidthPx(), homeFab)
columnPresenter.setOnColumnUpdateCallback { columnCount ->
presenter.setGridColumnWidth(columnPresenter.getGridColumnWidthPx())
presenter.setImageOnly(columnPresenter.columnCountType.ordinal > ColumnCountType.STANDARD.ordinal)
(feedList.layoutManager as StaggeredGridLayoutManager).spanCount = columnCount
feedList.adapter.notifyItemRangeChanged(0, feedList.adapter.itemCount)
}
scaleGestureDetector = ScaleGestureDetector(context, ScaleListener(columnPresenter, feedList))
// feed
feedList.layoutManager = StaggeredGridLayoutManager(
gridColumnCount, StaggeredGridLayoutManager.VERTICAL)
feedList.addItemDecoration(HorizontalEqualSpaceItemDecoration(columnPresenter.gridPadding))
feedList.clearOnScrollListeners()
feedList.addOnScrollListener(
InfiniteGridScrollListener(feedList.layoutManager as StaggeredGridLayoutManager)
{ presenter.loadPhotos() })
feedList.addOnScrollListener(VerticalScrollListener(
{ AnimationUtils.hideFab(homeFab) }, { AnimationUtils.showFab(homeFab) }))
feedList.setOnTouchListener { _: View, event: MotionEvent ->
scaleGestureDetector.onTouchEvent(event)
event.pointerCount > 1 // don't scroll while performing multi-finger gestures
}
// slide select view
val slideSelectViewBuilder = SlideSelectView.Builder(context)
.setSelectedIndex(presenter.features.indexOf(presenter.currentFeature))
.setOnDismiss {
AnimationUtils.showFab(homeFab)
}
for (feature in presenter.features) {
slideSelectViewBuilder.addItem(getFeatureName(feature),
View.OnClickListener{ presenter.refreshPhotos(feature) })
}
val dragSelectView = slideSelectViewBuilder.build()
dragSelectView.visibility = View.GONE
homeRootView.addView(dragSelectView, FrameLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT))
// fab
homeFab.setOnClickListener {
AnimationUtils.hideFab(homeFab)
dragSelectView.show()
}
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
presenter.onBind()
}
override fun onDetachedFromWindow() {
presenter.onUnbind()
super.onDetachedFromWindow()
}
private fun getFeatureName(feature: String): String {
when (feature) {
presenter.features[0] -> return context.getString(R.string.popular)
presenter.features[1] -> return context.getString(R.string.editors)
presenter.features[2] -> return context.getString(R.string.upcoming)
presenter.features[3] -> return context.getString(R.string.fresh)
}
return ""
}
class ScaleListener(private val columnPresenter: ColumnPresenter, private val view: View)
: SimpleOnScaleGestureListener() {
private var previousSpan = 1f
private var scaleFactor = 1f
private val scaleThreshold = 0.3f
private val ignoreScaleThreshold = 25
private var ignoreScaleCount = 0 // workaround to ignore buggy scale events
override fun onScale(detector: ScaleGestureDetector?): Boolean {
if (detector == null) return false
if (ignoreScaleCount > 0) {
ignoreScaleCount--
return false
}
var delta: Int
scaleFactor *= getScaleFactor(previousSpan, detector.currentSpan)
when {
scaleFactor < 1 - scaleThreshold -> delta = 1
scaleFactor > 1 + scaleThreshold -> delta = -1
else -> {
delta = 0
scaleView(view, scaleFactor)
}
}
if (delta != 0) {
previousSpan = detector.currentSpan
columnPresenter.adjustCount(delta)
scaleFactor = 1f
scaleView(view, scaleFactor)
ignoreScaleCount = ignoreScaleThreshold
}
return true
}
override fun onScaleBegin(detector: ScaleGestureDetector?): Boolean {
scaleFactor = 1f
previousSpan = detector?.currentSpan!!
return true
}
override fun onScaleEnd(detector: ScaleGestureDetector?) {
scaleFactor = 1f
scaleView(view, scaleFactor)
}
private fun getScaleFactor(previousSpan: Float, currentSpan: Float): Float {
return if (previousSpan > 0 && currentSpan > 0) {
currentSpan / previousSpan
} else {
1.0f
}
}
private fun scaleView(view: View, scaleFactor: Float) {
view.scaleX = scaleFactor
view.scaleY = scaleFactor
view.alpha = 1 - Math.abs(scaleFactor - 1)
}
}
} | mit | adf1ca5e2e69f1d0e497303ad9ccf951 | 39.96319 | 110 | 0.665968 | 5.163186 | false | false | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/platform/liteloader/creator/LiteLoaderProjectConfig.kt | 1 | 1906 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.liteloader.creator
import com.demonwav.mcdev.creator.ProjectConfig
import com.demonwav.mcdev.creator.ProjectCreator
import com.demonwav.mcdev.creator.buildsystem.BuildSystemType
import com.demonwav.mcdev.creator.buildsystem.gradle.GradleBuildSystem
import com.demonwav.mcdev.creator.buildsystem.gradle.GradleCreator
import com.demonwav.mcdev.platform.PlatformType
import com.demonwav.mcdev.platform.forge.creator.Fg2ProjectCreator
import com.demonwav.mcdev.platform.mcp.McpVersionPair
import com.demonwav.mcdev.util.MinecraftVersions
import com.demonwav.mcdev.util.SemanticVersion
import com.demonwav.mcdev.util.VersionRange
import com.intellij.openapi.module.Module
import com.intellij.util.lang.JavaVersion
import java.nio.file.Path
class LiteLoaderProjectConfig : ProjectConfig(), GradleCreator {
lateinit var mainClass: String
var mcpVersion = McpVersionPair("", SemanticVersion.release())
var mcVersion: SemanticVersion = SemanticVersion.release()
override var type = PlatformType.LITELOADER
override val preferredBuildSystem = BuildSystemType.GRADLE
override val javaVersion: JavaVersion
get() = MinecraftVersions.requiredJavaVersion(mcVersion)
override val compatibleGradleVersions: VersionRange = VersionRange.fixed(Fg2ProjectCreator.FG_WRAPPER_VERSION)
override fun buildGradleCreator(
rootDirectory: Path,
module: Module,
buildSystem: GradleBuildSystem
): ProjectCreator {
return LiteLoaderProjectCreator(rootDirectory, module, buildSystem, this)
}
override fun configureRootGradle(
rootDirectory: Path,
buildSystem: GradleBuildSystem
) {
buildSystem.gradleVersion = Fg2ProjectCreator.FG_WRAPPER_VERSION
}
}
| mit | ac16f3cc4387e02bcb0450fff41cec6c | 31.862069 | 114 | 0.783316 | 4.717822 | false | true | false | false |
andstatus/andstatus | app/src/main/kotlin/org/andstatus/app/util/MyHtml.kt | 1 | 7253 | /*
* Copyright (C) 2014 yvolk (Yuri Volkov), http://yurivolkov.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.andstatus.app.util
import android.text.Html
import org.andstatus.app.context.MyLocale.MY_DEFAULT_LOCALE
import org.andstatus.app.data.TextMediaType
import org.apache.commons.lang3.text.translate.AggregateTranslator
import org.apache.commons.lang3.text.translate.CharSequenceTranslator
import org.apache.commons.lang3.text.translate.EntityArrays
import org.apache.commons.lang3.text.translate.LookupTranslator
import org.apache.commons.lang3.text.translate.NumericEntityUnescaper
import java.util.regex.Pattern
object MyHtml {
private val SPACES_PATTERN = Pattern.compile("[\n\\s]+")
private val SPACES_FOR_SEARCH_PATTERN = Pattern.compile("[\\[\\](){}\n\'\"<>,:;\\s]+")
private val PUNCTUATION_BEFORE_COMMA_PATTERN = Pattern.compile("[,.!?]+,")
private val MENTION_HASH_PREFIX_PATTERN = Pattern.compile("(,[@#!]([^@#!,]+))")
val LINEBREAK_HTML: String = "<br />"
private val HTML_LINEBREAK_PATTERN = Pattern.compile(LINEBREAK_HTML)
private val LINEBREAK_PLAIN: String = "\n"
private val LINEBREAK_PATTERN = Pattern.compile(LINEBREAK_PLAIN)
private val LINEBREAK_ESCAPED_PATTERN = Pattern.compile(" ")
private val SPACE_ESCAPED_PATTERN = Pattern.compile(" ")
private val THREE_LINEBREAKS_REGEX: String = "\n\\s*\n\\s*\n"
private val THREE_LINEBREAKS_PATTERN = Pattern.compile(THREE_LINEBREAKS_REGEX)
private val DOUBLE_LINEBREAK_REPLACE: String = "\n\n"
private val PLAIN_LINEBREAK_AFTER_HTML_LINEBREAK = Pattern.compile(
"(</p>|<br[ /]*>)(\n\\s*)")
fun prepareForView(html: String?): String {
if (html.isNullOrEmpty()) return ""
val endWith = if (html.endsWith("</p>")) "</p>" else if (html.endsWith("</p>\n")) "</p>\n" else ""
return if (!endWith.isNullOrEmpty() && StringUtil.countOfOccurrences(html, "<p") == 1) {
html.replace("<p[^>]*>".toRegex(), "").replace(endWith.toRegex(), "")
} else html
}
/** Following ActivityStreams convention, default mediaType for content is "text/html" */
fun toContentStored(text: String?, inputMediaType: TextMediaType?, isHtmlContentAllowed: Boolean): String {
if (text.isNullOrEmpty()) return ""
val mediaType = if (inputMediaType == TextMediaType.UNKNOWN) calcTextMediaType(text) else inputMediaType
val escaped: String?
escaped = when (mediaType) {
TextMediaType.HTML -> {
if (isHtmlContentAllowed) return text
Html.fromHtml(text, Html.FROM_HTML_MODE_COMPACT).toString()
}
TextMediaType.PLAIN -> escapeHtmlExceptLineBreaksAndSpace(text)
TextMediaType.PLAIN_ESCAPED -> if (isHtmlContentAllowed || !hasHtmlMarkup(text)) text else escapeHtmlExceptLineBreaksAndSpace(text)
else -> escapeHtmlExceptLineBreaksAndSpace(text)
}
// Maybe htmlify...
return LINEBREAK_PATTERN.matcher(stripExcessiveLineBreaks(escaped)).replaceAll(LINEBREAK_HTML)
}
private fun calcTextMediaType(text: String?): TextMediaType {
if (text.isNullOrEmpty()) return TextMediaType.PLAIN
return if (hasHtmlMarkup(text)) TextMediaType.HTML else TextMediaType.PLAIN
}
fun fromContentStored(html: String?, outputMediaType: TextMediaType?): String {
return if (html.isNullOrEmpty()) "" else when (outputMediaType) {
TextMediaType.HTML -> html
TextMediaType.PLAIN -> htmlToPlainText(html)
TextMediaType.PLAIN_ESCAPED -> escapeHtmlExceptLineBreaksAndSpace(htmlToPlainText(html))
else -> html
}
}
fun getContentToSearch(html: String?): String {
return normalizeWordsForSearch(htmlToCompactPlainText(html)).toLowerCase(MY_DEFAULT_LOCALE)
}
/** Strips ALL markup from the String, including line breaks. And remove all whiteSpace */
fun htmlToCompactPlainText(html: String?): String {
return SPACES_PATTERN.matcher(htmlToPlainText(html)).replaceAll(" ")
}
/** Strips ALL markup from the String, excluding line breaks */
fun htmlToPlainText(html: String?): String {
if (html.isNullOrEmpty()) return ""
val str0 = HTML_LINEBREAK_PATTERN.matcher(html).replaceAll("\n")
val str1 = if (hasHtmlMarkup(str0)) Html.fromHtml(html, Html.FROM_HTML_MODE_COMPACT).toString() else str0
val str2 = unescapeHtml(str1)
return stripExcessiveLineBreaks(str2)
}
private fun unescapeHtml(textEscaped: String?): String {
return if (textEscaped.isNullOrEmpty()) ""
else UNESCAPE_HTML.translate(textEscaped) // This is needed to avoid visible text truncation,
// see https://github.com/andstatus/andstatus/issues/441
.replace("<>".toRegex(), "< >")
}
private val UNESCAPE_HTML: CharSequenceTranslator = AggregateTranslator(
LookupTranslator(*EntityArrays.BASIC_UNESCAPE()),
LookupTranslator(*EntityArrays.ISO8859_1_UNESCAPE()),
LookupTranslator(*EntityArrays.HTML40_EXTENDED_UNESCAPE()),
LookupTranslator(*EntityArrays.APOS_UNESCAPE()),
NumericEntityUnescaper()
)
private fun escapeHtmlExceptLineBreaksAndSpace(plainText: String?): String {
return if (plainText.isNullOrEmpty()) "" else SPACE_ESCAPED_PATTERN.matcher(
LINEBREAK_ESCAPED_PATTERN.matcher(Html.escapeHtml(plainText)).replaceAll(LINEBREAK_PLAIN)
).replaceAll(" ")
}
fun stripExcessiveLineBreaks(plainText: String?): String {
return if (plainText.isNullOrEmpty()) {
""
} else {
var text2 = THREE_LINEBREAKS_PATTERN.matcher(plainText.trim { it <= ' ' }).replaceAll(DOUBLE_LINEBREAK_REPLACE).trim { it <= ' ' }
while (text2.endsWith(LINEBREAK_PLAIN)) {
text2 = text2.substring(0, text2.length - LINEBREAK_PLAIN.length).trim { it <= ' ' }
}
text2
}
}
fun normalizeWordsForSearch(text: String?): String {
return if (text.isNullOrEmpty()) {
""
} else {
MENTION_HASH_PREFIX_PATTERN.matcher(
PUNCTUATION_BEFORE_COMMA_PATTERN.matcher(
SPACES_FOR_SEARCH_PATTERN.matcher(
",$text,"
).replaceAll(",")
).replaceAll(",")
).replaceAll(",$2$1")
}
}
/** Very simple method */
fun hasHtmlMarkup(text: String?): Boolean {
return if (text.isNullOrEmpty()) false else text.contains("<") && text.contains(">")
}
}
| apache-2.0 | 932fd7e1ea08278aab00c1eb2cf51d27 | 45.793548 | 143 | 0.656004 | 4.314694 | false | false | false | false |
handstandsam/ShoppingApp | shopping-cart-room/src/main/java/com/handstandsam/shoppingapp/cart/RoomShoppingCartDao.kt | 1 | 2704 | package com.handstandsam.shoppingapp.cart
import androidx.room.Room
import com.handstandsam.shoppingapp.models.Item
import com.handstandsam.shoppingapp.models.ItemWithQuantity
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.ConflatedBroadcastChannel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.launch
/**
* Implements the app's [ShoppingCartDao] interface, but makes queries to our [Room] database [RoomItemInCartDatabase]
*/
class RoomShoppingCartDao(itemInCartDatabase: RoomItemInCartDatabase) :
CoroutineScope by CoroutineScope(Dispatchers.IO),
ShoppingCartDao {
private val itemInCartDao: RoomItemInCartDao = itemInCartDatabase.itemInCartDao()
private val channel = ConflatedBroadcastChannel(listOf<ItemWithQuantity>())
init {
/**
* Initialize a Listener/Observer to the Room Database to publish updates to the [ReceiveChannel]
*/
itemInCartDao.selectAllStream().observeForever { list ->
launch {
channel.send(list.toItemWithQuantityList())
}
}
}
override val allItems: Flow<List<ItemWithQuantity>>
get() = channel.asFlow()
override suspend fun findByLabel(label: String): ItemWithQuantity? {
return itemInCartDao.findByLabel(label)?.toItemWithQuantity()
}
override suspend fun upsert(itemWithQuantity: ItemWithQuantity) {
itemInCartDao.upsert(itemWithQuantity.toItemInCart())
}
override suspend fun remove(itemWithQuantity: ItemWithQuantity) {
itemInCartDao.remove(itemWithQuantity.toItemInCart())
}
override suspend fun empty() {
itemInCartDao.empty()
}
}
/**
* Extension Function to convert [ItemWithQuantity] -> [RoomItemInCartEntity]
*/
private fun ItemWithQuantity.toItemInCart(): RoomItemInCartEntity {
return RoomItemInCartEntity(
image = this.item.image,
label = this.item.label,
link = this.item.link,
quantity = this.quantity
)
}
/**
* Extension Function to convert [RoomItemInCartEntity] -> [ItemWithQuantity]
*/
private fun RoomItemInCartEntity.toItemWithQuantity(): ItemWithQuantity {
return ItemWithQuantity(
item = Item(
image = this.image,
label = this.label,
link = this.link
),
quantity = this.quantity
)
}
/**
* Extension Function to convert a [List] of [RoomItemInCartEntity] -> [List] of [ItemWithQuantity]
*/
private fun List<RoomItemInCartEntity>.toItemWithQuantityList(): List<ItemWithQuantity> {
return map { it.toItemWithQuantity() }
} | apache-2.0 | 6f592ef105120f2c72e38df1f8540c13 | 30.091954 | 118 | 0.713018 | 4.74386 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.