repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
GunoH/intellij-community
|
plugins/kotlin/code-insight/inspections-shared/src/org/jetbrains/kotlin/idea/codeInsight/inspections/shared/DelegationToVarPropertyInspection.kt
|
2
|
1850
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.codeInsight.inspections.shared
import com.intellij.codeInspection.*
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
import org.jetbrains.kotlin.idea.codeinsights.impl.base.quickFix.ChangeVariableMutabilityFix
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.psi.delegatedSuperTypeEntry
class DelegationToVarPropertyInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) =
delegatedSuperTypeEntry(fun(delegatedSuperTypeEntry) {
val parameter = delegatedSuperTypeEntry.delegateExpression?.mainReference?.resolve() as? KtParameter ?: return
if (parameter.valOrVarKeyword?.node?.elementType != KtTokens.VAR_KEYWORD) return
holder.registerProblem(
parameter,
KotlinBundle.message("delegating.to.var.property.does.not.take.its.changes.into.account"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
IntentionWrapper(ChangeVariableMutabilityFix(parameter, false)),
RemoveVarKeyword()
)
})
}
private class RemoveVarKeyword : LocalQuickFix {
override fun getName() = KotlinBundle.message("remove.var.keyword.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
(descriptor.psiElement as? KtParameter)?.valOrVarKeyword?.delete()
}
}
|
apache-2.0
|
3204a4ce5948806c28d80288e399eb39
| 47.710526 | 122 | 0.757297 | 4.920213 | false | false | false | false |
yongce/AndroidLib
|
baseLib/src/main/java/me/ycdev/android/lib/common/internalapi/android/os/UserHandleIA.kt
|
1
|
1240
|
package me.ycdev.android.lib.common.internalapi.android.os
import android.annotation.SuppressLint
import android.os.UserHandle
import androidx.annotation.RestrictTo
import timber.log.Timber
import java.lang.reflect.InvocationTargetException
import java.lang.reflect.Method
@SuppressLint("PrivateApi")
object UserHandleIA {
private const val TAG = "UserHandleIA"
private var sMtd_myUserId: Method? = null
init {
try {
sMtd_myUserId = UserHandle::class.java.getMethod("myUserId")
} catch (e: NoSuchMethodException) {
Timber.tag(TAG).w(e, "method not found")
}
}
fun myUserId(): Int {
if (sMtd_myUserId != null) {
try {
return sMtd_myUserId!!.invoke(null) as Int
} catch (e: IllegalAccessException) {
Timber.tag(TAG).w(e, "Failed to invoke #myUserId()")
} catch (e: InvocationTargetException) {
Timber.tag(TAG).w(e, "Failed to invoke #myUserId() ag")
}
}
return 0
}
/**
* Just for unit test.
*/
@RestrictTo(RestrictTo.Scope.TESTS)
internal fun checkReflectMyUserId(): Boolean {
return sMtd_myUserId != null
}
}
|
apache-2.0
|
ba56ffdc495ef215fc84321bd942e228
| 27.181818 | 72 | 0.615323 | 4.119601 | false | false | false | false |
jk1/intellij-community
|
platform/configuration-store-impl/src/ComponentStoreImpl.kt
|
1
|
22309
|
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.configurationStore
import com.intellij.configurationStore.StateStorageManager.ExternalizationSession
import com.intellij.notification.NotificationsManager
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ex.DecodeDefaultsUtil
import com.intellij.openapi.application.runUndoTransparentWriteAction
import com.intellij.openapi.components.*
import com.intellij.openapi.components.StateStorage.SaveSession
import com.intellij.openapi.components.StateStorageChooserEx.Resolution
import com.intellij.openapi.components.impl.ComponentManagerImpl
import com.intellij.openapi.components.impl.stores.IComponentStore
import com.intellij.openapi.components.impl.stores.SaveSessionAndFile
import com.intellij.openapi.components.impl.stores.StoreUtil
import com.intellij.openapi.components.impl.stores.UnknownMacroNotification
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.InvalidDataException
import com.intellij.openapi.util.JDOMExternalizable
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vfs.newvfs.impl.VfsRootAccess
import com.intellij.ui.AppUIUtil
import com.intellij.util.ArrayUtilRt
import com.intellij.util.SmartList
import com.intellij.util.SystemProperties
import com.intellij.util.containers.SmartHashSet
import com.intellij.util.containers.isNullOrEmpty
import com.intellij.util.lang.CompoundRuntimeException
import com.intellij.util.messages.MessageBus
import com.intellij.util.xmlb.JDOMXIncluder
import com.intellij.util.xmlb.XmlSerializerUtil
import gnu.trove.THashMap
import org.jdom.Element
import org.jetbrains.annotations.TestOnly
import java.io.IOException
import java.nio.file.Paths
import java.util.*
import java.util.concurrent.TimeUnit
import com.intellij.openapi.util.Pair as JBPair
internal val LOG = Logger.getInstance(ComponentStoreImpl::class.java)
internal val deprecatedComparator = Comparator<Storage> { o1, o2 ->
val w1 = if (o1.deprecated) 1 else 0
val w2 = if (o2.deprecated) 1 else 0
w1 - w2
}
private class PersistenceStateAdapter(val component: Any) : PersistentStateComponent<Any> {
override fun getState() = component
override fun loadState(state: Any) {
XmlSerializerUtil.copyBean(state, component)
}
}
private val NOT_ROAMABLE_COMPONENT_SAVE_THRESHOLD_DEFAULT = TimeUnit.MINUTES.toSeconds(4).toInt()
private var NOT_ROAMABLE_COMPONENT_SAVE_THRESHOLD = NOT_ROAMABLE_COMPONENT_SAVE_THRESHOLD_DEFAULT
@TestOnly
internal fun restoreDefaultNotRoamableComponentSaveThreshold() {
NOT_ROAMABLE_COMPONENT_SAVE_THRESHOLD = NOT_ROAMABLE_COMPONENT_SAVE_THRESHOLD_DEFAULT
}
@TestOnly
internal fun setRoamableComponentSaveThreshold(thresholdInSeconds: Int) {
NOT_ROAMABLE_COMPONENT_SAVE_THRESHOLD = thresholdInSeconds
}
abstract class ComponentStoreImpl : IComponentStore {
private val components = Collections.synchronizedMap(THashMap<String, ComponentInfo>())
internal open val project: Project?
get() = null
open val loadPolicy: StateLoadPolicy
get() = StateLoadPolicy.LOAD
override abstract val storageManager: StateStorageManager
override fun initComponent(component: Any, isService: Boolean) {
var componentName = ""
try {
@Suppress("DEPRECATION")
if (component is PersistentStateComponent<*>) {
componentName = initPersistenceStateComponent(component, StoreUtil.getStateSpec(component), isService)
}
else if (component is JDOMExternalizable) {
componentName = ComponentManagerImpl.getComponentName(component)
@Suppress("DEPRECATION")
initJdomExternalizable(component, componentName)
}
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: Exception) {
LOG.error("Cannot init $componentName component state", e)
return
}
}
override fun initPersistencePlainComponent(component: Any, key: String) {
initPersistenceStateComponent(PersistenceStateAdapter(component),
StateAnnotation(key, FileStorageAnnotation(StoragePathMacros.WORKSPACE_FILE, false)), false)
}
private fun initPersistenceStateComponent(component: PersistentStateComponent<*>, stateSpec: State, isService: Boolean): String {
val componentName = stateSpec.name
val info = doAddComponent(componentName, component, stateSpec)
if (initComponent(info, null, false) && isService) {
// if not service, so, component manager will check it later for all components
project?.let {
val app = ApplicationManager.getApplication()
if (!app.isHeadlessEnvironment && !app.isUnitTestMode && it.isInitialized) {
notifyUnknownMacros(this, it, componentName)
}
}
}
return componentName
}
override final fun save(readonlyFiles: MutableList<SaveSessionAndFile>, isForce: Boolean) {
val errors: MutableList<Throwable> = SmartList<Throwable>()
beforeSaveComponents(errors)
val externalizationSession = if (components.isEmpty()) null else storageManager.startExternalization()
if (externalizationSession != null) {
doSaveComponents(isForce, externalizationSession, errors)
}
afterSaveComponents(errors)
try {
saveAdditionalComponents(isForce)
}
catch (e: Throwable) {
errors.add(e)
}
if (externalizationSession != null) {
doSave(externalizationSession.createSaveSessions(), readonlyFiles, errors)
}
CompoundRuntimeException.throwIfNotEmpty(errors)
}
protected open fun saveAdditionalComponents(isForce: Boolean) {
}
protected open fun beforeSaveComponents(errors: MutableList<Throwable>) {
}
protected open fun afterSaveComponents(errors: MutableList<Throwable>) {
}
protected open fun doSaveComponents(isForce: Boolean, externalizationSession: ExternalizationSession, errors: MutableList<Throwable>): MutableList<Throwable>? {
val isUseModificationCount = Registry.`is`("store.save.use.modificationCount", true)
val names = ArrayUtilRt.toStringArray(components.keys)
Arrays.sort(names)
val timeLogPrefix = "Saving"
val timeLog = if (LOG.isDebugEnabled) StringBuilder(timeLogPrefix) else null
// well, strictly speaking each component saving takes some time, but +/- several seconds doesn't matter
val nowInSeconds: Int = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()).toInt()
for (name in names) {
val start = if (timeLog == null) 0 else System.currentTimeMillis()
try {
val info = components.get(name)!!
var currentModificationCount = -1L
if (info.isModificationTrackingSupported) {
currentModificationCount = info.currentModificationCount
if (currentModificationCount == info.lastModificationCount) {
LOG.debug { "${if (isUseModificationCount) "Skip " else ""}$name: modificationCount ${currentModificationCount} equals to last saved" }
if (isUseModificationCount) {
continue
}
}
}
if (info.lastSaved != -1) {
if (isForce || (nowInSeconds - info.lastSaved) > NOT_ROAMABLE_COMPONENT_SAVE_THRESHOLD) {
info.lastSaved = nowInSeconds
}
else {
LOG.debug { "Skip $name: was already saved in last ${TimeUnit.SECONDS.toMinutes(NOT_ROAMABLE_COMPONENT_SAVE_THRESHOLD_DEFAULT.toLong())} minutes (lastSaved ${info.lastSaved}, now: $nowInSeconds)" }
continue
}
}
commitComponent(externalizationSession, info, name)
info.updateModificationCount(currentModificationCount)
}
catch (e: Throwable) {
errors.add(Exception("Cannot get $name component state", e))
}
timeLog?.let {
val duration = System.currentTimeMillis() - start
if (duration > 10) {
it.append("\n").append(name).append(" took ").append(duration).append(" ms: ").append((duration / 60000)).append(" min ").append(
((duration % 60000) / 1000)).append("sec")
}
}
}
if (timeLog != null && timeLog.length > timeLogPrefix.length) {
LOG.debug(timeLog.toString())
}
return errors
}
@TestOnly
override fun saveApplicationComponent(component: PersistentStateComponent<*>) {
val externalizationSession = storageManager.startExternalization() ?: return
val stateSpec = StoreUtil.getStateSpec(component)
commitComponent(externalizationSession, ComponentInfoImpl(component, stateSpec), null)
val sessions = externalizationSession.createSaveSessions()
if (sessions.isEmpty()) {
return
}
val absolutePath = Paths.get(storageManager.expandMacros(findNonDeprecated(stateSpec.storages).path)).toAbsolutePath().toString()
runUndoTransparentWriteAction {
try {
VfsRootAccess.allowRootAccess(absolutePath)
val errors: MutableList<Throwable> = SmartList<Throwable>()
doSave(sessions, errors = errors)
CompoundRuntimeException.throwIfNotEmpty(errors)
}
finally {
VfsRootAccess.disallowRootAccess(absolutePath)
}
}
}
private fun commitComponent(session: ExternalizationSession, info: ComponentInfo, componentName: String?) {
val component = info.component
@Suppress("DEPRECATION")
if (component is PersistentStateComponent<*>) {
component.state?.let {
val stateSpec = info.stateSpec!!
session.setState(getStorageSpecs(component, stateSpec, StateStorageOperation.WRITE), component, componentName ?: stateSpec.name, it)
}
}
else if (component is JDOMExternalizable) {
session.setStateInOldStorage(component, componentName ?: ComponentManagerImpl.getComponentName(component), component)
}
}
protected open fun doSave(saveSessions: List<SaveSession>,
readonlyFiles: MutableList<SaveSessionAndFile> = arrayListOf(),
errors: MutableList<Throwable>) {
for (session in saveSessions) {
executeSave(session, readonlyFiles, errors)
}
return
}
private fun initJdomExternalizable(@Suppress("DEPRECATION") component: JDOMExternalizable, componentName: String): String? {
doAddComponent(componentName, component, null)
if (loadPolicy != StateLoadPolicy.LOAD) {
return null
}
try {
getDefaultState(component, componentName, Element::class.java)?.let { component.readExternal(it) }
}
catch (e: Throwable) {
LOG.error(e)
}
val element = storageManager.getOldStorage(component, componentName, StateStorageOperation.READ)?.getState(component, componentName,
Element::class.java, null,
false) ?: return null
try {
component.readExternal(element)
}
catch (e: InvalidDataException) {
LOG.error(e)
return null
}
return componentName
}
private fun doAddComponent(name: String, component: Any, stateSpec: State?): ComponentInfo {
val newInfo = createComponentInfo(component, stateSpec)
val existing = components.put(name, newInfo)
if (existing != null && existing.component !== component) {
components.put(name, existing)
LOG.error("Conflicting component name '$name': ${existing.component.javaClass} and ${component.javaClass}")
return existing
}
return newInfo
}
private fun initComponent(info: ComponentInfo, changedStorages: Set<StateStorage>?, reloadData: Boolean): Boolean {
if (loadPolicy == StateLoadPolicy.NOT_LOAD) {
return false
}
@Suppress("UNCHECKED_CAST")
if (doInitComponent(info.stateSpec!!, info.component as PersistentStateComponent<Any>, changedStorages, reloadData)) {
// if component was initialized, update lastModificationCount
info.updateModificationCount()
return true
}
return false
}
private fun doInitComponent(stateSpec: State,
component: PersistentStateComponent<Any>,
changedStorages: Set<StateStorage>?,
reloadData: Boolean): Boolean {
val name = stateSpec.name
@Suppress("UNCHECKED_CAST")
val stateClass: Class<Any> = if (component is PersistenceStateAdapter) component.component::class.java as Class<Any>
else ComponentSerializationUtil.getStateClass<Any>(component.javaClass)
if (!stateSpec.defaultStateAsResource && LOG.isDebugEnabled && getDefaultState(component, name, stateClass) != null) {
LOG.error("$name has default state, but not marked to load it")
}
val defaultState = if (stateSpec.defaultStateAsResource) getDefaultState(component, name, stateClass) else null
if (loadPolicy == StateLoadPolicy.LOAD) {
val storageChooser = component as? StateStorageChooserEx
for (storageSpec in getStorageSpecs(component, stateSpec, StateStorageOperation.READ)) {
if (storageChooser?.getResolution(storageSpec, StateStorageOperation.READ) == Resolution.SKIP) {
continue
}
val storage = storageManager.getStateStorage(storageSpec)
val stateGetter = createStateGetter(isUseLoadedStateAsExistingForComponent(storage, name), storage, component, name, stateClass,
reloadData = reloadData)
var state = stateGetter.getState(defaultState)
if (state == null) {
if (changedStorages != null && changedStorages.contains(storage)) {
// state will be null if file deleted
// we must create empty (initial) state to reinit component
state = deserializeState(Element("state"), stateClass, null)!!
}
else {
continue
}
}
try {
component.loadState(state)
}
finally {
stateGetter.close()
}
return true
}
}
// we load default state even if isLoadComponentState false - required for app components (for example, at least one color scheme must exists)
if (defaultState == null) {
component.noStateLoaded()
}
else {
component.loadState(defaultState)
}
return true
}
// todo fix FacetManager
// use.loaded.state.as.existing used in upsource
private fun isUseLoadedStateAsExistingForComponent(storage: StateStorage, name: String): Boolean {
return isUseLoadedStateAsExisting(storage) &&
name != "AntConfiguration" &&
name != "ProjectModuleManager" /* why after loadState we get empty state on getState, test CMakeWorkspaceContentRootsTest */ &&
name != "FacetManager" &&
name != "ProjectRunConfigurationManager" && /* ProjectRunConfigurationManager is used only for IPR, avoid relatively cost call getState */
name != "NewModuleRootManager" /* will be changed only on actual user change, so, to speed up module loading, skip it */ &&
name != "DeprecatedModuleOptionManager" /* doesn't make sense to check it */ &&
SystemProperties.getBooleanProperty("use.loaded.state.as.existing", true)
}
protected open fun isUseLoadedStateAsExisting(storage: StateStorage): Boolean = (storage as? XmlElementStorage)?.roamingType != RoamingType.DISABLED
protected open fun getPathMacroManagerForDefaults(): PathMacroManager? = null
private fun <T : Any> getDefaultState(component: Any, componentName: String, stateClass: Class<T>): T? {
val url = DecodeDefaultsUtil.getDefaults(component, componentName) ?: return null
try {
val documentElement = JDOMXIncluder.resolve(JDOMUtil.loadDocument(url), url.toExternalForm()).detachRootElement()
getPathMacroManagerForDefaults()?.expandPaths(documentElement)
return deserializeState(documentElement, stateClass, null)
}
catch (e: Throwable) {
throw IOException("Error loading default state from $url", e)
}
}
protected open fun <T> getStorageSpecs(component: PersistentStateComponent<T>,
stateSpec: State,
operation: StateStorageOperation): List<Storage> {
val storages = stateSpec.storages
if (storages.size == 1 || component is StateStorageChooserEx) {
return storages.toList()
}
if (storages.isEmpty()) {
if (stateSpec.defaultStateAsResource) {
return emptyList()
}
throw AssertionError("No storage specified")
}
return storages.sortByDeprecated()
}
final override fun isReloadPossible(componentNames: Set<String>): Boolean = !componentNames.any { isNotReloadable(it) }
private fun isNotReloadable(name: String): Boolean {
val component = components.get(name)?.component ?: return false
return component !is PersistentStateComponent<*> || !StoreUtil.getStateSpec(component).reloadable
}
fun getNotReloadableComponents(componentNames: Collection<String>): Collection<String> {
var notReloadableComponents: MutableSet<String>? = null
for (componentName in componentNames) {
if (isNotReloadable(componentName)) {
if (notReloadableComponents == null) {
notReloadableComponents = LinkedHashSet()
}
notReloadableComponents.add(componentName)
}
}
return notReloadableComponents ?: emptySet()
}
override final fun reloadStates(componentNames: Set<String>, messageBus: MessageBus) {
runBatchUpdate(messageBus) {
reinitComponents(componentNames)
}
}
override final fun reloadState(componentClass: Class<out PersistentStateComponent<*>>) {
val stateSpec = StoreUtil.getStateSpecOrError(componentClass)
val info = components.get(stateSpec.name) ?: return
(info.component as? PersistentStateComponent<*>)?.let {
initComponent(info, emptySet(), true)
}
}
private fun reloadState(componentName: String, changedStorages: Set<StateStorage>): Boolean {
val info = components.get(componentName) ?: return false
if (info.component !is PersistentStateComponent<*>) {
return false
}
val changedStoragesEmpty = changedStorages.isEmpty()
initComponent(info, if (changedStoragesEmpty) null else changedStorages, changedStoragesEmpty)
return true
}
/**
* null if reloaded
* empty list if nothing to reload
* list of not reloadable components (reload is not performed)
*/
fun reload(changedStorages: Set<StateStorage>): Collection<String>? {
if (changedStorages.isEmpty()) {
return emptySet()
}
val componentNames = SmartHashSet<String>()
for (storage in changedStorages) {
try {
// we must update (reload in-memory storage data) even if non-reloadable component will be detected later
// not saved -> user does own modification -> new (on disk) state will be overwritten and not applied
storage.analyzeExternalChangesAndUpdateIfNeed(componentNames)
}
catch (e: Throwable) {
LOG.error(e)
}
}
if (componentNames.isEmpty) {
return emptySet()
}
val notReloadableComponents = getNotReloadableComponents(componentNames)
reinitComponents(componentNames, changedStorages, notReloadableComponents)
return if (notReloadableComponents.isEmpty()) null else notReloadableComponents
}
// used in settings repository plugin
/**
* You must call it in batch mode (use runBatchUpdate)
*/
fun reinitComponents(componentNames: Set<String>,
changedStorages: Set<StateStorage> = emptySet(),
notReloadableComponents: Collection<String> = emptySet()) {
for (componentName in componentNames) {
if (!notReloadableComponents.contains(componentName)) {
reloadState(componentName, changedStorages)
}
}
}
@TestOnly
fun removeComponent(name: String) {
components.remove(name)
}
}
internal fun executeSave(session: SaveSession, readonlyFiles: MutableList<SaveSessionAndFile>, errors: MutableList<Throwable>) {
try {
session.save()
}
catch (e: ReadOnlyModificationException) {
LOG.warn(e)
readonlyFiles.add(SaveSessionAndFile(e.session ?: session, e.file))
}
catch (e: Exception) {
errors.add(e)
}
}
private fun findNonDeprecated(storages: Array<Storage>) = storages.firstOrNull { !it.deprecated } ?: throw AssertionError(
"All storages are deprecated")
enum class StateLoadPolicy {
LOAD, LOAD_ONLY_DEFAULT, NOT_LOAD
}
internal fun Array<out Storage>.sortByDeprecated(): List<Storage> {
if (size < 2) {
return toList()
}
if (!first().deprecated) {
val othersAreDeprecated = (1 until size).any { get(it).deprecated }
if (othersAreDeprecated) {
return toList()
}
}
return sortedWith(deprecatedComparator)
}
private fun notifyUnknownMacros(store: IComponentStore, project: Project, componentName: String) {
val substitutor = store.storageManager.macroSubstitutor ?: return
val immutableMacros = substitutor.getUnknownMacros(componentName)
if (immutableMacros.isEmpty()) {
return
}
val macros = LinkedHashSet(immutableMacros)
AppUIUtil.invokeOnEdt(Runnable {
var notified: MutableList<String>? = null
val manager = NotificationsManager.getNotificationsManager()
for (notification in manager.getNotificationsOfType(UnknownMacroNotification::class.java, project)) {
if (notified == null) {
notified = SmartList<String>()
}
notified.addAll(notification.macros)
}
if (!notified.isNullOrEmpty()) {
macros.removeAll(notified!!)
}
if (macros.isEmpty()) {
return@Runnable
}
LOG.debug("Reporting unknown path macros $macros in component $componentName")
doNotify(macros, project, Collections.singletonMap(substitutor, store))
}, project.disposed)
}
|
apache-2.0
|
cd5eb5e5ad3c24df07af31feacfcc73d
| 37.333333 | 209 | 0.702721 | 5.116743 | false | false | false | false |
ktorio/ktor
|
buildSrc/src/main/kotlin/JsConfig.kt
|
1
|
1956
|
/*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
@file:Suppress("UNUSED_VARIABLE")
import org.gradle.api.*
import org.gradle.kotlin.dsl.*
import java.io.*
fun Project.configureJs() {
configureJsTasks()
kotlin {
sourceSets {
val jsTest by getting {
dependencies {
implementation(npm("puppeteer", "*"))
}
}
}
}
configureTestTask()
}
private fun Project.configureJsTasks() {
kotlin {
js {
nodejs {
testTask {
useMocha {
timeout = "10000"
}
}
}
browser {
testTask {
useKarma {
useChromeHeadless()
useConfigDirectory(File(project.rootProject.projectDir, "karma"))
}
}
}
val main by compilations.getting
main.kotlinOptions.apply {
metaInfo = true
sourceMap = true
moduleKind = "umd"
this.main = "noCall"
sourceMapEmbedSources = "always"
}
val test by compilations.getting
test.kotlinOptions.apply {
metaInfo = true
sourceMap = true
moduleKind = "umd"
this.main = "call"
sourceMapEmbedSources = "always"
}
}
}
}
private fun Project.configureTestTask() {
val shouldRunJsBrowserTest = !hasProperty("teamcity") || hasProperty("enable-js-tests")
val jsLegacyBrowserTest by tasks.getting
jsLegacyBrowserTest.onlyIf { shouldRunJsBrowserTest }
val jsIrBrowserTest by tasks.getting
jsIrBrowserTest.onlyIf { shouldRunJsBrowserTest }
}
|
apache-2.0
|
a219eb1598c79895ce1b3df41e524f87
| 25.08 | 119 | 0.503579 | 5.133858 | false | true | false | false |
inorichi/mangafeed
|
app/src/main/java/eu/kanade/tachiyomi/data/download/DownloadProvider.kt
|
2
|
5225
|
package eu.kanade.tachiyomi.data.download
import android.content.Context
import androidx.core.net.toUri
import com.hippo.unifile.UniFile
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.database.models.Chapter
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.preference.PreferencesHelper
import eu.kanade.tachiyomi.source.Source
import eu.kanade.tachiyomi.util.storage.DiskUtil
import eu.kanade.tachiyomi.util.system.logcat
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import logcat.LogPriority
import uy.kohesive.injekt.injectLazy
/**
* This class is used to provide the directories where the downloads should be saved.
* It uses the following path scheme: /<root downloads dir>/<source name>/<manga>/<chapter>
*
* @param context the application context.
*/
class DownloadProvider(private val context: Context) {
private val preferences: PreferencesHelper by injectLazy()
private val scope = MainScope()
/**
* The root directory for downloads.
*/
private var downloadsDir = preferences.downloadsDirectory().get().let {
val dir = UniFile.fromUri(context, it.toUri())
DiskUtil.createNoMediaFile(dir, context)
dir
}
init {
preferences.downloadsDirectory().asFlow()
.onEach { downloadsDir = UniFile.fromUri(context, it.toUri()) }
.launchIn(scope)
}
/**
* Returns the download directory for a manga. For internal use only.
*
* @param manga the manga to query.
* @param source the source of the manga.
*/
internal fun getMangaDir(manga: Manga, source: Source): UniFile {
try {
return downloadsDir
.createDirectory(getSourceDirName(source))
.createDirectory(getMangaDirName(manga))
} catch (e: Throwable) {
logcat(LogPriority.ERROR, e) { "Invalid download directory" }
throw Exception(context.getString(R.string.invalid_download_dir))
}
}
/**
* Returns the download directory for a source if it exists.
*
* @param source the source to query.
*/
fun findSourceDir(source: Source): UniFile? {
return downloadsDir.findFile(getSourceDirName(source), true)
}
/**
* Returns the download directory for a manga if it exists.
*
* @param manga the manga to query.
* @param source the source of the manga.
*/
fun findMangaDir(manga: Manga, source: Source): UniFile? {
val sourceDir = findSourceDir(source)
return sourceDir?.findFile(getMangaDirName(manga), true)
}
/**
* Returns the download directory for a chapter if it exists.
*
* @param chapter the chapter to query.
* @param manga the manga of the chapter.
* @param source the source of the chapter.
*/
fun findChapterDir(chapter: Chapter, manga: Manga, source: Source): UniFile? {
val mangaDir = findMangaDir(manga, source)
return getValidChapterDirNames(chapter).asSequence()
.mapNotNull { mangaDir?.findFile(it, true) }
.firstOrNull()
}
/**
* Returns a list of downloaded directories for the chapters that exist.
*
* @param chapters the chapters to query.
* @param manga the manga of the chapter.
* @param source the source of the chapter.
*/
fun findChapterDirs(chapters: List<Chapter>, manga: Manga, source: Source): List<UniFile> {
val mangaDir = findMangaDir(manga, source) ?: return emptyList()
return chapters.mapNotNull { chapter ->
getValidChapterDirNames(chapter).asSequence()
.mapNotNull { mangaDir.findFile(it) }
.firstOrNull()
}
}
/**
* Returns the download directory name for a source.
*
* @param source the source to query.
*/
fun getSourceDirName(source: Source): String {
return DiskUtil.buildValidFilename(source.toString())
}
/**
* Returns the download directory name for a manga.
*
* @param manga the manga to query.
*/
fun getMangaDirName(manga: Manga): String {
return DiskUtil.buildValidFilename(manga.title)
}
/**
* Returns the chapter directory name for a chapter.
*
* @param chapter the chapter to query.
*/
fun getChapterDirName(chapter: Chapter): String {
return DiskUtil.buildValidFilename(
when {
chapter.scanlator != null -> "${chapter.scanlator}_${chapter.name}"
else -> chapter.name
}
)
}
/**
* Returns valid downloaded chapter directory names.
*
* @param chapter the chapter to query.
*/
fun getValidChapterDirNames(chapter: Chapter): List<String> {
val chapterName = getChapterDirName(chapter)
return listOf(
// Folder of images
chapterName,
// Archived chapters
"$chapterName.cbz",
// Legacy chapter directory name used in v0.9.2 and before
DiskUtil.buildValidFilename(chapter.name)
)
}
}
|
apache-2.0
|
df80fc0d2ba5e02790cd8e43f99a822c
| 31.055215 | 95 | 0.644211 | 4.543478 | false | false | false | false |
cfieber/orca
|
orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/handler/AbortStageHandlerTest.kt
|
1
|
5253
|
/*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.q.handler
import com.netflix.spinnaker.orca.ExecutionStatus.*
import com.netflix.spinnaker.orca.events.StageComplete
import com.netflix.spinnaker.orca.fixture.pipeline
import com.netflix.spinnaker.orca.fixture.stage
import com.netflix.spinnaker.orca.pipeline.model.Execution.ExecutionType.PIPELINE
import com.netflix.spinnaker.orca.pipeline.model.SyntheticStageOwner.STAGE_BEFORE
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.orca.q.AbortStage
import com.netflix.spinnaker.orca.q.CancelStage
import com.netflix.spinnaker.orca.q.CompleteExecution
import com.netflix.spinnaker.orca.q.CompleteStage
import com.netflix.spinnaker.orca.time.toInstant
import com.netflix.spinnaker.q.Queue
import com.netflix.spinnaker.time.fixedClock
import com.nhaarman.mockito_kotlin.*
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.dsl.on
import org.jetbrains.spek.api.lifecycle.CachingMode.GROUP
import org.jetbrains.spek.subject.SubjectSpek
import org.springframework.context.ApplicationEventPublisher
object AbortStageHandlerTest : SubjectSpek<AbortStageHandler>({
val queue: Queue = mock()
val repository: ExecutionRepository = mock()
val publisher: ApplicationEventPublisher = mock()
val clock = fixedClock()
subject(GROUP) {
AbortStageHandler(queue, repository, publisher, clock)
}
fun resetMocks() {
reset(queue, repository, publisher)
}
describe("aborting a stage") {
given("a stage that already completed") {
val pipeline = pipeline {
application = "whatever"
stage {
refId = "1"
type = "whatever"
status = SUCCEEDED
}
}
val message = AbortStage(pipeline.stageByRef("1"))
beforeGroup {
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving a message") {
subject.handle(message)
}
it("does nothing at all") {
verifyZeroInteractions(queue)
verifyZeroInteractions(publisher)
verify(repository, never()).storeStage(any())
}
}
given("a top level stage") {
val pipeline = pipeline {
application = "whatever"
stage {
refId = "1"
type = "whatever"
status = RUNNING
}
}
val message = AbortStage(pipeline.stageByRef("1"))
beforeGroup {
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving a message") {
subject.handle(message)
}
it("marks the stage as TERMINAL") {
verify(repository).storeStage(check {
assertThat(it.status).isEqualTo(TERMINAL)
assertThat(it.endTime.toInstant()).isEqualTo(clock.instant())
})
}
it("cancels the stage") {
verify(queue).push(CancelStage(message))
}
it("completes the execution") {
verify(queue).push(CompleteExecution(message))
}
it("emits an event") {
verify(publisher).publishEvent(check<StageComplete> {
assertThat(it.status).isEqualTo(TERMINAL)
})
}
}
given("a synthetic level stage") {
val pipeline = pipeline {
application = "whatever"
stage {
refId = "1"
type = "whatever"
status = RUNNING
stage {
refId = "1<1"
type = "whatever"
status = RUNNING
syntheticStageOwner = STAGE_BEFORE
}
}
}
val message = AbortStage(pipeline.stageByRef("1<1"))
beforeGroup {
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving a message") {
subject.handle(message)
}
it("marks the stage as TERMINAL") {
verify(repository).storeStage(check {
assertThat(it.status).isEqualTo(TERMINAL)
assertThat(it.endTime.toInstant()).isEqualTo(clock.instant())
})
}
it("cancels the stage") {
verify(queue).push(CancelStage(message))
}
it("completes the parent stage") {
verify(queue).push(CompleteStage(pipeline.stageByRef("1")))
}
it("emits an event") {
verify(publisher).publishEvent(check<StageComplete> {
assertThat(it.status).isEqualTo(TERMINAL)
})
}
}
}
})
|
apache-2.0
|
867a54f356418225a83c7573529c3cc5
| 27.862637 | 81 | 0.660765 | 4.436655 | false | false | false | false |
airbnb/lottie-android
|
snapshot-tests/src/androidTest/java/com/airbnb/lottie/snapshots/tests/TextTestCase.kt
|
1
|
11013
|
package com.airbnb.lottie.snapshots.tests
import android.graphics.Typeface
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import com.airbnb.lottie.LottieProperty
import com.airbnb.lottie.TextDelegate
import com.airbnb.lottie.compose.LottieAnimation
import com.airbnb.lottie.compose.LottieCompositionSpec
import com.airbnb.lottie.compose.rememberLottieComposition
import com.airbnb.lottie.compose.rememberLottieDynamicProperties
import com.airbnb.lottie.compose.rememberLottieDynamicProperty
import com.airbnb.lottie.snapshots.LocalSnapshotReady
import com.airbnb.lottie.snapshots.SnapshotTestCase
import com.airbnb.lottie.snapshots.SnapshotTestCaseContext
import com.airbnb.lottie.snapshots.snapshotComposable
import com.airbnb.lottie.snapshots.withAnimationView
class TextTestCase : SnapshotTestCase {
override suspend fun SnapshotTestCaseContext.run() {
withAnimationView("Tests/DynamicText.json", "Dynamic Text", "Hello World") { animationView ->
val textDelegate = TextDelegate(animationView)
animationView.setTextDelegate(textDelegate)
textDelegate.setText("NAME", "Hello World")
}
withAnimationView("Tests/DynamicText.json", "Dynamic Text", "Hello World with getText") { animationView ->
val textDelegate = object : TextDelegate(animationView) {
override fun getText(input: String): String {
return when (input) {
"NAME" -> "Hello World"
else -> input
}
}
}
animationView.setTextDelegate(textDelegate)
}
withAnimationView("Tests/DynamicText.json", "Dynamic Text", "Emoji") { animationView ->
val textDelegate = TextDelegate(animationView)
animationView.setTextDelegate(textDelegate)
textDelegate.setText("NAME", "🔥💪💯")
}
withAnimationView("Tests/DynamicText.json", "Dynamic Text", "Taiwanese") { animationView ->
val textDelegate = TextDelegate(animationView)
animationView.setTextDelegate(textDelegate)
textDelegate.setText("NAME", "我的密碼")
}
withAnimationView("Tests/DynamicText.json", "Dynamic Text", "Fire Taiwanese") { animationView ->
val textDelegate = TextDelegate(animationView)
animationView.setTextDelegate(textDelegate)
textDelegate.setText("NAME", "🔥的A")
}
withAnimationView("Tests/DynamicText.json", "Dynamic Text", "Family man man girl boy") { animationView ->
val textDelegate = TextDelegate(animationView)
animationView.setTextDelegate(textDelegate)
textDelegate.setText("NAME", "\uD83D\uDC68\u200D\uD83D\uDC68\u200D\uD83D\uDC67\u200D\uD83D\uDC66")
}
withAnimationView("Tests/DynamicText.json", "Dynamic Text", "Family woman woman girl girl") { animationView ->
val textDelegate = TextDelegate(animationView)
animationView.setTextDelegate(textDelegate)
textDelegate.setText("NAME", "\uD83D\uDC69\u200D\uD83D\uDC69\u200D\uD83D\uDC67\u200D\uD83D\uDC67")
}
withAnimationView("Tests/DynamicText.json", "Dynamic Text", "Brown Police Man") { animationView ->
val textDelegate = TextDelegate(animationView)
animationView.setTextDelegate(textDelegate)
textDelegate.setText("NAME", "\uD83D\uDC6E\uD83C\uDFFF\u200D♀️")
}
withAnimationView("Tests/DynamicText.json", "Dynamic Text", "Family and Brown Police Man") { animationView ->
val textDelegate = TextDelegate(animationView)
animationView.setTextDelegate(textDelegate)
textDelegate.setText("NAME", "\uD83D\uDC68\u200D\uD83D\uDC68\u200D\uD83D\uDC67\u200D\uD83D\uDC67\uD83D\uDC6E\uD83C\uDFFF\u200D♀️")
}
withAnimationView("Tests/DynamicText.json", "Dynamic Text", "Family, Brown Police Man, emoji and chars") { animationView ->
val textDelegate = TextDelegate(animationView)
animationView.setTextDelegate(textDelegate)
textDelegate.setText("NAME", "🔥\uD83D\uDC68\u200D\uD83D\uDC68\u200D\uD83D\uDC67\u200D\uD83D\uDC67\uD83D\uDC6E\uD83C\uDFFF\u200D♀的Aabc️")
}
withAnimationView("Tests/DynamicText.json", "Dynamic Text", "Fire English Fire Brown Police Man Fire") { animationView ->
val textDelegate = TextDelegate(animationView)
animationView.setTextDelegate(textDelegate)
textDelegate.setText("NAME", "🔥c️🔥\uD83D\uDC6E\uD83C\uDFFF\u200D♀️\uD83D\uDD25")
}
withAnimationView("Tests/DynamicText.json", "Dynamic Text", "American Flag") { animationView ->
val textDelegate = TextDelegate(animationView)
animationView.setTextDelegate(textDelegate)
textDelegate.setText("NAME", "\uD83C\uDDFA\uD83C\uDDF8")
}
withAnimationView("Tests/DynamicText.json", "Dynamic Text", "Checkered Flag") { animationView ->
val textDelegate = TextDelegate(animationView)
animationView.setTextDelegate(textDelegate)
textDelegate.setText("NAME", "\uD83C\uDFC1")
}
withAnimationView("Tests/DynamicText.json", "Dynamic Text", "Pirate Flag") { animationView ->
val textDelegate = TextDelegate(animationView)
animationView.setTextDelegate(textDelegate)
textDelegate.setText("NAME", "\uD83C\uDFF4\u200D☠️")
}
withAnimationView("Tests/DynamicText.json", "Dynamic Text", "3 Oclock") { animationView ->
val textDelegate = TextDelegate(animationView)
animationView.setTextDelegate(textDelegate)
textDelegate.setText("NAME", "\uD83D\uDD52")
}
withAnimationView("Tests/DynamicText.json", "Dynamic Text", "Woman frowning") { animationView ->
val textDelegate = TextDelegate(animationView)
animationView.setTextDelegate(textDelegate)
textDelegate.setText("NAME", "\uD83D\uDE4D\u200D♀️")
}
withAnimationView("Tests/DynamicText.json", "Dynamic Text", "Gay couple") { animationView ->
val textDelegate = TextDelegate(animationView)
animationView.setTextDelegate(textDelegate)
textDelegate.setText("NAME", "\uD83D\uDC68\u200D❤️\u200D\uD83D\uDC68️")
}
withAnimationView("Tests/DynamicText.json", "Dynamic Text", "Lesbian couple") { animationView ->
val textDelegate = TextDelegate(animationView)
animationView.setTextDelegate(textDelegate)
textDelegate.setText("NAME", "\uD83D\uDC69\u200D❤️\u200D\uD83D\uDC69️")
}
withAnimationView("Tests/DynamicText.json", "Dynamic Text", "Straight couple") { animationView ->
val textDelegate = TextDelegate(animationView)
animationView.setTextDelegate(textDelegate)
textDelegate.setText("NAME", "\uD83D\uDC91")
}
snapshotComposable("Compose FontMap", "Text") {
val composition by rememberLottieComposition(LottieCompositionSpec.Asset("Tests/Text.json"))
val snapshotReady = LocalSnapshotReady.current
LaunchedEffect(snapshotReady, composition != null) {
snapshotReady.value = composition != null
}
LottieAnimation(composition, { 0f }, fontMap = mapOf("Helvetica" to Typeface.SERIF))
}
snapshotComposable("Compose Dynamic Text", "Emoji") {
val composition by rememberLottieComposition(LottieCompositionSpec.Asset("Tests/DynamicText.json"))
val snapshotReady = LocalSnapshotReady.current
LaunchedEffect(snapshotReady, composition != null) {
snapshotReady.value = composition != null
}
val dynamicProperties = rememberLottieDynamicProperties(
rememberLottieDynamicProperty(LottieProperty.TEXT, "NAME") {
"🔥💪💯"
},
)
LottieAnimation(composition, { 0f }, dynamicProperties = dynamicProperties)
}
snapshotComposable("Compose Dynamic Text", "Taiwanese") {
val composition by rememberLottieComposition(LottieCompositionSpec.Asset("Tests/DynamicText.json"))
val snapshotReady = LocalSnapshotReady.current
LaunchedEffect(snapshotReady, composition != null) {
snapshotReady.value = composition != null
}
val dynamicProperties = rememberLottieDynamicProperties(
rememberLottieDynamicProperty(LottieProperty.TEXT, "我的密碼", "NAME"),
)
LottieAnimation(composition, { 0f }, dynamicProperties = dynamicProperties)
}
snapshotComposable("Compose Dynamic Text", "Hindi") {
val composition by rememberLottieComposition(LottieCompositionSpec.Asset("Tests/DynamicText.json"))
val snapshotReady = LocalSnapshotReady.current
LaunchedEffect(snapshotReady, composition != null) {
snapshotReady.value = composition != null
}
val dynamicProperties = rememberLottieDynamicProperties(
rememberLottieDynamicProperty(LottieProperty.TEXT, "आपका लेख", "NAME"),
)
LottieAnimation(composition, { 0f }, dynamicProperties = dynamicProperties)
}
snapshotComposable("Compose Dynamic Text", "FrameInfo.startValue") {
val composition by rememberLottieComposition(LottieCompositionSpec.Asset("Tests/DynamicText.json"))
val snapshotReady = LocalSnapshotReady.current
LaunchedEffect(snapshotReady, composition != null) {
snapshotReady.value = composition != null
}
val dynamicProperties = rememberLottieDynamicProperties(
rememberLottieDynamicProperty(LottieProperty.TEXT, "NAME") { frameInfo ->
"${frameInfo.startValue}!!!"
},
)
LottieAnimation(composition, { 0f }, dynamicProperties = dynamicProperties)
}
snapshotComposable("Compose Dynamic Text", "FrameInfo.endValue") {
val composition by rememberLottieComposition(LottieCompositionSpec.Asset("Tests/DynamicText.json"))
val snapshotReady = LocalSnapshotReady.current
LaunchedEffect(snapshotReady, composition != null) {
snapshotReady.value = composition != null
}
val dynamicProperties = rememberLottieDynamicProperties(
rememberLottieDynamicProperty(LottieProperty.TEXT, "NAME") { frameInfo ->
"${frameInfo.endValue}!!!"
},
)
LottieAnimation(composition, { 0f }, dynamicProperties = dynamicProperties)
}
}
}
|
apache-2.0
|
5f14ba8e8db5710e94b3b3e0875ebc33
| 49.518519 | 148 | 0.65796 | 4.758395 | false | true | false | false |
hea3ven/IdolScraper
|
src/main/kotlin/com/hea3ven/idolscraper/ui/MainWindow.kt
|
1
|
8589
|
package com.hea3ven.idolscraper.ui
import com.hea3ven.idolscraper.Config
import com.hea3ven.idolscraper.PreserveOriginalSaveStrategy
import com.hea3ven.idolscraper.getFileNameStrategy
import com.hea3ven.idolscraper.getSaveStrategy
import com.hea3ven.idolscraper.page.ScrapingTask
import com.hea3ven.idolscraper.page.getPageHandler
import java.awt.*
import java.awt.event.ActionEvent
import java.awt.event.FocusEvent
import java.awt.event.FocusListener
import java.io.BufferedInputStream
import java.io.InputStream
import java.io.PrintWriter
import java.io.StringWriter
import java.net.IDN
import java.net.MalformedURLException
import java.net.URL
import java.nio.file.Files
import java.nio.file.Paths
import javax.imageio.ImageIO
import javax.swing.*
import javax.swing.border.EmptyBorder
class MainWindow : JFrame("Idol Scraper") {
private val dirChooser = JFileChooser().apply {
dialogTitle = "Target destination"
fileSelectionMode = JFileChooser.DIRECTORIES_ONLY
isAcceptAllFileFilterUsed = false
selectedFile = Config.getDestinationDir()
}
init {
defaultCloseOperation = EXIT_ON_CLOSE
size = Dimension(600, 900)
layout = GridBagLayout()
val urlLbl = JLabel("URL:")
urlLbl.border = EmptyBorder(0, 5, 0, 0)
val urlTxt = JTextField()
urlTxt.addFocusListener(object : FocusListener {
override fun focusLost(e: FocusEvent?) {
}
override fun focusGained(e: FocusEvent?) {
urlTxt.select(0, urlTxt.text.length)
}
})
val destLbl = JLabel("Destination:")
destLbl.border = EmptyBorder(0, 5, 0, 0)
val destTxt = JTextField(Config.getDestinationDir()?.absolutePath ?: "")
destTxt.addFocusListener(object : FocusListener {
override fun focusLost(e: FocusEvent?) {
}
override fun focusGained(e: FocusEvent?) {
destTxt.select(0, destTxt.text.length)
}
})
val destBtn = JButton()
destBtn.action = object : AbstractAction() {
override fun actionPerformed(e: ActionEvent?) {
if (dirChooser.showOpenDialog(this@MainWindow) == JFileChooser.APPROVE_OPTION) {
destTxt.text = dirChooser.selectedFile.absolutePath
Config.setDestinationDir(dirChooser.selectedFile)
}
}
}
destBtn.text = "..."
val formatLbl = JLabel("Format:")
formatLbl.border = EmptyBorder(0, 5, 0, 0)
val formatCb = JComboBox(arrayOf("original", "png", "jpg"))
formatCb.preferredSize = Dimension(100, 25)
formatCb.border = EmptyBorder(2, 2, 2, 5)
formatCb.selectedItem = Config.getFormat()
formatCb.action = object : AbstractAction() {
override fun actionPerformed(e: ActionEvent?) {
Config.setFormat(formatCb.selectedItem as String?)
}
}
val fileNameLbl = JLabel("File Name:")
fileNameLbl.border = EmptyBorder(0, 5, 0, 0)
val fileNameCb = JComboBox(arrayOf("original", "numbered"))
fileNameCb.preferredSize = Dimension(100, 25)
fileNameCb.border = EmptyBorder(2, 2, 2, 5)
fileNameCb.selectedItem = Config.getFileNameFormat()
fileNameCb.action = object : AbstractAction() {
override fun actionPerformed(e: ActionEvent?) {
Config.setFileNameFormat(fileNameCb.selectedItem as String?)
}
}
val scanBtn = JButton()
scanBtn.preferredSize = Dimension(72, 22)
val logTxtArea = JTextArea()
logTxtArea.isEditable = false
val logTxtAreaScrlPn = JScrollPane(logTxtArea)
scanBtn.action = object : AbstractAction() {
override fun actionPerformed(e: ActionEvent?) {
val destDir1 = Paths.get(destTxt.text)
if (destTxt.text.length == 0 || !Files.exists(destDir1) || !Files.isDirectory(destDir1)) {
logTxtArea.text += "Invalid destination directory"
return
}
val fileNameStgy = fileNameCb.selectedItem as String
val formatStgy = formatCb.selectedItem as String
val task = ScrapingTask(destDir1, getSaveStrategy(formatStgy),
getFileNameStrategy(fileNameStgy))
val worker = object : SwingWorker<Any, String>() {
override fun doInBackground() {
task.log = { publish(it) }
try {
val url = URL(urlTxt.text)
task.url = URL(url.protocol, IDN.toASCII(url.host), url.port, url.file)
} catch(e: MalformedURLException) {
task.log("Invalid url")
return
}
val pageHandler = getPageHandler(task.url)
pageHandler.handle(task, task.url)
try {
task.images.forEach {
downloadImage(it)
}
task.log("Done")
} catch(e: Exception) {
val ss = StringWriter()
e.printStackTrace(PrintWriter(ss))
task.log("Unknown error: " + ss.toString())
}
return
}
private fun downloadImage(urlString: String) {
val url: URL
try {
url = URL(task.url, urlString)
} catch(e: MalformedURLException) {
task.log("Bad url " + urlString)
return
}
try {
val conn = url.openConnection()
BufferedInputStream(conn.inputStream).use { stream ->
if (conn.contentType == "video/mp4") {
PreserveOriginalSaveStrategy().save(task, conn, stream)
} else {
stream.mark(Int.MAX_VALUE)
val size = getImageSize(stream)
if (size == null) {
task.log(" Error: unable to download")
return
}
stream.reset()
if (size.first < 300 || size.second < 300) {
// Ignore really small images
return
}
task.log("Downloading image " + url)
task.log(" Size " + size.first + "x" + size.second)
if ((size.first < 800 || size.second < 800)
&& (size.first * size.second < 600 * 600)) {
task.log(" Too small, not saving")
return
}
task.saveStrategy.save(task, conn, stream)
}
}
} catch(e: Exception) {
task.log(" Error: " + e.toString())
return
}
}
private fun getImageSize(stream: InputStream): Pair<Int, Int>? {
ImageIO.createImageInputStream(stream).use {
val readers = ImageIO.getImageReaders(it)
if (readers.hasNext()) {
val reader = readers.next()
try {
reader.input = it
return reader.getWidth(0) to reader.getHeight(0)
} finally {
reader.dispose()
}
}
}
return null
}
override fun process(chunks: MutableList<String>) {
val vertScroll = logTxtAreaScrlPn.verticalScrollBar
val doScroll = vertScroll.value == vertScroll.maximum
chunks.forEach { logTxtArea.text += it + "\n" }
if (doScroll)
vertScroll.value = vertScroll.maximum
}
override fun done() {
super.done()
scanBtn.isEnabled = true
}
}
scanBtn.isEnabled = false
worker.execute()
}
}
scanBtn.text = "Scan"
add(urlLbl, GridBagConstraints().apply {
gridy = 0
fill = GridBagConstraints.HORIZONTAL
weightx = 0.0
weighty = 0.0
})
add(JPanel().apply {
border = EmptyBorder(5, 2, 2, 5)
layout = BorderLayout()
add(urlTxt, BorderLayout.CENTER)
}, GridBagConstraints().apply {
gridy = 0
gridx = 1
gridwidth = 2
fill = GridBagConstraints.HORIZONTAL
weightx = 1.0
weighty = 0.0
})
add(destLbl, GridBagConstraints().apply {
gridy = 1
fill = GridBagConstraints.HORIZONTAL
weightx = 0.0
weighty = 0.0
})
add(JPanel().apply {
layout = GridBagLayout()
border = EmptyBorder(2, 2, 2, 5)
add(destTxt, GridBagConstraints().apply {
weightx = 1.0
fill = GridBagConstraints.HORIZONTAL
})
add(destBtn, GridBagConstraints().apply {
weightx = 0.0
})
}, GridBagConstraints().apply {
gridy = 1
gridx = 1
gridwidth = 2
fill = GridBagConstraints.HORIZONTAL
weightx = 1.0
weighty = 0.0
})
add(JPanel().apply {
layout = FlowLayout(FlowLayout.LEFT, 0, 0)
add(formatLbl)
add(formatCb)
add(fileNameLbl)
add(fileNameCb)
}, GridBagConstraints().apply {
gridy = 2
gridwidth = 2
fill = GridBagConstraints.HORIZONTAL
weightx = 0.0
weighty = 0.0
})
add(JPanel(), GridBagConstraints().apply {
gridy = 3
gridx = 1
fill = GridBagConstraints.HORIZONTAL
weightx = 1.0
})
add(JPanel().apply {
add(scanBtn)
}, GridBagConstraints().apply {
gridy = 3
gridx = 2
fill = GridBagConstraints.NONE
weightx = 0.0
weighty = 0.0
})
add(JPanel().apply {
layout = BorderLayout()
border = EmptyBorder(0, 5, 5, 5)
add(logTxtAreaScrlPn, BorderLayout.CENTER)
}, GridBagConstraints().apply {
gridy = 4
gridx = 0
gridwidth = 3
fill = GridBagConstraints.BOTH
weightx = 1.0
weighty = 1.0
})
}
}
|
mit
|
c82fb499df954994fba97ea7cad318c9
| 26.353503 | 94 | 0.65025 | 3.517199 | false | false | false | false |
pureal-code/pureal-os
|
traits/src/net/pureal/traits/graphics/Color.kt
|
1
|
1353
|
package net.pureal.traits.graphics
import net.pureal.traits.*
trait Color {
val r: Number
val g: Number
val b: Number
val a: Number
override fun equals(other: Any?) = if (other is Color) (r.toDouble() == other.r.toDouble() && g.toDouble() == other.g.toDouble() && b.toDouble() == other.b.toDouble() && a.toDouble() == other.a.toDouble()) else false
fun times(factor: Number): Color {
val f = factor.toDouble()
return color(r = r.toDouble() * f, g = g.toDouble() * f, b = b.toDouble() * f, a = a.toDouble() * f)
}
fun plus(other: Color) = color(r = r.toDouble() + other.r.toDouble(), g = g.toDouble() + other.g.toDouble(), b = b.toDouble() + other.b.toDouble(), a = a.toDouble() + other.a.toDouble())
override fun toString() = "color(r=${r.toDouble()}, g=${g.toDouble()}, b=${b.toDouble()}, a=${a.toDouble()})"
}
fun color(r: Number = 0, g: Number = 0, b: Number = 0, a: Number = 1): Color = object : Color {
override val r = r
override val g = g
override val b = b
override val a = a
}
object Colors {
val black = color()
val red = color(r = 1)
val green = color(g = 1)
val blue = color(b = 1)
fun gray(brightness: Number) = color(brightness, brightness, brightness)
val gray = gray(.5)
val white = color(1, 1, 1)
val transparent = color(a = 0)
}
|
bsd-3-clause
|
d33fa2b8da32adeb0ac57c27a86d52ca
| 34.631579 | 220 | 0.593496 | 3.244604 | false | false | false | false |
jovr/imgui
|
core/src/main/kotlin/imgui/demo/showExampleApp/Console.kt
|
2
|
13520
|
package imgui.demo.showExampleApp
import glm_.b
import glm_.vec2.Vec2
import glm_.vec4.Vec4
import imgui.*
import imgui.ImGui.begin
import imgui.ImGui.beginChild
import imgui.ImGui.beginPopup
import imgui.ImGui.beginPopupContextWindow
import imgui.ImGui.button
import imgui.ImGui.checkbox
import imgui.ImGui.end
import imgui.ImGui.endChild
import imgui.ImGui.endPopup
import imgui.ImGui.frameHeightWithSpacing
import imgui.ImGui.inputText
import imgui.ImGui.logFinish
import imgui.ImGui.logToClipboard
import imgui.ImGui.menuItem
import imgui.ImGui.openPopup
import imgui.ImGui.popStyleColor
import imgui.ImGui.popStyleVar
import imgui.ImGui.pushStyleColor
import imgui.ImGui.pushStyleVar
import imgui.ImGui.sameLine
import imgui.ImGui.scrollMaxY
import imgui.ImGui.scrollY
import imgui.ImGui.selectable
import imgui.ImGui.separator
import imgui.ImGui.setItemDefaultFocus
import imgui.ImGui.setKeyboardFocusHere
import imgui.ImGui.setNextWindowSize
import imgui.ImGui.setScrollHereY
import imgui.ImGui.smallButton
import imgui.ImGui.style
import imgui.ImGui.textUnformatted
import imgui.ImGui.textWrapped
import imgui.classes.InputTextCallbackData
import imgui.classes.TextFilter
import imgui.dsl.popupContextItem
import uno.kotlin.getValue
import uno.kotlin.setValue
import java.util.*
import kotlin.reflect.KMutableProperty0
import imgui.InputTextFlag as Itf
import imgui.WindowFlag as Wf
object Console {
// Demonstrate creating a simple console window, with scrolling, filtering, completion and history.
// For the console example, we are using a more C++ like approach of declaring a class to hold both data and functions.
val console = ExampleAppConsole()
operator fun invoke(open: KMutableProperty0<Boolean>) = console.draw("Example: Console", open)
class ExampleAppConsole {
val inputBuf = ByteArray(256)
val items = ArrayList<String>()
// "CLASSIFY" is here to provide the test case where "C"+[tab] completes to "CL" and display multiple matches.
val commands = arrayListOf("HELP", "HISTORY", "CLEAR", "CLASSIFY")
val history = ArrayList<String>()
/** -1: new line, 0..History.Size-1 browsing history. */
var historyPos = -1
val filter = TextFilter()
var autoScroll = true
var scrollToBottom = false
init {
addLog("Welcome to Dear ImGui!")
}
fun clearLog() = items.clear()
fun addLog(fmt: String, vararg args: Any) {
items += fmt.format(*args)
}
fun draw(title: String, pOpen: KMutableProperty0<Boolean>) {
var open by pOpen
setNextWindowSize(Vec2(520, 600), Cond.FirstUseEver)
if (!begin(title, pOpen)) {
end()
return
}
// As a specific feature guaranteed by the library, after calling Begin() the last Item represent the title bar.
// So e.g. IsItemHovered() will return true when hovering the title bar.
// Here we create a context menu only available from the title bar.
popupContextItem { if (menuItem("Close Console")) open = false }
textWrapped(
"This example implements a console with basic coloring, completion (TAB key) and history (Up/Down keys). A more elaborate "
+ "implementation may want to store entries along with extra data such as timestamp, emitter, etc.")
textWrapped("Enter 'HELP' for help.")
if (smallButton("Add Debug Text")) {
addLog("%d some text",
items.size); addLog("some more text"); addLog("display very important message here!"); }
sameLine()
if (smallButton("Add Debug Error")) addLog("[error] something went wrong")
sameLine()
if (smallButton("Clear")) clearLog()
sameLine()
val copyToClipboard = smallButton("Copy")
//var t = 0.0; if (ImGui.time - t > 0.02f) { t = ImGui.time; addLog("Spam %f", t); }
separator()
// Options menu
if (beginPopup("Options")) {
checkbox("Auto-scroll", ::autoScroll)
endPopup()
}
// Options, Filter
if (button("Options")) openPopup("Options")
sameLine()
filter.draw("Filter (\"incl,-excl\") (\"error\")", 180f)
separator()
// Reserve enough left-over height for 1 separator + 1 input text
val footerHeightToReserve = style.itemSpacing.y + frameHeightWithSpacing
beginChild("ScrollingRegion", Vec2(0, -footerHeightToReserve), false, Wf.HorizontalScrollbar.i)
if (beginPopupContextWindow()) {
if (selectable("Clear")) clearLog()
endPopup()
}
// Display every line as a separate entry so we can change their color or add custom widgets.
// If you only want raw text you can use ImGui::TextUnformatted(log.begin(), log.end());
// NB- if you have thousands of entries this approach may be too inefficient and may require user-side clipping
// to only process visible items. The clipper will automatically measure the height of your first item and then
// "seek" to display only items in the visible area.
// To use the clipper we can replace your standard loop:
// for (int i = 0; i < Items.Size; i++)
// With:
// ImGuiListClipper clipper;
// clipper.Begin(Items.Size);
// while (clipper.Step())
// for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)
// - That your items are evenly spaced (same height)
// - That you have cheap random access to your elements (you can access them given their index,
// without processing all the ones before)
// You cannot this code as-is if a filter is active because it breaks the 'cheap random-access' property.
// We would need random-access on the post-filtered list.
// A typical application wanting coarse clipping and filtering may want to pre-compute an array of indices
// or offsets of items that passed the filtering test, recomputing this array when user changes the filter,
// and appending newly elements as they are inserted. This is left as a task to the user until we can manage
// to improve this example code!
// If your items are of variable height:
// - Split them into same height items would be simpler and facilitate random-seeking into your list.
// - Consider using manual call to IsRectVisible() and skipping extraneous decoration from your items.
pushStyleVar(StyleVar.ItemSpacing, Vec2(4, 1)) // Tighten spacing
if (copyToClipboard) logToClipboard()
for (i in items) {
if (!filter.passFilter(i)) continue
// Normally you would store more information in your item than just a string.
// (e.g. make Items[] an array of structure, store color/type etc.)
var color: Vec4? = null
if ("[error]" in i) color = Vec4(1f, 0.4f, 0.4f, 1f)
else if (i.startsWith("# ")) color = Vec4(1f, 0.8f, 0.6f, 1f)
if (color != null) pushStyleColor(Col.Text, color)
textUnformatted(i)
if (color != null) popStyleColor()
}
if (copyToClipboard) logFinish()
if (scrollToBottom || (autoScroll && scrollY >= scrollMaxY)) setScrollHereY(1f)
scrollToBottom = false
popStyleVar()
endChild()
separator()
// Command-line
var reclaimFocus = false
val inputTextFlags = Itf.EnterReturnsTrue or Itf.CallbackCompletion or Itf.CallbackHistory
if (inputText("Input", inputBuf, inputTextFlags, textEditCallbackStub, this)) {
val s = inputBuf.cStr.trimEnd()
if (s.isNotEmpty()) execCommand(s)
reclaimFocus = true
}
setItemDefaultFocus()
if (reclaimFocus) setKeyboardFocusHere(-1)
end()
}
fun execCommand(cmdLine: String) {
addLog("# $cmdLine\n")
// Insert into history. First find match and delete it so it can be pushed to the back.
// This isn't trying to be smart or optimal.
historyPos = -1
history -= cmdLine
history += cmdLine
// Process command
when (cmdLine.toUpperCase()) {
"CLEAR" -> clearLog()
"HELP" -> {
addLog("Commands:")
commands.forEach { addLog("- $it") }
}
"HISTORY" -> {
val first = history.size - 10
for (i in (if (first > 0) first else 0) until history.size) addLog("%3d: ${history[i]}\n", i)
}
else -> addLog("Unknown command: '$cmdLine'\n")
}
// On command input, we scroll to bottom even if AutoScroll==false
scrollToBottom = true
}
// In C++11 you'd be better off using lambdas for this sort of forwarding callbacks
val textEditCallbackStub: InputTextCallback = { data: InputTextCallbackData ->
(data.userData as ExampleAppConsole).inputTextCallback(data)
}
fun inputTextCallback(data: InputTextCallbackData): Boolean {
when (data.eventFlag) {
imgui.InputTextFlag.CallbackCompletion.i -> {
val wordEnd = data.cursorPos
var wordStart = wordEnd
while (wordStart > 0) {
val c = data.buf[wordStart]
if (c == ' '.b || c == '\t'.b || c == ','.b || c == ';'.b) break
wordStart--
}
val word = data.buf.copyOfRange(wordStart, wordEnd).cStr
val candidates = ArrayList<String>()
for (c in commands) if (c.startsWith(word)) candidates += c
when { // No match
candidates.isEmpty() -> addLog("No match for \"%s\"!\n",
word) // Single match. Delete the beginning of the word and replace it entirely so we've got nice casing.
candidates.size == 1 -> { // Single match. Delete the beginning of the word and replace it entirely so we've got nice casing.
data.deleteChars(wordStart, wordEnd)
data.insertChars(data.cursorPos, candidates[0])
data.insertChars(data.cursorPos, " ")
} // Multiple matches. Complete as much as we can..
// So inputing "C"+Tab will complete to "CL" then display "CLEAR" and "CLASSIFY" as matches.
else -> { // Multiple matches. Complete as much as we can..
// So inputing "C"+Tab will complete to "CL" then display "CLEAR" and "CLASSIFY" as matches.
var matchLen = wordEnd - wordStart
while (true) {
var c = 0.toChar()
var allCandidatesMatch = true
var i = 0
while ((i < candidates.size) and allCandidatesMatch) {
if (i == 0) c = candidates[i][matchLen].toUpperCase()
else if ((c == 0.toChar()) or (c != candidates[i][matchLen].toUpperCase())) allCandidatesMatch =
false
++i
}
if (!allCandidatesMatch) break
matchLen++
}
if (matchLen > 0) {
data.deleteChars(wordStart, wordEnd - wordStart)
data.insertChars(data.cursorPos, candidates[0].toByteArray(), matchLen)
}
}
}
}
Itf.CallbackHistory.i -> {
val prevHistoryPos = historyPos
if (data.eventKey == Key.UpArrow) {
if (historyPos == -1) historyPos = history.size - 1
else --historyPos
} else if (data.eventKey == Key.DownArrow) {
if (historyPos != -1) {
if (++historyPos >= history.size) --historyPos
}
}
// A better implementation would preserve the data on the current input line along with cursor position.
if (prevHistoryPos != historyPos) {
val historyStr = if (historyPos >= 0) history[historyPos] else ""
data.deleteChars(0, data.bufTextLen)
data.insertChars(0, historyStr)
}
}
}
return false
}
}
}
|
mit
|
41e18f66d5705541f7ea0f50dc72883b
| 44.07 | 149 | 0.55821 | 4.838941 | false | false | false | false |
JetBrains/spek
|
spek-ide-plugin-intellij-idea/src/main/kotlin/org/spekframework/intellij/SpekJvmSettingsEditor.kt
|
1
|
3119
|
package org.spekframework.intellij
import com.intellij.application.options.ModulesComboBox
import com.intellij.execution.ui.CommonJavaParametersPanel
import com.intellij.execution.ui.ConfigurationModuleSelector
import com.intellij.execution.ui.DefaultJreSelector
import com.intellij.execution.ui.JrePathEditor
import com.intellij.openapi.module.Module
import com.intellij.openapi.options.SettingsEditor
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.LabeledComponent
import com.intellij.ui.TextFieldWithHistory
import org.spekframework.spek2.runtime.scope.PathBuilder
import javax.swing.JPanel
import kotlin.properties.Delegates
/**
* @author Ranie Jade Ramiso
*/
class SpekJvmSettingsEditor(project: Project): SettingsEditor<SpekJvmRunConfiguration>() {
private lateinit var panel: JPanel
private lateinit var mainPanel: JPanel
private lateinit var commonJavaParameters: CommonJavaParametersPanel
private lateinit var module: LabeledComponent<ModulesComboBox>
private lateinit var jrePathEditor: JrePathEditor
private lateinit var path: LabeledComponent<TextFieldWithHistory>
var moduleSelector: ConfigurationModuleSelector
private var selectedModule: Module?
get() {
return module.component.selectedModule
}
set(value) {
module.component.selectedModule = value
}
private var selectedPath by Delegates.observable(PathBuilder.ROOT) { _, _, value ->
path.component.setTextAndAddToHistory(value.toString())
}
init {
module.component.fillModules(project)
moduleSelector = ConfigurationModuleSelector(project, module.component)
jrePathEditor.setDefaultJreSelector(DefaultJreSelector.fromModuleDependencies(module.component, false))
commonJavaParameters.setModuleContext(selectedModule)
commonJavaParameters.setHasModuleMacro()
module.component.addActionListener {
commonJavaParameters.setModuleContext(selectedModule)
}
}
override fun resetEditorFrom(configuration: SpekJvmRunConfiguration) {
selectedModule = configuration.configurationModule.module
moduleSelector.reset(configuration)
commonJavaParameters.reset(configuration)
selectedPath = configuration.data.path
jrePathEditor.setPathOrName(configuration.alternativeJrePath, configuration.isAlternativeJrePathEnabled)
}
override fun applyEditorTo(configuration: SpekJvmRunConfiguration) {
configuration.alternativeJrePath = jrePathEditor.jrePathOrName
configuration.isAlternativeJrePathEnabled = jrePathEditor.isAlternativeJreSelected
configuration.setModule(selectedModule)
moduleSelector.applyTo(configuration)
commonJavaParameters.applyTo(configuration)
configuration.data.path = selectedPath
}
override fun createEditor() = panel
private fun createUIComponents() {
path = LabeledComponent.create(
TextFieldWithHistory(),
"Scope", "West"
)
path.component.isEditable = false
}
}
|
bsd-3-clause
|
2fcac779df6614bf6de4b7a58a3cebfc
| 37.036585 | 112 | 0.762103 | 5.331624 | false | true | false | false |
ThePreviousOne/tachiyomi
|
app/src/main/java/eu/kanade/tachiyomi/ui/recent_updates/RecentChaptersFragment.kt
|
1
|
9671
|
package eu.kanade.tachiyomi.ui.recent_updates
import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.support.v7.view.ActionMode
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import android.view.*
import com.afollestad.materialdialogs.MaterialDialog
import eu.davidea.flexibleadapter.FlexibleAdapter
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.download.model.Download
import eu.kanade.tachiyomi.ui.base.adapter.FlexibleViewHolder
import eu.kanade.tachiyomi.ui.base.fragment.BaseRxFragment
import eu.kanade.tachiyomi.ui.main.MainActivity
import eu.kanade.tachiyomi.ui.reader.ReaderActivity
import eu.kanade.tachiyomi.widget.DeletingChaptersDialog
import kotlinx.android.synthetic.main.fragment_recent_chapters.*
import nucleus.factory.RequiresPresenter
import timber.log.Timber
/**
* Fragment that shows recent chapters.
* Uses [R.layout.fragment_recent_chapters].
* UI related actions should be called from here.
*/
@RequiresPresenter(RecentChaptersPresenter::class)
class RecentChaptersFragment
: BaseRxFragment<RecentChaptersPresenter>(), ActionMode.Callback, FlexibleViewHolder.OnListItemClickListener {
companion object {
/**
* Create new RecentChaptersFragment.
* @return a new instance of [RecentChaptersFragment].
*/
fun newInstance(): RecentChaptersFragment {
return RecentChaptersFragment()
}
}
/**
* Action mode for multiple selection.
*/
private var actionMode: ActionMode? = null
/**
* Adapter containing the recent chapters.
*/
lateinit var adapter: RecentChaptersAdapter
private set
/**
* Called when view gets created
* @param inflater layout inflater
* @param container view group
* @param savedState status of saved state
*/
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedState: Bundle?): View {
// Inflate view
return inflater.inflate(R.layout.fragment_recent_chapters, container, false)
}
/**
* Called when view is created
* @param view created view
* @param savedState status of saved sate
*/
override fun onViewCreated(view: View, savedState: Bundle?) {
// Init RecyclerView and adapter
recycler.layoutManager = LinearLayoutManager(activity)
recycler.addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL))
recycler.setHasFixedSize(true)
adapter = RecentChaptersAdapter(this)
recycler.adapter = adapter
// Update toolbar text
setToolbarTitle(R.string.label_recent_updates)
}
/**
* Returns selected chapters
* @return list of selected chapters
*/
fun getSelectedChapters(): List<RecentChapter> {
return adapter.selectedItems.map { adapter.getItem(it) as? RecentChapter }.filterNotNull()
}
/**
* Called when item in list is clicked
* @param position position of clicked item
*/
override fun onListItemClick(position: Int): Boolean {
// Get item from position
val item = adapter.getItem(position)
if (item is RecentChapter) {
if (actionMode != null && adapter.mode == FlexibleAdapter.MODE_MULTI) {
toggleSelection(position)
return true
} else {
openChapter(item)
return false
}
}
return false
}
/**
* Called when item in list is long clicked
* @param position position of clicked item
*/
override fun onListItemLongClick(position: Int) {
if (actionMode == null)
actionMode = activity.startSupportActionMode(this)
toggleSelection(position)
}
/**
* Called to toggle selection
* @param position position of selected item
*/
private fun toggleSelection(position: Int) {
adapter.toggleSelection(position, false)
val count = adapter.selectedItemCount
if (count == 0) {
actionMode?.finish()
} else {
setContextTitle(count)
actionMode?.invalidate()
}
}
/**
* Set the context title
* @param count count of selected items
*/
private fun setContextTitle(count: Int) {
actionMode?.title = getString(R.string.label_selected, count)
}
/**
* Open chapter in reader
* @param chapter selected chapter
*/
private fun openChapter(chapter: RecentChapter) {
val intent = ReaderActivity.newIntent(activity, chapter.manga, chapter)
startActivity(intent)
}
/**
* Download selected items
* @param chapters list of selected [RecentChapter]s
*/
fun downloadChapters(chapters: List<RecentChapter>) {
destroyActionModeIfNeeded()
presenter.downloadChapters(chapters)
}
/**
* Populate adapter with chapters
* @param chapters list of [Any]
*/
fun onNextRecentChapters(chapters: List<Any>) {
(activity as MainActivity).updateEmptyView(chapters.isEmpty(),
R.string.information_no_recent, R.drawable.ic_update_black_128dp)
destroyActionModeIfNeeded()
adapter.setItems(chapters)
}
/**
* Update download status of chapter
* @param download [Download] object containing download progress.
*/
fun onChapterStatusChange(download: Download) {
getHolder(download)?.notifyStatus(download.status)
}
/**
* Returns holder belonging to chapter
* @param download [Download] object containing download progress.
*/
private fun getHolder(download: Download): RecentChaptersHolder? {
return recycler.findViewHolderForItemId(download.chapter.id!!) as? RecentChaptersHolder
}
/**
* Mark chapter as read
* @param chapters list of chapters
*/
fun markAsRead(chapters: List<RecentChapter>) {
presenter.markChapterRead(chapters, true)
if (presenter.preferences.removeAfterMarkedAsRead()) {
deleteChapters(chapters)
}
}
/**
* Delete selected chapters
* @param chapters list of [RecentChapter] objects
*/
fun deleteChapters(chapters: List<RecentChapter>) {
destroyActionModeIfNeeded()
DeletingChaptersDialog().show(childFragmentManager, DeletingChaptersDialog.TAG)
presenter.deleteChapters(chapters)
}
/**
* Destory [ActionMode] if it's shown
*/
fun destroyActionModeIfNeeded() {
actionMode?.finish()
}
/**
* Mark chapter as unread
* @param chapters list of selected [RecentChapter]
*/
fun markAsUnread(chapters: List<RecentChapter>) {
presenter.markChapterRead(chapters, false)
}
/**
* Start downloading chapter
* @param chapter selected chapter with manga
*/
fun downloadChapter(chapter: RecentChapter) {
presenter.downloadChapter(chapter)
}
/**
* Start deleting chapter
* @param chapter selected chapter with manga
*/
fun deleteChapter(chapter: RecentChapter) {
DeletingChaptersDialog().show(childFragmentManager, DeletingChaptersDialog.TAG)
presenter.deleteChapters(listOf(chapter))
}
/**
* Called when chapters are deleted
*/
fun onChaptersDeleted() {
dismissDeletingDialog()
adapter.notifyDataSetChanged()
}
/**
* Called when error while deleting
* @param error error message
*/
fun onChaptersDeletedError(error: Throwable) {
dismissDeletingDialog()
Timber.e(error)
}
/**
* Called to dismiss deleting dialog
*/
fun dismissDeletingDialog() {
(childFragmentManager.findFragmentByTag(DeletingChaptersDialog.TAG) as? DialogFragment)?.dismiss()
}
override fun onPrepareActionMode(mode: ActionMode?, menu: Menu?): Boolean {
return false
}
/**
* Called when ActionMode item clicked
* @param mode the ActionMode object
* @param item item from ActionMode.
*/
override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_mark_as_read -> markAsRead(getSelectedChapters())
R.id.action_mark_as_unread -> markAsUnread(getSelectedChapters())
R.id.action_download -> downloadChapters(getSelectedChapters())
R.id.action_delete -> {
MaterialDialog.Builder(activity)
.content(R.string.confirm_delete_chapters)
.positiveText(android.R.string.yes)
.negativeText(android.R.string.no)
.onPositive { dialog, action -> deleteChapters(getSelectedChapters()) }
.show()
}
else -> return false
}
return true
}
/**
* Called when ActionMode created.
* @param mode the ActionMode object
* @param menu menu object of ActionMode
*/
override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean {
mode.menuInflater.inflate(R.menu.chapter_recent_selection, menu)
adapter.mode = FlexibleAdapter.MODE_MULTI
return true
}
/**
* Called when ActionMode destroyed
* @param mode the ActionMode object
*/
override fun onDestroyActionMode(mode: ActionMode?) {
adapter.mode = FlexibleAdapter.MODE_SINGLE
adapter.clearSelection()
actionMode = null
}
}
|
apache-2.0
|
fe7d0e7a5879ff683743687fe8d26a57
| 29.900958 | 110 | 0.652259 | 5.003104 | false | false | false | false |
zbeboy/ISY
|
src/main/java/top/zbeboy/isy/service/common/UploadServiceImpl.kt
|
1
|
8026
|
package top.zbeboy.isy.service.common
import org.slf4j.LoggerFactory
import org.springframework.http.MediaType
import org.springframework.stereotype.Service
import org.springframework.util.FileCopyUtils
import org.springframework.util.StringUtils
import org.springframework.web.multipart.MultipartFile
import org.springframework.web.multipart.MultipartHttpServletRequest
import top.zbeboy.isy.config.Workbook
import top.zbeboy.isy.service.util.IPTimeStamp
import top.zbeboy.isy.web.bean.file.FileBean
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException
import java.util.*
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
/**
* Created by zbeboy 2017-12-20 .
**/
@Service("uploadService")
open class UploadServiceImpl : UploadService {
private val log = LoggerFactory.getLogger(UploadServiceImpl::class.java)
override fun upload(request: MultipartHttpServletRequest, path: String, address: String): List<FileBean> {
val list = ArrayList<FileBean>()
//1. build an iterator.
val iterator = request.fileNames
var multipartFile: MultipartFile
//2. get each file
while (iterator.hasNext()) {
val fileBean = FileBean()
//2.1 get next MultipartFile
multipartFile = request.getFile(iterator.next())!!
log.info(multipartFile.originalFilename!! + " uploaded!")
fileBean.contentType = multipartFile.contentType
val ipTimeStamp = IPTimeStamp(address)
val words = multipartFile.originalFilename!!.split("\\.".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
if (words.size > 1) {
val ext = words[words.size - 1].toLowerCase()
var filename = ipTimeStamp.getIPTimeRand() + "." + ext
if (filename.contains(":")) {
filename = filename.substring(filename.lastIndexOf(':') + 1, filename.length)
}
fileBean.originalFileName = multipartFile.originalFilename!!.substring(0, multipartFile.originalFilename!!.lastIndexOf('.'))
fileBean.ext = ext
fileBean.newName = filename
fileBean.size = multipartFile.size
//copy file to local disk (make sure the path "e.g. D:/temp/files" exists)
buildList(fileBean, list, path, filename, multipartFile)
} else {
// no filename
val filename = ipTimeStamp.getIPTimeRand()
fileBean.originalFileName = if (multipartFile.originalFilename!!.lastIndexOf('.') >= 0) {
multipartFile.originalFilename!!.substring(0, multipartFile.originalFilename!!.lastIndexOf('.'))
} else {
multipartFile.originalFilename
}
fileBean.newName = filename
fileBean.size = multipartFile.size
// copy file to local disk (make sure the path "e.g. D:/temp/files" exists)
buildList(fileBean, list, path, filename, multipartFile)
}
}
return list
}
@Throws(IOException::class)
private fun buildPath(path: String, filename: String, multipartFile: MultipartFile): String? {
var lastPath: String
val saveFile = File(path, filename)
if (!saveFile.parentFile.exists()) {//create file, linux need first create path
saveFile.parentFile.mkdirs()
}
if ((multipartFile.size < File(path.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0] + ":").freeSpace /*windows*/) ||
(multipartFile.size < File(path).freeSpace) /*linux*/) {// has space with disk
log.info(path)
FileCopyUtils.copy(multipartFile.bytes, FileOutputStream(path + File.separator + filename))
lastPath = path + filename
lastPath = lastPath.replace("\\\\".toRegex(), Workbook.DIRECTORY_SPLIT)
} else {
log.info("not valiablespace!")
return null
}
return lastPath
}
private fun buildList(fileBean: FileBean, list: MutableList<FileBean>, path: String, filename: String, multipartFile: MultipartFile) {
try {
if (!StringUtils.isEmpty(path.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0])) {
fileBean.lastPath = buildPath(path, filename, multipartFile)
list.add(fileBean)
}
} catch (e: IOException) {
log.error("Build File list exception, is {}", e)
}
}
override fun download(fileName: String, filePath: String, response: HttpServletResponse, request: HttpServletRequest) {
try {
val path = Workbook.DIRECTORY_SPLIT + filePath
val fileFullName = completionFileName(fileName, path)
response.contentType = "application/x-msdownload"
response.setHeader("Content-disposition", "attachment; filename=\"" + String((fileFullName).toByteArray(charset("gb2312")), charset("ISO8859-1")) + "\"")
val realPath = request.session.servletContext.getRealPath(Workbook.DIRECTORY_SPLIT)
val inputStream = FileInputStream(realPath + path)
FileCopyUtils.copy(inputStream, response.outputStream)
} catch (e: Exception) {
log.error(" file is not found exception is {} ", e)
}
}
override fun download(fileName: String, file: File, response: HttpServletResponse, request: HttpServletRequest) {
try {
val fileFullName = completionFileName(fileName, file.name)
response.contentType = "application/x-msdownload"
response.setHeader("Content-disposition", "attachment; filename=\"" + String((fileFullName).toByteArray(charset("gb2312")), charset("ISO8859-1")) + "\"")
val inputStream = FileInputStream(file)
FileCopyUtils.copy(inputStream, response.outputStream)
} catch (e: Exception) {
log.error(" file is not found exception is {} ", e)
}
}
override fun reviewPic(filePath: String, request: HttpServletRequest, response: HttpServletResponse) {
try {
val path = Workbook.DIRECTORY_SPLIT + filePath
val realPath = request.session.servletContext.getRealPath(Workbook.DIRECTORY_SPLIT)
val file = File(realPath + path)
if (file.exists()) {
val mediaType: MediaType
val ext = path.substring(path.lastIndexOf('.') + 1)
mediaType = if (ext.equals("png", ignoreCase = true)) {
MediaType.IMAGE_PNG
} else if (ext.equals("gif", ignoreCase = true)) {
MediaType.IMAGE_GIF
} else if (ext.equals("jpg", ignoreCase = true) || ext.equals("jpeg", ignoreCase = true)) {
MediaType.IMAGE_JPEG
} else {
MediaType.APPLICATION_OCTET_STREAM
}
response.contentType = mediaType.toString()
response.setHeader("Content-disposition", "attachment; filename=\"" + file.name + "\"")
val inputStream = FileInputStream(file)
FileCopyUtils.copy(inputStream, response.outputStream)
}
} catch (e: Exception) {
log.error(" file is not found exception is {} ", e)
}
}
/**
* 文件名加后缀补全操作
*
* @param fileName 无后缀的文件名
* @param fileFullName 文件名全称(带后缀或不带后缀)
* @return 带后缀的文件名
*/
private fun completionFileName(fileName: String, fileFullName: String): String {
var tempName = fileName
val extLocal = fileFullName.lastIndexOf('.')
if (extLocal > 0) {
tempName += fileFullName.substring(extLocal)
}
return tempName
}
}
|
mit
|
e040c272b8c65d79bc7d4073f4d96361
| 44.971098 | 165 | 0.617832 | 4.716489 | false | false | false | false |
paplorinc/intellij-community
|
plugins/github/src/org/jetbrains/plugins/github/pullrequest/avatars/CachingGithubAvatarIconsProvider.kt
|
1
|
3579
|
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest.avatars
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.runInEdt
import com.intellij.util.IconUtil
import com.intellij.util.ui.JBUIScale
import com.intellij.util.ui.JBValue
import icons.GithubIcons
import org.jetbrains.annotations.CalledInAwt
import org.jetbrains.plugins.github.api.GithubApiRequestExecutor
import org.jetbrains.plugins.github.api.data.GithubUser
import org.jetbrains.plugins.github.util.CachingGithubUserAvatarLoader
import org.jetbrains.plugins.github.util.GithubImageResizer
import java.awt.Component
import java.awt.Graphics
import java.awt.Image
import java.util.concurrent.CompletableFuture
import javax.swing.Icon
/**
* @param component which will be repainted when icons are loaded
*/
internal class CachingGithubAvatarIconsProvider(private val avatarsLoader: CachingGithubUserAvatarLoader,
private val imagesResizer: GithubImageResizer,
private val requestExecutor: GithubApiRequestExecutor,
private val iconSize: JBValue,
private val component: Component) {
private val scaleContext = JBUIScale.ScaleContext.create(component)
private var defaultIcon = createDefaultIcon(iconSize.get())
private val icons = mutableMapOf<GithubUser, Icon>()
private fun createDefaultIcon(size: Int): Icon {
val standardDefaultAvatar = GithubIcons.DefaultAvatar
val scale = size.toFloat() / standardDefaultAvatar.iconWidth.toFloat()
return IconUtil.scale(standardDefaultAvatar, null, scale)
}
@CalledInAwt
fun getIcon(user: GithubUser): Icon {
val iconSize = iconSize.get()
// so that icons are rescaled when any scale changes (be it font size or current DPI)
if (scaleContext.update(JBUIScale.ScaleContext.create(component))) {
defaultIcon = createDefaultIcon(iconSize)
icons.clear()
}
val modality = ModalityState.stateForComponent(component)
return icons.getOrPut(user) {
val icon = DelegatingIcon(defaultIcon)
avatarsLoader
.requestAvatar(requestExecutor, user)
.thenCompose<Image?> {
if (it != null) imagesResizer.requestImageResize(it, iconSize, scaleContext)
else CompletableFuture.completedFuture(null)
}
.thenAccept {
if (it != null) runInEdt(modality) {
icon.delegate = IconUtil.createImageIcon(it)
component.repaint()
}
}
icon
}
}
private class DelegatingIcon(var delegate: Icon) : Icon {
override fun getIconHeight() = delegate.iconHeight
override fun getIconWidth() = delegate.iconWidth
override fun paintIcon(c: Component?, g: Graphics?, x: Int, y: Int) = delegate.paintIcon(c, g, x, y)
}
// helper to avoid passing all the services to clients
class Factory(private val avatarsLoader: CachingGithubUserAvatarLoader,
private val imagesResizer: GithubImageResizer,
private val requestExecutor: GithubApiRequestExecutor) {
fun create(iconSize: JBValue, component: Component) = CachingGithubAvatarIconsProvider(avatarsLoader, imagesResizer,
requestExecutor, iconSize, component)
}
}
|
apache-2.0
|
13751c7fd4a2b01c1ed88d7e91d53930
| 42.120482 | 140 | 0.695166 | 5.134864 | false | false | false | false |
google/intellij-community
|
plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/expressions/KotlinUReturnExpression.kt
|
2
|
1231
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.uast.kotlin
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.kotlin.psi.KtReturnExpression
import org.jetbrains.uast.*
@ApiStatus.Internal
class KotlinUReturnExpression(
override val sourcePsi: KtReturnExpression,
givenParent: UElement?
) : KotlinAbstractUExpression(givenParent), UReturnExpression, KotlinUElementWithType {
override val returnExpression by lz {
baseResolveProviderService.baseKotlinConverter.convertOrNull(sourcePsi.returnedExpression, this)
}
override val label: String?
get() = sourcePsi.getTargetLabel()?.getReferencedName()
override val jumpTarget: UElement?
get() = generateSequence(uastParent) { it.uastParent }
.find {
it is ULabeledExpression && it.label == label ||
(it is UMethod || it is KotlinLocalFunctionULambdaExpression) && label == null ||
it is ULambdaExpression && it.uastParent.let { parent -> parent is UCallExpression && parent.methodName == label }
}
}
|
apache-2.0
|
1baf1bf25798b2072b0c4b614c76dc34
| 42.964286 | 158 | 0.70918 | 5.260684 | false | false | false | false |
seatgeek/spreedly-java
|
src/main/java/cc/protea/spreedly/model/SpreedlyBankAccountRequest.kt
|
1
|
405
|
package cc.protea.spreedly.model
import org.simpleframework.xml.Default
import org.simpleframework.xml.Element
import org.simpleframework.xml.Root
@Default(required = false)
@Root(name = "payment_method")
data class SpreedlyBankAccountRequest(
@field:Element(name = "bank_account")
var bankAccount: SpreedlyBankAccount? = null,
@field:Element(required = false)
var data: Any? = null
)
|
mit
|
f80841fa82c77d44dce96547e8cdc716
| 24.3125 | 49 | 0.755556 | 3.461538 | false | false | false | false |
chrislo27/RhythmHeavenRemixEditor2
|
core/src/main/kotlin/io/github/chrislo27/rhre3/news/ThumbnailFetcher.kt
|
2
|
5123
|
package io.github.chrislo27.rhre3.news
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.files.FileHandle
import com.badlogic.gdx.graphics.Pixmap
import com.badlogic.gdx.graphics.PixmapIO
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.utils.Disposable
import io.github.chrislo27.rhre3.RHRE3
import io.github.chrislo27.rhre3.RHRE3Application
import org.asynchttpclient.AsyncHttpClient
import org.asynchttpclient.ListenableFuture
import org.asynchttpclient.Response
import java.math.BigInteger
import java.security.MessageDigest
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ConcurrentMap
import kotlin.concurrent.thread
object ThumbnailFetcher : Disposable {
private val httpClient: AsyncHttpClient
get() = RHRE3Application.httpClient
val thumbnailFolder: FileHandle by lazy { RHRE3.RHRE3_FOLDER.child("thumbnails/").apply(FileHandle::mkdirs) }
val map: ConcurrentMap<String, Texture> = ConcurrentHashMap()
private val fetching: ConcurrentMap<String, ListenableFuture<Response>> = ConcurrentHashMap()
init {
Runtime.getRuntime().addShutdownHook(thread(start = false, isDaemon = true) {
thumbnailFolder.list(".png")
.filter { (System.currentTimeMillis() - it.lastModified()) / (1000 * 60 * 60 * 24) > 7 }
.forEach { it.delete() }
})
}
@Synchronized
override fun dispose() {
cancelAll()
removeAll()
}
@Synchronized
fun disposeOf(texture: Texture) {
val found = texture in map.values
if (found) {
map.entries.filter { it.value == texture }.forEach {
map.remove(it.key, it.value)
}
texture.dispose()
}
}
@Synchronized
fun removeAll() {
map.forEach { (_, t) ->
t.dispose()
}
map.clear()
}
@Synchronized
fun cancelAll() {
fetching.keys.forEach(ThumbnailFetcher::cancel)
}
@Synchronized
fun cancel(url: String) {
if (url in fetching) {
fetching.remove(url)?.cancel(true)
}
}
@Synchronized
fun fetch(url: String, callback: (Texture?, Exception?) -> Unit) {
if (url in map || url in fetching)
return
val urlHash: String = MessageDigest.getInstance("SHA-1").let {
it.update(url.toByteArray())
BigInteger(1, it.digest()).toString(16)
}
val cachedFile: FileHandle = thumbnailFolder.let {
it.mkdirs()
it.child("$urlHash.png")
}
fun doFetch() {
val future = httpClient.prepareGet(url).execute()
fetching[url] = future
future.addListener(Runnable {
fetching.remove(url)
try {
val value = future.get()
if (future.isDone && !future.isCancelled && value.statusCode == 200) {
Gdx.app.postRunnable {
try {
val bytes = value.responseBodyAsBytes
val pixmap = Pixmap(bytes, 0, bytes.size)
val texture = Texture(pixmap)
try {
// Cache to file
PixmapIO.writePNG(cachedFile, pixmap)
} catch (e: Exception) {
e.printStackTrace()
}
pixmap.dispose()
map[url] = texture
try {
callback.invoke(texture, null)
} catch (e: Exception) {
e.printStackTrace()
}
} catch (e: Exception) {
e.printStackTrace()
callback(null, e)
}
}
}
} catch (e: Exception) {
e.printStackTrace()
callback(null, e)
}
}, null)
}
if (cachedFile.exists()) {
Gdx.app.postRunnable {
try {
val bytes = cachedFile.readBytes()
val pixmap = Pixmap(bytes, 0, bytes.size)
val texture = Texture(pixmap)
pixmap.dispose()
map[url] = texture
try {
callback.invoke(texture, null)
} catch (e: Exception) {
e.printStackTrace()
}
} catch (e: Exception) {
e.printStackTrace()
cachedFile.delete()
map.remove(url)
doFetch()
}
}
} else {
doFetch()
}
}
}
|
gpl-3.0
|
06f800e550e4f2fd47fdf3278eb1ce99
| 32.272727 | 113 | 0.486239 | 5.211597 | false | false | false | false |
allotria/intellij-community
|
plugins/github/src/org/jetbrains/plugins/github/pullrequest/data/GHPRDataContextRepository.kt
|
2
|
9406
|
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest.data
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.util.concurrency.annotations.RequiresBackgroundThread
import com.intellij.util.concurrency.annotations.RequiresEdt
import org.jetbrains.plugins.github.api.GHGQLRequests
import org.jetbrains.plugins.github.api.GHRepositoryCoordinates
import org.jetbrains.plugins.github.api.GHRepositoryPath
import org.jetbrains.plugins.github.api.GithubApiRequestExecutor
import org.jetbrains.plugins.github.api.data.GHRepositoryOwnerName
import org.jetbrains.plugins.github.api.data.GHUser
import org.jetbrains.plugins.github.api.data.request.search.GithubIssueSearchType
import org.jetbrains.plugins.github.api.util.GithubApiSearchQueryBuilder
import org.jetbrains.plugins.github.api.util.SimpleGHGQLPagesLoader
import org.jetbrains.plugins.github.authentication.accounts.GithubAccount
import org.jetbrains.plugins.github.authentication.accounts.GithubAccountInformationProvider
import org.jetbrains.plugins.github.i18n.GithubBundle
import org.jetbrains.plugins.github.pullrequest.GHPRDiffRequestModelImpl
import org.jetbrains.plugins.github.pullrequest.data.service.*
import org.jetbrains.plugins.github.pullrequest.search.GHPRSearchQueryHolderImpl
import org.jetbrains.plugins.github.ui.avatars.GHAvatarIconsProvider
import org.jetbrains.plugins.github.util.*
import java.io.IOException
import java.util.concurrent.CompletableFuture
@Service
internal class GHPRDataContextRepository(private val project: Project) {
private val repositories = mutableMapOf<GHRepositoryCoordinates, LazyCancellableBackgroundProcessValue<GHPRDataContext>>()
@RequiresEdt
fun acquireContext(repository: GHRepositoryCoordinates, remote: GitRemoteUrlCoordinates,
account: GithubAccount, requestExecutor: GithubApiRequestExecutor): CompletableFuture<GHPRDataContext> {
return repositories.getOrPut(repository) {
val contextDisposable = Disposer.newDisposable()
LazyCancellableBackgroundProcessValue.create { indicator ->
ProgressManager.getInstance().submitIOTask(indicator) {
try {
loadContext(indicator, account, requestExecutor, repository, remote)
}
catch (e: Exception) {
if (e !is ProcessCanceledException) LOG.info("Error occurred while creating data context", e)
throw e
}
}.successOnEdt { ctx ->
if (Disposer.isDisposed(contextDisposable)) {
Disposer.dispose(ctx)
}
else {
Disposer.register(contextDisposable, ctx)
}
ctx
}
}.also {
it.addDropEventListener {
Disposer.dispose(contextDisposable)
}
}
}.value
}
@RequiresEdt
fun clearContext(repository: GHRepositoryCoordinates) {
repositories.remove(repository)?.drop()
}
@RequiresBackgroundThread
@Throws(IOException::class)
private fun loadContext(indicator: ProgressIndicator,
account: GithubAccount,
requestExecutor: GithubApiRequestExecutor,
parsedRepositoryCoordinates: GHRepositoryCoordinates,
remoteCoordinates: GitRemoteUrlCoordinates): GHPRDataContext {
indicator.text = GithubBundle.message("pull.request.loading.account.info")
val accountDetails = GithubAccountInformationProvider.getInstance().getInformation(requestExecutor, indicator, account)
indicator.checkCanceled()
indicator.text = GithubBundle.message("pull.request.loading.repo.info")
val repositoryInfo =
requestExecutor.execute(indicator, GHGQLRequests.Repo.find(GHRepositoryCoordinates(account.server,
parsedRepositoryCoordinates.repositoryPath)))
?: throw IllegalArgumentException(
"Repository ${parsedRepositoryCoordinates.repositoryPath} does not exist at ${account.server} or you don't have access.")
val currentUser = GHUser(accountDetails.nodeId, accountDetails.login, accountDetails.htmlUrl, accountDetails.avatarUrl!!,
accountDetails.name)
indicator.text = GithubBundle.message("pull.request.loading.user.teams.info")
val repoOwner = repositoryInfo.owner
val currentUserTeams = if (repoOwner is GHRepositoryOwnerName.Organization)
SimpleGHGQLPagesLoader(requestExecutor, {
GHGQLRequests.Organization.Team.findByUserLogins(account.server, repoOwner.login, listOf(currentUser.login), it)
}).loadAll(indicator)
else emptyList()
indicator.checkCanceled()
// repository might have been renamed/moved
val apiRepositoryPath = repositoryInfo.path
val apiRepositoryCoordinates = GHRepositoryCoordinates(account.server, apiRepositoryPath)
val securityService = GHPRSecurityServiceImpl(GithubSharedProjectSettings.getInstance(project),
account, currentUser, currentUserTeams,
repositoryInfo)
val detailsService = GHPRDetailsServiceImpl(ProgressManager.getInstance(), requestExecutor, apiRepositoryCoordinates)
val stateService = GHPRStateServiceImpl(ProgressManager.getInstance(), securityService,
requestExecutor, account.server, apiRepositoryPath)
val commentService = GHPRCommentServiceImpl(ProgressManager.getInstance(), requestExecutor, apiRepositoryCoordinates)
val changesService = GHPRChangesServiceImpl(ProgressManager.getInstance(), project, requestExecutor,
remoteCoordinates, apiRepositoryCoordinates)
val reviewService = GHPRReviewServiceImpl(ProgressManager.getInstance(), securityService, requestExecutor, apiRepositoryCoordinates)
val searchHolder = GHPRSearchQueryHolderImpl().apply {
query = GHPRSearchQuery.DEFAULT
}
val listLoader = GHGQLPagedListLoader(ProgressManager.getInstance(),
SimpleGHGQLPagesLoader(requestExecutor, { p ->
GHGQLRequests.PullRequest.search(account.server,
buildQuery(apiRepositoryPath, searchHolder.query),
p)
}))
val listUpdatesChecker = GHPRListETagUpdateChecker(ProgressManager.getInstance(), requestExecutor, account.server, apiRepositoryPath)
val dataProviderRepository = GHPRDataProviderRepositoryImpl(detailsService, stateService, reviewService, commentService,
changesService) { id ->
GHGQLPagedListLoader(ProgressManager.getInstance(),
SimpleGHGQLPagesLoader(requestExecutor, { p ->
GHGQLRequests.PullRequest.Timeline.items(account.server, apiRepositoryPath.owner, apiRepositoryPath.repository,
id.number, p)
}, true))
}
val repoDataService = GHPRRepositoryDataServiceImpl(ProgressManager.getInstance(), requestExecutor,
remoteCoordinates, apiRepositoryCoordinates,
repoOwner,
repositoryInfo.id, repositoryInfo.defaultBranch, repositoryInfo.isFork)
val avatarIconsProvider = GHAvatarIconsProvider(CachingGHUserAvatarLoader.getInstance(), requestExecutor)
val filesManager = GHPRFilesManagerImpl(project, parsedRepositoryCoordinates)
indicator.checkCanceled()
val creationService = GHPRCreationServiceImpl(ProgressManager.getInstance(), requestExecutor, repoDataService)
return GHPRDataContext(searchHolder, listLoader, listUpdatesChecker, dataProviderRepository,
securityService, repoDataService, creationService, detailsService, avatarIconsProvider, filesManager,
GHPRDiffRequestModelImpl())
}
@RequiresEdt
fun findContext(repositoryCoordinates: GHRepositoryCoordinates): GHPRDataContext? = repositories[repositoryCoordinates]?.lastLoadedValue
companion object {
private val LOG = logger<GHPRDataContextRepository>()
fun getInstance(project: Project) = project.service<GHPRDataContextRepository>()
private fun buildQuery(repoPath: GHRepositoryPath, searchQuery: GHPRSearchQuery?): String {
return GithubApiSearchQueryBuilder.searchQuery {
qualifier("type", GithubIssueSearchType.pr.name)
qualifier("repo", repoPath.toString())
searchQuery?.buildApiSearchQuery(this)
}
}
}
}
|
apache-2.0
|
15f7e6544ef32df345c9c26ecf116a2b
| 53.375723 | 140 | 0.701573 | 5.968274 | false | false | false | false |
code-helix/slatekit
|
src/lib/kotlin/slatekit-tests/src/test/kotlin/test/entities/Data_04_Entity_Service_Types.kt
|
1
|
6095
|
/**
* <slate_header>
* url: www.slatekit.com
* git: www.github.com/code-helix/slatekit
* org: www.codehelix.co
* author: Kishore Reddy
* copyright: 2016 CodeHelix Solutions Inc.
* license: refer to website and/or github
* about: A tool-kit, utility library and server-backend
* mantra: Simplicity above all else
* </slate_header>
*/
package test.entities
import kotlinx.coroutines.runBlocking
import org.junit.Assert
import org.junit.Test
import org.threeten.bp.*
import slatekit.common.DateTimes
import slatekit.common.data.Connections
import slatekit.common.data.Vendor
import slatekit.common.ids.UPIDs
import slatekit.data.core.LongId
import slatekit.db.Db
import slatekit.entities.EntityService
import slatekit.query.Op
import test.TestApp
import test.setup.Address
import test.setup.StatusEnum
import test.setup.TestSupport
import java.util.*
class Data_04_Entity_Service_Types : TestSupport {
val sampleUUID1 = "67bdb72a-1d74-11e8-b467-0ed5f89f7181"
val sampleUUID2 = "67bdb72a-1d74-11e8-b467-0ed5f89f7182"
val sampleUUID3 = "67bdb72a-1d74-11e8-b467-0ed5f89f7183"
val sampleUUID4 = "67bdb72a-1d74-11e8-b467-0ed5f89f7184"
@Test fun can_build() {
val db1 = Db.of(TestApp::class.java, EntitySetup.dbConfPath)
val db2 = Db.of(EntitySetup.con)
val db3 = Db.of(EntitySetup.cons)
Assert.assertEquals(db1.driver, db2.driver)
Assert.assertEquals(db2.driver, db3.driver)
}
@Test fun can_use_all_types() {
runBlocking {
val entities = EntitySetup.realDb()
entities.register<Long, SampleEntityImmutable>(LongId { s -> s.id }, "sample_entity", Vendor.MySql) { repo -> EntityService(repo) }
val svc = entities.getService<Long, SampleEntityImmutable>()
val id = svc.create(SampleEntityImmutable(
test_string = "abc",
test_string_enc = "abc123",
test_bool = false,
test_short = 1,
test_int = 2,
test_long = 3,
test_float = 4.5f,
test_double = 5.5,
test_enum = StatusEnum.Active,
test_localdate = LocalDate.of(2021, 1, 20),
test_localtime = LocalTime.of(13, 30, 45),
test_localdatetime = LocalDateTime.of(2021, 1, 20, 13, 30, 45),
test_zoneddatetime = DateTimes.of(2021, 1, 20, 13, 30, 45),
test_uuid = UUID.fromString(EntitySetup.uuid),
test_uniqueId = UPIDs.parse(EntitySetup.upid)
))
val created = svc.getById(id)
val update = created!!.copy(
test_string = "update",
test_string_enc = "original 123 v2",
test_bool = true,
test_short = 124,
test_int = 21234,
test_long = 212345,
test_float = 2123456.7f,
test_double = 21234567.89,
test_enum = StatusEnum.Active,
test_localdate = LocalDate.of(2017, 7, 7),
test_localtime = LocalTime.of(12, 30, 0),
test_localdatetime = LocalDateTime.of(2017, 7, 7, 12, 30, 0),
//test_timestamp = Instant.now(),
test_uuid = UUID.fromString(sampleUUID1),
test_uniqueId = UPIDs.parse("abc:" + sampleUUID2)
)
svc.update(update)
val updated = svc.getById(id)!!
Assert.assertTrue(updated.id == update.id)
Assert.assertTrue(updated.test_string == update.test_string)
Assert.assertTrue(updated.test_string_enc == update.test_string_enc)
Assert.assertTrue(updated.test_bool == update.test_bool)
Assert.assertTrue(updated.test_short == update.test_short)
Assert.assertTrue(updated.test_int == update.test_int)
Assert.assertTrue(updated.test_long == update.test_long)
Assert.assertTrue(updated.test_double == update.test_double)
Assert.assertTrue(updated.test_localdate == update.test_localdate)
Assert.assertTrue(updated.test_localtime == update.test_localtime)
Assert.assertTrue(updated.test_localdatetime == update.test_localdatetime)
Assert.assertTrue(updated.test_uuid == update.test_uuid)
Assert.assertTrue(updated.test_uniqueId == update.test_uniqueId)
}
}
@Test fun can_query_use_sub_object() {
runBlocking {
val entities = EntitySetup.realDb()
entities.register<Long, SampleEntityImmutable>(LongId { s -> s.id }, "sample_entity", Vendor.MySql) { repo -> EntityService(repo) }
val svc = entities.getService<Long, SampleEntityImmutable>()
val zip = "10208"
val id = svc.create(SampleEntityImmutable(
test_string = "abc",
test_string_enc = "abc123",
test_bool = false,
test_short = 1,
test_int = 2,
test_long = 3,
test_float = 4.5f,
test_double = 5.5,
test_enum = StatusEnum.Active,
test_localdate = LocalDate.of(2021, 1, 20),
test_localtime = LocalTime.of(13, 30, 45),
test_localdatetime = LocalDateTime.of(2021, 1, 20, 13, 30, 45),
test_zoneddatetime = DateTimes.of(2021, 1, 20, 13, 30, 45),
test_uuid = UUID.fromString(EntitySetup.uuid),
test_uniqueId = UPIDs.parse(EntitySetup.upid),
test_object = Address("addr 1", "queens", "new york", 100, zip, false)
))
val update = svc.findOneByField("test_object_" + Address::zip.name, Op.Eq,"10012")
Assert.assertNotNull(update)
Assert.assertEquals("10012", update?.test_object?.zip)
}
}
}
|
apache-2.0
|
14ab474c97b413d0041e8b31833fdf23
| 41.622378 | 143 | 0.574405 | 3.98366 | false | true | false | false |
faceofcat/Tesla-Core-Lib
|
src/main/kotlin/net/ndrei/teslacorelib/render/selfrendering/RawCube.kt
|
1
|
6563
|
package net.ndrei.teslacorelib.render.selfrendering
import net.minecraft.block.state.IBlockState
import net.minecraft.client.Minecraft
import net.minecraft.client.renderer.BufferBuilder
import net.minecraft.client.renderer.block.model.BakedQuad
import net.minecraft.client.renderer.texture.TextureAtlasSprite
import net.minecraft.client.renderer.vertex.VertexFormat
import net.minecraft.item.ItemStack
import net.minecraft.util.EnumFacing
import net.minecraft.util.math.Vec2f
import net.minecraft.util.math.Vec3d
import net.minecraftforge.common.model.TRSRTransformation
import javax.vecmath.Matrix4d
import javax.vecmath.Vector3f
class RawCube(val p1: Vec3d, val p2: Vec3d, val sprite: TextureAtlasSprite? = null)
: IBakery, IRawFigure, IBakeable, IDrawable {
override fun getQuads(state: IBlockState?, stack: ItemStack?, side: EnumFacing?, vertexFormat: VertexFormat, transform: TRSRTransformation)
= mutableListOf<BakedQuad>().also { this.bake(it, vertexFormat, transform) }
private val map = mutableMapOf<EnumFacing, RawCubeSideInfo>()
private var lastSide: EnumFacing? = null
private var autoUVFlag = false
private var dualSideFlag = false
override fun getFaces(): List<IRawFace> = this.map.map {
object : IRawFace {
private lateinit var facing: EnumFacing
private lateinit var side: RawCubeSideInfo
override val face: EnumFacing
get() = this.facing
override var tintIndex: Int
get() = this.side.tint
set(value) {
this.side.tint = value
}
override var sprite: TextureAtlasSprite?
get() = this.side.sprite ?: Minecraft.getMinecraft().textureMapBlocks.missingSprite
set(value) {
this.side.sprite = value
}
override fun clone() = TODO("this should never happen!")
fun initialize(facing: EnumFacing, side: RawCubeSideInfo) = this.also {
this.facing = facing
this.side = side
}
}.initialize(it.key, it.value)
}
override fun clone(sprite: TextureAtlasSprite?, reTexture: Boolean) = RawCube(this.p1, this.p2, this.sprite).also {
this.map.forEach { pair ->
it.map[pair.key] = pair.value.clone()
if (reTexture || (sprite != null)) {
it.map[pair.key]!!.sprite = sprite
}
}
}
fun addFace(face: EnumFacing) = this.also {
this.map[face] = RawCubeSideInfo()
this.lastSide = face
this.getLastSideInfo().also {
if (this.autoUVFlag) {
it.autoUV(this, face)
}
it.bothSides = this.dualSideFlag
}
}
private fun getLastSideInfo()
= (if (this.lastSide != null) this.map[this.lastSide!!] else null)
?: throw Exception("No side created yet!")
fun sprite(sprite: TextureAtlasSprite) = this.also {
this.getLastSideInfo().sprite = sprite
}
fun autoUV(flag: Boolean = true) = this.also {
if (this.lastSide != null) {
throw Exception("You can only set this before creating any sides!")
// this.getLastSideInfo().autoUV(if (flag) this else null)
}
// else {
this.autoUVFlag = flag
// }
}
fun uv(u1: Float, v1: Float, u2: Float, v2: Float) = this.uv(Vec2f(u1, v1), Vec2f(u2, v2))
fun uv(t1: Vec2f, t2: Vec2f) = this.also {
this.getLastSideInfo().also {
it.from = t1
it.to = t2
}
}
fun color(color: Int) = this.also {
this.getLastSideInfo().color = color
}
fun tint(tint: Int) = this.also {
this.getLastSideInfo().tint = tint
}
fun dualSide(flag: Boolean = true) = this.also {
if (this.lastSide != null) {
this.getLastSideInfo().bothSides = flag
} else {
this.dualSideFlag = flag
}
}
fun addMissingFaces(): RawCube {
EnumFacing.VALUES.forEach {
if (!this.map.containsKey(it))
this.addFace(it)
}
return this
}
fun getRawQuads(transform: TRSRTransformation): List<RawQuad> {
val rawrs = mutableListOf<RawQuad>()
val p1 = Vector3f(this.p1.x.toFloat(), this.p1.y.toFloat(), this.p1.z.toFloat())
val p2 = Vector3f(this.p2.x.toFloat(), this.p2.y.toFloat(), this.p2.z.toFloat())
// transform.matrix.transform(p1)
// transform.matrix.transform(p2)
// order coords TODO: maybe not needed?
val (x1, x2) = (if (p1.x < p2.x) Pair(p1.x, p2.x) else Pair(p2.x, p1.x)) // .let { Pair(it.first.toDouble(), it.second.toDouble()) }
val (y1, y2) = (if (p1.y < p2.y) Pair(p1.y, p2.y) else Pair(p2.y, p1.y)) // .let { Pair(it.first.toDouble(), it.second.toDouble()) }
val (z1, z2) = (if (p1.z < p2.z) Pair(p1.z, p2.z) else Pair(p2.z, p1.z)) // .let { Pair(it.first.toDouble(), it.second.toDouble()) }
this.map.forEach { face, info ->
val sprite = info.sprite ?: this.sprite ?: Minecraft.getMinecraft().textureMapBlocks.missingSprite
val tface = face // transform.rotate(face)
val v1 = Vector3f(x1, y1, z1)
val v2 = Vector3f(x2, y2, z2)
// transform.matrix.transform(v1)
// transform.matrix.transform(v2)
if (info.bothSides) {
rawrs.addDoubleFace(tface, sprite, info.color,
Vec3d(v1.x.toDouble(), v1.y.toDouble(), v1.z.toDouble()),
Vec3d(v2.x.toDouble(), v2.y.toDouble(), v2.z.toDouble()),
info.from, info.to, transform, info.tint)
}
else {
rawrs.addSingleFace(tface, sprite, info.color,
Vec3d(v1.x.toDouble(), v1.y.toDouble(), v1.z.toDouble()),
Vec3d(v2.x.toDouble(), v2.y.toDouble(), v2.z.toDouble()),
info.from, info.to, transform, info.tint)
}
}
return rawrs
}
override fun bake(quads: MutableList<BakedQuad>, format: VertexFormat, transform: TRSRTransformation, matrix: Matrix4d?) {
this.getRawQuads(transform).mapTo(quads) { it.applyMatrix(matrix ?: Matrix4d().also { it.setIdentity() }).bake(format) }
}
override fun draw(buffer: BufferBuilder) {
this.getRawQuads(TRSRTransformation.identity()).forEach { it.draw(buffer) }
}
}
|
mit
|
0e4675db83c202579daa24436ad0070b
| 36.936416 | 143 | 0.591041 | 3.656267 | false | false | false | false |
JuliusKunze/kotlin-native
|
backend.native/tests/external/stdlib/text/RegexTest/matchGroups.kt
|
2
|
1022
|
import kotlin.text.*
import kotlin.test.*
fun box() {
val input = "1a 2b 3c"
val pattern = "(\\d)(\\w)".toRegex()
val matches = pattern.findAll(input).toList()
assertTrue(matches.all { it.groups.size == 3 })
matches[0].let { m ->
assertEquals("1a", m.groups[0]?.value)
assertEquals("1", m.groups[1]?.value)
assertEquals("a", m.groups[2]?.value)
assertEquals(listOf("1a", "1", "a"), m.groupValues)
val (g1, g2) = m.destructured
assertEquals("1", g1)
assertEquals("a", g2)
assertEquals(listOf("1", "a"), m.destructured.toList())
}
matches[1].let { m ->
assertEquals("2b", m.groups[0]?.value)
assertEquals("2", m.groups[1]?.value)
assertEquals("b", m.groups[2]?.value)
assertEquals(listOf("2b", "2", "b"), m.groupValues)
val (g1, g2) = m.destructured
assertEquals("2", g1)
assertEquals("b", g2)
assertEquals(listOf("2", "b"), m.destructured.toList())
}
}
|
apache-2.0
|
c061eda70182f368c43c2725f08ff5cc
| 25.894737 | 63 | 0.554795 | 3.406667 | false | false | false | false |
smmribeiro/intellij-community
|
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/actions/diff/MoveDiffPreviewAction.kt
|
5
|
2442
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.changes.actions.diff
import com.intellij.diff.editor.DiffContentVirtualFile
import com.intellij.diff.editor.DiffEditorTabFilesManager.Companion.isDiffOpenedInNewWindow
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.VcsDataKeys.VIRTUAL_FILES
import com.intellij.openapi.vcs.changes.VcsEditorTabFilesManager
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.containers.JBIterable
internal abstract class MoveDiffPreviewAction(private val openInNewWindow: Boolean) : DumbAwareAction() {
abstract fun isEnabledAndVisible(project: Project, file: VirtualFile): Boolean
override fun update(e: AnActionEvent) {
val project = e.project
val diffPreviewFile = e.findDiffPreviewFile()
e.presentation.isEnabledAndVisible = project != null &&
diffPreviewFile != null &&
isEnabledAndVisible(project, diffPreviewFile)
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project!!
val diffPreviewFile = e.findDiffPreviewFile()!!
VcsEditorTabFilesManager.getInstance().openFile(project, diffPreviewFile, true, openInNewWindow, true)
}
}
private fun AnActionEvent.findDiffPreviewFile(): VirtualFile? {
val file = JBIterable.from(getData(VIRTUAL_FILES)).single()
if (file == null) return null
if (file is DiffContentVirtualFile) return file
// in case if Find Action executed, the first selected (focused) file will be a possible candidate
val selectedFile = project?.let { FileEditorManager.getInstance(it).selectedFiles.firstOrNull() }
return if (selectedFile is DiffContentVirtualFile) selectedFile else null
}
internal class MoveDiffPreviewToEditorAction : MoveDiffPreviewAction(false) {
override fun isEnabledAndVisible(project: Project, file: VirtualFile): Boolean = isDiffOpenedInNewWindow(file)
}
internal class MoveDiffPreviewToNewWindowAction : MoveDiffPreviewAction(true) {
override fun isEnabledAndVisible(project: Project, file: VirtualFile): Boolean = !isDiffOpenedInNewWindow(file)
}
|
apache-2.0
|
348d8b816ab3972ad202e6515bfa16e7
| 45.075472 | 158 | 0.780098 | 4.714286 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/jvm-debugger/test/testData/evaluation/multipleBreakpoints/whenEntry.kt
|
13
|
499
|
package whenEntry
fun main(args: Array<String>) {
val a = 1
// EXPRESSION: a
// RESULT: 1: I
val b = when {
//Breakpoint!
a == 1 -> 1 + 1
else -> 1 + 2
}
// EXPRESSION: a
// RESULT: 1: I
val c = when {
//Breakpoint!
a == 1 -> { 1 + 1 }
else -> 1 + 2
}
// EXPRESSION: a
// RESULT: 1: I
val d = when {
//Breakpoint!
a == 1 -> {
1 + 1
}
else -> 1 + 2
}
}
|
apache-2.0
|
24b20a033a8c03b3fb29fa709b608747
| 15.129032 | 31 | 0.368737 | 3.514085 | false | false | false | false |
fabmax/kool
|
kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/ksl/lang/KslVectorAccessorF4.kt
|
1
|
1000
|
package de.fabmax.kool.modules.ksl.lang
// common vec4 component swizzles - defined in a separate file to avoid JVM signature clashes
val KslVectorExpression<KslTypeFloat4, KslTypeFloat1>.xy get() = float2("xy")
val KslVectorExpression<KslTypeFloat4, KslTypeFloat1>.xz get() = float2("xz")
val KslVectorExpression<KslTypeFloat4, KslTypeFloat1>.yz get() = float2("xz")
val KslVectorExpression<KslTypeFloat4, KslTypeFloat1>.xw get() = float2("xw")
val KslVectorExpression<KslTypeFloat4, KslTypeFloat1>.yw get() = float2("yw")
val KslVectorExpression<KslTypeFloat4, KslTypeFloat1>.zw get() = float2("zw")
val KslVectorExpression<KslTypeFloat4, KslTypeFloat1>.rg get() = float2("rg")
val KslVectorExpression<KslTypeFloat4, KslTypeFloat1>.rb get() = float2("rb")
val KslVectorExpression<KslTypeFloat4, KslTypeFloat1>.gb get() = float2("gb")
val KslVectorExpression<KslTypeFloat4, KslTypeFloat1>.xyz get() = float3("xyz")
val KslVectorExpression<KslTypeFloat4, KslTypeFloat1>.rgb get() = float3("rgb")
|
apache-2.0
|
9faabfddf3f8052bd904d4e322602cb2
| 57.823529 | 93 | 0.783 | 4.065041 | false | false | false | false |
idea4bsd/idea4bsd
|
python/src/com/jetbrains/python/console/PyConsoleCopyHandler.kt
|
5
|
3027
|
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.console
import com.intellij.execution.impl.ConsoleViewUtil
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.editor.Caret
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.actionSystem.EditorActionHandler
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.editor.richcopy.settings.RichCopySettings
import com.intellij.openapi.ide.CopyPasteManager
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.TextRange
import java.awt.datatransfer.StringSelection
/**
* Created by Yuli Fiterman on 9/17/2016.
*/
class PyConsoleCopyHandler(val originalHandler: EditorActionHandler) : EditorActionHandler() {
override fun doExecute(editor: Editor, caret: Caret?, dataContext: DataContext) {
if (!RichCopySettings.getInstance().isEnabled) {
return originalHandler.execute(editor, null, dataContext);
}
if (true != editor.getUserData(ConsoleViewUtil.EDITOR_IS_CONSOLE_HISTORY_VIEW)) {
return originalHandler.execute(editor, null, dataContext);
}
doCopyWithoutPrompt(editor as EditorEx);
}
private fun doCopyWithoutPrompt(editor: EditorEx) {
val start = editor.selectionModel.selectionStart
val end = editor.selectionModel.selectionEnd
val document = editor.document
val beginLine = document.getLineNumber(start)
val endLine = document.getLineNumber(end)
val sb = StringBuilder()
for (i in beginLine..endLine) {
var lineStart = document.getLineStartOffset(i)
val r = Ref.create<Int>()
editor.markupModel.processRangeHighlightersOverlappingWith(lineStart, lineStart) {
val length = it.getUserData(PROMPT_LENGTH_MARKER) ?: return@processRangeHighlightersOverlappingWith true
r.set(length)
false
}
if (!r.isNull) {
lineStart += r.get()
}
val rangeStart = Math.max(lineStart, start)
val rangeEnd = Math.min(document.getLineEndOffset(i), end)
if (rangeStart < rangeEnd) {
sb.append(document.getText(TextRange(rangeStart, rangeEnd)))
sb.append("\n")
}
}
if (!sb.isEmpty()) {
CopyPasteManager.getInstance().setContents(StringSelection(sb.toString()))
}
}
companion object {
@JvmField
val PROMPT_LENGTH_MARKER: Key<Int?> = Key.create<Int>("PROMPT_LENGTH_MARKER");
}
}
|
apache-2.0
|
36385a3a6d0a0cfdf7121e4ee8439ffc
| 35.914634 | 112 | 0.73439 | 4.251404 | false | false | false | false |
jwren/intellij-community
|
build/tasks/src/org/jetbrains/intellij/build/io/ZipFileWriter.kt
|
1
|
8878
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.intellij.build.io
import java.nio.ByteBuffer
import java.nio.channels.FileChannel
import java.nio.channels.FileChannel.MapMode
import java.nio.channels.WritableByteChannel
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardOpenOption
import java.util.*
import java.util.zip.CRC32
import java.util.zip.Deflater
import java.util.zip.ZipEntry
import kotlin.math.min
// 1 MB
private const val largeFileThreshold = 1_048_576
private const val compressThreshold = 8 * 1024
// 8 MB (as JDK)
private const val mappedTransferSize = 8L * 1024L * 1024L
internal inline fun writeNewZip(file: Path, compress: Boolean = false, task: (ZipFileWriter) -> Unit) {
Files.createDirectories(file.parent)
ZipFileWriter(channel = FileChannel.open(file, W_CREATE_NEW),
deflater = if (compress) Deflater(Deflater.DEFAULT_COMPRESSION, true) else null).use {
task(it)
}
}
// you must pass SeekableByteChannel if files will be written (`file` method)
internal class ZipFileWriter(channel: WritableByteChannel, private val deflater: Deflater? = null) : AutoCloseable {
// size is written as part of optimized metadata - so, if compression is enabled, optimized metadata will be incorrect
val resultStream = ZipArchiveOutputStream(channel, withOptimizedMetadataEnabled = deflater == null)
private val crc32 = CRC32()
private val bufferAllocator = ByteBufferAllocator()
private val deflateBufferAllocator = if (deflater == null) null else ByteBufferAllocator()
@Suppress("DuplicatedCode")
fun file(nameString: String, file: Path) {
var isCompressed = deflater != null && !nameString.endsWith(".png")
val name = nameString.toByteArray()
val headerSize = 30 + name.size
crc32.reset()
val input: ByteBuffer
val size: Int
FileChannel.open(file, EnumSet.of(StandardOpenOption.READ)).use { channel ->
size = channel.size().toInt()
if (size == 0) {
writeEmptyFile(name, headerSize)
return
}
if (size < compressThreshold) {
isCompressed = false
}
if (size > largeFileThreshold || isCompressed) {
val headerPosition = resultStream.getChannelPositionAndAdd(headerSize)
var compressedSize = writeLargeFile(size.toLong(), channel, if (isCompressed) deflater else null).toInt()
val crc = crc32.value
val method: Int
if (compressedSize == -1) {
method = ZipEntry.STORED
compressedSize = size
}
else {
method = ZipEntry.DEFLATED
}
val buffer = bufferAllocator.allocate(headerSize)
writeLocalFileHeader(name = name, size = size, compressedSize = compressedSize, crc32 = crc, method = method, buffer = buffer)
buffer.position(0)
assert(buffer.remaining() == headerSize)
resultStream.writeEntryHeaderAt(name = name,
header = buffer,
position = headerPosition,
size = size,
compressedSize = compressedSize,
crc = crc,
method = method)
return
}
input = bufferAllocator.allocate(headerSize + size)
input.position(headerSize)
// set position to compute CRC
input.mark()
do {
channel.read(input)
}
while (input.hasRemaining())
input.reset()
crc32.update(input)
}
val crc = crc32.value
input.position(0)
writeLocalFileHeader(name, size, size, crc, ZipEntry.STORED, input)
input.position(0)
assert(input.remaining() == (size + headerSize))
resultStream.writeRawEntry(input, name, size, size, ZipEntry.STORED, crc, headerSize)
}
private fun writeLargeFile(fileSize: Long, channel: FileChannel, deflater: Deflater?): Long {
// channel.transferTo will use a slow path for untrusted (custom) WritableByteChannel implementations, so, duplicate what JDK does
// see FileChannelImpl.transferFromFileChannel
var remaining = fileSize
var position = 0L
var compressedSize = 0L
var effectiveDeflater = deflater
while (remaining > 0L) {
val size = min(remaining, mappedTransferSize)
val buffer = channel.map(MapMode.READ_ONLY, position, size)
remaining -= size
position += size
try {
buffer.mark()
crc32.update(buffer)
buffer.reset()
buffer.mark()
if (effectiveDeflater == null) {
resultStream.writeBuffer(buffer)
compressedSize = -1
}
else {
val output = deflateBufferAllocator!!.allocate(size.toInt() + 4096)
effectiveDeflater.setInput(buffer)
if (remaining <= 0) {
effectiveDeflater.finish()
}
do {
val n = effectiveDeflater.deflate(output, Deflater.SYNC_FLUSH)
assert(n != 0)
}
while (buffer.hasRemaining())
output.flip()
compressedSize += output.remaining()
if (position == 0L && compressedSize > size) {
// incompressible
effectiveDeflater = null
buffer.reset()
resultStream.writeBuffer(buffer)
compressedSize = -1
}
else {
resultStream.writeBuffer(output)
}
}
}
finally {
unmapBuffer(buffer)
}
}
effectiveDeflater?.reset()
return compressedSize
}
@Suppress("DuplicatedCode")
fun compressedData(nameString: String, data: ByteArray) {
val name = nameString.toByteArray()
val headerSize = 30 + name.size
val input = ByteBuffer.wrap(data)
val size = data.size
crc32.reset()
crc32.update(data)
val crc = crc32.value
input.position(0)
val output = deflateBufferAllocator!!.allocate(headerSize + size + 4096)
output.position(headerSize)
deflater!!.setInput(input)
deflater.finish()
do {
val n = deflater.deflate(output, Deflater.SYNC_FLUSH)
assert(n != 0)
}
while (input.hasRemaining())
deflater.reset()
output.limit(output.position())
output.position(0)
val compressedSize = output.remaining() - headerSize
writeLocalFileHeader(name, size, compressedSize, crc, ZipEntry.DEFLATED, output)
output.position(0)
assert(output.remaining() == (compressedSize + headerSize))
resultStream.writeRawEntry(output, name, size, compressedSize, ZipEntry.DEFLATED, crc, headerSize)
}
fun uncompressedData(nameString: String, data: String) {
uncompressedData(nameString, ByteBuffer.wrap(data.toByteArray()))
}
fun uncompressedData(nameString: String, data: ByteBuffer) {
val name = nameString.toByteArray()
val headerSize = 30 + name.size
if (!data.hasRemaining()) {
writeEmptyFile(name, headerSize)
return
}
data.mark()
crc32.reset()
crc32.update(data)
val crc = crc32.value
data.reset()
val size = data.remaining()
val header = bufferAllocator.allocate(headerSize)
writeLocalFileHeader(name, size, size, crc, ZipEntry.STORED, header)
header.position(0)
resultStream.writeRawEntry(header, data, name, size, size, ZipEntry.STORED, crc)
}
fun uncompressedData(nameString: String, maxSize: Int, dataWriter: (ByteBuffer) -> Unit) {
val name = nameString.toByteArray()
val headerSize = 30 + name.size
val output = bufferAllocator.allocate(headerSize + maxSize)
output.position(headerSize)
dataWriter(output)
output.limit(output.position())
output.position(headerSize)
val size = output.remaining()
crc32.reset()
crc32.update(output)
val crc = crc32.value
output.position(0)
writeLocalFileHeader(name, size, size, crc, ZipEntry.STORED, output)
output.position(0)
assert(output.remaining() == (size + headerSize))
resultStream.writeRawEntry(output, name, size, size, ZipEntry.STORED, crc, headerSize)
}
private fun writeEmptyFile(name: ByteArray, headerSize: Int) {
val input = bufferAllocator.allocate(headerSize)
writeLocalFileHeader(name, size = 0, compressedSize = 0, crc32 = 0, method = ZipEntry.STORED, buffer = input)
input.position(0)
input.limit(headerSize)
resultStream.writeRawEntry(input, name, 0, 0, ZipEntry.STORED, 0, headerSize)
}
fun dir(name: String) {
resultStream.addDirEntry(name)
}
override fun close() {
@Suppress("ConvertTryFinallyToUseCall")
try {
bufferAllocator.close()
deflateBufferAllocator?.close()
deflater?.end()
}
finally {
resultStream.close()
}
}
}
|
apache-2.0
|
a4e86dc5384c7dbf490d683837c7d155
| 30.938849 | 134 | 0.65116 | 4.371246 | false | false | false | false |
vovagrechka/fucking-everything
|
attic/pizdatron/src/fekjs/jquery.kt
|
1
|
1767
|
@file:Suppress("UnsafeCastFromDynamic")
package fekjs
import org.w3c.dom.*
import jquery.*
import kotlin.browser.*
external interface JQueryPosition {
val left: Double
val top: Double
}
operator fun JQuery.get(index: Int): HTMLElement? = this.asDynamic()[index]
fun JQuery.scrollTop(value: Double): Unit = this.asDynamic().scrollTop(value)
fun JQuery.scrollTop(value: Int): Unit = this.asDynamic().scrollTop(value)
fun JQuery.scrollTop(): Double = this.asDynamic().scrollTop()
fun JQuery.offset(): JQueryPosition = this.asDynamic().offset()
fun JQuery.text(): String = this.asDynamic().text()
fun JQuery.remove(): String = this.asDynamic().remove()
val JQuery.length: Int get() = this.asDynamic().length
fun JQuery.css(prop: String, value: Any?): JQuery = this.asDynamic().css(prop, value)
fun JQuery.setVal(value: String?): JQuery = this.asDynamic().`val`(value)
fun JQuery.outerWidth(includeMargin: Boolean = false): Double = this.asDynamic().outerWidth(includeMargin)
fun JQuery.outerHeight(includeMargin: Boolean = false): Double = this.asDynamic().outerHeight(includeMargin)
fun JQuery.each(block: (index: Int, element: HTMLElement) -> Unit): Unit = this.asDynamic().each(block)
val jqbody: JQuery get() = jq(document.body!!)
fun byid(id: String): JQuery {
val selector = "#$id".replace(Regex("\\."), "\\.")
return jq(selector)
}
fun byid0(id: String): HTMLElement? {
val selector = "#$id".replace(Regex("\\."), "\\.")
return jq(selector)[0]
}
fun byid0ForSure(id: String): HTMLElement {
return requireNotNull(byid0(id)) {"I want fucking element #$id"}
}
fun JQuery.not(selector: String): JQuery = this.asDynamic().not(selector)
fun JQuery.scrollBodyToShit(dy: Int = 0) {
jqbody.scrollTop(this.offset().top - 50 + dy)
}
|
apache-2.0
|
75cbb78fbd81770b590553cb70bdf522
| 35.8125 | 108 | 0.711375 | 3.512922 | false | false | false | false |
jwren/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceArrayOfWithLiteralInspection.kt
|
1
|
3112
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.intentions.isArrayOfMethod
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
class ReplaceArrayOfWithLiteralInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor = callExpressionVisitor(fun(expression) {
val calleeExpression = expression.calleeExpression as? KtNameReferenceExpression ?: return
when (val parent = expression.parent) {
is KtValueArgument -> {
if (parent.parent?.parent !is KtAnnotationEntry) return
if (parent.getSpreadElement() != null && !parent.isNamed()) return
}
is KtParameter -> {
val constructor = parent.parent?.parent as? KtPrimaryConstructor ?: return
val containingClass = constructor.getContainingClassOrObject()
if (!containingClass.isAnnotation()) return
}
else -> return
}
if (!expression.isArrayOfMethod()) return
val calleeName = calleeExpression.getReferencedName()
holder.registerProblem(
calleeExpression,
KotlinBundle.message("0.call.should.be.replaced.with.array.literal", calleeName),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
ReplaceWithArrayLiteralFix()
)
})
private class ReplaceWithArrayLiteralFix : LocalQuickFix {
override fun getFamilyName() = KotlinBundle.message("replace.with.array.literal.fix.family.name")
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val calleeExpression = descriptor.psiElement as KtExpression
val callExpression = calleeExpression.parent as KtCallExpression
val valueArgument = callExpression.getParentOfType<KtValueArgument>(false)
valueArgument?.getSpreadElement()?.delete()
val arguments = callExpression.valueArguments
val arrayLiteral = KtPsiFactory(callExpression).buildExpression {
appendFixedText("[")
for ((index, argument) in arguments.withIndex()) {
appendExpression(argument.getArgumentExpression())
if (index != arguments.size - 1) {
appendFixedText(", ")
}
}
appendFixedText("]")
} as KtCollectionLiteralExpression
callExpression.replace(arrayLiteral)
}
}
}
|
apache-2.0
|
0cb63601b78a83a43c961de3c508fde8
| 43.457143 | 158 | 0.679627 | 5.91635 | false | false | false | false |
cdietze/klay
|
tripleklay/src/main/kotlin/tripleklay/ui/Field.kt
|
1
|
11376
|
package tripleklay.ui
import euklid.f.Rectangle
import klay.core.Input
import klay.core.Keyboard
import klay.scene.LayerUtil
import klay.scene.Pointer
import react.Signal
import react.SignalView
import react.Value
import tripleklay.platform.NativeTextField
import tripleklay.platform.TPPlatform
import kotlin.reflect.KClass
/**
* Displays text which can be edited via the [Input.getText] popup.
*/
class Field constructor(initialText: String = "", styles: Styles = Styles.none()) : TextWidget<Field>() {
/** Exposes protected field information required for native fields. */
inner class Native {
/** Resolves the given style for the field. */
fun <T> resolveStyle(style: Style<T>): T {
return [email protected](style)
}
/** Tests if the proposed text is valid. */
fun isValid(text: String): Boolean {
return [email protected](text)
}
/** Transforms the given text. */
fun transform(text: String): String {
return [email protected](text)
}
/** A signal that is dispatched when the native text field has lost focus. Value is false if
* editing was canceled */
fun finishedEditing(): Signal<Boolean> {
return _finishedEditing
}
/** Refreshes the bounds of this field's native field. Used as a platform callback to
* support some degree of animation for UI containing native fields. */
fun refreshBounds() {
updateNativeFieldBounds()
}
fun field(): Field {
return this@Field
}
}
/** For native text fields, decides whether to block a keypress based on the proposed content
* of the field. */
interface Validator {
/** Return false if the keypress causing this text should be blocked. */
fun isValid(text: String): Boolean
}
/** For native text fields, transforms text during typing. */
interface Transformer {
/** Transform the specified text. */
fun transform(text: String): String
}
/** Blocks keypresses for a native text field when the length is at a given maximum. */
class MaxLength(
/** The maximum length accepted. */
val max: Int) : Validator {
override fun isValid(text: String): Boolean {
return text.length <= max
}
}
/** The text displayed by this widget. */
val text: Value<String>
private var _nativeField: NativeTextField? = null
private var _validator: Validator? = null
private var _transformer: Transformer? = null
private var _textType: Keyboard.TextType? = null
private var _fullTimeNative: Boolean = false
private val _finishedEditing: Signal<Boolean>
// used when popping up a text entry interface on mobile platforms
private var _popupLabel: String? = null
constructor(styles: Styles) : this("", styles)
init {
setStyles(styles)
text = Value("")
_finishedEditing = Signal()
if (hasNative()) {
_finishedEditing.connect({ if (!_fullTimeNative) updateMode(false) })
}
this.text.update(initialText)
this.text.connect(textDidChange())
}
/** Returns a signal that is dispatched when text editing is complete. */
fun finishedEditing(): SignalView<Boolean> {
return _finishedEditing
}
/**
* Configures the label to be displayed when text is requested via a popup.
*/
fun setPopupLabel(label: String): Field {
_popupLabel = label
return this
}
/**
* Forcibly notify the NativeTextField backing this field that its screen position has changed.
* @return this for call chaining.
*/
fun updateNativeFieldBounds(): Field {
if (_nativeField != null) _nativeField!!.setBounds(nativeFieldBounds)
return this
}
/** Attempt to focus on this field, if it is backed by a native field. If the platform
* uses a virtual keyboard, this will cause it slide up, just as though the use had tapped
* the field. For hardware keyboard, a blinking caret will appear in the field. */
fun focus() {
if (_nativeField != null) _nativeField!!.focus()
}
override fun setVisible(visible: Boolean): Field {
if (_nativeField != null) {
if (visible) {
_nativeField!!.add()
} else {
_nativeField!!.remove()
}
}
return super.setVisible(visible)
}
/** Returns this field's native text field, if it has one, otherwise null. */
fun exposeNativeField(): NativeTextField? {
return _nativeField
}
/**
* Main entry point for deciding whether to reject keypresses on a native field. By default,
* consults the current validator instance, set up by [.VALIDATOR].
*/
private fun textIsValid(text: String): Boolean {
return _validator == null || _validator!!.isValid(text)
}
/**
* Called when the native field's value is changed. Override and return a modified value to
* perform text transformation while the user is editing the field. By default, consults
* the current transformer instance, set up by [.TRANSFORMER].
*/
private fun transformText(text: String): String {
return if (_transformer == null) text else _transformer!!.transform(text)
}
override val styleClass: KClass<*>
get() = Field::class
override fun text(): String? {
val ctext = text.get()
// we always want non-empty text so that we force ourselves to always have a text layer and
// sane dimensions even if the text field contains no text
return if (ctext == null || ctext.isEmpty()) " " else ctext
}
override fun icon(): Icon? {
return null // fields never have an icon
}
override fun wasRemoved() {
super.wasRemoved()
// make sure the field is gone
updateMode(false)
}
override fun createBehavior(): Behavior<Field>? {
return object : Behavior.Select<Field>(this) {
override fun onClick(iact: Pointer.Interaction) {
if (!_fullTimeNative) startEdit()
}
}
}
override fun createLayoutData(hintX: Float, hintY: Float): LayoutData {
return FieldLayoutData(hintX, hintY)
}
private fun startEdit() {
if (hasNative()) {
updateMode(true)
_nativeField!!.focus()
} else {
// TODO: multi-line keyboard.getText
root()!!.iface.plat.input.getText(_textType!!, _popupLabel!!, text.get()).onSuccess({ result: String? ->
// null result is a canceled entry dialog
if (result != null) text.update(result)
_finishedEditing.emit(result != null)
})
}
}
private val nativeFieldBounds: Rectangle
get() {
val insets = resolveStyle(Style.BACKGROUND).insets
val screenCoords = LayerUtil.layerToScreen(layer, insets.left(), insets.top())
return Rectangle(screenCoords.x, screenCoords.y,
_size.width - insets.width(), _size.height - insets.height())
}
private fun updateMode(nativeField: Boolean) {
if (!hasNative()) return
if (nativeField) {
_nativeField = if (_nativeField == null)
TPPlatform.instance().createNativeTextField(Native())
else
TPPlatform.instance().refresh(_nativeField!!)
_nativeField!!.setEnabled(isEnabled)
updateNativeFieldBounds()
_nativeField!!.add()
setGlyphLayerVisible(false)
} else if (_nativeField != null) {
_nativeField!!.remove()
setGlyphLayerVisible(true)
}
}
private fun setGlyphLayerVisible(visible: Boolean) {
if (_tglyph.layer() != null) _tglyph.layer()!!.setVisible(visible)
}
private inner class FieldLayoutData(hintX: Float, hintY: Float) : TextWidget<Field>.TextLayoutData(hintX, hintY) {
override fun layout(left: Float, top: Float, width: Float, height: Float) {
super.layout(left, top, width, height)
_fullTimeNative = hasNative() && resolveStyle(FULLTIME_NATIVE_FIELD)
if (_fullTimeNative || _nativeField != null) updateMode(true)
// make sure our cached bits are up to date
_validator = resolveStyle(VALIDATOR)
_transformer = resolveStyle(TRANSFORMER)
_textType = resolveStyle(TEXT_TYPE)
}
}
companion object {
/** Creates a style binding for the given maximum length. */
fun maxLength(max: Int): Style.Binding<Validator?> {
return VALIDATOR.`is`(MaxLength(max))
}
/** Checks if the platform has native text fields. */
fun hasNative(): Boolean {
return TPPlatform.instance().hasNativeTextFields()
}
/** If on a platform that utilizes native fields and this is true, the native field is
* displayed whenever this Field is visible, and the native field is responsible for all text
* rendering. If false, the native field is only displayed while actively editing (after a user
* click). */
val FULLTIME_NATIVE_FIELD: Style.Flag = Style.newFlag(false, true)
/** Controls the behavior of native text fields with respect to auto-capitalization on
* platforms that support it. */
// TODO: iOS supports multiple styles of autocap, support them here?
val AUTOCAPITALIZATION: Style.Flag = Style.newFlag(false, true)
/** Controls the behavior of native text fields with respect to auto-correction on platforms
* that support it. */
val AUTOCORRECTION: Style.Flag = Style.newFlag(false, true)
/** Controls secure text entry on native text fields: typically this will mean dots or asterix
* displayed instead of the typed character. */
val SECURE_TEXT_ENTRY: Style.Flag = Style.newFlag(false, false)
/** Sets the Keyboard.TextType in use by this Field. */
val TEXT_TYPE: Style<Keyboard.TextType> = Style.newStyle(
false, Keyboard.TextType.DEFAULT)
/** Sets the validator to use when censoring keypresses into native text fields.
* @see MaxLength
*/
val VALIDATOR = Style.newStyle<Validator?>(true, null)
/** Sets the transformner to use when updating native text fields while being typed into. */
val TRANSFORMER = Style.newStyle<Transformer?>(true, null)
/** Sets the label used on the "return" key of the virtual keyboard on native keyboards. Be
* aware that some platforms (such as iOS) have a limited number of options. The underlying
* native implementation is responsible for attempting to match this style, but may be unable
* to do so. Defaults to null (uses platform default). */
val RETURN_KEY_LABEL = Style.newStyle<String?>(false, null)
/** Sets the field to allow the return key to insert a line break in the text. */
val MULTILINE: Style.Flag = Style.newFlag(false, false)
}
}
|
apache-2.0
|
26c49b7a661e01aef7c8d3b44b255fd7
| 35.696774 | 118 | 0.623154 | 4.57971 | false | false | false | false |
androidx/androidx
|
navigation/navigation-runtime/src/main/java/androidx/navigation/NavInflater.kt
|
3
|
14700
|
/*
* 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 androidx.navigation
import android.annotation.SuppressLint
import android.content.Context
import android.content.res.Resources
import android.content.res.TypedArray
import android.content.res.XmlResourceParser
import android.os.Bundle
import android.util.AttributeSet
import android.util.TypedValue
import android.util.Xml
import androidx.annotation.NavigationRes
import androidx.annotation.RestrictTo
import androidx.core.content.res.use
import androidx.core.content.withStyledAttributes
import androidx.navigation.common.R
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserException
import java.io.IOException
/**
* Class which translates a navigation XML file into a [NavGraph]
*/
public class NavInflater(
private val context: Context,
private val navigatorProvider: NavigatorProvider
) {
/**
* Inflate a NavGraph from the given XML resource id.
*
* @param graphResId
* @return
*/
@SuppressLint("ResourceType")
public fun inflate(@NavigationRes graphResId: Int): NavGraph {
val res = context.resources
val parser = res.getXml(graphResId)
val attrs = Xml.asAttributeSet(parser)
return try {
var type: Int
while (parser.next().also { type = it } != XmlPullParser.START_TAG &&
type != XmlPullParser.END_DOCUMENT
) { /* Empty loop */
}
if (type != XmlPullParser.START_TAG) {
throw XmlPullParserException("No start tag found")
}
val rootElement = parser.name
val destination = inflate(res, parser, attrs, graphResId)
require(destination is NavGraph) {
"Root element <$rootElement> did not inflate into a NavGraph"
}
destination
} catch (e: Exception) {
throw RuntimeException(
"Exception inflating ${res.getResourceName(graphResId)} line ${parser.lineNumber}",
e
)
} finally {
parser.close()
}
}
@Throws(XmlPullParserException::class, IOException::class)
private fun inflate(
res: Resources,
parser: XmlResourceParser,
attrs: AttributeSet,
graphResId: Int
): NavDestination {
val navigator = navigatorProvider.getNavigator<Navigator<*>>(parser.name)
val dest = navigator.createDestination()
dest.onInflate(context, attrs)
val innerDepth = parser.depth + 1
var type: Int
var depth = 0
while (parser.next().also { type = it } != XmlPullParser.END_DOCUMENT &&
(parser.depth.also { depth = it } >= innerDepth || type != XmlPullParser.END_TAG)
) {
if (type != XmlPullParser.START_TAG) {
continue
}
if (depth > innerDepth) {
continue
}
val name = parser.name
if (TAG_ARGUMENT == name) {
inflateArgumentForDestination(res, dest, attrs, graphResId)
} else if (TAG_DEEP_LINK == name) {
inflateDeepLink(res, dest, attrs)
} else if (TAG_ACTION == name) {
inflateAction(res, dest, attrs, parser, graphResId)
} else if (TAG_INCLUDE == name && dest is NavGraph) {
res.obtainAttributes(attrs, androidx.navigation.R.styleable.NavInclude).use {
val id = it.getResourceId(androidx.navigation.R.styleable.NavInclude_graph, 0)
dest.addDestination(inflate(id))
}
} else if (dest is NavGraph) {
dest.addDestination(inflate(res, parser, attrs, graphResId))
}
}
return dest
}
@Throws(XmlPullParserException::class)
private fun inflateArgumentForDestination(
res: Resources,
dest: NavDestination,
attrs: AttributeSet,
graphResId: Int
) {
res.obtainAttributes(attrs, R.styleable.NavArgument).use { array ->
val name = array.getString(R.styleable.NavArgument_android_name)
?: throw XmlPullParserException("Arguments must have a name")
val argument = inflateArgument(array, res, graphResId)
dest.addArgument(name, argument)
}
}
@Throws(XmlPullParserException::class)
private fun inflateArgumentForBundle(
res: Resources,
bundle: Bundle,
attrs: AttributeSet,
graphResId: Int
) {
res.obtainAttributes(attrs, R.styleable.NavArgument).use { array ->
val name = array.getString(R.styleable.NavArgument_android_name)
?: throw XmlPullParserException("Arguments must have a name")
val argument = inflateArgument(array, res, graphResId)
if (argument.isDefaultValuePresent) {
argument.putDefaultValue(name, bundle)
}
}
}
@Throws(XmlPullParserException::class)
private fun inflateArgument(a: TypedArray, res: Resources, graphResId: Int): NavArgument {
val argumentBuilder = NavArgument.Builder()
argumentBuilder.setIsNullable(a.getBoolean(R.styleable.NavArgument_nullable, false))
var value = sTmpValue.get()
if (value == null) {
value = TypedValue()
sTmpValue.set(value)
}
var defaultValue: Any? = null
var navType: NavType<*>? = null
val argType = a.getString(R.styleable.NavArgument_argType)
if (argType != null) {
navType = NavType.fromArgType(argType, res.getResourcePackageName(graphResId))
}
if (a.getValue(R.styleable.NavArgument_android_defaultValue, value)) {
if (navType === NavType.ReferenceType) {
defaultValue = if (value.resourceId != 0) {
value.resourceId
} else if (value.type == TypedValue.TYPE_FIRST_INT && value.data == 0) {
// Support "0" as a default value for reference types
0
} else {
throw XmlPullParserException(
"unsupported value '${value.string}' for ${navType.name}. Must be a " +
"reference to a resource."
)
}
} else if (value.resourceId != 0) {
if (navType == null) {
navType = NavType.ReferenceType
defaultValue = value.resourceId
} else {
throw XmlPullParserException(
"unsupported value '${value.string}' for ${navType.name}. You must use a " +
"\"${NavType.ReferenceType.name}\" type to reference other resources."
)
}
} else if (navType === NavType.StringType) {
defaultValue = a.getString(R.styleable.NavArgument_android_defaultValue)
} else {
when (value.type) {
TypedValue.TYPE_STRING -> {
val stringValue = value.string.toString()
if (navType == null) {
navType = NavType.inferFromValue(stringValue)
}
defaultValue = navType.parseValue(stringValue)
}
TypedValue.TYPE_DIMENSION -> {
navType = checkNavType(
value, navType, NavType.IntType, argType, "dimension"
)
defaultValue = value.getDimension(res.displayMetrics).toInt()
}
TypedValue.TYPE_FLOAT -> {
navType = checkNavType(value, navType, NavType.FloatType, argType, "float")
defaultValue = value.float
}
TypedValue.TYPE_INT_BOOLEAN -> {
navType = checkNavType(value, navType, NavType.BoolType, argType, "boolean")
defaultValue = value.data != 0
}
else ->
if (value.type >= TypedValue.TYPE_FIRST_INT &&
value.type <= TypedValue.TYPE_LAST_INT
) {
if (navType === NavType.FloatType) {
navType = checkNavType(
value, navType, NavType.FloatType, argType, "float"
)
defaultValue = value.data.toFloat()
} else {
navType = checkNavType(
value, navType, NavType.IntType, argType, "integer"
)
defaultValue = value.data
}
} else {
throw XmlPullParserException("unsupported argument type ${value.type}")
}
}
}
}
if (defaultValue != null) {
argumentBuilder.setDefaultValue(defaultValue)
}
if (navType != null) {
argumentBuilder.setType(navType)
}
return argumentBuilder.build()
}
@Throws(XmlPullParserException::class)
private fun inflateDeepLink(res: Resources, dest: NavDestination, attrs: AttributeSet) {
res.obtainAttributes(attrs, R.styleable.NavDeepLink).use { array ->
val uri = array.getString(R.styleable.NavDeepLink_uri)
val action = array.getString(R.styleable.NavDeepLink_action)
val mimeType = array.getString(R.styleable.NavDeepLink_mimeType)
if (uri.isNullOrEmpty() && action.isNullOrEmpty() && mimeType.isNullOrEmpty()) {
throw XmlPullParserException(
"Every <$TAG_DEEP_LINK> must include at least one of app:uri, app:action, or " +
"app:mimeType"
)
}
val builder = NavDeepLink.Builder()
if (uri != null) {
builder.setUriPattern(uri.replace(APPLICATION_ID_PLACEHOLDER, context.packageName))
}
if (!action.isNullOrEmpty()) {
builder.setAction(action.replace(APPLICATION_ID_PLACEHOLDER, context.packageName))
}
if (mimeType != null) {
builder.setMimeType(
mimeType.replace(
APPLICATION_ID_PLACEHOLDER,
context.packageName
)
)
}
dest.addDeepLink(builder.build())
}
}
@Throws(IOException::class, XmlPullParserException::class)
private fun inflateAction(
res: Resources,
dest: NavDestination,
attrs: AttributeSet,
parser: XmlResourceParser,
graphResId: Int
) {
context.withStyledAttributes(attrs, R.styleable.NavAction) {
val id = getResourceId(R.styleable.NavAction_android_id, 0)
val destId = getResourceId(R.styleable.NavAction_destination, 0)
val action = NavAction(destId)
val builder = NavOptions.Builder()
builder.setLaunchSingleTop(getBoolean(R.styleable.NavAction_launchSingleTop, false))
builder.setRestoreState(getBoolean(R.styleable.NavAction_restoreState, false))
builder.setPopUpTo(
getResourceId(R.styleable.NavAction_popUpTo, -1),
getBoolean(R.styleable.NavAction_popUpToInclusive, false),
getBoolean(R.styleable.NavAction_popUpToSaveState, false)
)
builder.setEnterAnim(getResourceId(R.styleable.NavAction_enterAnim, -1))
builder.setExitAnim(getResourceId(R.styleable.NavAction_exitAnim, -1))
builder.setPopEnterAnim(getResourceId(R.styleable.NavAction_popEnterAnim, -1))
builder.setPopExitAnim(getResourceId(R.styleable.NavAction_popExitAnim, -1))
action.navOptions = builder.build()
val args = Bundle()
val innerDepth = parser.depth + 1
var type: Int
var depth = 0
while (parser.next().also { type = it } != XmlPullParser.END_DOCUMENT &&
(parser.depth.also { depth = it } >= innerDepth || type != XmlPullParser.END_TAG)
) {
if (type != XmlPullParser.START_TAG) {
continue
}
if (depth > innerDepth) {
continue
}
val name = parser.name
if (TAG_ARGUMENT == name) {
inflateArgumentForBundle(res, args, attrs, graphResId)
}
}
if (!args.isEmpty) {
action.defaultArguments = args
}
dest.putAction(id, action)
}
}
public companion object {
private const val TAG_ARGUMENT = "argument"
private const val TAG_DEEP_LINK = "deepLink"
private const val TAG_ACTION = "action"
private const val TAG_INCLUDE = "include"
/**
* @hide
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public const val APPLICATION_ID_PLACEHOLDER: String = "\${applicationId}"
private val sTmpValue = ThreadLocal<TypedValue>()
@Throws(XmlPullParserException::class)
internal fun checkNavType(
value: TypedValue,
navType: NavType<*>?,
expectedNavType: NavType<*>,
argType: String?,
foundType: String
): NavType<*> {
if (navType != null && navType !== expectedNavType) {
throw XmlPullParserException("Type is $argType but found $foundType: ${value.data}")
}
return navType ?: expectedNavType
}
}
}
|
apache-2.0
|
6ca03c54503c57c2b8e3b9783e4a48c4
| 40.764205 | 100 | 0.555782 | 5.095321 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/pushDown/KotlinPushDownDialog.kt
|
4
|
4503
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.pushDown
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiNamedElement
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.classMembers.*
import com.intellij.refactoring.ui.RefactoringDialog
import org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringSettings
import org.jetbrains.kotlin.idea.refactoring.memberInfo.KotlinMemberInfo
import org.jetbrains.kotlin.idea.refactoring.memberInfo.KotlinMemberSelectionPanel
import org.jetbrains.kotlin.idea.refactoring.memberInfo.KotlinUsesDependencyMemberInfoModel
import org.jetbrains.kotlin.idea.refactoring.memberInfo.qualifiedClassNameForRendering
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtProperty
import java.awt.BorderLayout
import java.awt.GridBagConstraints
import java.awt.GridBagLayout
import java.awt.Insets
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JPanel
class KotlinPushDownDialog(
project: Project,
private val memberInfos: List<KotlinMemberInfo>,
private val sourceClass: KtClass
) : RefactoringDialog(project, true) {
init {
title = PUSH_MEMBERS_DOWN
init()
}
private var memberInfoModel: MemberInfoModel<KtNamedDeclaration, KotlinMemberInfo>? = null
private val selectedMemberInfos: List<KotlinMemberInfo>
get() = memberInfos.filter { it.isChecked && memberInfoModel?.isMemberEnabled(it) ?: false }
override fun getDimensionServiceKey() = "#" + this::class.java.name
override fun createNorthPanel(): JComponent {
val gbConstraints = GridBagConstraints()
val panel = JPanel(GridBagLayout())
gbConstraints.insets = Insets(4, 0, 10, 8)
gbConstraints.weighty = 1.0
gbConstraints.weightx = 1.0
gbConstraints.gridy = 0
gbConstraints.gridwidth = GridBagConstraints.REMAINDER
gbConstraints.fill = GridBagConstraints.BOTH
gbConstraints.anchor = GridBagConstraints.WEST
panel.add(
JLabel(
RefactoringBundle.message(
"push.members.from.0.down.label",
sourceClass.qualifiedClassNameForRendering()
)
), gbConstraints
)
return panel
}
override fun createCenterPanel(): JComponent {
val panel = JPanel(BorderLayout())
val memberSelectionPanel = KotlinMemberSelectionPanel(
RefactoringBundle.message("members.to.be.pushed.down.panel.title"),
memberInfos,
RefactoringBundle.message("keep.abstract.column.header")
)
panel.add(memberSelectionPanel, BorderLayout.CENTER)
memberInfoModel = object : DelegatingMemberInfoModel<KtNamedDeclaration, KotlinMemberInfo>(
ANDCombinedMemberInfoModel<KtNamedDeclaration, KotlinMemberInfo>(
KotlinUsesDependencyMemberInfoModel<KtNamedDeclaration, KotlinMemberInfo>(sourceClass, null, false),
UsedByDependencyMemberInfoModel<KtNamedDeclaration, PsiNamedElement, KotlinMemberInfo>(sourceClass)
)
) {
override fun isFixedAbstract(member: KotlinMemberInfo?) = null
override fun isAbstractEnabled(memberInfo: KotlinMemberInfo): Boolean {
val member = memberInfo.member
if (member.hasModifier(KtTokens.INLINE_KEYWORD) ||
member.hasModifier(KtTokens.EXTERNAL_KEYWORD) ||
member.hasModifier(KtTokens.LATEINIT_KEYWORD)
) return false
return member is KtNamedFunction || member is KtProperty
}
}
memberInfoModel!!.memberInfoChanged(MemberInfoChange(memberInfos))
memberSelectionPanel.table.memberInfoModel = memberInfoModel
memberSelectionPanel.table.addMemberInfoChangeListener(memberInfoModel)
return panel
}
override fun doAction() {
if (!isOKActionEnabled) return
KotlinRefactoringSettings.instance.PUSH_DOWN_PREVIEW_USAGES = isPreviewUsages
invokeRefactoring(KotlinPushDownProcessor(project, sourceClass, selectedMemberInfos))
}
}
|
apache-2.0
|
7377572dc61149e8b1b5998f7ad63bc2
| 40.703704 | 158 | 0.723296 | 5.399281 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/base/plugin/src/org/jetbrains/kotlin/idea/compiler/configuration/KotlinIdePlugin.kt
|
2
|
2369
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.compiler.configuration
import com.intellij.ide.plugins.IdeaPluginDescriptor
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.internal.statistic.utils.PluginInfo
import com.intellij.internal.statistic.utils.getPluginInfoById
import com.intellij.openapi.extensions.PluginId
object KotlinIdePlugin {
val id: PluginId
/**
* If `true`, the installed Kotlin IDE plugin is post-processed to be included in some other IDE, such as AppCode.
*/
val isPostProcessed: Boolean
/**
* If `true`, the plugin version was patched in runtime, using the `kotlin.plugin.version` Java system property.
*/
val hasPatchedVersion: Boolean
/**
* An original (non-patched) plugin version from the plugin descriptor.
*/
val originalVersion: String
/**
* Kotlin IDE plugin version (the patched version if provided, the version from the plugin descriptor otherwise).
*/
val version: String
val isSnapshot: Boolean
val isRelease: Boolean
get() = !isSnapshot && KotlinPluginLayout.standaloneCompilerVersion.isRelease
val isPreRelease: Boolean
get() = !isRelease
val isDev: Boolean
get() = !isSnapshot && KotlinPluginLayout.standaloneCompilerVersion.isDev
fun getPluginInfo(): PluginInfo = getPluginInfoById(id)
init {
val mainPluginId = "org.jetbrains.kotlin"
val allPluginIds = listOf(
mainPluginId,
"com.intellij.appcode.kmm",
"org.jetbrains.kotlin.native.appcode"
)
val pluginDescriptor = PluginManagerCore.getPlugins().firstOrNull { it.pluginId.idString in allPluginIds }
?: error("Kotlin IDE plugin not found above the active plugins: " + PluginManagerCore.getPlugins().contentToString())
val patchedVersion = System.getProperty("kotlin.plugin.version", null)
id = pluginDescriptor.pluginId
isPostProcessed = id.idString == mainPluginId
hasPatchedVersion = patchedVersion != null
originalVersion = pluginDescriptor.version
version = patchedVersion ?: originalVersion
isSnapshot = version == "@snapshot@" || version.contains("-SNAPSHOT")
}
}
|
apache-2.0
|
aa8d3a1984ea2effdd1549a9f13da39d
| 34.373134 | 129 | 0.702828 | 4.987368 | false | false | false | false |
jwren/intellij-community
|
platform/build-scripts/groovy/org/jetbrains/intellij/build/impl/ModuleOutputPatcher.kt
|
1
|
3845
|
// 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.intellij.build.impl
import io.opentelemetry.api.common.AttributeKey
import io.opentelemetry.api.common.Attributes
import io.opentelemetry.api.trace.Span
import java.nio.ByteBuffer
import java.nio.charset.StandardCharsets
import java.nio.file.Path
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.CopyOnWriteArrayList
class ModuleOutputPatcher {
val patchDirs: ConcurrentHashMap<String, CopyOnWriteArrayList<Path>> = ConcurrentHashMap()
val patches: ConcurrentHashMap<String, MutableMap<String, ByteArray>> = ConcurrentHashMap()
@JvmOverloads
fun patchModuleOutput(moduleName: String, path: String, content: String, overwrite: Boolean = false) {
patchModuleOutput(moduleName, path, content.toByteArray(StandardCharsets.UTF_8), overwrite)
}
@JvmOverloads
fun patchModuleOutput(moduleName: String, path: String, content: ByteArray, overwrite: Boolean = false) {
val pathToData = patches.computeIfAbsent(moduleName) { Collections.synchronizedMap(LinkedHashMap()) }
if (overwrite) {
val overwritten = pathToData.put(path, content) != null
Span.current().addEvent("patch module output", Attributes.of(
AttributeKey.stringKey("module"), moduleName,
AttributeKey.stringKey("path"), path,
AttributeKey.booleanKey("overwrite"), true,
AttributeKey.booleanKey("overwritten"), overwritten,
))
}
else {
val existing = pathToData.putIfAbsent(path, content)
val span = Span.current()
if (existing != null) {
span.addEvent("failed to patch because path is duplicated", Attributes.of(
AttributeKey.stringKey("path"), path,
AttributeKey.stringKey("oldContent"), byteArrayToTraceStringValue(existing),
AttributeKey.stringKey("newContent"), byteArrayToTraceStringValue(content),
))
error("Patched directory $path is already added for module $moduleName")
}
span.addEvent("patch module output", Attributes.of(
AttributeKey.stringKey("module"), moduleName,
AttributeKey.stringKey("path"), path,
))
}
}
private fun byteArrayToTraceStringValue(value: ByteArray): String {
try {
return StandardCharsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(value)).toString()
}
catch (_: CharacterCodingException) {
return Base64.getMimeEncoder().encodeToString(value)
}
}
fun getPatchedPluginXmlIfExists(moduleName: String): String? {
val result = patches[moduleName]?.entries?.firstOrNull { entry -> entry.key == "META-INF/plugin.xml" }?.value
return if (result == null) null else String(result, StandardCharsets.UTF_8)
}
fun getPatchedPluginXml(moduleName: String): ByteArray {
val result = patches[moduleName]?.entries?.firstOrNull { it.key == "META-INF/plugin.xml" }?.value
if (result == null) {
error("patched plugin.xml not found for $moduleName module")
}
return result
}
/**
* Contents of {@code pathToDirectoryWithPatchedFiles} will be used to patch the module output.
*/
fun patchModuleOutput(moduleName: String, pathToDirectoryWithPatchedFiles: Path) {
val list = patchDirs.computeIfAbsent(moduleName) { CopyOnWriteArrayList() }
if (list.contains(pathToDirectoryWithPatchedFiles)) {
error("Patched directory $pathToDirectoryWithPatchedFiles is already added for module $moduleName")
}
list.add(pathToDirectoryWithPatchedFiles)
}
fun getPatchedDir(moduleName: String): Collection<Path> = patchDirs[moduleName] ?: emptyList()
fun getPatchedContent(moduleName: String): Map<String, ByteArray> = patches[moduleName] ?: emptyMap()
}
|
apache-2.0
|
415e28d0cf4a99437718a765f436ff31
| 42.202247 | 158 | 0.727438 | 4.582837 | false | false | false | false |
jwren/intellij-community
|
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/PackageSearchUI.kt
|
1
|
8055
|
package com.jetbrains.packagesearch.intellij.plugin.ui
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.Presentation
import com.intellij.openapi.actionSystem.ex.CustomComponentAction
import com.intellij.openapi.editor.colors.EditorColors
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.ui.Gray
import com.intellij.ui.JBColor
import com.intellij.util.ui.JBEmptyBorder
import com.intellij.util.ui.JBValue
import com.intellij.util.ui.StartupUiUtil
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.components.BorderLayoutPanel
import com.jetbrains.packagesearch.intellij.plugin.ui.components.BrowsableLinkLabel
import com.jetbrains.packagesearch.intellij.plugin.ui.util.ScalableUnits
import com.jetbrains.packagesearch.intellij.plugin.ui.util.ScaledPixels
import com.jetbrains.packagesearch.intellij.plugin.ui.util.scaled
import org.jetbrains.annotations.Nls
import java.awt.CardLayout
import java.awt.Color
import java.awt.Component
import java.awt.Dimension
import java.awt.FlowLayout
import java.awt.Rectangle
import java.awt.event.ActionEvent
import javax.swing.AbstractAction
import javax.swing.BorderFactory
import javax.swing.BoxLayout
import javax.swing.Icon
import javax.swing.JCheckBox
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JMenuItem
import javax.swing.JPanel
import javax.swing.JScrollPane
import javax.swing.JTextField
import javax.swing.KeyStroke
import javax.swing.Scrollable
object PackageSearchUI {
private val MAIN_BG_COLOR: Color = JBColor.namedColor("Plugins.background", UIUtil.getListBackground())
internal val GRAY_COLOR: Color = JBColor.namedColor("Label.infoForeground", JBColor(Gray._120, Gray._135))
internal val HeaderBackgroundColor = MAIN_BG_COLOR
internal val SectionHeaderBackgroundColor = JBColor.namedColor("Plugins.SectionHeader.background", 0xF7F7F7, 0x3C3F41)
internal val UsualBackgroundColor = MAIN_BG_COLOR
internal val ListRowHighlightBackground = JBColor.namedColor("PackageSearch.SearchResult.background", 0xF2F5F9, 0x4C5052)
internal val InfoBannerBackground = JBColor.lazy {
EditorColorsManager.getInstance().globalScheme.getColor(EditorColors.NOTIFICATION_BACKGROUND)
?: JBColor(0xE6EEF7, 0x1C3956)
}
internal val MediumHeaderHeight = JBValue.Float(30f)
internal val SmallHeaderHeight = JBValue.Float(24f)
@Suppress("MagicNumber") // Thanks, Swing
internal fun headerPanel(init: BorderLayoutPanel.() -> Unit) = object : BorderLayoutPanel() {
init {
border = JBEmptyBorder(2, 0, 2, 12)
init()
}
override fun getBackground() = HeaderBackgroundColor
}
internal fun cardPanel(cards: List<JPanel> = emptyList(), backgroundColor: Color = UsualBackgroundColor, init: JPanel.() -> Unit) =
object : JPanel() {
init {
layout = CardLayout()
cards.forEach { add(it) }
init()
}
override fun getBackground() = backgroundColor
}
internal fun borderPanel(backgroundColor: Color = UsualBackgroundColor, init: BorderLayoutPanel.() -> Unit) = object : BorderLayoutPanel() {
init {
init()
}
override fun getBackground() = backgroundColor
}
internal fun boxPanel(axis: Int = BoxLayout.Y_AXIS, backgroundColor: Color = UsualBackgroundColor, init: JPanel.() -> Unit) =
object : JPanel() {
init {
layout = BoxLayout(this, axis)
init()
}
override fun getBackground() = backgroundColor
}
internal fun flowPanel(backgroundColor: Color = UsualBackgroundColor, init: JPanel.() -> Unit) = object : JPanel() {
init {
layout = FlowLayout(FlowLayout.LEFT)
init()
}
override fun getBackground() = backgroundColor
}
fun checkBox(@Nls title: String, init: JCheckBox.() -> Unit = {}) = object : JCheckBox(title) {
init {
init()
}
override fun getBackground() = UsualBackgroundColor
}
fun textField(init: JTextField.() -> Unit): JTextField = JTextField().apply {
init()
}
internal fun menuItem(@Nls title: String, icon: Icon?, handler: () -> Unit): JMenuItem {
if (icon != null) {
return JMenuItem(title, icon).apply { addActionListener { handler() } }
}
return JMenuItem(title).apply { addActionListener { handler() } }
}
fun createLabel(@Nls text: String? = null, init: JLabel.() -> Unit = {}) = JLabel().apply {
font = StartupUiUtil.getLabelFont()
if (text != null) this.text = text
init()
}
internal fun createLabelWithLink(init: BrowsableLinkLabel.() -> Unit = {}) = BrowsableLinkLabel().apply {
font = StartupUiUtil.getLabelFont()
init()
}
internal fun getTextColorPrimary(isSelected: Boolean = false): Color = when {
isSelected -> JBColor.lazy { UIUtil.getListSelectionForeground(true) }
else -> JBColor.lazy { UIUtil.getListForeground() }
}
internal fun getTextColorSecondary(isSelected: Boolean = false): Color = when {
isSelected -> getTextColorPrimary(isSelected)
else -> GRAY_COLOR
}
internal fun setHeight(component: JComponent, @ScalableUnits height: Int, keepWidth: Boolean = false) {
setHeightPreScaled(component, height.scaled(), keepWidth)
}
internal fun setHeightPreScaled(component: JComponent, @ScaledPixels height: Int, keepWidth: Boolean = false) {
component.apply {
preferredSize = Dimension(if (keepWidth) preferredSize.width else 0, height)
minimumSize = Dimension(if (keepWidth) minimumSize.width else 0, height)
maximumSize = Dimension(if (keepWidth) maximumSize.width else Int.MAX_VALUE, height)
}
}
internal fun verticalScrollPane(c: Component) = object : JScrollPane(
VerticalScrollPanelWrapper(c),
VERTICAL_SCROLLBAR_AS_NEEDED,
HORIZONTAL_SCROLLBAR_NEVER
) {
init {
border = BorderFactory.createEmptyBorder()
viewport.background = UsualBackgroundColor
}
}
internal fun overrideKeyStroke(c: JComponent, stroke: String, action: () -> Unit) = overrideKeyStroke(c, stroke, stroke, action)
internal fun overrideKeyStroke(c: JComponent, key: String, stroke: String, action: () -> Unit) {
val inputMap = c.getInputMap(JComponent.WHEN_FOCUSED)
inputMap.put(KeyStroke.getKeyStroke(stroke), key)
c.actionMap.put(
key,
object : AbstractAction() {
override fun actionPerformed(arg: ActionEvent) {
action()
}
}
)
}
private class VerticalScrollPanelWrapper(content: Component) : JPanel(), Scrollable {
init {
layout = BoxLayout(this, BoxLayout.Y_AXIS)
add(content)
}
override fun getPreferredScrollableViewportSize(): Dimension = preferredSize
override fun getScrollableUnitIncrement(visibleRect: Rectangle, orientation: Int, direction: Int) = 10
override fun getScrollableBlockIncrement(visibleRect: Rectangle, orientation: Int, direction: Int) = 100
override fun getScrollableTracksViewportWidth() = true
override fun getScrollableTracksViewportHeight() = false
override fun getBackground() = UsualBackgroundColor
}
}
internal class ComponentActionWrapper(private val myComponentCreator: () -> JComponent) : DumbAwareAction(), CustomComponentAction {
override fun createCustomComponent(presentation: Presentation, place: String) = myComponentCreator()
override fun actionPerformed(e: AnActionEvent) {
// No-op
}
}
internal fun JComponent.updateAndRepaint() {
invalidate()
repaint()
}
|
apache-2.0
|
6d3a08d42e382189ef790657ec83231e
| 36.640187 | 144 | 0.686778 | 4.855335 | false | false | false | false |
jwren/intellij-community
|
platform/lang-impl/src/com/intellij/openapi/roots/ui/UiUtils.kt
|
5
|
4190
|
// 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.
@file:JvmName("UiUtils")
package com.intellij.openapi.roots.ui
import com.intellij.openapi.ui.isTextUnderMouse as isTextUnderMouseImpl
import com.intellij.openapi.ui.getActionShortcutText as getActionShortcutTextImpl
import com.intellij.openapi.ui.getKeyStrokes as getKeyStrokesImpl
import com.intellij.openapi.ui.removeKeyboardAction as removeKeyboardActionImpl
import com.intellij.openapi.ui.addKeyboardAction as addKeyboardActionImpl
import com.intellij.openapi.observable.util.whenItemSelected as whenItemSelectedImpl
import com.intellij.openapi.observable.util.whenTextChanged as whenTextModifiedImpl
import com.intellij.openapi.observable.util.whenFocusGained as whenFocusGainedImpl
import com.intellij.openapi.observable.util.onceWhenFocusGained as whenFirstFocusGainedImpl
import com.intellij.openapi.ui.ComboBox
import org.jetbrains.annotations.ApiStatus
import java.awt.event.*
import javax.swing.JComponent
import javax.swing.KeyStroke
import javax.swing.text.JTextComponent
//@formatter:off
@Deprecated("Use function from platform API", ReplaceWith("isTextUnderMouse(e)", "com.intellij.openapi.ui.isTextUnderMouse"))
@ApiStatus.ScheduledForRemoval
fun JTextComponent.isTextUnderMouse(e: MouseEvent) = isTextUnderMouseImpl(e)
@Deprecated("Use function from platform API", ReplaceWith("getActionShortcutText(actionId)", "com.intellij.openapi.ui.getActionShortcutText"))
@ApiStatus.ScheduledForRemoval
fun getActionShortcutText(actionId: String) = getActionShortcutTextImpl(actionId)
@Deprecated("Use function from platform API", ReplaceWith("getKeyStrokes(*actionIds)", "com.intellij.openapi.ui.getKeyStrokes"))
@ApiStatus.ScheduledForRemoval
fun getKeyStrokes(vararg actionIds: String) = getKeyStrokesImpl(*actionIds)
@Deprecated("Use function from platform API", ReplaceWith("removeKeyboardAction(*keyStrokes)", "com.intellij.openapi.ui.removeKeyboardAction"))
@ApiStatus.ScheduledForRemoval
fun JComponent.removeKeyboardAction(vararg keyStrokes: KeyStroke) = removeKeyboardActionImpl(*keyStrokes)
@Deprecated("Use function from platform API", ReplaceWith("removeKeyboardAction(keyStrokes)", "com.intellij.openapi.ui.removeKeyboardAction"))
@ApiStatus.ScheduledForRemoval
fun JComponent.removeKeyboardAction(keyStrokes: List<KeyStroke>) = removeKeyboardActionImpl(keyStrokes)
@Deprecated("Use function from platform API", ReplaceWith("addKeyboardAction(*keyStrokes) { action(it) }", "com.intellij.openapi.ui.addKeyboardAction"))
@ApiStatus.ScheduledForRemoval
fun JComponent.addKeyboardAction(vararg keyStrokes: KeyStroke, action: (ActionEvent) -> Unit) = addKeyboardActionImpl(*keyStrokes) { action(it) }
@Deprecated("Use function from platform API", ReplaceWith("addKeyboardAction(keyStrokes, action)", "com.intellij.openapi.ui.addKeyboardAction"))
@ApiStatus.ScheduledForRemoval
fun JComponent.addKeyboardAction(keyStrokes: List<KeyStroke>, action: (ActionEvent) -> Unit) = addKeyboardActionImpl(keyStrokes, action)
@Deprecated("Use function from platform API", ReplaceWith("whenItemSelected(listener)", "com.intellij.openapi.observable.util.whenItemSelected"))
@ApiStatus.ScheduledForRemoval
fun <E> ComboBox<E>.whenItemSelected(listener: (E) -> Unit) = whenItemSelectedImpl(listener = listener)
@Deprecated("Use function from platform API", ReplaceWith("whenTextChanged { listener() }", "com.intellij.openapi.observable.util.whenTextChanged"))
@ApiStatus.ScheduledForRemoval
fun JTextComponent.whenTextModified(listener: () -> Unit) = whenTextModifiedImpl { listener() }
@Deprecated("Use function from platform API", ReplaceWith("whenFocusGained { listener() }", "com.intellij.openapi.observable.util.whenFocusGained"))
@ApiStatus.ScheduledForRemoval
fun JComponent.whenFocusGained(listener: () -> Unit) = whenFocusGainedImpl { listener() }
@Deprecated("Use function from platform API", ReplaceWith("onceWhenFocusGained { listener() }", "com.intellij.openapi.observable.util.onceWhenFocusGained"))
@ApiStatus.ScheduledForRemoval
fun JComponent.whenFirstFocusGained(listener: () -> Unit) = whenFirstFocusGainedImpl { listener() }
|
apache-2.0
|
13af1cd9590f671af2a60cd111a0e129
| 75.181818 | 156 | 0.82673 | 4.505376 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/plugins/buildSystem/gradle/GradlePlugin.kt
|
3
|
9202
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.gradle
import kotlinx.collections.immutable.toPersistentList
import org.jetbrains.kotlin.tools.projectWizard.Versions
import org.jetbrains.kotlin.tools.projectWizard.core.*
import org.jetbrains.kotlin.tools.projectWizard.core.entity.PipelineTask
import org.jetbrains.kotlin.tools.projectWizard.core.entity.properties.Property
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.PluginSetting
import org.jetbrains.kotlin.tools.projectWizard.core.service.FileSystemWizardService
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.*
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.gradle.SettingsGradleFileIR
import org.jetbrains.kotlin.tools.projectWizard.phases.GenerationPhase
import org.jetbrains.kotlin.tools.projectWizard.plugins.StructurePlugin
import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.*
import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.KotlinPlugin
import org.jetbrains.kotlin.tools.projectWizard.plugins.printer.GradlePrinter
import org.jetbrains.kotlin.tools.projectWizard.plugins.printer.printBuildFile
import org.jetbrains.kotlin.tools.projectWizard.plugins.projectPath
import org.jetbrains.kotlin.tools.projectWizard.plugins.templates.TemplatesPlugin
import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.updateBuildFiles
import org.jetbrains.kotlin.tools.projectWizard.settings.version.Version
import org.jetbrains.kotlin.tools.projectWizard.templates.FileTemplate
import org.jetbrains.kotlin.tools.projectWizard.templates.FileTemplateDescriptor
abstract class GradlePlugin(context: Context) : BuildSystemPlugin(context) {
override val path = pluginPath
companion object : PluginSettingsOwner() {
override val pluginPath = "buildSystem.gradle"
val gradleProperties by listProperty(
"kotlin.code.style" to "official"
)
val settingsGradleFileIRs by listProperty<BuildSystemIR>()
val createGradlePropertiesFile by pipelineTask(GenerationPhase.PROJECT_GENERATION) {
runAfter(KotlinPlugin.createModules)
runBefore(TemplatesPlugin.renderFileTemplates)
isAvailable = isGradle
withAction {
TemplatesPlugin.addFileTemplate.execute(
FileTemplate(
FileTemplateDescriptor(
"gradle/gradle.properties.vm",
"gradle.properties".asPath()
),
StructurePlugin.projectPath.settingValue,
mapOf(
"properties" to gradleProperties
.propertyValue
.distinctBy { it.first }
)
)
)
}
}
val localProperties by listProperty<Pair<String, String>>()
val createLocalPropertiesFile by pipelineTask(GenerationPhase.PROJECT_GENERATION) {
runAfter(KotlinPlugin.createModules)
runBefore(TemplatesPlugin.renderFileTemplates)
isAvailable = isGradle
withAction {
val properties = localProperties.propertyValue
if (properties.isEmpty()) return@withAction UNIT_SUCCESS
TemplatesPlugin.addFileTemplate.execute(
FileTemplate(
FileTemplateDescriptor(
"gradle/local.properties.vm",
"local.properties".asPath()
),
StructurePlugin.projectPath.settingValue,
mapOf(
"properties" to localProperties.propertyValue
)
)
)
}
}
private val isGradle = checker { buildSystemType.isGradle }
val gradleVersion by valueSetting(
"<GRADLE_VERSION>",
GenerationPhase.PROJECT_GENERATION,
parser = Version.parser
) {
defaultValue = value(Versions.GRADLE)
}
val initGradleWrapperTask by pipelineTask(GenerationPhase.PROJECT_GENERATION) {
runBefore(TemplatesPlugin.renderFileTemplates)
isAvailable = isGradle
withAction {
TemplatesPlugin.addFileTemplate.execute(
FileTemplate(
FileTemplateDescriptor(
"gradle/gradle-wrapper.properties.vm",
"gradle" / "wrapper" / "gradle-wrapper.properties"
),
StructurePlugin.projectPath.settingValue,
mapOf(
"version" to gradleVersion.settingValue
)
)
)
}
}
val mergeCommonRepositories by pipelineTask(GenerationPhase.PROJECT_GENERATION) {
runBefore(createModules)
runAfter(takeRepositoriesFromDependencies)
runAfter(KotlinPlugin.createPluginRepositories)
isAvailable = isGradle
withAction {
val buildFiles = buildFiles.propertyValue
if (buildFiles.size == 1) return@withAction UNIT_SUCCESS
val moduleRepositories = buildFiles.mapNotNull { buildFileIR ->
if (buildFileIR.isRoot) null
else buildFileIR.irs.mapNotNull { it.safeAs<RepositoryIR>()?.repository }
}
val allRepositories = moduleRepositories.flatMapTo(hashSetOf()) { it }
val commonRepositories = allRepositories.filterTo(
KotlinPlugin.version.propertyValue.repositories.toMutableSet()
) { repo ->
moduleRepositories.all { repo in it }
}
updateBuildFiles { buildFile ->
buildFile.withReplacedIrs(
buildFile.irs
.filterNot { it.safeAs<RepositoryIR>()?.repository in commonRepositories }
.toPersistentList()
).let {
if (it.isRoot && commonRepositories.isNotEmpty()) {
val repositories = commonRepositories.map(::RepositoryIR).distinctAndSorted()
it.withIrs(AllProjectsRepositoriesIR(repositories))
} else it
}.asSuccess()
}
}
}
val createSettingsFileTask by pipelineTask(GenerationPhase.PROJECT_GENERATION) {
runAfter(KotlinPlugin.createModules)
runAfter(KotlinPlugin.createPluginRepositories)
isAvailable = isGradle
withAction {
val (createBuildFile, buildFileName) = settingsGradleBuildFileData ?: return@withAction UNIT_SUCCESS
val repositories = getPluginRepositoriesWithDefaultOnes().map { PluginManagementRepositoryIR(RepositoryIR(it)) }
val settingsGradleIR = SettingsGradleFileIR(
StructurePlugin.name.settingValue,
allModulesPaths.map { path -> path.joinToString(separator = "") { ":$it" } },
buildPersistenceList {
+repositories
+settingsGradleFileIRs.propertyValue
}
)
val buildFileText = createBuildFile().printBuildFile { settingsGradleIR.render(this) }
service<FileSystemWizardService>().createFile(
projectPath / buildFileName,
buildFileText
)
}
}
}
override val settings: List<PluginSetting<*, *>> = super.settings +
listOf(
gradleVersion,
)
override val pipelineTasks: List<PipelineTask> = super.pipelineTasks +
listOf(
createGradlePropertiesFile,
createLocalPropertiesFile,
initGradleWrapperTask,
createSettingsFileTask,
mergeCommonRepositories,
)
override val properties: List<Property<*>> = super.properties +
listOf(
gradleProperties,
settingsGradleFileIRs,
localProperties
)
}
val Reader.settingsGradleBuildFileData
get() = when (buildSystemType) {
BuildSystemType.GradleKotlinDsl ->
BuildFileData(
{ GradlePrinter(GradlePrinter.GradleDsl.KOTLIN) },
"settings.gradle.kts"
)
BuildSystemType.GradleGroovyDsl ->
BuildFileData(
{ GradlePrinter(GradlePrinter.GradleDsl.GROOVY) },
"settings.gradle"
)
else -> null
}
|
apache-2.0
|
4b166130a5fb37bffae491973b88f8a8
| 41.804651 | 158 | 0.596501 | 6.200809 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/pushDown/JavaToKotlinPushDownDelegate.kt
|
3
|
5496
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.pushDown
import com.intellij.psi.*
import com.intellij.refactoring.memberPushDown.JavaPushDownDelegate
import com.intellij.refactoring.memberPushDown.NewSubClassData
import com.intellij.refactoring.memberPushDown.PushDownData
import com.intellij.refactoring.util.RefactoringUtil
import com.intellij.refactoring.util.classMembers.MemberInfo
import com.intellij.util.containers.MultiMap
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaClassDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaMemberDescriptor
import org.jetbrains.kotlin.idea.core.getOrCreateCompanionObject
import org.jetbrains.kotlin.idea.j2k.j2k
import org.jetbrains.kotlin.idea.j2k.j2kText
import org.jetbrains.kotlin.idea.refactoring.isInterfaceClass
import org.jetbrains.kotlin.idea.refactoring.pullUp.addMemberToTarget
import org.jetbrains.kotlin.idea.util.getTypeSubstitution
import org.jetbrains.kotlin.idea.util.orEmpty
import org.jetbrains.kotlin.idea.util.toSubstitutor
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtCallableDeclaration
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtPsiFactory
class JavaToKotlinPushDownDelegate : JavaPushDownDelegate() {
override fun checkTargetClassConflicts(
targetClass: PsiElement?,
pushDownData: PushDownData<MemberInfo, PsiMember>,
conflicts: MultiMap<PsiElement, String>,
subClassData: NewSubClassData?
) {
super.checkTargetClassConflicts(targetClass, pushDownData, conflicts, subClassData)
val ktClass = targetClass?.unwrapped as? KtClassOrObject ?: return
val targetClassDescriptor = ktClass.unsafeResolveToDescriptor() as ClassDescriptor
for (memberInfo in pushDownData.membersToMove) {
val member = memberInfo.member ?: continue
checkExternalUsages(conflicts, member, targetClassDescriptor, ktClass.getResolutionFacade())
}
}
override fun pushDownToClass(targetClass: PsiElement, pushDownData: PushDownData<MemberInfo, PsiMember>) {
val superClass = pushDownData.sourceClass as? PsiClass ?: return
val subClass = targetClass.unwrapped as? KtClassOrObject ?: return
val resolutionFacade = subClass.getResolutionFacade()
val superClassDescriptor = superClass.getJavaClassDescriptor(resolutionFacade) ?: return
val subClassDescriptor = subClass.unsafeResolveToDescriptor() as ClassDescriptor
val substitutor = getTypeSubstitution(superClassDescriptor.defaultType, subClassDescriptor.defaultType)?.toSubstitutor().orEmpty()
val psiFactory = KtPsiFactory(subClass)
var hasAbstractMembers = false
members@ for (memberInfo in pushDownData.membersToMove) {
val member = memberInfo.member
val memberDescriptor = member.getJavaMemberDescriptor(resolutionFacade) ?: continue
when (member) {
is PsiMethod, is PsiField -> {
val ktMember = member.j2k() as? KtCallableDeclaration ?: continue@members
ktMember.removeModifier(KtTokens.DEFAULT_VISIBILITY_KEYWORD)
val isStatic = member.hasModifierProperty(PsiModifier.STATIC)
val targetMemberClass = if (isStatic && subClass is KtClass) subClass.getOrCreateCompanionObject() else subClass
val targetMemberClassDescriptor = resolutionFacade.resolveToDescriptor(targetMemberClass) as ClassDescriptor
if (member.hasModifierProperty(PsiModifier.ABSTRACT)) {
hasAbstractMembers = true
}
moveCallableMemberToClass(
ktMember,
memberDescriptor as CallableMemberDescriptor,
targetMemberClass,
targetMemberClassDescriptor,
substitutor,
memberInfo.isToAbstract
).apply {
if (subClass.isInterfaceClass()) {
removeModifier(KtTokens.ABSTRACT_KEYWORD)
}
}
}
is PsiClass -> {
if (memberInfo.overrides != null) {
val typeText =
RefactoringUtil.findReferenceToClass(superClass.implementsList, member)?.j2kText() ?: continue@members
subClass.addSuperTypeListEntry(psiFactory.createSuperTypeEntry(typeText))
} else {
val ktClass = member.j2k() as? KtClassOrObject ?: continue@members
addMemberToTarget(ktClass, subClass)
}
}
}
}
if (hasAbstractMembers && !subClass.isInterfaceClass()) {
subClass.addModifier(KtTokens.ABSTRACT_KEYWORD)
}
}
}
|
apache-2.0
|
f6466f49a075eea67718969f7264f68c
| 52.359223 | 158 | 0.694505 | 5.545913 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/idea/tests/testData/decompiler/stubBuilder/AnnotationsOnParenthesizedTypes/AnnotationsOnParenthesizedTypes.kt
|
15
|
681
|
public class AnnotationsOnParenthesizedTypes {
fun B<(@A C)>.receiverArgument() {}
fun parameter(a: (@A C)) {}
fun parameterArgument(a: B<(@A C)>) {}
fun returnValue(): (@A C) = null!!
fun <T> returnTypeParameterValue(): (@A T) = null!!
fun returnArgument(): B<(@A C)> = null!!
val lambdaType: (@A() (() -> C)) = null!!
val lambdaParameter: ((@A C)) -> C = null!!
val lambdaReturnValue: () -> (@A C) = null!!
val lambdaReceiver: (@A C).() -> C = null!!
val lambdaTypeWithNullableReceiver: (@A C)?.() -> C = null!!
}
@Target(AnnotationTarget.TYPE, AnnotationTarget.TYPE_PARAMETER)
annotation class A
interface B<T>
interface C
|
apache-2.0
|
e1770c2a3f65afaf72cd7b8eabf9cc8f
| 22.517241 | 64 | 0.597651 | 3.584211 | false | false | false | false |
ianhanniballake/muzei
|
example-watchface/src/main/java/com/example/muzei/watchface/ArtworkImageLoader.kt
|
1
|
3770
|
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.muzei.watchface
import android.content.Context
import android.database.ContentObserver
import android.graphics.Bitmap
import android.util.Log
import android.util.Size
import com.google.android.apps.muzei.api.MuzeiContract
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.channels.sendBlocking
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import java.io.FileNotFoundException
/**
* Class which provides access to the current Muzei artwork image. It also
* registers a ContentObserver to ensure the image stays up to date
*/
@OptIn(ExperimentalCoroutinesApi::class, FlowPreview::class)
class ArtworkImageLoader(private val context: Context) {
private val requestSizeSharedFlow = MutableSharedFlow<Size?>(
replay = 1,
onBufferOverflow = BufferOverflow.DROP_OLDEST)
var requestedSize: Size?
get() = requestSizeSharedFlow.replayCache.firstOrNull()
set(value) {
requestSizeSharedFlow.tryEmit(value)
}
private val unsizedArtworkFlow: Flow<Bitmap> = callbackFlow {
// Create a lambda that should be ran to update the artwork
val updateArtwork = {
try {
MuzeiContract.Artwork.getCurrentArtworkBitmap(context)?.run {
sendBlocking(this)
}
} catch (e: FileNotFoundException) {
Log.e("ArtworkImageLoader", "Error getting artwork image", e)
}
}
// Set up a ContentObserver that will update the artwork when it changes
val contentObserver: ContentObserver = object : ContentObserver(null) {
override fun onChange(selfChange: Boolean) {
updateArtwork()
}
}
context.contentResolver.registerContentObserver(
MuzeiContract.Artwork.CONTENT_URI, true, contentObserver)
// And update the artwork immediately to ensure we have the
// latest artwork
updateArtwork()
awaitClose {
context.contentResolver.unregisterContentObserver(contentObserver)
}
}
val artworkFlow = unsizedArtworkFlow.combine(
requestSizeSharedFlow.distinctUntilChanged()
) { image, size ->
// Resize the image to the specified size
when {
size == null -> image
image.width > image.height -> {
val scalingFactor = size.height * 1f / image.height
Bitmap.createScaledBitmap(image, (scalingFactor * image.width).toInt(),
size.height, true)
}
else -> {
val scalingFactor = size.width * 1f / image.width
Bitmap.createScaledBitmap(image, size.width,
(scalingFactor * image.height).toInt(), true)
}
}
}
}
|
apache-2.0
|
bfe084a504c47e30508bdb8d3da636db
| 37.080808 | 87 | 0.675332 | 4.954008 | false | false | false | false |
MaTriXy/dexcount-gradle-plugin
|
src/main/kotlin/com/getkeepsafe/dexcount/DexMethodCountExtension.kt
|
1
|
3959
|
/*
* Copyright (C) 2015-2016 KeepSafe Software
*
* 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.getkeepsafe.dexcount
import java.util.Locale
/**
* Configuration properties for [DexMethodCountTask] instances.
*/
open class DexMethodCountExtension {
/**
* When false, does not automatically count methods following the `package` task.
*/
var runOnEachPackage: Boolean = true
/**
* When false, does not automatically count methods following the `package` task.
*
* Deprecated since 0.7.0, as dexcount no longer depends on the `assemble` task.
* Currently a synonym for {@link #runOnEachPackage}; will be removed in a future
* version.
*/
@Deprecated("since 0.7.0; prefer {@link #runOnEachPackage}.", ReplaceWith("runOnEachPackage"))
var runOnEachAssemble: Boolean
get() = runOnEachPackage
set(value) {
runOnEachPackage = value
}
/**
* The format of the method count output, either "list", "tree", "json", or "yaml".
*/
var format: Any = OutputFormat.LIST
set(value) {
if (value is OutputFormat) {
field = value
} else {
try {
field = OutputFormat.valueOf("$value".toUpperCase(Locale.US))
} catch (ignored: IllegalArgumentException) {
throw IllegalArgumentException("Unrecognized output format '$value'")
}
}
}
/**
* When true, individual classes will be include in the package list - otherwise, only packages
* are included.
*/
var includeClasses: Boolean = false
/**
* When true, the number of classes in a package or class will be included in the printed output.
*/
var includeClassCount = false
/**
* When true, the number of fields in a package or class will be included in the printed output.
*/
var includeFieldCount = true
/**
* When true, the total number of methods in the application will be included in the printed
* output.
*/
var includeTotalMethodCount = false
/**
* When true, packages will be sorted in descending order by the number of methods they contain.
*/
var orderByMethodCount: Boolean = false
/**
* When true, the output file will also be printed to the build's standard output.
*/
var verbose: Boolean = false
/**
* Sets the max number of package segments in the output - i.e. when set to 2, counts stop at
* com.google, when set to 3 you get com.google.android, etc. "Unlimited" by default.
*/
var maxTreeDepth = Integer.MAX_VALUE
/**
* When true, Team City integration strings will be printed.
*/
var teamCityIntegration = false
/**
* A string which, if specified, will be added to TeamCity stat names. Null by default.
*/
var teamCitySlug: String? = null
/**
* When set, the build will fail when the APK/AAR has more methods than the max. 0 by default.
*/
var maxMethodCount = -1
/**
* If the user has passed '--stacktrace' or '--full-stacktrace', assume that they are trying to
* report a dexcount bug. Help us help them out by printing the current plugin title and version.
*/
var printVersion: Boolean = false
/**
* Timeout when running Dx in seconds.
*/
var dxTimeoutSec = 60
}
|
apache-2.0
|
8ac0f5510b3aa9cbb6f7af9d27ebc88b
| 31.45082 | 101 | 0.640566 | 4.453318 | false | false | false | false |
MartinStyk/AndroidApkAnalyzer
|
app/src/main/java/sk/styk/martin/apkanalyzer/manager/appanalysis/AndroidManifestManager.kt
|
1
|
5767
|
package sk.styk.martin.apkanalyzer.manager.appanalysis
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.content.res.Resources
import android.content.res.XmlResourceParser
import android.text.TextUtils
import sk.styk.martin.apkanalyzer.util.TAG_APP_ANALYSIS
import timber.log.Timber
import java.io.ByteArrayInputStream
import java.io.StringWriter
import javax.inject.Inject
import javax.xml.transform.OutputKeys
import javax.xml.transform.TransformerFactory
import javax.xml.transform.stream.StreamResult
import javax.xml.transform.stream.StreamSource
class AndroidManifestManager @Inject constructor(private val packageManager: PackageManager) {
fun loadAndroidManifest(packageName: String, packagePath: String): String {
val manifest = readManifest(packageManager, packageName, packagePath)
return formatManifest(manifest)
}
private fun readManifest(packageManager: PackageManager, packageName: String, packagePath: String): String {
val stringBuilder = StringBuilder()
try {
val apkResources = try {
packageManager.getResourcesForApplication(packageName)
} catch (exception: PackageManager.NameNotFoundException) {
packageManager.getPackageArchiveInfo(packagePath, 0)?.let {
packageManager.getResourcesForApplication(it.applicationInfo)
}
}
if (apkResources == null) {
Timber.tag(TAG_APP_ANALYSIS).w("Resources for package $packageName not found")
return ""
}
val parser = apkResources.assets.openXmlResourceParser("AndroidManifest.xml")
var eventType: Int = parser.next()
while (eventType != XmlResourceParser.END_DOCUMENT) {
// start tag found
if (eventType == XmlResourceParser.START_TAG) {
//start with opening element and writing its name
stringBuilder.append("<").append(parser.name)
//for each attribute in given element append attrName="attrValue"
for (attribute in 0 until parser.attributeCount) {
val attributeName = parser.getAttributeName(attribute)
val attributeValue = getAttributeValue(attributeName, parser.getAttributeValue(attribute), apkResources)
stringBuilder.append(" ").append(attributeName).append("=\"").append(attributeValue).append("\"")
}
stringBuilder.append(">")
if (parser.text != null) {
// if there is body of xml element, add it there
stringBuilder.append(parser.text)
}
} else if (eventType == XmlResourceParser.END_TAG) {
stringBuilder.append("</").append(parser.name).append(">")
}
eventType = parser.next()
}
} catch (e: Exception) {
Timber.tag(TAG_APP_ANALYSIS).e(e, "Error parsing manifest for $packageName")
}
return stringBuilder.toString()
}
private fun formatManifest(manifest: String): String {
return try {
val transformer = TransformerFactory.newInstance().newTransformer()
transformer.setOutputProperty(OutputKeys.INDENT, "yes")
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2")
val result = StreamResult(StringWriter())
val source = StreamSource(ByteArrayInputStream(manifest.toByteArray(charset("UTF-8"))))
transformer.transform(source, result)
result.writer.toString()
} catch (e: Exception) {
Timber.tag(TAG_APP_ANALYSIS).e(e, "Error formatting manifest $manifest")
""
}
}
private fun getAttributeValue(attributeName: String, attributeValue: String, resources: Resources): String {
if (attributeValue.startsWith("@")) {
try {
val id = Integer.valueOf(attributeValue.substring(1))
val value: String = when (attributeName) {
"theme", "resource" -> resources.getResourceEntryName(id)
else -> resources.getString(id)
}
return TextUtils.htmlEncode(value)
} catch (e: Exception) {
Timber.tag(TAG_APP_ANALYSIS).w(e, "Error reading attribute value $attributeName, $attributeValue")
}
}
return attributeValue
}
companion object {
/**
* It is not possible to get minSdkVersions using Android PackageManager - parse AndroidManifest of app
*/
fun getMinSdkVersion(applicationInfo: ApplicationInfo, packageManager: PackageManager): Int? {
try {
val apkResources = packageManager.getResourcesForApplication(applicationInfo)
val parser = apkResources.assets.openXmlResourceParser("AndroidManifest.xml")
var eventType = -1
while (eventType != XmlResourceParser.END_DOCUMENT) {
if (eventType == XmlResourceParser.START_TAG) {
if ("uses-sdk" == parser.name)
return parser.getAttributeIntValue("http://schemas.android.com/apk/res/android", "minSdkVersion", 0)
}
eventType = parser.next()
}
} catch (e: Exception) {
Timber.tag(TAG_APP_ANALYSIS).e(e, "Error reading minSdkValue for $applicationInfo")
}
return null
}
}
}
|
gpl-3.0
|
8ed4204d71d83f1a42d406f9d58029ec
| 39.900709 | 128 | 0.608635 | 5.409944 | false | false | false | false |
Waboodoo/HTTP-Shortcuts
|
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/main/ShortcutListViewModel.kt
|
1
|
22902
|
package ch.rmy.android.http_shortcuts.activities.main
import android.app.Application
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.lifecycle.viewModelScope
import ch.rmy.android.framework.extensions.context
import ch.rmy.android.framework.extensions.logException
import ch.rmy.android.framework.extensions.logInfo
import ch.rmy.android.framework.extensions.swapped
import ch.rmy.android.framework.extensions.toLocalizable
import ch.rmy.android.framework.extensions.truncate
import ch.rmy.android.framework.ui.IntentBuilder
import ch.rmy.android.framework.utils.FileUtil
import ch.rmy.android.framework.utils.localization.QuantityStringLocalizable
import ch.rmy.android.framework.utils.localization.StringResLocalizable
import ch.rmy.android.framework.viewmodel.BaseViewModel
import ch.rmy.android.framework.viewmodel.WithDialog
import ch.rmy.android.framework.viewmodel.viewstate.DialogState
import ch.rmy.android.framework.viewmodel.viewstate.ProgressDialogState
import ch.rmy.android.http_shortcuts.R
import ch.rmy.android.http_shortcuts.activities.ExecuteActivity
import ch.rmy.android.http_shortcuts.activities.main.usecases.GetContextMenuDialogUseCase
import ch.rmy.android.http_shortcuts.activities.main.usecases.GetCurlExportDialogUseCase
import ch.rmy.android.http_shortcuts.activities.main.usecases.GetExportOptionsDialogUseCase
import ch.rmy.android.http_shortcuts.activities.main.usecases.GetMoveOptionsDialogUseCase
import ch.rmy.android.http_shortcuts.activities.main.usecases.GetMoveToCategoryDialogUseCase
import ch.rmy.android.http_shortcuts.activities.main.usecases.GetShortcutDeletionDialogUseCase
import ch.rmy.android.http_shortcuts.activities.main.usecases.GetShortcutInfoDialogUseCase
import ch.rmy.android.http_shortcuts.activities.variables.usecases.GetUsedVariableIdsUseCase
import ch.rmy.android.http_shortcuts.dagger.getApplicationComponent
import ch.rmy.android.http_shortcuts.data.domains.app.AppRepository
import ch.rmy.android.http_shortcuts.data.domains.categories.CategoryId
import ch.rmy.android.http_shortcuts.data.domains.categories.CategoryRepository
import ch.rmy.android.http_shortcuts.data.domains.pending_executions.PendingExecutionsRepository
import ch.rmy.android.http_shortcuts.data.domains.shortcuts.ShortcutId
import ch.rmy.android.http_shortcuts.data.domains.shortcuts.ShortcutRepository
import ch.rmy.android.http_shortcuts.data.domains.variables.VariableRepository
import ch.rmy.android.http_shortcuts.data.domains.widgets.WidgetsRepository
import ch.rmy.android.http_shortcuts.data.enums.CategoryBackgroundType
import ch.rmy.android.http_shortcuts.data.enums.SelectionMode
import ch.rmy.android.http_shortcuts.data.enums.ShortcutClickBehavior
import ch.rmy.android.http_shortcuts.data.models.CategoryModel
import ch.rmy.android.http_shortcuts.data.models.PendingExecutionModel
import ch.rmy.android.http_shortcuts.data.models.ShortcutModel
import ch.rmy.android.http_shortcuts.data.models.VariableModel
import ch.rmy.android.http_shortcuts.extensions.createDialogState
import ch.rmy.android.http_shortcuts.extensions.toLauncherShortcut
import ch.rmy.android.http_shortcuts.extensions.type
import ch.rmy.android.http_shortcuts.import_export.CurlExporter
import ch.rmy.android.http_shortcuts.import_export.ExportFormat
import ch.rmy.android.http_shortcuts.import_export.Exporter
import ch.rmy.android.http_shortcuts.scheduling.ExecutionScheduler
import ch.rmy.android.http_shortcuts.usecases.GetExportDestinationOptionsDialogUseCase
import ch.rmy.android.http_shortcuts.utils.LauncherShortcutManager
import ch.rmy.android.http_shortcuts.utils.Settings
import ch.rmy.curlcommand.CurlCommand
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import javax.inject.Inject
class ShortcutListViewModel(
application: Application,
) : BaseViewModel<ShortcutListViewModel.InitData, ShortcutListViewState>(application), WithDialog {
@Inject
lateinit var appRepository: AppRepository
@Inject
lateinit var shortcutRepository: ShortcutRepository
@Inject
lateinit var categoryRepository: CategoryRepository
@Inject
lateinit var variableRepository: VariableRepository
@Inject
lateinit var pendingExecutionsRepository: PendingExecutionsRepository
@Inject
lateinit var widgetsRepository: WidgetsRepository
@Inject
lateinit var curlExporter: CurlExporter
@Inject
lateinit var executionScheduler: ExecutionScheduler
@Inject
lateinit var settings: Settings
@Inject
lateinit var getCurlExportDialog: GetCurlExportDialogUseCase
@Inject
lateinit var getShortcutInfoDialog: GetShortcutInfoDialogUseCase
@Inject
lateinit var getShortcutDeletionDialog: GetShortcutDeletionDialogUseCase
@Inject
lateinit var getExportOptionsDialog: GetExportOptionsDialogUseCase
@Inject
lateinit var getExportDestinationOptionsDialog: GetExportDestinationOptionsDialogUseCase
@Inject
lateinit var getMoveOptionsDialog: GetMoveOptionsDialogUseCase
@Inject
lateinit var getContextMenuDialog: GetContextMenuDialogUseCase
@Inject
lateinit var getMoveToCategoryDialog: GetMoveToCategoryDialogUseCase
@Inject
lateinit var exporter: Exporter
@Inject
lateinit var getUsedVariableIds: GetUsedVariableIdsUseCase
@Inject
lateinit var launcherShortcutMapper: LauncherShortcutMapper
@Inject
lateinit var launcherShortcutManager: LauncherShortcutManager
init {
getApplicationComponent().inject(this)
}
private lateinit var category: CategoryModel
private var categories: List<CategoryModel> = emptyList()
private var variables: List<VariableModel> = emptyList()
private var pendingShortcuts: List<PendingExecutionModel> = emptyList()
private var exportingShortcutId: ShortcutId? = null
private var isAppLocked = false
private var currentJob: Job? = null
override var dialogState: DialogState?
get() = currentViewState?.dialogState
set(value) {
updateViewState {
copy(dialogState = value)
}
}
override fun onInitializationStarted(data: InitData) {
viewModelScope.launch {
categoryRepository.getObservableCategory(data.categoryId)
.collect { category ->
[email protected] = category
if (isInitialized) {
recomputeShortcutList()
} else {
finalizeInitialization()
}
}
}
viewModelScope.launch {
[email protected] = categoryRepository.getCategories()
}
viewModelScope.launch {
variableRepository.getObservableVariables()
.collect { variables ->
[email protected] = variables
}
}
viewModelScope.launch {
pendingExecutionsRepository.getObservablePendingExecutions()
.collect { pendingShortcuts ->
[email protected] = pendingShortcuts
if (isInitialized) {
recomputeShortcutList()
}
}
}
viewModelScope.launch {
appRepository.getObservableLock().collect { appLock ->
isAppLocked = appLock != null
if (isInitialized) {
updateViewState {
copy(isAppLocked = [email protected])
}
}
}
}
}
override fun initViewState() = ShortcutListViewState(
isAppLocked = isAppLocked,
shortcuts = mapShortcuts(),
background = category.categoryBackgroundType,
)
private fun recomputeShortcutList() {
updateViewState {
copy(shortcuts = mapShortcuts())
}
}
private fun mapShortcuts(): List<ShortcutListItem> {
val shortcuts = category.shortcuts
return if (shortcuts.isEmpty()) {
listOf(ShortcutListItem.EmptyState)
} else {
val textColor = when (category.categoryBackgroundType) {
is CategoryBackgroundType.Default -> ShortcutListItem.TextColor.DARK
is CategoryBackgroundType.Color -> ShortcutListItem.TextColor.BRIGHT
is CategoryBackgroundType.Wallpaper -> ShortcutListItem.TextColor.BRIGHT
}
shortcuts.map { shortcut ->
ShortcutListItem.Shortcut(
id = shortcut.id,
name = shortcut.name,
description = shortcut.description,
icon = shortcut.icon,
isPending = pendingShortcuts.any { it.shortcutId == shortcut.id },
textColor = textColor,
useTextShadow = category.categoryBackgroundType.useTextShadow,
)
}
}
}
fun onPaused() {
if (isInitialized && currentViewState!!.isInMovingMode) {
disableMovingMode()
}
}
fun onBackPressed(): Boolean =
if (isInitialized && currentViewState!!.isInMovingMode) {
disableMovingMode()
true
} else {
false
}
fun onMoveModeOptionSelected() {
enableMovingMode()
}
private fun enableMovingMode() {
updateViewState {
copy(isInMovingMode = true)
}
emitEvent(ShortcutListEvent.MovingModeChanged(true))
showSnackbar(R.string.message_moving_enabled, long = true)
}
private fun disableMovingMode() {
updateViewState {
copy(isInMovingMode = false)
}
emitEvent(ShortcutListEvent.MovingModeChanged(false))
updateLauncherShortcuts()
}
private fun updateLauncherShortcuts() {
viewModelScope.launch {
val categories = categoryRepository.getCategories()
launcherShortcutManager.updateAppShortcuts(launcherShortcutMapper(categories))
}
}
fun onShortcutMoved(shortcutId1: ShortcutId, shortcutId2: ShortcutId) {
updateViewState {
copy(shortcuts = shortcuts.swapped(shortcutId1, shortcutId2) { (this as? ShortcutListItem.Shortcut)?.id })
}
launchWithProgressTracking {
shortcutRepository.swapShortcutPositions(category.id, shortcutId1, shortcutId2)
}
}
fun onShortcutClicked(shortcutId: ShortcutId) {
doWithViewState { viewState ->
logInfo("Shortcut clicked")
if (viewState.isInMovingMode) {
showSnackbar(R.string.message_moving_enabled)
return@doWithViewState
}
if (initData.selectionMode != SelectionMode.NORMAL) {
selectShortcut(shortcutId)
return@doWithViewState
}
if (viewState.isAppLocked) {
executeShortcut(shortcutId)
return@doWithViewState
}
when (category.clickBehavior ?: settings.clickBehavior) {
ShortcutClickBehavior.RUN -> executeShortcut(shortcutId)
ShortcutClickBehavior.EDIT -> editShortcut(shortcutId)
ShortcutClickBehavior.MENU -> showContextMenu(shortcutId)
}
}
}
private fun selectShortcut(shortcutId: ShortcutId) {
emitEvent(ShortcutListEvent.SelectShortcut(shortcutId))
}
private fun executeShortcut(shortcutId: ShortcutId) {
logInfo("Preparing to execute shortcut")
openActivity(ExecuteActivity.IntentBuilder(shortcutId))
}
private fun editShortcut(shortcutId: ShortcutId) {
logInfo("Preparing to edit shortcut")
emitEvent(
ShortcutListEvent.OpenShortcutEditor(
shortcutId = shortcutId,
categoryId = category.id,
)
)
}
private fun showContextMenu(shortcutId: ShortcutId) {
val shortcut = getShortcutById(shortcutId) ?: return
dialogState = getContextMenuDialog(
shortcutId,
title = shortcut.name,
isPending = pendingShortcuts.any { it.shortcutId == shortcut.id },
isMovable = canMoveWithinCategory() || canMoveAcrossCategories(),
viewModel = this,
)
}
private fun canMoveWithinCategory() =
category.shortcuts.size > 1
private fun canMoveAcrossCategories() =
categories.size > 1
fun onShortcutLongClicked(shortcutId: ShortcutId) {
doWithViewState { viewState ->
if (viewState.isLongClickingEnabled) {
showContextMenu(shortcutId)
}
}
}
private fun getShortcutById(shortcutId: ShortcutId): ShortcutModel? =
category.shortcuts.firstOrNull { it.id == shortcutId }
fun onPlaceOnHomeScreenOptionSelected(shortcutId: ShortcutId) {
val shortcut = getShortcutById(shortcutId) ?: return
emitEvent(ShortcutListEvent.PlaceShortcutOnHomeScreen(shortcut.toLauncherShortcut()))
}
fun onExecuteOptionSelected(shortcutId: ShortcutId) {
executeShortcut(shortcutId)
}
fun onCancelPendingExecutionOptionSelected(shortcutId: ShortcutId) {
cancelPendingExecution(shortcutId)
}
private fun cancelPendingExecution(shortcutId: ShortcutId) {
val shortcut = getShortcutById(shortcutId) ?: return
viewModelScope.launch {
pendingExecutionsRepository.removePendingExecutionsForShortcut(shortcutId)
executionScheduler.schedule()
showSnackbar(StringResLocalizable(R.string.pending_shortcut_execution_cancelled, shortcut.name))
}
}
fun onEditOptionSelected(shortcutId: ShortcutId) {
editShortcut(shortcutId)
}
fun onMoveOptionSelected(shortcutId: ShortcutId) {
val canMoveWithinCategory = canMoveWithinCategory()
val canMoveAcrossCategories = canMoveAcrossCategories()
when {
canMoveWithinCategory && canMoveAcrossCategories -> showMoveOptionsDialog(shortcutId)
canMoveWithinCategory -> enableMovingMode()
canMoveAcrossCategories -> onMoveToCategoryOptionSelected(shortcutId)
}
}
private fun showMoveOptionsDialog(shortcutId: ShortcutId) {
dialogState = getMoveOptionsDialog(shortcutId, this)
}
fun onDuplicateOptionSelected(shortcutId: ShortcutId) {
duplicateShortcut(shortcutId)
}
private fun duplicateShortcut(shortcutId: ShortcutId) {
val shortcut = getShortcutById(shortcutId) ?: return
val name = shortcut.name
val newName = context.getString(R.string.template_shortcut_name_copy, shortcut.name)
.truncate(ShortcutModel.NAME_MAX_LENGTH)
val categoryId = category.id
val newPosition = category.shortcuts
.indexOfFirst { it.id == shortcut.id }
.takeIf { it != -1 }
?.let { it + 1 }
launchWithProgressTracking {
shortcutRepository.duplicateShortcut(shortcutId, newName, newPosition, categoryId)
updateLauncherShortcuts()
showSnackbar(StringResLocalizable(R.string.shortcut_duplicated, name))
}
}
fun onDeleteOptionSelected(shortcutId: ShortcutId) {
showDeletionDialog(getShortcutById(shortcutId) ?: return)
}
private fun showDeletionDialog(shortcut: ShortcutModel) {
dialogState = getShortcutDeletionDialog(shortcut.id, shortcut.name.toLocalizable(), this)
}
fun onShowInfoOptionSelected(shortcutId: ShortcutId) {
showShortcutInfoDialog(getShortcutById(shortcutId) ?: return)
}
private fun showShortcutInfoDialog(shortcut: ShortcutModel) {
dialogState = getShortcutInfoDialog(shortcut.id, shortcut.name)
}
fun onExportOptionSelected(shortcutId: ShortcutId) {
val shortcut = getShortcutById(shortcutId) ?: return
if (shortcut.type.usesUrl) {
showExportOptionsDialog(shortcutId)
} else {
showFileExportDialog(shortcutId)
}
}
private fun showExportOptionsDialog(shortcutId: ShortcutId) {
dialogState = getExportOptionsDialog(shortcutId, this)
}
fun onExportAsCurlOptionSelected(shortcutId: ShortcutId) {
val shortcut = getShortcutById(shortcutId) ?: return
viewModelScope.launch {
try {
val command = curlExporter.generateCommand(shortcut)
showCurlExportDialog(shortcut.name, command)
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
showToast(R.string.error_generic)
logException(e)
}
}
}
private fun showCurlExportDialog(name: String, command: CurlCommand) {
dialogState = getCurlExportDialog(name, command)
}
fun onExportAsFileOptionSelected(shortcutId: ShortcutId) {
showFileExportDialog(shortcutId)
}
private fun showFileExportDialog(shortcutId: ShortcutId) {
exportingShortcutId = shortcutId
dialogState = getExportDestinationOptionsDialog(
onExportToFileOptionSelected = {
emitEvent(ShortcutListEvent.OpenFilePickerForExport(getExportFormat()))
},
onExportViaSharingOptionSelected = {
sendExport()
},
)
}
fun onFilePickedForExport(file: Uri) {
val shortcut = exportingShortcutId?.let(::getShortcutById) ?: return
currentJob?.cancel()
currentJob = viewModelScope.launch {
showProgressDialog(R.string.export_in_progress)
try {
val status = try {
val variableIds = getUsedVariableIds(shortcut.id)
exporter.exportToUri(
file,
format = getExportFormat(),
excludeDefaults = true,
shortcutIds = setOf(shortcut.id),
variableIds = variableIds,
)
} finally {
hideProgressDialog()
}
showSnackbar(
QuantityStringLocalizable(
R.plurals.shortcut_export_success,
status.exportedShortcuts,
status.exportedShortcuts,
)
)
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
logException(e)
dialogState = createDialogState {
message(context.getString(R.string.export_failed_with_reason, e.message))
.positive(R.string.dialog_ok)
.build()
}
}
}
}
private fun sendExport() {
val shortcut = exportingShortcutId?.let(::getShortcutById) ?: return
currentJob?.cancel()
currentJob = viewModelScope.launch {
showProgressDialog(R.string.export_in_progress)
try {
val format = getExportFormat()
val cacheFile = FileUtil.createCacheFile(context, format.getFileName(single = true))
exporter.exportToUri(
cacheFile,
excludeDefaults = true,
shortcutIds = setOf(shortcut.id),
variableIds = getUsedVariableIds(shortcut.id),
)
openActivity(object : IntentBuilder {
override fun build(context: Context) =
Intent(Intent.ACTION_SEND)
.setType(format.fileTypeForSharing)
.putExtra(Intent.EXTRA_STREAM, cacheFile)
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
.let {
Intent.createChooser(it, context.getString(R.string.title_export))
}
})
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
handleUnexpectedError(e)
} finally {
hideProgressDialog()
}
}
}
private fun showProgressDialog(message: Int) {
dialogState = ProgressDialogState(StringResLocalizable(message), ::onProgressDialogCanceled)
}
private fun hideProgressDialog() {
if (dialogState?.id == ProgressDialogState.DIALOG_ID) {
dialogState = null
}
}
private fun onProgressDialogCanceled() {
currentJob?.cancel()
}
private fun getExportFormat() =
if (settings.useLegacyExportFormat) ExportFormat.LEGACY_JSON else ExportFormat.ZIP
fun onMoveToCategoryOptionSelected(shortcutId: ShortcutId) {
dialogState = getMoveToCategoryDialog(
shortcutId,
categoryOptions = categories
.filter { it.id != category.id }
.map { category ->
GetMoveToCategoryDialogUseCase.CategoryOption(category.id, category.name)
},
viewModel = this,
)
}
fun onMoveTargetCategorySelected(shortcutId: ShortcutId, categoryId: CategoryId) {
val shortcut = getShortcutById(shortcutId) ?: return
launchWithProgressTracking {
shortcutRepository.moveShortcutToCategory(shortcutId, categoryId)
showSnackbar(StringResLocalizable(R.string.shortcut_moved, shortcut.name))
if (shortcut.launcherShortcut) {
updateLauncherShortcuts()
}
}
}
fun onShortcutEdited() {
logInfo("Shortcut editing completed")
emitEvent(ShortcutListEvent.ShortcutEdited)
}
fun onDeletionConfirmed(shortcutId: ShortcutId) {
val shortcut = getShortcutById(shortcutId) ?: return
launchWithProgressTracking {
shortcutRepository.deleteShortcut(shortcutId)
pendingExecutionsRepository.removePendingExecutionsForShortcut(shortcutId)
widgetsRepository.deleteDeadWidgets()
showSnackbar(StringResLocalizable(R.string.shortcut_deleted, shortcut.name))
updateLauncherShortcuts()
emitEvent(ShortcutListEvent.RemoveShortcutFromHomeScreen(shortcut.toLauncherShortcut()))
}
}
data class InitData(
val categoryId: CategoryId,
val selectionMode: SelectionMode,
)
}
|
mit
|
560001cc99b5c8b4d1593205cdac55d2
| 35.93871 | 118 | 0.659331 | 5.373534 | false | false | false | false |
ThiagoGarciaAlves/intellij-community
|
python/python-terminal/src/com/jetbrains/python/sdk/PyVirtualEnvTerminalCustomizer.kt
|
2
|
4798
|
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.sdk
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.options.UnnamedConfigurable
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.util.SystemInfo
import com.intellij.util.EnvironmentUtil
import com.jetbrains.python.run.PyVirtualEnvReader
import com.jetbrains.python.run.findActivateScript
import org.jetbrains.plugins.terminal.LocalTerminalCustomizer
import java.io.File
import javax.swing.JCheckBox
/**
* @author traff
*/
class PyVirtualEnvTerminalCustomizer : LocalTerminalCustomizer() {
override fun customizeCommandAndEnvironment(project: Project,
command: Array<out String>,
envs: MutableMap<String, String>): Array<out String> {
val sdk: Sdk? = findSdk(project)
if (sdk != null && (PythonSdkType.isVirtualEnv(sdk) || PythonSdkType.isCondaVirtualEnv(
sdk)) && PyVirtualEnvTerminalSettings.getInstance(project).virtualEnvActivate) {
// in case of virtualenv sdk on unix we activate virtualenv
val path = sdk.homePath
if (path != null) {
val shellPath = command[0]
val shellName = File(shellPath).name
if (shellName == "bash" || (SystemInfo.isMac && shellName == "sh") || (shellName == "zsh") ||
((shellName == "fish") && PythonSdkType.isVirtualEnv(sdk))) { //fish shell works only for virtualenv and not for conda
//for bash we pass activate script to jediterm shell integration (see jediterm-bash.in) to source it there
findActivateScript(path, shellPath)?.let { activate ->
val pathEnv = EnvironmentUtil.getEnvironmentMap().get("PATH")
if (pathEnv != null) {
envs.put("PATH", pathEnv)
}
envs.put("JEDITERM_SOURCE", if (activate.second != null) "${activate.first} ${activate.second}" else activate.first)
}
}
else {
//for other shells we read envs from activate script by the default shell and pass them to the process
val reader = PyVirtualEnvReader(path)
reader.activate?.let {
// we add only envs that are setup by the activate script, because adding other variables from the different shell
// can break the actual shell
envs.putAll(reader.readPythonEnv().mapKeys { k -> k.key.toUpperCase() }.filterKeys { k ->
k in PyVirtualEnvReader.virtualEnvVars
})
}
}
}
}
// for some reason virtualenv isn't activated in the rcfile for the login shell, so we make it non-login
return command.filter { arg -> arg != "--login" && arg != "-l" }.toTypedArray()
}
private fun findSdk(project: Project): Sdk? {
for (m in ModuleManager.getInstance(project).modules) {
val sdk: Sdk? = PythonSdkType.findPythonSdk(m)
if (sdk != null && !PythonSdkType.isRemote(sdk)) {
return sdk
}
}
return null
}
override fun getDefaultFolder(project: Project): String? {
return null
}
override fun getConfigurable(project: Project) = object : UnnamedConfigurable {
val settings = PyVirtualEnvTerminalSettings.getInstance(project)
var myCheckbox: JCheckBox = JCheckBox("Activate virtualenv")
override fun createComponent() = myCheckbox
override fun isModified() = myCheckbox.isSelected != settings.virtualEnvActivate
override fun apply() {
settings.virtualEnvActivate = myCheckbox.isSelected
}
override fun reset() {
myCheckbox.isSelected = settings.virtualEnvActivate
}
}
}
class SettingsState {
var virtualEnvActivate = true
}
@State(name = "PyVirtualEnvTerminalCustomizer", storages = arrayOf(Storage("python-terminal.xml")))
class PyVirtualEnvTerminalSettings : PersistentStateComponent<SettingsState> {
var myState = SettingsState()
var virtualEnvActivate: Boolean
get() = myState.virtualEnvActivate
set(value) {
myState.virtualEnvActivate = value
}
override fun getState() = myState
override fun loadState(state: SettingsState) {
myState.virtualEnvActivate = state.virtualEnvActivate
}
companion object {
fun getInstance(project: Project): PyVirtualEnvTerminalSettings {
return ServiceManager.getService(project, PyVirtualEnvTerminalSettings::class.java)
}
}
}
|
apache-2.0
|
44b017e7387658d4e36f23003aacf4f4
| 34.540741 | 140 | 0.689662 | 4.774129 | false | false | false | false |
mapzen/eraser-map
|
app/src/main/kotlin/com/mapzen/erasermap/presenter/RoutePresenterImpl.kt
|
1
|
5192
|
package com.mapzen.erasermap.presenter
import com.mapzen.erasermap.model.event.RouteCancelEvent
import com.mapzen.erasermap.view.MapListToggleButton
import com.mapzen.erasermap.view.RouteViewController
import com.mapzen.helpers.RouteEngine
import com.mapzen.model.ValhallaLocation
import com.mapzen.valhalla.Instruction
import com.mapzen.valhalla.Route
import com.mapzen.valhalla.Router
import com.squareup.otto.Bus
class RoutePresenterImpl(private val routeEngine: RouteEngine,
private val routeEngineListener: RouteEngineListener,
private val bus: Bus,
private val vsm: ViewStateManager) : RoutePresenter {
override var routeController: RouteViewController? = null
set(value) {
field = value
routeEngineListener.controller = value
}
override var currentInstructionIndex: Int = 0
override var currentSnapLocation: ValhallaLocation? = null
private var route: Route? = null
private var isTrackingCurrentLocation: Boolean = true
override fun onLocationChanged(location: ValhallaLocation) {
routeEngine.onLocationChanged(location)
}
override fun onRouteStart(route: Route?) {
this.route = route
routeEngine.setListener(routeEngineListener)
currentInstructionIndex = 0
routeController?.setCurrentInstruction(0)
routeEngine.route = route
isTrackingCurrentLocation = true
}
override fun onRouteResume(route: Route?) {
routeController?.setCurrentInstruction(currentInstructionIndex)
if (!isTrackingCurrentLocation) {
routeController?.showResumeButton()
}
}
override fun onRouteResumeForMap(route: Route?) {
val location = route?.getRouteInstructions()?.get(currentInstructionIndex)?.location
if (location != null) {
routeController?.showRouteIcon(location)
}
}
override fun onMapPan(deltaX: Float, deltaY: Float) {
if (Math.abs(deltaX) >= RoutePresenter.GESTURE_MIN_DELTA ||
Math.abs(deltaY) >= RoutePresenter.GESTURE_MIN_DELTA) {
isTrackingCurrentLocation = false
routeController?.showResumeButton()
}
}
override fun onResumeButtonClick() {
isTrackingCurrentLocation = true
routeController?.hideResumeButton()
}
override fun onInstructionPagerTouch() {
isTrackingCurrentLocation = false
routeController?.showResumeButton()
}
override fun onInstructionSelected(instruction: Instruction) {
if (!isTrackingCurrentLocation) {
routeController?.centerMapOnLocation(instruction.location)
}
}
override fun onUpdateSnapLocation(location: ValhallaLocation) {
routeController?.showRouteIcon(location)
if (isTrackingCurrentLocation) {
routeController?.centerMapOnLocation(location)
}
}
override fun onRouteClear() {
routeController?.hideRouteIcon()
routeController?.hideRouteLine()
}
override fun onMapListToggleClick(state: MapListToggleButton.MapListState) {
if (state == MapListToggleButton.MapListState.LIST) {
routeController?.showRouteDirectionList()
vsm.viewState = ViewStateManager.ViewState.ROUTE_DIRECTION_LIST
} else {
routeController?.hideRouteDirectionList()
vsm.viewState = ViewStateManager.ViewState.ROUTING
}
}
override fun onRouteCancelButtonClick() {
bus.post(RouteCancelEvent())
}
override fun isTrackingCurrentLocation(): Boolean {
return isTrackingCurrentLocation
}
/**
* When we center the map on a location we want to dynamically change the map's zoom level.
* We will zoom the map out if the current maneuver is long and we are still far away from
* completing it. If the maneuver is relatively short we won't adjust the zoom level which will
* prevent changing the zoom too frequently
*/
override fun mapZoomLevelForCurrentInstruction(): Float {
var liveDistanceThreshold: Int = 0
var distanceThreshold: Int = 0
when (route?.units) {
Router.DistanceUnits.MILES -> {
liveDistanceThreshold = (Instruction.MI_TO_METERS * 2).toInt()
distanceThreshold = (Instruction.MI_TO_METERS * 3).toInt()
}
Router.DistanceUnits.KILOMETERS -> {
liveDistanceThreshold = Instruction.KM_TO_METERS * 3
distanceThreshold = Instruction.KM_TO_METERS * 3
}
}
val instruction = route?.getCurrentInstruction()
if (instruction != null && instruction.liveDistanceToNext > liveDistanceThreshold
&& instruction.distance > distanceThreshold) {
return MainPresenter.LONG_MANEUVER_ZOOM
} else {
return MainPresenter.ROUTING_ZOOM
}
}
override fun onSetCurrentInstruction(index: Int) {
val finalInstructionIndex = route?.getRouteInstructions()?.size?.minus(1)
if (index != finalInstructionIndex) routeController?.displayInstruction(index)
}
}
|
gpl-3.0
|
ca3f1fd409646965a167d4abf70176f3
| 35.055556 | 99 | 0.677003 | 4.916667 | false | false | false | false |
nischalbasnet/kotlin-android-tictactoe
|
app/src/main/java/com/nbasnet/extensions/activity/ActivityExtensions.kt
|
1
|
1914
|
package com.nbasnet.extensions.activity
import android.content.Context
import android.content.Intent
import android.hardware.input.InputManager
import android.os.Bundle
import android.support.v4.app.FragmentActivity
import android.support.v7.app.AppCompatActivity
import android.view.Window
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import android.widget.Toast
import es.dmoral.toasty.Toasty
/**
* Adds toast extension
*/
fun FragmentActivity.toast(message: String, duration: Int = Toast.LENGTH_LONG): Unit {
Toasty.info(this, message, duration).show()
}
fun FragmentActivity.failToast(message: String, duration: Int = Toast.LENGTH_LONG): Unit {
Toasty.error(this, message, duration).show()
}
fun FragmentActivity.successToast(message: String, duration: Int = Toast.LENGTH_LONG): Unit {
Toasty.success(this, message, duration).show()
}
fun FragmentActivity.startActivity(cls: Class<*>, payLoad: Bundle? = null): Unit {
val intent = Intent(this, cls)
if (payLoad != null) intent.putExtra("payload", payLoad)
startActivity(intent)
}
fun FragmentActivity.getInputMethodManager(): InputMethodManager {
return getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
}
fun FragmentActivity.hideKeyboard(inputMethodManager: InputMethodManager): Unit {
inputMethodManager.hideSoftInputFromWindow(
currentFocus.windowToken,
InputMethodManager.RESULT_UNCHANGED_SHOWN
)
}
fun FragmentActivity.fullScreenMode(): Unit {
requestWindowFeature(Window.FEATURE_NO_TITLE)
window.setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN
)
}
fun FragmentActivity.refreshActivity(withoutBlink: Boolean = false): Unit {
finish()
overridePendingTransition(0, 0)
startActivity(intent)
overridePendingTransition(0, 0)
}
|
mit
|
c5e02b59d899157a2c70485fc01dab82
| 29.887097 | 93 | 0.764368 | 4.410138 | false | false | false | false |
Commit451/Addendum
|
app/src/main/java/com/commit451/addendum/sample/Main2Activity.kt
|
1
|
1637
|
package com.commit451.addendum.sample
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.commit451.addendum.extra
import com.commit451.addendum.parceler.parcelerExtra
import com.commit451.addendum.parceler.parcelerExtraOrNull
import com.commit451.addendum.parceler.putParcelerParcelableExtra
class Main2Activity : AppCompatActivity() {
companion object {
const val KEY_STRING = "string"
const val KEY_INT = "int"
const val KEY_PARCEL = "parcel"
const val KEY_PARCEL_THING = "parcel_thing"
const val KEY_NOTHING = "nothing"
fun intent(context: Context): Intent {
val thing = Thing()
thing.someValue = 200
val parcelThing = ParcelThing()
val intent = Intent(context, Main2Activity::class.java)
intent.putExtra(KEY_STRING, "asdf")
intent.putExtra(KEY_INT, 100)
intent.putExtra(KEY_PARCEL, thing)
intent.putParcelerParcelableExtra(KEY_PARCEL_THING, parcelThing)
intent.putParcelerParcelableExtra(KEY_NOTHING, null)
return intent
}
}
val string by extra<String>(KEY_STRING)
val someInt by extra<Int>(KEY_INT)
val someParcel by extra<Thing>(KEY_PARCEL)
val someParcelThing by parcelerExtra<ParcelThing>(KEY_PARCEL_THING)
val nothing by parcelerExtraOrNull<ParcelThing>(KEY_NOTHING)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
}
}
|
apache-2.0
|
605a1391667ccdb6981c385c02e82514
| 34.586957 | 76 | 0.697618 | 4.38874 | false | false | false | false |
getsentry/raven-java
|
sentry/src/test/java/io/sentry/transport/RateLimiterTest.kt
|
1
|
6027
|
package io.sentry.transport
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.whenever
import io.sentry.ISerializer
import io.sentry.NoOpLogger
import io.sentry.SentryEnvelope
import io.sentry.SentryEnvelopeHeader
import io.sentry.SentryEnvelopeItem
import io.sentry.SentryEvent
import io.sentry.SentryTracer
import io.sentry.TransactionContext
import io.sentry.protocol.SentryTransaction
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
class RateLimiterTest {
private class Fixture {
val currentDateProvider = mock<ICurrentDateProvider>()
val serializer = mock<ISerializer>()
fun getSUT(): RateLimiter {
return RateLimiter(currentDateProvider, NoOpLogger.getInstance())
}
}
private val fixture = Fixture()
@Test
fun `uses X-Sentry-Rate-Limit and allows sending if time has passed`() {
val rateLimiter = fixture.getSUT()
whenever(fixture.currentDateProvider.currentTimeMillis).thenReturn(0, 0, 1001)
val eventItem = SentryEnvelopeItem.fromEvent(fixture.serializer, SentryEvent())
val envelope = SentryEnvelope(SentryEnvelopeHeader(), arrayListOf(eventItem))
rateLimiter.updateRetryAfterLimits("50:transaction:key, 1:default;error;security:organization", null, 1)
val result = rateLimiter.filter(envelope, null)
assertNotNull(result)
assertEquals(1, result.items.count())
}
@Test
fun `parse X-Sentry-Rate-Limit and set its values and retry after should be true`() {
val rateLimiter = fixture.getSUT()
whenever(fixture.currentDateProvider.currentTimeMillis).thenReturn(0)
val eventItem = SentryEnvelopeItem.fromEvent(fixture.serializer, SentryEvent())
val transaction = SentryTransaction(SentryTracer(TransactionContext("name", "op"), mock()))
val transactionItem = SentryEnvelopeItem.fromEvent(fixture.serializer, transaction)
val envelope = SentryEnvelope(SentryEnvelopeHeader(), arrayListOf(eventItem, transactionItem))
rateLimiter.updateRetryAfterLimits("50:transaction:key, 2700:default;error;security:organization", null, 1)
val result = rateLimiter.filter(envelope, null)
assertNull(result)
}
@Test
fun `parse X-Sentry-Rate-Limit and set its values and retry after should be false`() {
val rateLimiter = fixture.getSUT()
whenever(fixture.currentDateProvider.currentTimeMillis).thenReturn(0, 0, 1001)
val eventItem = SentryEnvelopeItem.fromEvent(fixture.serializer, SentryEvent())
val transaction = SentryTransaction(SentryTracer(TransactionContext("name", "op"), mock()))
val transactionItem = SentryEnvelopeItem.fromEvent(fixture.serializer, transaction)
val envelope = SentryEnvelope(SentryEnvelopeHeader(), arrayListOf(eventItem, transactionItem))
rateLimiter.updateRetryAfterLimits("1:transaction:key, 1:default;error;security:organization", null, 1)
val result = rateLimiter.filter(envelope, null)
assertNotNull(result)
assertEquals(2, result.items.count())
}
@Test
fun `When X-Sentry-Rate-Limit categories are empty, applies to all the categories`() {
val rateLimiter = fixture.getSUT()
whenever(fixture.currentDateProvider.currentTimeMillis).thenReturn(0)
val eventItem = SentryEnvelopeItem.fromEvent(fixture.serializer, SentryEvent())
val envelope = SentryEnvelope(SentryEnvelopeHeader(), arrayListOf(eventItem))
rateLimiter.updateRetryAfterLimits("50::key", null, 1)
val result = rateLimiter.filter(envelope, null)
assertNull(result)
}
@Test
fun `When all categories is set but expired, applies only for specific category`() {
val rateLimiter = fixture.getSUT()
whenever(fixture.currentDateProvider.currentTimeMillis).thenReturn(0, 0, 1001)
val eventItem = SentryEnvelopeItem.fromEvent(fixture.serializer, SentryEvent())
val envelope = SentryEnvelope(SentryEnvelopeHeader(), arrayListOf(eventItem))
rateLimiter.updateRetryAfterLimits("1::key, 60:default;error;security:organization", null, 1)
val result = rateLimiter.filter(envelope, null)
assertNull(result)
}
@Test
fun `When category has shorter rate limiting, do not apply new timestamp`() {
val rateLimiter = fixture.getSUT()
whenever(fixture.currentDateProvider.currentTimeMillis).thenReturn(0, 0, 1001)
val eventItem = SentryEnvelopeItem.fromEvent(fixture.serializer, SentryEvent())
val envelope = SentryEnvelope(SentryEnvelopeHeader(), arrayListOf(eventItem))
rateLimiter.updateRetryAfterLimits("60:error:key, 1:error:organization", null, 1)
val result = rateLimiter.filter(envelope, null)
assertNull(result)
}
@Test
fun `When category has longer rate limiting, apply new timestamp`() {
val rateLimiter = fixture.getSUT()
whenever(fixture.currentDateProvider.currentTimeMillis).thenReturn(0, 0, 1001)
val eventItem = SentryEnvelopeItem.fromEvent(fixture.serializer, SentryEvent())
val envelope = SentryEnvelope(SentryEnvelopeHeader(), arrayListOf(eventItem))
rateLimiter.updateRetryAfterLimits("1:error:key, 5:error:organization", null, 1)
val result = rateLimiter.filter(envelope, null)
assertNull(result)
}
@Test
fun `When both retry headers are not present, default delay is set`() {
val rateLimiter = fixture.getSUT()
whenever(fixture.currentDateProvider.currentTimeMillis).thenReturn(0, 0, 1001)
val eventItem = SentryEnvelopeItem.fromEvent(fixture.serializer, SentryEvent())
val envelope = SentryEnvelope(SentryEnvelopeHeader(), arrayListOf(eventItem))
rateLimiter.updateRetryAfterLimits(null, null, 429)
val result = rateLimiter.filter(envelope, null)
assertNull(result)
}
}
|
bsd-3-clause
|
ea7f9f3d2d7b39acf4352d7d2d7e4035
| 41.744681 | 115 | 0.723411 | 4.810056 | false | true | false | false |
jorgefranconunes/jeedemos
|
vertx/vertx-kotlin-HelloWorldController/src/main/kotlin/com/varmateo/controller/HelloWorldController.kt
|
1
|
2240
|
package com.varmateo.controller
import io.vertx.core.http.HttpMethod
import io.vertx.core.http.HttpServerResponse
import io.vertx.core.json.Json
import io.vertx.ext.web.Router
import io.vertx.ext.web.RoutingContext
import com.varmateo.controller.GreetMessageResponse
private const val PARAM_INPUT = "input"
private const val PARAM_NAME = "name"
class HelloWorldController {
val hello = get("/hello", ::doHello)
val greetings = get("/greetings", ::doGreetings)
val greetMessage = get("/greet-message", ::doGreetMessage)
private fun doHello(context: RoutingContext): Unit {
context.response().end("Hello, world!")
}
fun doGreetings(context: RoutingContext): Unit {
val name: String? = context.request().getParam(PARAM_NAME)
val response: HttpServerResponse = context.response()
if (name != null) {
response
.setChunked(true)
.write("Hello, ${name}")
} else {
response.setStatusCode(400)
}
response.end()
}
fun doGreetMessage(context: RoutingContext): Unit {
var input: String? = context.request().getParam(PARAM_INPUT)
var response: HttpServerResponse = context.response()
if (input != null) {
var result = GreetMessageResponse(
input = input,
output = "Hello, ${input.capitalize()}!")
response
.setChunked(true)
.putHeader("content-type", "application/json; charset=utf-8")
.write(Json.encodePrettily(result))
} else {
response.setStatusCode(400)
}
response.end()
}
}
data class RouteDescription(
val method: HttpMethod,
val path: String,
val handler: (RoutingContext) -> Unit)
fun Router.addRoute(routeDescription: RouteDescription): Router {
this.route(routeDescription.path)
.method(routeDescription.method)
.handler(routeDescription.handler)
return this
}
private fun get(
path: String,
handler: (RoutingContext) -> Unit)
: RouteDescription = RouteDescription(HttpMethod.GET, path, handler)
|
gpl-3.0
|
bb9d21ff28acd1397dd086ea28e29936
| 25.352941 | 81 | 0.616071 | 4.383562 | false | false | false | false |
DR-YangLong/spring-boot-kotlin-demo
|
src/main/kotlin/site/yanglong/promotion/model/UserPerms.kt
|
1
|
1226
|
package site.yanglong.promotion.model
import java.io.Serializable
import com.baomidou.mybatisplus.enums.IdType
import com.baomidou.mybatisplus.annotations.TableId
import com.baomidou.mybatisplus.activerecord.Model
import com.baomidou.mybatisplus.annotations.TableField
import com.baomidou.mybatisplus.annotations.TableLogic
import com.baomidou.mybatisplus.annotations.TableName
/**
*
*
*
*
*
* @author Dr.YangLong
* @since 2017-11-01
*/
@TableName("user_perms")
class UserPerms : Model<UserPerms>() {
/**
* 编号
*/
@TableId(value = "id", type = IdType.AUTO)
var id: Long? = null
/**
* 用户id
*/
var userId: Long? = null
/**
* 权限id
*/
var permId: Long? = null
/**
* 是否启用
*/
@TableField
@TableLogic
var enable: String? = null
override fun pkVal(): Serializable? {
return this.id
}
override fun toString(): String {
return "UserPerms{" +
", id=" + id +
", userId=" + userId +
", permId=" + permId +
", enable=" + enable +
"}"
}
companion object {
private val serialVersionUID = 1L
}
}
|
apache-2.0
|
93ebc8acd64ba2c40824eab33f81b796
| 18.770492 | 54 | 0.579602 | 3.890323 | false | false | false | false |
proxer/ProxerLibAndroid
|
library/src/main/kotlin/me/proxer/library/enums/UserMediaProgress.kt
|
2
|
471
|
package me.proxer.library.enums
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import me.proxer.library.entity.info.Entry
/**
* Enum holding the available progress types of an user at a media [Entry].
*
* @author Ruben Gees
*/
@JsonClass(generateAdapter = false)
enum class UserMediaProgress {
@Json(name = "0")
WATCHED,
@Json(name = "1")
WATCHING,
@Json(name = "2")
WILL_WATCH,
@Json(name = "3")
CANCELLED
}
|
gpl-3.0
|
de4f57319bca1da4dd1dca4676b9e1be
| 17.115385 | 75 | 0.670913 | 3.437956 | false | false | false | false |
SourceUtils/steam-utils
|
src/main/kotlin/com/timepath/steam/io/DiffGen.kt
|
1
|
2197
|
package com.timepath.steam.io
import com.timepath.steam.io.storage.ACF
import com.timepath.vfs.VFile
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.util.logging.Logger
import kotlin.platform.platformStatic
public class DiffGen private constructor() {
companion object {
private val LOG = Logger.getLogger(javaClass<DiffGen>().getName())
private val blacklist = arrayOf(".*/bin", ".*/cache", ".*tf/custom", ".*tf/download", ".*tf/replay", ".*tf/screenshots", ".*sounds?\\.cache", ".*cfg/config\\.cfg", ".*media/viewed\\.res", ".*tf/console\\.log", ".*tf/condump.*\\.txt", ".*tf/demoheader\\.tmp", ".*tf/voice_ban\\.dt", ".*tf/trainingprogress\\.txt")
private val K = 1024
private val M = K * K
private val G = M * K
private fun check(f: File): Boolean {
val path = f.getPath()
for (r in blacklist) {
if (path.matches(r.toRegex())) {
LOG.info(path)
return false
}
}
return true
}
throws(IOException::class)
private fun <V : VFile<V>> extract(v: V, dir: File) {
val out = File(dir, v.name)
if (!check(out)) {
return
}
if (v.isDirectory) {
out.mkdir()
for (e in v.list()) {
extract(e, out)
}
} else {
out.createNewFile()
v.openStream()!!.copyTo(FileOutputStream(out).buffered())
}
}
throws(IOException::class)
public platformStatic fun main(args: Array<String>) {
val apps = intArrayOf(440)
val container = File(System.getProperty("user.home"), "steamtracker")
for (i in apps) {
val repo = File(container, i.toString())
repo.mkdirs()
val acf = ACF.fromManifest(i)
val files = acf.list()
for (v in files) {
extract(v, repo)
}
}
LOG.info("EXTRACTED")
}
}
}
|
artistic-2.0
|
9828f042c02fc1b223575c96996ec3fe
| 33.328125 | 320 | 0.503414 | 4.282651 | false | false | false | false |
AlexanderDashkov/hpcourse
|
csc/2016/kve/src/communication/Server.kt
|
3
|
2734
|
package communication
import taskExecution.Task
import taskExecution.TaskExecutor
import java.io.OutputStream
import java.net.ServerSocket
import java.net.Socket
import java.util.concurrent.atomic.AtomicInteger
class Server(executorSize: Int = 800, val port: Int = 47255) {
private var idCounter: AtomicInteger = AtomicInteger()
val myTaskExecutor: TaskExecutor = TaskExecutor(executorSize)
fun start() {
Thread { run() }.start()
myTaskExecutor.create()
}
private fun run() {
val serverSocket = ServerSocket(port)
while (true) {
val socket = serverSocket.accept()
val requestWrapper = Protocol.WrapperMessage.parseDelimitedFrom(socket.inputStream)
val request = requestWrapper.request
when {
request.submit.isInitialized -> {
submitTask(request, socket)
}
request.subscribe.isInitialized -> {
myTaskExecutor.subscribeToResults(request.subscribe.taskId, request.requestId, socket)
}
request.list.isInitialized -> {
sendListResponse(myTaskExecutor.listTasks, request.requestId, socket)
}
}
}
}
private fun submitTask(request: Protocol.ServerRequest, socket: Socket) {
val task = request.submit.task
if (task != null) {
val taskId = idCounter.andIncrement
val myTask = Task(task, taskId, request.clientId)
sendSubmitResponse(request.requestId, socket.outputStream, taskId)
myTaskExecutor.execute(myTask)
}
}
private fun sendSubmitResponse(id: Long, outputStream: OutputStream, taskId: Int) {
val responseWrapper = Protocol.WrapperMessage.newBuilder().apply {
this.response = Protocol.ServerResponse.newBuilder().apply {
requestId = id
submitResponse = Protocol.SubmitTaskResponse.newBuilder().apply {
submittedTaskId = taskId
status = Protocol.Status.OK
}.build()
}.build()
}.build()
print("Response created: " + Protocol.ServerResponse.newBuilder()
.setRequestId(id)
.setSubmitResponse(Protocol.SubmitTaskResponse.newBuilder()
.setSubmittedTaskId(taskId)
.setStatus(Protocol.Status.OK)).build().toString())
try {
responseWrapper.writeDelimitedTo(outputStream)
outputStream.flush()
} catch(e: Exception) {
print("Error while sending response: " + e.message + e.cause)
}
}
}
|
gpl-2.0
|
9dc88aa2a0f5a9458facbfde6217c4f4
| 34.986842 | 106 | 0.600585 | 5.17803 | false | false | false | false |
AlmasB/FXGL
|
fxgl-gameplay/src/main/kotlin/com/almasb/fxgl/minigames/triggermash/TriggerMashMiniGame.kt
|
1
|
5609
|
/*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package com.almasb.fxgl.minigames.triggermash
import com.almasb.fxgl.animation.Animation
import com.almasb.fxgl.animation.AnimationBuilder
import com.almasb.fxgl.input.Input
import com.almasb.fxgl.input.KeyTrigger
import com.almasb.fxgl.input.UserAction
import com.almasb.fxgl.minigames.MiniGame
import com.almasb.fxgl.minigames.MiniGameResult
import com.almasb.fxgl.minigames.MiniGameView
import javafx.beans.property.SimpleDoubleProperty
import javafx.geometry.Point2D
import javafx.geometry.VPos
import javafx.scene.effect.DropShadow
import javafx.scene.layout.StackPane
import javafx.scene.paint.Color
import javafx.scene.paint.CycleMethod
import javafx.scene.paint.LinearGradient
import javafx.scene.paint.Stop
import javafx.scene.shape.Arc
import javafx.scene.shape.ArcType
import javafx.scene.shape.Circle
import javafx.scene.text.Font
import javafx.scene.text.Text
import javafx.scene.transform.Scale
import javafx.util.Duration
import kotlin.math.max
import kotlin.math.min
class TriggerMashView(trigger: KeyTrigger, miniGame: TriggerMashMiniGame = TriggerMashMiniGame(trigger)) : MiniGameView<TriggerMashMiniGame>(miniGame) {
private val animation: Animation<*>
init {
val circle = Circle(50.0, null)
circle.stroke = Color.GREEN
circle.strokeWidth = 2.5
val innerCircle = Circle(1.0, Color.color(0.0, 0.67, 0.2, 0.65))
innerCircle.radiusProperty().bind(miniGame.fillValue.divide(100.0).multiply(circle.radiusProperty()))
val letter = Text(miniGame.trigger.toString())
letter.font = Font.font(36.0)
letter.stroke = Color.BLACK
letter.fill = Color.YELLOW
letter.strokeWidth = 1.5
val letterCircle = Circle(35.0, null)
letterCircle.stroke = Color.color(0.76, 0.9, 0.0, 0.76)
animation = AnimationBuilder().duration(Duration.seconds(0.09))
.autoReverse(true)
.repeat(2)
.scale(letter, letterCircle)
.from(Point2D(1.0, 1.0))
.to(Point2D(1.4, 1.4))
.build()
children.addAll(StackPane(innerCircle, circle, letter, letterCircle))
}
override fun onUpdate(tpf: Double) {
animation.onUpdate(tpf)
}
override fun onInitInput(input: Input) {
input.addAction(object : UserAction("Button Mash") {
override fun onActionBegin() {
animation.start()
miniGame.boost()
}
}, miniGame.trigger.key)
}
}
class CircleTriggerMashView(trigger: KeyTrigger, miniGame: TriggerMashMiniGame = TriggerMashMiniGame(trigger)) : MiniGameView<TriggerMashMiniGame>(miniGame) {
private val animation: Animation<*>
init {
val circle = Circle(100.0, 100.0, 40.0, null)
circle.stroke = Color.DARKGREEN
circle.strokeWidth = 5.0
val arc = Arc()
arc.centerX = 100.0
arc.centerY = 100.0
arc.radiusX = circle.radius
arc.radiusY = circle.radius
arc.startAngle = 90.0
arc.type = ArcType.OPEN
arc.fill = null
arc.stroke = Color.YELLOW
arc.strokeWidth = 3.0
arc.transforms.add(Scale(-1.0, 1.0, arc.centerX, arc.centerY))
arc.lengthProperty().bind(miniGame.fillValue.divide(100.0).multiply(360))
val letter = Text(miniGame.trigger.toString())
letter.font = Font.font(36.0)
letter.stroke = Color.BLACK
letter.fill = Color.YELLOW
letter.strokeWidth = 1.5
letter.textOrigin = VPos.TOP
letter.translateX = 100.0 - letter.layoutBounds.width / 2
letter.translateY = 100.0 - letter.layoutBounds.height / 2 - 1.5
val letterCircle = Circle(100.0, 100.0, 20.0, null)
letterCircle.stroke = Color.color(0.76, 0.9, 0.0, 0.76)
animation = AnimationBuilder().duration(Duration.seconds(0.09))
.autoReverse(true)
.repeat(2)
.scale(letter, letterCircle)
.from(Point2D(1.0, 1.0))
.to(Point2D(1.4, 1.4))
.build()
val bg = Circle(100.0, 100.0, 100.0, LinearGradient(
0.0, 0.0, 1.0, 1.0, true, CycleMethod.NO_CYCLE,
Stop(0.1, Color.color(0.1, 0.4, 0.9, 0.8)),
Stop(0.9, Color.color(0.1, 0.9, 0.1, 0.4))
))
effect = DropShadow(20.0, Color.BLACK)
children.addAll(bg, circle, arc, letter, letterCircle)
}
override fun onUpdate(tpf: Double) {
animation.onUpdate(tpf)
}
override fun onInitInput(input: Input) {
input.addAction(object : UserAction("Button Mash") {
override fun onActionBegin() {
animation.start()
miniGame.boost()
}
}, miniGame.trigger.key)
}
}
/**
*
* @author Almas Baimagambetov ([email protected])
*/
class TriggerMashMiniGame(var trigger: KeyTrigger) : MiniGame<TriggerMashResult>() {
var decayRate = 0.1
var boostRate = 1.7
val fillValue = SimpleDoubleProperty(0.0)
override fun onUpdate(tpf: Double) {
fillValue.value = max(0.0, fillValue.value - decayRate)
}
fun boost() {
fillValue.value = min(100.0, fillValue.value + boostRate)
if (fillValue.value == 100.0) {
isDone = true
result = TriggerMashResult(true)
}
}
}
class TriggerMashResult(override val isSuccess: Boolean) : MiniGameResult
|
mit
|
c0455f7cb746f9043bae364f3fc1de95
| 30.335196 | 158 | 0.637725 | 3.632772 | false | false | false | false |
arcao/Geocaching4Locus
|
app/src/main/java/com/arcao/geocaching4locus/importgc/ImportUrlViewModel.kt
|
1
|
4496
|
package com.arcao.geocaching4locus.importgc
import android.net.Uri
import com.arcao.geocaching4locus.R
import com.arcao.geocaching4locus.authentication.util.isPremium
import com.arcao.geocaching4locus.base.BaseViewModel
import com.arcao.geocaching4locus.base.coroutine.CoroutinesDispatcherProvider
import com.arcao.geocaching4locus.base.usecase.GetGeocacheCodeFromGuidUseCase
import com.arcao.geocaching4locus.base.usecase.GetPointFromGeocacheCodeUseCase
import com.arcao.geocaching4locus.base.usecase.WritePointToPackPointsFileUseCase
import com.arcao.geocaching4locus.base.util.AnalyticsManager
import com.arcao.geocaching4locus.base.util.Command
import com.arcao.geocaching4locus.base.util.invoke
import com.arcao.geocaching4locus.data.account.AccountManager
import com.arcao.geocaching4locus.error.handler.ExceptionHandler
import com.arcao.geocaching4locus.settings.manager.FilterPreferenceManager
import kotlinx.coroutines.Job
import locus.api.manager.LocusMapManager
import timber.log.Timber
import java.util.regex.Pattern
class ImportUrlViewModel(
private val accountManager: AccountManager,
private val exceptionHandler: ExceptionHandler,
private val getGeocacheCodeFromGuid: GetGeocacheCodeFromGuidUseCase,
private val getPointFromGeocacheCode: GetPointFromGeocacheCodeUseCase,
private val writePointToPackPointsFile: WritePointToPackPointsFileUseCase,
private val filterPreferenceManager: FilterPreferenceManager,
private val locusMapManager: LocusMapManager,
private val analyticsManager: AnalyticsManager,
dispatcherProvider: CoroutinesDispatcherProvider
) : BaseViewModel(dispatcherProvider) {
val action = Command<ImportUrlAction>()
private var job: Job? = null
fun startImport(uri: Uri) {
if (locusMapManager.isLocusMapNotInstalled) {
action(ImportUrlAction.LocusMapNotInstalled)
return
}
if (accountManager.account == null) {
action(ImportUrlAction.SignIn)
return
}
if (job?.isActive == true) {
job?.cancel()
}
job = mainLaunch {
performImport(uri)
}
}
private suspend fun performImport(uri: Uri) = computationContext {
analyticsManager.actionImport(accountManager.isPremium)
try {
showProgress(R.string.progress_download_geocache) {
val geocacheCode = retrieveGeocacheCode(uri)
if (geocacheCode == null) {
mainContext {
action(ImportUrlAction.Cancel)
}
return@showProgress
}
Timber.i("source: import;%s", geocacheCode)
val point = getPointFromGeocacheCode(
referenceCode = geocacheCode,
liteData = !accountManager.isPremium,
geocacheLogsCount = filterPreferenceManager.geocacheLogsCount
)
writePointToPackPointsFile(point)
mainContext {
val intent = locusMapManager.createSendPointsIntent(
callImport = true,
center = true
)
action(ImportUrlAction.Finish(intent))
}
}
} catch (e: Exception) {
mainContext {
action(ImportUrlAction.Error(exceptionHandler(e)))
}
}
}
private suspend fun retrieveGeocacheCode(uri: Uri): String? = computationContext {
val url = uri.toString()
val cacheCodeMatcher = CACHE_CODE_PATTERN.matcher(url)
if (cacheCodeMatcher.find()) {
return@computationContext cacheCodeMatcher.group(1)
}
val guidMatcher = GUID_PATTERN.matcher(url)
if (!guidMatcher.find()) {
return@computationContext null
}
val guid = guidMatcher.group(1) ?: return@computationContext null
return@computationContext getGeocacheCodeFromGuid(guid)
}
fun cancelImport() {
job?.cancel()
action(ImportUrlAction.Cancel)
}
companion object {
val CACHE_CODE_PATTERN: Pattern =
Pattern.compile("(GC[A-HJKMNPQRTV-Z0-9]+)", Pattern.CASE_INSENSITIVE)
private val GUID_PATTERN = Pattern.compile(
"guid=([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})",
Pattern.CASE_INSENSITIVE
)
}
}
|
gpl-3.0
|
540a8a9efbd0039f9cfef2a90bdb18cd
| 35.258065 | 86 | 0.659698 | 4.625514 | false | false | false | false |
kittinunf/ReactiveAndroid
|
sample/src/main/kotlin/com.github.kittinunf.reactiveandroid.sample/view/SignInActivity.kt
|
1
|
2769
|
package com.github.kittinunf.reactiveandroid.sample.view
//import com.github.kittinunf.reactiveandroid.widget.rx_afterTextChanged
//import com.github.kittinunf.reactiveandroid.widget.rx_text
//import com.github.kittinunf.reactiveandroid.widget.rx_textChanged
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.Toast
import com.github.kittinunf.reactiveandroid.sample.R
import com.github.kittinunf.reactiveandroid.sample.viewmodel.SignInViewAction
import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.activity_sign_in.titleTextView
class SignInActivity : AppCompatActivity(), SignInViewAction {
val subscriptions = CompositeDisposable()
// val viewModel by lazy(LazyThreadSafetyMode.NONE) { SignInViewModel(this) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_sign_in)
//title
titleTextView.text = javaClass.simpleName
//button
// viewModel.signInAction.apply {
// values.observeOn(AndroidThreadScheduler.main)
// .map { "Yey! Sign In successfully" }
// .bindTo(this@SignInActivity, SignInActivity::handleSuccess)
// .addTo(subscriptions)
// errors.observeOn(AndroidThreadScheduler.main)
// .bindTo(this@SignInActivity, SignInActivity::handleFailure)
// .addTo(subscriptions)
// }
// signInButton.rx_applyAction(viewModel.signInAction).addTo(subscriptions)
//progressBar
// loadingProgressBar.rx_visibility.bindTo(viewModel.signInAction.executing.map { if (it) View.VISIBLE else View.INVISIBLE }).addTo(subscriptions)
// userNameEditText.rx_textChanged().subscribe {
// Log.e(javaClass.simpleName, "typing username ...")
// }.addTo(subscriptions)
// passwordEditText.rx_textChanged().subscribe {
// Log.e(javaClass.simpleName, "typing password ...")
// }.addTo(subscriptions)
}
override fun onDestroy() {
super.onDestroy()
subscriptions.dispose()
}
// override fun usernameObservable() = userNameEditText.rx_afterTextChanged().map { it.toString() }
// override fun passwordObservable() = passwordEditText.rx_afterTextChanged().map { it.toString() }
// override fun username() = userNameEditText.rx_text
// override fun password() = passwordEditText.rx_text
fun handleSuccess(message: String) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
fun handleFailure(throwable: Throwable) {
Toast.makeText(this, throwable.message, Toast.LENGTH_SHORT).show()
}
}
|
mit
|
a0276b78a806e595267f0cf4e1f226bd
| 35.92 | 153 | 0.698447 | 4.517129 | false | false | false | false |
ericberman/MyFlightbookAndroid
|
app/src/main/java/model/ApproachDescription.kt
|
1
|
3174
|
/*
MyFlightbook for Android - provides native access to MyFlightbook
pilot's logbook
Copyright (C) 2017-2022 MyFlightbook, LLC
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 model
import java.util.*
class ApproachDescription {
var approachName = ""
var approachCount = 0
var runwayName = ""
var airportName = ""
var addToApproachCount = true
override fun toString(): String {
approachName = approachName.trim { it <= ' ' }
runwayName = runwayName.trim { it <= ' ' }
airportName = airportName.trim { it <= ' ' }
return if (approachCount == 0) "" else String.format(
Locale.getDefault(), "%d%s%s%s%s",
approachCount,
if (approachName.isNotEmpty()) "-$approachName" else "",
if (runwayName.isNotEmpty()) "-RWY" else "",
runwayName,
if (airportName.isNotEmpty()) "@$airportName" else ""
)
}
companion object {
val ApproachNames = arrayOf(
"CONTACT",
"COPTER",
"GCA",
"GLS",
"ILS",
"ILS (Cat I)",
"ILS (Cat II)",
"ILS (Cat III)",
"ILS/PRM",
"JPLAS",
"LAAS",
"LDA",
"LOC",
"LOC-BC",
"MLS",
"NDB",
"OSAP",
"PAR",
"RNAV/GPS",
"SDF",
"SRA/ASR",
"TACAN",
"TYPE1",
"TYPE2",
"TYPE3",
"TYPE4",
"TYPEA",
"TYPEB",
"VISUAL",
"VOR",
"VOR/DME",
"VOR/DME-ARC"
)
val ApproachSuffixes = arrayOf("", "-A", "-B", "-C", "-D", "-V", "-W", "-X", "-Y", "-Z")
val RunwayNames = arrayOf(
"",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12",
"13",
"14",
"15",
"16",
"17",
"18",
"19",
"20",
"21",
"22",
"23",
"24",
"25",
"26",
"27",
"28",
"29",
"30",
"31",
"32",
"33",
"34",
"35",
"36"
)
val RunwayModifiers = arrayOf("", "L", "R", "C")
}
}
|
gpl-3.0
|
5e67fc9c84dd638d698f0257b793fe37
| 25.458333 | 96 | 0.430057 | 4.122078 | false | false | false | false |
nsk-mironov/smuggler
|
smuggler-compiler/src/main/java/com/joom/smuggler/compiler/SmugglerOptions.kt
|
1
|
1004
|
package com.joom.smuggler.compiler
import java.io.File
import java.util.ArrayList
data class SmugglerOptions(
val project: Collection<File>,
val subprojects: Collection<File>,
val libraries: Collection<File>,
val bootclasspath: Collection<File>,
val output: File
) {
class Builder(val output: File) {
private val project = ArrayList<File>()
private val subprojects = ArrayList<File>()
private val bootclasspath = ArrayList<File>()
private val libraries = ArrayList<File>()
fun project(files: Collection<File>) = apply {
project.addAll(files)
}
fun subprojects(files: Collection<File>) = apply {
subprojects.addAll(files)
}
fun bootclasspath(files: Collection<File>) = apply {
bootclasspath.addAll(files)
}
fun libraries(files: Collection<File>) = apply {
libraries.addAll(files)
}
fun build(): SmugglerOptions {
return SmugglerOptions(project, subprojects, libraries, bootclasspath, output)
}
}
}
|
mit
|
8270756c76b0e0dcb6019e53a34da5fe
| 24.74359 | 84 | 0.690239 | 4.14876 | false | false | false | false |
DevCharly/kotlin-ant-dsl
|
src/main/kotlin/com/devcharly/kotlin/ant/taskdefs/delete.kt
|
1
|
7027
|
/*
* Copyright 2016 Karl Tauber
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.devcharly.kotlin.ant
import org.apache.tools.ant.taskdefs.Delete
import org.apache.tools.ant.types.ResourceCollection
import org.apache.tools.ant.types.selectors.AndSelector
import org.apache.tools.ant.types.selectors.ContainsRegexpSelector
import org.apache.tools.ant.types.selectors.ContainsSelector
import org.apache.tools.ant.types.selectors.DateSelector
import org.apache.tools.ant.types.selectors.DependSelector
import org.apache.tools.ant.types.selectors.DepthSelector
import org.apache.tools.ant.types.selectors.DifferentSelector
import org.apache.tools.ant.types.selectors.ExtendSelector
import org.apache.tools.ant.types.selectors.FileSelector
import org.apache.tools.ant.types.selectors.FilenameSelector
import org.apache.tools.ant.types.selectors.MajoritySelector
import org.apache.tools.ant.types.selectors.NoneSelector
import org.apache.tools.ant.types.selectors.NotSelector
import org.apache.tools.ant.types.selectors.OrSelector
import org.apache.tools.ant.types.selectors.PresentSelector
import org.apache.tools.ant.types.selectors.SelectSelector
import org.apache.tools.ant.types.selectors.SizeSelector
import org.apache.tools.ant.types.selectors.TypeSelector
import org.apache.tools.ant.types.selectors.modifiedselector.ModifiedSelector
/******************************************************************************
DO NOT EDIT - this file was generated
******************************************************************************/
fun Ant.delete(
file: String? = null,
dir: String? = null,
verbose: Boolean? = null,
quiet: Boolean? = null,
failonerror: Boolean? = null,
deleteonexit: Boolean? = null,
includeemptydirs: Boolean? = null,
performgconfaileddelete: Boolean? = null,
includes: String? = null,
excludes: String? = null,
defaultexcludes: Boolean? = null,
includesfile: String? = null,
excludesfile: String? = null,
casesensitive: Boolean? = null,
followsymlinks: Boolean? = null,
removenotfollowedsymlinks: Boolean? = null,
nested: (KDelete.() -> Unit)? = null)
{
Delete().execute("delete") { task ->
if (file != null)
task.setFile(project.resolveFile(file))
if (dir != null)
task.setDir(project.resolveFile(dir))
if (verbose != null)
task.setVerbose(verbose)
if (quiet != null)
task.setQuiet(quiet)
if (failonerror != null)
task.setFailOnError(failonerror)
if (deleteonexit != null)
task.setDeleteOnExit(deleteonexit)
if (includeemptydirs != null)
task.setIncludeEmptyDirs(includeemptydirs)
if (performgconfaileddelete != null)
task.setPerformGcOnFailedDelete(performgconfaileddelete)
if (includes != null)
task.setIncludes(includes)
if (excludes != null)
task.setExcludes(excludes)
if (defaultexcludes != null)
task.setDefaultexcludes(defaultexcludes)
if (includesfile != null)
task.setIncludesfile(project.resolveFile(includesfile))
if (excludesfile != null)
task.setExcludesfile(project.resolveFile(excludesfile))
if (casesensitive != null)
task.setCaseSensitive(casesensitive)
if (followsymlinks != null)
task.setFollowSymlinks(followsymlinks)
if (removenotfollowedsymlinks != null)
task.setRemoveNotFollowedSymlinks(removenotfollowedsymlinks)
if (nested != null)
nested(KDelete(task))
}
}
class KDelete(override val component: Delete) :
IFileSelectorNested,
IResourceCollectionNested,
ISelectSelectorNested,
IAndSelectorNested,
IOrSelectorNested,
INotSelectorNested,
INoneSelectorNested,
IMajoritySelectorNested,
IDateSelectorNested,
ISizeSelectorNested,
IFilenameSelectorNested,
IExtendSelectorNested,
IContainsSelectorNested,
IPresentSelectorNested,
IDepthSelectorNested,
IDependSelectorNested,
IContainsRegexpSelectorNested,
IModifiedSelectorNested,
IDifferentSelectorNested,
ITypeSelectorNested
{
fun include(name: String? = null, If: String? = null, unless: String? = null) {
component.createInclude().apply {
_init(name, If, unless)
}
}
fun includesfile(name: String? = null, If: String? = null, unless: String? = null) {
component.createIncludesFile().apply {
_init(name, If, unless)
}
}
fun exclude(name: String? = null, If: String? = null, unless: String? = null) {
component.createExclude().apply {
_init(name, If, unless)
}
}
fun excludesfile(name: String? = null, If: String? = null, unless: String? = null) {
component.createExcludesFile().apply {
_init(name, If, unless)
}
}
fun patternset(includes: String? = null, excludes: String? = null, includesfile: String? = null, excludesfile: String? = null, nested: (KPatternSet.() -> Unit)? = null) {
component.createPatternSet().apply {
component.project.setProjectReference(this)
_init(includes, excludes, includesfile, excludesfile, nested)
}
}
override fun _addFileSelector(value: FileSelector) = component.add(value)
override fun _addResourceCollection(value: ResourceCollection) = component.add(value)
override fun _addSelectSelector(value: SelectSelector) = component.addSelector(value)
override fun _addAndSelector(value: AndSelector) = component.addAnd(value)
override fun _addOrSelector(value: OrSelector) = component.addOr(value)
override fun _addNotSelector(value: NotSelector) = component.addNot(value)
override fun _addNoneSelector(value: NoneSelector) = component.addNone(value)
override fun _addMajoritySelector(value: MajoritySelector) = component.addMajority(value)
override fun _addDateSelector(value: DateSelector) = component.addDate(value)
override fun _addSizeSelector(value: SizeSelector) = component.addSize(value)
override fun _addFilenameSelector(value: FilenameSelector) = component.addFilename(value)
override fun _addExtendSelector(value: ExtendSelector) = component.addCustom(value)
override fun _addContainsSelector(value: ContainsSelector) = component.addContains(value)
override fun _addPresentSelector(value: PresentSelector) = component.addPresent(value)
override fun _addDepthSelector(value: DepthSelector) = component.addDepth(value)
override fun _addDependSelector(value: DependSelector) = component.addDepend(value)
override fun _addContainsRegexpSelector(value: ContainsRegexpSelector) = component.addContainsRegexp(value)
override fun _addModifiedSelector(value: ModifiedSelector) = component.addModified(value)
override fun _addDifferentSelector(value: DifferentSelector) = component.addDifferent(value)
override fun _addTypeSelector(value: TypeSelector) = component.addType(value)
}
|
apache-2.0
|
167890c89f19db7e3d2a9ad9766ada79
| 40.335294 | 171 | 0.760638 | 3.763792 | false | false | false | false |
wireapp/wire-android
|
storage/src/main/kotlin/com/waz/zclient/storage/db/notifications/EncryptedPushNotificationEventEntity.kt
|
1
|
597
|
package com.waz.zclient.storage.db.notifications
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "EncryptedPushNotificationEvents", primaryKeys = ["pushId", "event_index"])
data class EncryptedPushNotificationEventEntity(
@ColumnInfo(name = "pushId")
val pushId: String,
@ColumnInfo(name = "event_index", defaultValue = "0")
val eventIndex: Int,
@ColumnInfo(name = "event", defaultValue = "")
val eventJson: String,
@ColumnInfo(name = "transient", defaultValue = "0")
val isTransient: Boolean
)
|
gpl-3.0
|
ab0d44f2116c648793818a5eb50b0d74
| 27.428571 | 95 | 0.726968 | 4.089041 | false | false | false | false |
facebook/litho
|
litho-core-kotlin/src/main/kotlin/com/facebook/litho/theming/TextStyle.kt
|
1
|
1458
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("KtDataClass")
package libraries.components.litho.theming
import android.graphics.Color
import android.graphics.Typeface
import androidx.annotation.ColorInt
import com.facebook.litho.Dimen
import com.facebook.litho.sp
data class Typography(
val h1: TextStyle = TextStyle(fontSize = 48.sp, typeface = Typeface.DEFAULT_BOLD),
val h2: TextStyle = TextStyle(fontSize = 30.sp, typeface = Typeface.DEFAULT_BOLD),
val subtitle1: TextStyle =
TextStyle(
fontColor = Color.GRAY,
fontSize = 16.sp,
),
val body1: TextStyle =
TextStyle(
fontColor = Color.GRAY,
fontSize = 14.sp,
),
)
data class TextStyle(
@ColorInt val fontColor: Int = Color.BLACK,
val fontSize: Dimen = 18.sp,
val typeface: Typeface = Typeface.DEFAULT,
)
|
apache-2.0
|
0bcfb22b1cffa66024fd99079e0a1fff
| 30.695652 | 86 | 0.698217 | 4.095506 | false | false | false | false |
DadosAbertosBrasil/android-radar-politico
|
app/src/main/kotlin/br/edu/ifce/engcomp/francis/radarpolitico/controllers/AdicionarPoliticosActivity.kt
|
1
|
5608
|
package br.edu.ifce.engcomp.francis.radarpolitico.controllers
import android.app.SearchManager
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.support.v4.view.MenuCompat
import android.support.v4.view.MenuItemCompat
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.SearchView
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import br.edu.ifce.engcomp.francis.radarpolitico.R
import br.edu.ifce.engcomp.francis.radarpolitico.helpers.VolleySharedQueue
import br.edu.ifce.engcomp.francis.radarpolitico.miscellaneous.CDUrlFormatter
import br.edu.ifce.engcomp.francis.radarpolitico.miscellaneous.adapters.AddDeputadoRecyclerViewAdapter
import br.edu.ifce.engcomp.francis.radarpolitico.miscellaneous.connection.parsers.CDXmlParser
import br.edu.ifce.engcomp.francis.radarpolitico.models.Deputado
import com.android.volley.Request
import com.android.volley.VolleyError
import com.android.volley.toolbox.StringRequest
import kotlinx.android.synthetic.main.activity_add_politicians.*
import kotlinx.android.synthetic.main.content_add_politicians.*
import java.util.*
class AdicionarPoliticosActivity : AppCompatActivity(), SearchView.OnQueryTextListener, SwipeRefreshLayout.OnRefreshListener{
var datasource: ArrayList<Deputado>
lateinit var adapter: AddDeputadoRecyclerViewAdapter
init {
this.datasource = ArrayList()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add_politicians)
if (toolbar != null ) {
setSupportActionBar(toolbar)
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
supportActionBar!!.setDisplayShowHomeEnabled(true)
}
initRecyclerView()
initSwipeRefreshLayout()
Toast.makeText(this, "Baixando lista de Deputados...", Toast.LENGTH_SHORT).show()
retrieveDeputiesFromServer()
}
override fun onBackPressed() {
val intent = Intent()
intent.putExtra("DEPUTADO_ADDED", adapter.deputadoAdded)
setResult(RESULT_OK, intent)
super.onBackPressed()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_add_deputado, menu)
val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager
val searchItem = menu.findItem(R.id.action_search)
var searchView: SearchView?
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
searchView = searchItem?.actionView as SearchView?
}
else {
searchView = MenuItemCompat.getActionView(searchItem) as SearchView?
}
searchView?.queryHint = "Pesquisar"
searchView?.setSearchableInfo(searchManager.getSearchableInfo(componentName))
searchView?.setOnQueryTextListener(this)
return true
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
if (item?.itemId == android.R.id.home){
onBackPressed()
}
return super.onOptionsItemSelected(item)
}
override fun onQueryTextSubmit(query: String?): Boolean {
return false
}
override fun onQueryTextChange(newText: String): Boolean {
if(newText.length > 3){
val politicos = datasource.filter { it.nomeParlamentar!!.contains(newText, true) }
adapter.changeDatasource(politicos as ArrayList<Deputado> )
}
else {
adapter.changeDatasource(datasource)
}
Log.i("SEARCH", datasource.count().toString())
return false
}
override fun onRefresh() {
adapter.changeDatasource(ArrayList())
retrieveDeputiesFromServer()
}
private fun initRecyclerView() {
val layoutManager = LinearLayoutManager(this)
this.adapter = AddDeputadoRecyclerViewAdapter(datasource, this)
addDeputadoRecyclerView.setHasFixedSize(false)
addDeputadoRecyclerView.layoutManager = layoutManager
addDeputadoRecyclerView.adapter = adapter
addDeputadoRecyclerView.itemAnimator = DefaultItemAnimator()
}
private fun initSwipeRefreshLayout(){
swipeRefreshLayout.setOnRefreshListener(this)
swipeRefreshLayout.setColorSchemeColors(R.color.colorPrimaryDark, R.color.colorPrimary, R.color.colorAccent)
}
private fun retrieveDeputiesFromServer() {
val requestUrl = CDUrlFormatter.obterDeputados()
val request = StringRequest(Request.Method.GET, requestUrl, {
stringResponse: String ->
val deputados = CDXmlParser.parseDeputadosFromXML(stringResponse.byteInputStream())
deputados.sortBy { it.nomeParlamentar }
datasource.clear()
datasource.addAll(deputados)
adapter.changeDatasource(deputados)
swipeRefreshLayout.isRefreshing = false
}, {
volleyError: VolleyError ->
Toast.makeText(this, "Ocorreu algum erro de rede. Tente mais tarde. :/", Toast.LENGTH_SHORT).show()
})
VolleySharedQueue.getQueue(this)?.add(request)
}
}
|
gpl-2.0
|
f77eccaf373b4ef32951c5e892ae749e
| 34.493671 | 201 | 0.701498 | 4.885017 | false | false | false | false |
nestlabs/connectedhomeip
|
src/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/clusterinteraction/ClusterDetailFragment.kt
|
2
|
16255
|
package com.google.chip.chiptool.clusterclient.clusterinteraction
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.AutoCompleteTextView
import android.widget.Button
import android.widget.LinearLayout
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.forEach
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import chip.clusterinfo.ClusterCommandCallback
import chip.clusterinfo.ClusterInfo
import chip.clusterinfo.InteractionInfo
import chip.clusterinfo.CommandResponseInfo
import chip.clusterinfo.DelegatedClusterCallback
import chip.devicecontroller.ChipClusters
import chip.devicecontroller.ChipDeviceController
import chip.devicecontroller.ClusterInfoMapping
import com.google.chip.chiptool.ChipClient
import com.google.chip.chiptool.ChipClient.getConnectedDevicePointer
import com.google.chip.chiptool.GenericChipDeviceListener
import com.google.chip.chiptool.R
import com.google.chip.chiptool.clusterclient.clusterinteraction.ClusterInteractionHistoryFragment.Companion.clusterInteractionHistoryList
import kotlin.properties.Delegates
import kotlinx.android.synthetic.main.cluster_callback_item.view.clusterCallbackDataTv
import kotlinx.android.synthetic.main.cluster_callback_item.view.clusterCallbackNameTv
import kotlinx.android.synthetic.main.cluster_callback_item.view.clusterCallbackTypeTv
import kotlinx.android.synthetic.main.cluster_detail_fragment.view.callbackList
import kotlinx.android.synthetic.main.cluster_detail_fragment.view.clusterAutoCompleteTv
import kotlinx.android.synthetic.main.cluster_detail_fragment.view.commandAutoCompleteTv
import kotlinx.android.synthetic.main.cluster_detail_fragment.view.invokeCommand
import kotlinx.android.synthetic.main.cluster_detail_fragment.view.parameterList
import kotlinx.android.synthetic.main.cluster_parameter_item.view.clusterParameterData
import kotlinx.android.synthetic.main.cluster_parameter_item.view.clusterParameterNameTv
import kotlinx.android.synthetic.main.cluster_parameter_item.view.clusterParameterTypeTv
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import java.util.*
import kotlin.collections.HashMap
/**
* ClusterDetailFragment allows user to pick cluster, command, specify parameters and see
* the callback result.
*/
class ClusterDetailFragment : Fragment() {
private val deviceController: ChipDeviceController
get() = ChipClient.getDeviceController(requireContext())
private lateinit var scope: CoroutineScope
private var clusterMap: Map<String, ClusterInfo> = ClusterInfoMapping().clusterMap
private lateinit var selectedClusterInfo: ClusterInfo
private lateinit var selectedCluster: ChipClusters.BaseChipCluster
private lateinit var selectedCommandCallback: DelegatedClusterCallback
private lateinit var selectedInteractionInfo: InteractionInfo
private var devicePtr by Delegates.notNull<Long>()
private var deviceId by Delegates.notNull<Long>()
private var endpointId by Delegates.notNull<Int>()
// when user opens detail page from home page of cluster interaction, historyCommand will be
// null, and nothing will be autocompleted. If the detail page is opened from history page,
// cluster name, command name and potential parameter list will be filled out based on historyCommand
private var historyCommand: HistoryCommand? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
scope = viewLifecycleOwner.lifecycleScope
deviceId = checkNotNull(requireArguments().getLong(DEVICE_ID))
scope.launch {
devicePtr = getConnectedDevicePointer(requireContext(), deviceId)
}
endpointId = checkNotNull(requireArguments().getInt(ENDPOINT_ID_KEY))
historyCommand = requireArguments().getSerializable(HISTORY_COMMAND) as HistoryCommand?
return inflater.inflate(R.layout.cluster_detail_fragment, container, false).apply {
deviceController.setCompletionListener(GenericChipDeviceListener())
if (historyCommand != null) {
autoCompleteBasedOnHistoryCommand(
historyCommand!!,
clusterAutoCompleteTv,
commandAutoCompleteTv,
parameterList,
inflater,
callbackList
)
} else {
commandAutoCompleteTv.visibility = View.GONE
clusterAutoCompleteSetup(
clusterAutoCompleteTv,
commandAutoCompleteTv,
parameterList,
callbackList
)
commandAutoCompleteSetup(commandAutoCompleteTv, inflater, parameterList, callbackList)
}
setInvokeCommandOnClickListener(
invokeCommand,
callbackList,
clusterAutoCompleteTv,
commandAutoCompleteTv,
parameterList
)
}
}
private fun setInvokeCommandOnClickListener(
invokeCommand: Button,
callbackList: LinearLayout,
clusterAutoCompleteTv: AutoCompleteTextView,
commandAutoCompleteTv: AutoCompleteTextView,
parameterList: LinearLayout
) {
invokeCommand.setOnClickListener {
callbackList.removeAllViews()
val commandArguments = HashMap<String, Any>()
clusterInteractionHistoryList.addFirst(
HistoryCommand(
clusterAutoCompleteTv.text.toString(),
commandAutoCompleteTv.text.toString(),
mutableListOf(),
null,
null,
endpointId,
deviceId
)
)
parameterList.forEach {
val parameterName = it.clusterParameterNameTv.text.toString()
val parameterType = selectedInteractionInfo.commandParameters[parameterName]!!.type
val parameterUnderlyingType = selectedInteractionInfo.commandParameters[parameterName]!!.underlyingType
val data = castStringToType(it.clusterParameterData.text.toString(), parameterType, parameterUnderlyingType)!!
commandArguments[it.clusterParameterNameTv.text.toString()] = data
clusterInteractionHistoryList[0].parameterList.add(
HistoryParameterInfo(
parameterName,
data.toString(),
parameterUnderlyingType
)
)
}
selectedInteractionInfo.getCommandFunction()
.invokeCommand(selectedCluster, selectedCommandCallback, commandArguments)
}
}
// Cluster name, command name and parameter list will be autofill based on the given historyCommand
private fun autoCompleteBasedOnHistoryCommand(
historyCommand: HistoryCommand,
clusterAutoComplete: AutoCompleteTextView,
commandAutoComplete: AutoCompleteTextView,
parameterList: LinearLayout, inflater: LayoutInflater,
callbackList: LinearLayout
) {
clusterAutoComplete.setText(historyCommand.clusterName)
commandAutoComplete.visibility = View.VISIBLE
commandAutoComplete.setText(historyCommand.commandName)
selectedClusterInfo = clusterMap[historyCommand.clusterName]!!
selectedCluster = selectedClusterInfo.createClusterFunction.create(devicePtr, endpointId)
selectedInteractionInfo = selectedClusterInfo.commands[historyCommand.commandName]!!
selectedCommandCallback = selectedInteractionInfo.commandCallbackSupplier.get()
setCallbackDelegate(inflater, callbackList)
historyCommand.parameterList.forEach {
val param = inflater.inflate(R.layout.cluster_parameter_item, null, false) as ConstraintLayout
param.clusterParameterNameTv.text = "${it.parameterName}"
param.clusterParameterTypeTv.text = formatParameterType(it.parameterType)
param.clusterParameterData.setText(it.parameterData)
parameterList.addView(param)
}
}
private fun formatParameterType(castType: Class<*>): String {
return if (castType == ByteArray::class.java) {
"Byte[]"
} else {
castType.toString()
}
}
private fun castStringToType(data: String, type: Class<*>, underlyingType: Class<*>): Any? {
return when (type) {
Int::class.java -> data.toInt()
Boolean::class.java -> data.toBoolean()
ByteArray::class.java -> data.encodeToByteArray()
Long::class.java -> data.toLong()
Optional::class.java -> if (data.isEmpty()) Optional.empty() else Optional.of(castStringToType(data, underlyingType, underlyingType)!!)
else -> data
}
}
private fun showMessage(msg: String) {
requireActivity().runOnUiThread {
Toast.makeText(requireContext(), msg, Toast.LENGTH_SHORT).show()
}
}
private fun clusterAutoCompleteSetup(
clusterAutoComplete: AutoCompleteTextView,
commandAutoComplete: AutoCompleteTextView,
parameterList: LinearLayout,
callbackList: LinearLayout
) {
val clusterNameList = constructHint(clusterMap)
val clusterAdapter =
ArrayAdapter(requireContext(), android.R.layout.simple_list_item_1, clusterNameList)
clusterAutoComplete.setAdapter(clusterAdapter)
clusterAutoComplete.setOnItemClickListener { parent, view, position, id ->
commandAutoComplete.visibility = View.VISIBLE
// when new cluster is selected, clear the command text and possible parameterList
commandAutoComplete.setText("", false)
parameterList.removeAllViews()
callbackList.removeAllViews()
// populate all the commands that belong to the selected cluster
val selectedCluster: String = clusterAutoComplete.adapter.getItem(position).toString()
val commandAdapter = getCommandOptions(selectedCluster)
commandAutoComplete.setAdapter(commandAdapter)
}
}
private fun commandAutoCompleteSetup(
commandAutoComplete: AutoCompleteTextView,
inflater: LayoutInflater,
parameterList: LinearLayout,
callbackList: LinearLayout
) {
commandAutoComplete.setOnItemClickListener { parent, view, position, id ->
// when new command is selected, clear all the parameterList and callbackList
parameterList.removeAllViews()
callbackList.removeAllViews()
selectedCluster = selectedClusterInfo.createClusterFunction.create(devicePtr, endpointId)
val selectedCommand: String = commandAutoComplete.adapter.getItem(position).toString()
selectedInteractionInfo = selectedClusterInfo.commands[selectedCommand]!!
selectedCommandCallback = selectedInteractionInfo.commandCallbackSupplier.get()
populateCommandParameter(inflater, parameterList)
setCallbackDelegate(inflater, callbackList)
}
}
private fun setCallbackDelegate(inflater: LayoutInflater, callbackList: LinearLayout) {
selectedCommandCallback.setCallbackDelegate(object : ClusterCommandCallback {
override fun onSuccess(responseValues: Map<CommandResponseInfo, Any>) {
showMessage("Command success")
// Populate UI based on response values. We know the types from CommandInfo.getCommandResponses().
requireActivity().runOnUiThread {
populateCallbackResult(
responseValues,
inflater,
callbackList,
)
}
clusterInteractionHistoryList[0].responseValue = responseValues
clusterInteractionHistoryList[0].status = "Success"
responseValues.forEach { Log.d(TAG, it.toString()) }
}
override fun onFailure(exception: Exception) {
showMessage("Command failed")
var errorStatus = exception.toString().split(':')
clusterInteractionHistoryList[0].status =
errorStatus[errorStatus.size - 2] + " " + errorStatus[errorStatus.size - 1]
Log.e(TAG, exception.toString())
}
})
}
private fun populateCommandParameter(inflater: LayoutInflater, parameterList: LinearLayout) {
selectedInteractionInfo.commandParameters.forEach { (paramName, paramInfo) ->
val param = inflater.inflate(R.layout.cluster_parameter_item, null, false) as ConstraintLayout
param.clusterParameterNameTv.text = "${paramName}"
// byte[].class will be output as class [B, which is not readable, so dynamically change it
// to Byte[]. If more custom logic is required, should add a className field in
// commandParameterInfo
param.clusterParameterTypeTv.text = formatParameterType(paramInfo.type)
parameterList.addView(param)
}
}
private fun populateCallbackResult(
responseValues: Map<CommandResponseInfo, Any>,
inflater: LayoutInflater,
callbackList: LinearLayout
) {
responseValues.forEach { (variableNameType, response) ->
if (response is List<*>) {
createListResponseView(response, inflater, callbackList, variableNameType)
} else {
createBasicResponseView(response, inflater, callbackList, variableNameType)
}
}
}
private fun createBasicResponseView(
response: Any,
inflater: LayoutInflater,
callbackList: LinearLayout,
variableNameType: CommandResponseInfo
) {
val callbackItem =
inflater.inflate(R.layout.cluster_callback_item, null, false) as ConstraintLayout
callbackItem.clusterCallbackNameTv.text = variableNameType.name
callbackItem.clusterCallbackDataTv.text = if (response.javaClass == ByteArray::class.java) {
(response as ByteArray).decodeToString()
} else {
response.toString()
}
callbackItem.clusterCallbackTypeTv.text = variableNameType.type
callbackList.addView(callbackItem)
}
private fun createListResponseView(
response: List<*>,
inflater: LayoutInflater,
callbackList: LinearLayout,
variableNameType: CommandResponseInfo
) {
if (response.isEmpty()) {
val emptyCallback =
inflater.inflate(R.layout.cluster_callback_item, null, false) as ConstraintLayout
emptyCallback.clusterCallbackNameTv.text = "Result is empty"
callbackList.addView(emptyCallback)
} else {
response.forEachIndexed { index, it ->
val attributeCallbackItem =
inflater.inflate(R.layout.cluster_callback_item, null, false) as ConstraintLayout
attributeCallbackItem.clusterCallbackNameTv.text = variableNameType.name + "[$index]"
val objectString = if (it!!.javaClass == ByteArray::class.java) {
(it as ByteArray).contentToString()
} else {
it.toString()
}
var callbackClassName = if (it!!.javaClass == ByteArray::class.java) {
"Byte[]"
} else {
it!!.javaClass.toString().split('$').last()
}
attributeCallbackItem.clusterCallbackDataTv.text = callbackClassName
attributeCallbackItem.clusterCallbackDataTv.setOnClickListener {
AlertDialog.Builder(requireContext())
.setTitle(callbackClassName)
.setMessage(objectString)
.create()
.show()
}
attributeCallbackItem.clusterCallbackTypeTv.text = "List<$callbackClassName>"
callbackList.addView(attributeCallbackItem)
}
}
}
private fun getCommandOptions(
clusterName: String
): ArrayAdapter<String> {
selectedClusterInfo = clusterMap[clusterName]!!
val commandNameList = constructHint(selectedClusterInfo.commands)
return ArrayAdapter(requireContext(), android.R.layout.simple_list_item_1, commandNameList)
}
private fun constructHint(clusterMap: Map<String, *>): Array<String> {
return clusterMap.keys.toTypedArray()
}
override fun onStop() {
super.onStop()
scope.cancel()
}
companion object {
private const val TAG = "ClusterDetailFragment"
private const val ENDPOINT_ID_KEY = "endpointId"
private const val HISTORY_COMMAND = "historyCommand"
private const val DEVICE_ID = "deviceId"
fun newInstance(
deviceId: Long,
endpointId: Int,
historyCommand: HistoryCommand?
): ClusterDetailFragment {
return ClusterDetailFragment().apply {
arguments = Bundle(4).apply {
putLong(DEVICE_ID, deviceId)
putSerializable(HISTORY_COMMAND, historyCommand)
putInt(ENDPOINT_ID_KEY, endpointId)
}
}
}
}
}
|
apache-2.0
|
b3aef750b5816048d5445e7875441d54
| 39.944584 | 141 | 0.741187 | 4.96791 | false | false | false | false |
google/horologist
|
compose-layout/src/main/java/com/google/android/horologist/compose/rotaryinput/Haptics.kt
|
1
|
6682
|
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.horologist.compose.rotaryinput
import android.view.HapticFeedbackConstants
import android.view.View
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalView
import com.google.android.horologist.compose.navscaffold.ExperimentalHorologistComposeLayoutApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.conflate
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.withContext
private const val DEBUG = false
/**
* Debug logging that can be enabled.
*/
private inline fun debugLog(generateMsg: () -> String) {
if (DEBUG) {
println("RotaryHaptics: ${generateMsg()}")
}
}
/**
* Throttling events within specified timeframe. Only first and last events will be received.
* For a flow emitting elements 1 to 30, with a 100ms delay between them:
* ```
* val flow = flow {
* for (i in 1..30) {
* delay(100)
* emit(i)
* }
* }
* ```
* With timeframe=1000 only those integers will be received: 1, 10, 20, 30 .
*/
internal fun <T> Flow<T>.throttleLatest(timeframe: Long): Flow<T> =
flow {
conflate().collect {
emit(it)
delay(timeframe)
}
}
/**
* Interface for Rotary haptic feedback
*/
@ExperimentalHorologistComposeLayoutApi
public interface RotaryHapticFeedback {
@ExperimentalHorologistComposeLayoutApi
public fun performHapticFeedback(type: RotaryHapticsType)
}
/**
* Rotary haptic types
*/
@ExperimentalHorologistComposeLayoutApi
@JvmInline
public value class RotaryHapticsType(private val type: Int) {
public companion object {
/**
* A scroll ticking haptic. Similar to texture haptic - performed each time when
* a scrollable content is scrolled by a certain distance
*/
@ExperimentalHorologistComposeLayoutApi
public val ScrollTick: RotaryHapticsType = RotaryHapticsType(1)
/**
* An item focus (snap) haptic. Performed when a scrollable content is snapped
* to a specific item.
*/
@ExperimentalHorologistComposeLayoutApi
public val ScrollItemFocus: RotaryHapticsType = RotaryHapticsType(2)
/**
* A limit(overscroll) haptic. Performed when a list reaches the limit
* (start or end) and can't scroll further
*/
@ExperimentalHorologistComposeLayoutApi
public val ScrollLimit: RotaryHapticsType = RotaryHapticsType(3)
}
}
/**
* Remember disabled haptics
*/
@ExperimentalHorologistComposeLayoutApi
@Composable
public fun rememberDisabledHaptic(): RotaryHapticFeedback = remember {
object : RotaryHapticFeedback {
override fun performHapticFeedback(type: RotaryHapticsType) {
// Do nothing
}
}
}
/**
* Remember rotary haptic feedback.
*/
@ExperimentalHorologistComposeLayoutApi
@Composable
public fun rememberRotaryHapticFeedback(
throttleThresholdMs: Long = 40,
hapticsChannel: Channel<RotaryHapticsType> = rememberHapticChannel(),
rotaryHaptics: RotaryHapticFeedback = rememberDefaultRotaryHapticFeedback()
): RotaryHapticFeedback {
return remember(hapticsChannel, rotaryHaptics) {
object : RotaryHapticFeedback {
override fun performHapticFeedback(type: RotaryHapticsType) {
hapticsChannel.trySend(type)
}
}
}.apply {
LaunchedEffect(hapticsChannel) {
hapticsChannel.receiveAsFlow()
.throttleLatest(throttleThresholdMs)
.collect { hapticType ->
// 'withContext' launches performHapticFeedback in a separate thread,
// as otherwise it produces a visible lag (b/219776664)
val currentTime = System.currentTimeMillis()
debugLog { "Haptics started" }
withContext(Dispatchers.Default) {
debugLog {
"Performing haptics, delay: " +
"${System.currentTimeMillis() - currentTime}"
}
rotaryHaptics.performHapticFeedback(hapticType)
}
}
}
}
}
@OptIn(ExperimentalHorologistComposeLayoutApi::class)
@Composable
private fun rememberHapticChannel() =
remember {
Channel<RotaryHapticsType>(
capacity = 2,
onBufferOverflow = BufferOverflow.DROP_OLDEST
)
}
@ExperimentalHorologistComposeLayoutApi
@Composable
public fun rememberDefaultRotaryHapticFeedback(): RotaryHapticFeedback =
LocalView.current.let { view -> remember { DefaultRotaryHapticFeedback(view) } }
/**
* Default Rotary implementation for [RotaryHapticFeedback]
*/
@ExperimentalHorologistComposeLayoutApi
public class DefaultRotaryHapticFeedback(private val view: View) : RotaryHapticFeedback {
@ExperimentalHorologistComposeLayoutApi
override fun performHapticFeedback(
type: RotaryHapticsType
) {
when (type) {
RotaryHapticsType.ScrollItemFocus -> {
view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)
}
RotaryHapticsType.ScrollTick -> {
view.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP)
}
RotaryHapticsType.ScrollLimit -> {
view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)
}
}
}
public companion object {
// Hidden constants from HapticFeedbackConstants.java
public const val ROTARY_SCROLL_TICK: Int = 18
public const val ROTARY_SCROLL_ITEM_FOCUS: Int = 19
public const val ROTARY_SCROLL_LIMIT: Int = 20
}
}
|
apache-2.0
|
1d7a2662ad07c9e4698113d064ea1277
| 31.916256 | 95 | 0.680485 | 4.725601 | false | false | false | false |
RyotaMurohoshi/android_playground
|
android/app/src/main/kotlin/com/muhron/playground/activity/TabActivity.kt
|
1
|
2086
|
package com.muhron.playground.activity
import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.support.design.widget.TabLayout
import android.support.v4.view.PagerAdapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.muhron.playground.R
import kotlinx.android.synthetic.main.activity_tab.*
import kotlinx.android.synthetic.main.view_pager.view.*
class TabActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_tab)
val list = listOf("Java", "Scala", "Kotlin", "Groovy", "Ceylon", "Xtend", "Gosu")
viewPager.adapter = SimpleAdapter(this, list)
tabLayout.setupWithViewPager(viewPager)
tabLayout.post({
if (tabLayout.width < resources.displayMetrics.widthPixels) {
tabLayout.layoutParams = tabLayout.layoutParams.let {
it.width = ViewGroup.LayoutParams.MATCH_PARENT
it
}
tabLayout.tabMode = TabLayout.MODE_FIXED
} else {
tabLayout.tabMode = TabLayout.MODE_SCROLLABLE
}
})
}
}
class SimpleAdapter(private val context: Context, private val list: List<String>) : PagerAdapter() {
val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
override fun instantiateItem(container: ViewGroup, position: Int): Any =
inflater.inflate(R.layout.view_pager, null).let {
it.textView.text = list[position]
container.addView(it)
it
}
override fun destroyItem(container: ViewGroup, position: Int, `object`: Any)
= container.removeView(`object` as View)
override fun getCount(): Int = list.size
override fun isViewFromObject(view: View, `object`: Any): Boolean = view.equals(`object`);
override fun getPageTitle(position: Int): CharSequence? = list[position]
}
|
mit
|
0b8fe9a419773bc13b9169e69b01f92e
| 34.965517 | 100 | 0.67162 | 4.574561 | false | false | false | false |
Constantinuous/Angus
|
test/src/test/kotlin/de/constantinuous/angus/extract/VbLexerTest.kt
|
1
|
3846
|
package de.constantinuous.angus.extract
import de.constantinuous.angus.parsing.CodePiece
import de.constantinuous.angus.test.*
import io.kotlintest.specs.FeatureSpec
import org.mockito.Mock
import org.mockito.Mockito
/**
* Created by RichardG on 24.11.2016.
*/
class VbLexerTest : FeatureSpec(){
lateinit var mockStringListener : StringListener
lateinit var vbLexer : VbLexer
override fun beforeEach() {
mockStringListener = mock<StringListener>()
vbLexer = VbLexer(mockStringListener)
}
init {
feature("Lexer should extract vb strings") {
scenario("should extract single line string") {
val codePiece = CodePiece("aString = \"good result\"", 0, 0)
vbLexer.parsePiece(codePiece)
Mockito.verify(mockStringListener).onString("good result")
}
scenario("should ignore comment") {
val codePiece = CodePiece("'aString = \"good result\"", 0, 0)
vbLexer.parsePiece(codePiece)
Mockito.verify(mockStringListener, Mockito.never()).onString(any())
}
scenario("should extract second line string") {
val codePiece = CodePiece("""
aString = "good result"
"""", 0, 0)
vbLexer.parsePiece(codePiece)
Mockito.verify(mockStringListener, Mockito.times(1)).onString("good result")
}
scenario("should extract both strings") {
val codePiece = CodePiece("""
aString = "good result"
aString = "better result"
"""", 0, 0)
vbLexer.parsePiece(codePiece)
Mockito.verify(mockStringListener, Mockito.times(1)).onString("good result")
Mockito.verify(mockStringListener, Mockito.times(1)).onString("better result")
}
scenario("should extract both strings even with data in between") {
val codePiece = CodePiece("""
aString = "good result"
aValue = 5
aString = "better result"
"""", 0, 0)
vbLexer.parsePiece(codePiece)
Mockito.verify(mockStringListener, Mockito.times(1)).onString("good result")
Mockito.verify(mockStringListener, Mockito.times(1)).onString("better result")
}
scenario("should extract three-line string as one") {
val codePiece = CodePiece("""
aString = "good" & _
", better" & _
", best result"
"""", 0, 0)
vbLexer.parsePiece(codePiece)
Mockito.verify(mockStringListener, Mockito.times(1)).onString("good, better, best result")
}
scenario("should extract three-line string with comment in between as one") {
val codePiece = CodePiece("""
aString = "good" & _
' "a comment" & _
", best result"
"""", 0, 0)
vbLexer.parsePiece(codePiece)
Mockito.verify(mockStringListener, Mockito.times(1)).onString("good, best result")
}
scenario("should extract three-line string as one, even with comment at the end") {
val codePiece = CodePiece("""
aString = "good" & _
", better" & _
", best result"
' another cool comment """", 0, 0)
vbLexer.parsePiece(codePiece)
Mockito.verify(mockStringListener, Mockito.times(1)).onString("good, better, best result")
}
}
}
}
|
mit
|
311bedd81b72b65ba2f15380edc2bead
| 33.348214 | 106 | 0.529641 | 4.874525 | false | false | false | false |
mrebollob/LoteriadeNavidad
|
androidApp/src/main/java/com/mrebollob/loteria/android/presentation/home/HomeViewModelState.kt
|
1
|
1076
|
package com.mrebollob.loteria.android.presentation.home
import com.mrebollob.loteria.android.presentation.platform.ErrorMessage
import com.mrebollob.loteria.domain.entity.SortingMethod
import com.mrebollob.loteria.domain.entity.Ticket
import java.util.Date
data class HomeViewModelState(
val today: Date = Date(),
val daysToLotteryDraw: Int = 0,
val tickets: List<Ticket> = emptyList(),
val sortingMethod: SortingMethod = SortingMethod.NAME,
val isLoading: Boolean = false,
val errorMessages: List<ErrorMessage> = emptyList(),
) {
fun toUiState(): HomeUiState {
return HomeUiState(
today = today,
daysToLotteryDraw = daysToLotteryDraw,
totalBet = tickets.map { it.bet }.sum(),
totalPrize = null,
tickets = when (sortingMethod) {
SortingMethod.NAME -> tickets.sortedBy { it.name }
SortingMethod.NUMBER -> tickets.sortedBy { it.number }
},
isLoading = isLoading,
errorMessages = errorMessages
)
}
}
|
apache-2.0
|
479238c0590df0099c2a0528bf22a294
| 33.709677 | 71 | 0.653346 | 4.598291 | false | false | false | false |
edvin/tornadofx-idea-plugin
|
src/main/kotlin/no/tornado/tornadofx/idea/configurations/TornadoFXRunConfigurationProducer.kt
|
1
|
2830
|
package no.tornado.tornadofx.idea.configurations
import com.intellij.execution.actions.ConfigurationContext
import com.intellij.execution.actions.LazyRunConfigurationProducer
import com.intellij.execution.actions.RunConfigurationProducer
import com.intellij.execution.configurations.ConfigurationFactory
import com.intellij.execution.configurations.runConfigurationType
import com.intellij.openapi.util.Ref
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiElement
import no.tornado.tornadofx.idea.FXTools.isApp
import no.tornado.tornadofx.idea.configurations.TornadoFXConfiguration.RunType.App
import no.tornado.tornadofx.idea.configurations.TornadoFXConfiguration.RunType.View
import no.tornado.tornadofx.idea.firstModuleWithTornadoFXLib
import org.jetbrains.kotlin.idea.refactoring.memberInfo.qualifiedClassNameForRendering
import org.jetbrains.kotlin.idea.search.allScope
import org.jetbrains.kotlin.psi.KtClass
class TornadoFXRunConfigurationProducer : LazyRunConfigurationProducer<TornadoFXConfiguration>() {
private val tornadoFXConfigurationType by lazy { runConfigurationType<TornadoFXConfigurationType>() }
override fun getConfigurationFactory(): ConfigurationFactory {
return tornadoFXConfigurationType.configurationFactories[0]
}
override fun setupConfigurationFromContext(configuration: TornadoFXConfiguration, context: ConfigurationContext, sourceElement: Ref<PsiElement>): Boolean {
val ktClass = sourceElement.get() as? KtClass ?: return false
val psiFacade = JavaPsiFacade.getInstance(ktClass.project)
val psiClass = psiFacade.findClass(ktClass.fqName.toString(), ktClass.project.allScope()) ?: return false
configuration.name = psiClass.name ?: ""
configuration.setModule(context.project.firstModuleWithTornadoFXLib())
if (isApp(psiClass)) {
configuration.RUN_TYPE = App
configuration.mainClassName = psiClass.qualifiedName
} else {
configuration.RUN_TYPE = View
configuration.mainClassName = "tornadofx.App"
configuration.viewClassName = psiClass.qualifiedClassNameForRendering()
}
return true
}
override fun isConfigurationFromContext(configuration: TornadoFXConfiguration, context: ConfigurationContext): Boolean {
val element = context.location!!.psiElement
if (element is KtClass) {
val psiFacade = JavaPsiFacade.getInstance(element.project)
val psiClass = psiFacade.findClass(element.fqName.toString(), element.project.allScope())!!
if (configuration.name == psiClass.name) {
val correctRunType = if (isApp(psiClass)) App else View
return correctRunType == configuration.RUN_TYPE
}
}
return false
}
}
|
apache-2.0
|
2acecaf165b291f9c73096454070a23b
| 46.166667 | 159 | 0.759364 | 5.329567 | false | true | false | false |
y2k/RssReader
|
app/src/main/kotlin/y2k/rssreader/common.kt
|
1
|
2500
|
package y2k.rssreader
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.support.v7.app.AppCompatActivity
import java8.util.concurrent.CompletableFuture
import org.funktionale.partials.partially1
import rx.Observable
import rx.Subscription
import rx.subjects.BehaviorSubject
import rx.subjects.PublishSubject
/**
* Created by y2k on 18/08/16.
*/
object Provider {
fun getRssItems(): Observable<RssItems> = getRssItems(provideSync(), ::loadFromRepo)
private fun provideSync(): () -> CompletableFuture<*> =
::syncRssWithWeb
.partially1(provideLoadFromWeb())
.partially1(::saveToRepo)
private fun provideLoadFromWeb(): (String) -> CompletableFuture<String> =
::loadFromWebCached
.partially1(::loadFromWeb)
.partially1(::loadDateFromRepo)
.partially1(::saveDateToRepo)
fun selectSubscription(subscription: RssSubscription) {
TODO()
}
}
inline fun <T> CompletableFuture<T>.peek(crossinline f: (T) -> Unit): CompletableFuture<T> = thenApply { f(it); it }
fun <P1, R> Function1<P1, R>.partially1(p1: P1): () -> R = { this(p1) }
fun <T> runAsync(action: () -> T): CompletableFuture<T> {
val promise = CompletableFuture<T>()
CompletableFuture.supplyAsync {
try {
val result = action()
FOREGROUND_HANDLER.post { promise.complete(result) }
} catch (e: Exception) {
FOREGROUND_HANDLER.post { promise.obtrudeException(e) }
}
}
return promise
}
private val FOREGROUND_HANDLER by lazy { Handler(Looper.getMainLooper()) }
open class BaseActivity : AppCompatActivity() {
val onResume: PublishSubject<Any> = PublishSubject.create()
val onPause: PublishSubject<Any> = PublishSubject.create()
override fun onResume() {
super.onResume()
onResume.onNext(Unit)
}
override fun onPause() {
super.onPause()
onPause.onNext(Unit)
}
}
fun <T> Observable<T>.toLiveCycleObservable(context: Context): Observable<T> {
val activity = context as BaseActivity
val subject = BehaviorSubject.create<T>()
var subscription: Subscription? = null
activity.onResume.subscribe {
subscription = subscribe(
{ subject.onNext(it) },
{ subject.onError(it) },
{ subject.onCompleted() })
}
activity.onPause.subscribe {
subscription?.unsubscribe()
}
return subject
}
|
mit
|
29276affc41676f24b3b14e86b8e5ce4
| 27.101124 | 116 | 0.6612 | 4.201681 | false | false | false | false |
talhacohen/android
|
app/src/main/java/com/etesync/syncadapter/syncadapter/SyncAdapterService.kt
|
1
|
8349
|
/*
* Copyright © 2013 – 2016 Ricki Hirner (bitfire web engineering).
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*/
package com.etesync.syncadapter.syncadapter
import android.accounts.Account
import android.app.PendingIntent
import android.app.Service
import android.content.*
import android.net.ConnectivityManager
import android.net.wifi.WifiManager
import android.os.Bundle
import android.os.IBinder
import android.support.v4.app.NotificationCompat
import android.support.v4.app.NotificationManagerCompat
import android.support.v4.util.Pair
import com.etesync.syncadapter.*
import com.etesync.syncadapter.journalmanager.Crypto
import com.etesync.syncadapter.journalmanager.Exceptions
import com.etesync.syncadapter.journalmanager.JournalManager
import com.etesync.syncadapter.model.CollectionInfo
import com.etesync.syncadapter.model.JournalEntity
import com.etesync.syncadapter.model.JournalModel
import com.etesync.syncadapter.ui.PermissionsActivity
import okhttp3.HttpUrl
import java.util.*
import java.util.logging.Level
//import com.android.vending.billing.IInAppBillingService;
abstract class SyncAdapterService : Service() {
protected abstract fun syncAdapter(): AbstractThreadedSyncAdapter
override fun onBind(intent: Intent): IBinder? {
return syncAdapter().syncAdapterBinder
}
abstract class SyncAdapter(context: Context) : AbstractThreadedSyncAdapter(context, false) {
override fun onPerformSync(account: Account, extras: Bundle, authority: String, provider: ContentProviderClient, syncResult: SyncResult) {
App.log.log(Level.INFO, "$authority sync of $account has been initiated.", extras.keySet().toTypedArray())
// required for dav4android (ServiceLoader)
Thread.currentThread().contextClassLoader = context.classLoader
}
override fun onSecurityException(account: Account, extras: Bundle, authority: String, syncResult: SyncResult) {
App.log.log(Level.WARNING, "Security exception when opening content provider for $authority")
syncResult.databaseError = true
val intent = Intent(context, PermissionsActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
val notify = NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_error_light)
.setLargeIcon(App.getLauncherBitmap(context))
.setContentTitle(context.getString(R.string.sync_error_permissions))
.setContentText(context.getString(R.string.sync_error_permissions_text))
.setContentIntent(PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT))
.setCategory(NotificationCompat.CATEGORY_ERROR)
.build()
val nm = NotificationManagerCompat.from(context)
nm.notify(Constants.NOTIFICATION_PERMISSIONS, notify)
}
protected fun checkSyncConditions(settings: AccountSettings): Boolean {
if (settings.syncWifiOnly) {
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val network = cm.activeNetworkInfo
if (network == null) {
App.log.info("No network available, stopping")
return false
}
if (network.type != ConnectivityManager.TYPE_WIFI || !network.isConnected) {
App.log.info("Not on connected WiFi, stopping")
return false
}
var onlySSID = settings.syncWifiOnlySSID
if (onlySSID != null) {
onlySSID = "\"" + onlySSID + "\""
val wifi = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
val info = wifi.connectionInfo
if (info == null || onlySSID != info.ssid) {
App.log.info("Connected to wrong WiFi network (" + info!!.ssid + ", required: " + onlySSID + "), ignoring")
return false
}
}
}
return true
}
inner class RefreshCollections internal constructor(private val account: Account, private val serviceType: CollectionInfo.Type) {
private val context: Context
init {
context = getContext()
}
@Throws(Exceptions.HttpException::class, Exceptions.IntegrityException::class, InvalidAccountException::class, Exceptions.GenericCryptoException::class)
internal fun run() {
App.log.info("Refreshing " + serviceType + " collections of service #" + serviceType.toString())
val settings = AccountSettings(context, account)
val httpClient = HttpClient.create(context, settings)
val journalsManager = JournalManager(httpClient, HttpUrl.get(settings.uri!!)!!)
val journals = LinkedList<Pair<JournalManager.Journal, CollectionInfo>>()
for (journal in journalsManager.list()) {
val crypto: Crypto.CryptoManager
if (journal.key != null) {
crypto = Crypto.CryptoManager(journal.version, settings.keyPair!!, journal.key)
} else {
crypto = Crypto.CryptoManager(journal.version, settings.password(), journal.uid!!)
}
journal.verify(crypto)
val info = CollectionInfo.fromJson(journal.getContent(crypto))
info.updateFromJournal(journal)
if (info.type == serviceType) {
journals.add(Pair(journal, info))
}
}
if (journals.isEmpty()) {
try {
val info = CollectionInfo.defaultForServiceType(serviceType)
val uid = JournalManager.Journal.genUid()
info.uid = uid
val crypto = Crypto.CryptoManager(info.version, settings.password(), uid)
val journal = JournalManager.Journal(crypto, info.toJson(), uid)
journalsManager.create(journal)
journals.add(Pair(journal, info))
} catch (e: Exceptions.AssociateNotAllowedException) {
// Skip for now
}
}
saveCollections(journals)
}
private fun saveCollections(journals: Iterable<Pair<JournalManager.Journal, CollectionInfo>>) {
val data = (context.applicationContext as App).data
val service = JournalModel.Service.fetch(data, account.name, serviceType)
val existing = HashMap<String, JournalEntity>()
for (journalEntity in JournalEntity.getJournals(data, service)) {
existing[journalEntity.uid] = journalEntity
}
for (pair in journals) {
val journal = pair.first
val collection = pair.second
App.log.log(Level.FINE, "Saving collection", journal!!.uid)
collection!!.serviceID = service.id
val journalEntity = JournalEntity.fetchOrCreate(data, collection)
journalEntity.owner = journal.owner
journalEntity.encryptedKey = journal.key
journalEntity.isReadOnly = journal.isReadOnly
journalEntity.isDeleted = false
data.upsert(journalEntity)
existing.remove(collection.uid)
}
for (journalEntity in existing.values) {
App.log.log(Level.FINE, "Deleting collection", journalEntity.uid)
journalEntity.isDeleted = true
data.update(journalEntity)
}
}
}
}
}
|
gpl-3.0
|
d5e7562e158be53f2adedf2c4aa609ff
| 43.631016 | 164 | 0.607596 | 5.239171 | false | false | false | false |
toastkidjp/Yobidashi_kt
|
app/src/test/java/jp/toastkid/yobidashi/libs/VectorToBitmapTest.kt
|
2
|
2484
|
/*
* Copyright (c) 2021 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.yobidashi.libs
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.drawable.Drawable
import androidx.core.content.ContextCompat
import io.mockk.MockKAnnotations
import io.mockk.every
import io.mockk.impl.annotations.InjectMockKs
import io.mockk.impl.annotations.MockK
import io.mockk.mockk
import io.mockk.mockkConstructor
import io.mockk.mockkStatic
import io.mockk.unmockkAll
import io.mockk.verify
import org.junit.After
import org.junit.Before
import org.junit.Test
class VectorToBitmapTest {
@InjectMockKs
private lateinit var vectorToBitmap: VectorToBitmap
@MockK
private lateinit var context: Context
@MockK
private lateinit var drawable: Drawable
@Before
fun setUp() {
MockKAnnotations.init(this)
every { drawable.setBounds(any(), any(), any(), any()) }.answers { Unit }
every { drawable.draw(any()) }.answers { Unit }
every { drawable.getIntrinsicWidth() }.returns(1)
every { drawable.getIntrinsicHeight() }.returns(1)
mockkConstructor(Canvas::class)
every { anyConstructed<Canvas>().getWidth() }.returns(1)
every { anyConstructed<Canvas>().getHeight() }.returns(1)
mockkStatic(Bitmap::class)
every { Bitmap.createBitmap(any(), any(), any()) }.returns(mockk())
mockkStatic(ContextCompat::class)
every { ContextCompat.getDrawable(any(), any()) }.returns(drawable)
}
@After
fun tearDown() {
unmockkAll()
}
@Test
fun testInvoke() {
vectorToBitmap.invoke(1)
verify(exactly = 1) { drawable.setBounds(any(), any(), any(), any()) }
verify(exactly = 1) { drawable.draw(any()) }
verify(exactly = 1) { drawable.getIntrinsicWidth() }
verify(exactly = 1) { drawable.getIntrinsicHeight() }
verify(exactly = 1) { anyConstructed<Canvas>().getWidth() }
verify(exactly = 1) { anyConstructed<Canvas>().getHeight() }
verify(exactly = 1) { Bitmap.createBitmap(any(), any(), any()) }
verify(exactly = 1) { ContextCompat.getDrawable(any(), any()) }
}
}
|
epl-1.0
|
88b4e45eabfd64f5c6dde19239b86737
| 31.272727 | 88 | 0.683575 | 4.253425 | false | true | false | false |
lgou2w/MoonLakeLauncher
|
src/main/kotlin/com/minecraft/moonlake/launcher/mc/download/HostDownloadSource.kt
|
1
|
1244
|
/*
* Copyright (C) 2017 The MoonLake Authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.minecraft.moonlake.launcher.mc.download
open class HostDownloadSource(val host: String): DownloadSource {
override fun getLibrariesDownloadURL(): String
= host + "libraries"
override fun getVersionsDownloadURL(): String
= host + "versions"
override fun getIndexesDownloadURL(): String
= host + "indexes"
override fun getVersionListDownloadURL(): String
= host + "version_manifest.json"
override fun getAssetsDownloadURL(): String
= host + "assets"
}
|
gpl-3.0
|
76bba817514490e2a36d01ea01cb6e0b
| 37.875 | 72 | 0.709003 | 4.458781 | false | false | false | false |
alygin/intellij-rust
|
src/test/kotlin/org/rust/ide/typing/RsEnterInLineCommentHandlerTest.kt
|
2
|
1038
|
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.typing
class RsEnterInLineCommentHandlerTest : RsTypingTestBase() {
override val dataPath = "org/rust/ide/typing/lineComment/fixtures"
fun testBeforeLineComment() = doTest()
fun testInLineComment() = doTest()
fun testAfterLineComment() = doTest()
fun testInBlockComment() = doTest()
fun testInOuterDocComment() = doTest()
fun testAfterOuterDocComment() = doTest()
fun testInInnerDocComment() = doTest()
fun testAfterInnerDocComment() = doTest()
fun testAfterModuleComment() = doTest()
fun testDirectlyAfterToken() = doTest()
fun testInsideToken() = doTest()
fun testInsideCommentDirectlyBeforeNextToken() = doTest()
fun testInsideCommentInsideToken() = doTest()
fun testAtFileBeginning() = doTest()
fun testInsideStringLiteral() = doTest()
fun testIssue578() = doTest() // https://github.com/intellij-rust/intellij-rust/issues/578
}
|
mit
|
f1df43a72b99bd300a399c05fcd6846a
| 32.483871 | 96 | 0.713873 | 4.202429 | false | true | false | false |
enchf/kotlin-koans
|
src/i_introduction/_2_Named_Arguments/n02NamedArguments.kt
|
1
|
843
|
package i_introduction._2_Named_Arguments
import i_introduction._1_Java_To_Kotlin_Converter.task1
import util.TODO
import util.doc2
// default values for arguments
fun bar(i: Int, s: String = "", b: Boolean = true) {}
fun usage() {
// named arguments
bar(1, b = false)
}
fun todoTask2(): Nothing = TODO(
"""
Task 2.
Print out the collection contents surrounded by curly braces using the library function 'joinToString'.
Specify only 'prefix' and 'postfix' arguments.
Don't forget to remove the 'todoTask2()' invocation which throws an exception.
""",
documentation = doc2(),
references = { collection: Collection<Int> -> task1(collection); collection.joinToString() })
fun task2(collection: Collection<Int>) = collection.joinToString(prefix = "{", postfix = "}", separator = ", ")
|
mit
|
2b70b68d3b7b7bb6c7eb8594f9273d33
| 31.423077 | 111 | 0.676157 | 4.072464 | false | false | false | false |
pyamsoft/zaptorch
|
app/src/main/java/com/pyamsoft/zaptorch/service/monitor/VolumeMonitorService.kt
|
1
|
2830
|
/*
* Copyright 2020 Peter Kenji Yamanaka
*
* 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.pyamsoft.zaptorch.service.monitor
import android.accessibilityservice.AccessibilityService
import android.content.Intent
import android.view.KeyEvent
import android.view.accessibility.AccessibilityEvent
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
import androidx.lifecycle.lifecycleScope
import com.pyamsoft.pydroid.core.requireNotNull
import com.pyamsoft.pydroid.inject.Injector
import com.pyamsoft.zaptorch.ZapTorchComponent
import com.pyamsoft.zaptorch.service.error.CameraErrorExplanation
import com.pyamsoft.zaptorch.service.monitor.ServiceEvent.RenderError
import javax.inject.Inject
import timber.log.Timber
class VolumeMonitorService : AccessibilityService(), LifecycleOwner {
@JvmField @Inject internal var binder: ServiceBinder? = null
private val registry by lazy(LazyThreadSafetyMode.NONE) { LifecycleRegistry(this) }
override fun getLifecycle(): Lifecycle {
return registry
}
override fun onKeyEvent(event: KeyEvent): Boolean {
val action = event.action
val keyCode = event.keyCode
binder?.handleKeyEvent(lifecycleScope, action, keyCode)
// Never consume events
return false
}
override fun onAccessibilityEvent(accessibilityEvent: AccessibilityEvent) {
Timber.d("onAccessibilityEvent")
}
override fun onInterrupt() {
Timber.e("onInterrupt")
}
override fun onCreate() {
super.onCreate()
Injector.obtainFromApplication<ZapTorchComponent>(this)
.plusServiceComponent()
.create()
.inject(this)
binder.requireNotNull().bind(lifecycleScope) {
return@bind when (it) {
is RenderError -> CameraErrorExplanation.showError(applicationContext)
}
}
registry.currentState = Lifecycle.State.RESUMED
}
override fun onServiceConnected() {
super.onServiceConnected()
binder.requireNotNull().start(lifecycleScope)
}
override fun onUnbind(intent: Intent): Boolean {
binder?.handleStop(lifecycleScope)
return super.onUnbind(intent)
}
override fun onDestroy() {
super.onDestroy()
binder?.unbind()
binder = null
registry.currentState = Lifecycle.State.DESTROYED
}
}
|
apache-2.0
|
9db18ca98f272ea92d38492427a76e3a
| 28.789474 | 85 | 0.757951 | 4.57189 | false | false | false | false |
jtransc/jtransc
|
benchmark_kotlin_mpp/src/commonMain/kotlin/simd/MutableMatrixFloat32x4x4.kt
|
1
|
2217
|
package simd
class MutableMatrixFloat32x4x4 private constructor() {
companion object {
fun create(): MutableMatrixFloat32x4x4 {
return MutableMatrixFloat32x4x4()
}
init {
Simd.ref()
}
}
//final private MutableFloat32x4[] v = new MutableFloat32x4[]{MutableFloat32x4.create(), MutableFloat32x4.create(), MutableFloat32x4.create(), MutableFloat32x4.create()};
private val x: MutableFloat32x4 = MutableFloat32x4.create()
private val y: MutableFloat32x4 = MutableFloat32x4.create()
private val z: MutableFloat32x4 = MutableFloat32x4.create()
private val w: MutableFloat32x4 = MutableFloat32x4.create()
fun setTo(
m00: Float, m01: Float, m02: Float, m03: Float,
m10: Float, m11: Float, m12: Float, m13: Float,
m20: Float, m21: Float, m22: Float, m23: Float,
m30: Float, m31: Float, m32: Float, m33: Float
) {
getX().setTo(m00, m01, m02, m03)
getY().setTo(m10, m11, m12, m13)
getZ().setTo(m20, m21, m22, m23)
getW().setTo(m30, m31, m32, m33)
}
fun setTo(x: MutableFloat32x4, y: MutableFloat32x4, z: MutableFloat32x4, w: MutableFloat32x4) {
getX().setTo(x)
getY().setTo(y)
getZ().setTo(z)
getW().setTo(w)
}
fun setX(v: MutableFloat32x4) {
getX().setTo(v)
}
fun setY(v: MutableFloat32x4) {
getY().setTo(v)
}
fun setZ(v: MutableFloat32x4) {
getZ().setTo(v)
}
fun setW(v: MutableFloat32x4) {
getW().setTo(v)
}
fun setRow(index: Int, v: MutableFloat32x4) {
//this.v[index].setTo(v);
when (index) {
0 -> x.setTo(v)
1 -> y.setTo(v)
2 -> z.setTo(v)
3 -> w.setTo(v)
}
}
fun getX(): MutableFloat32x4 {
return x
}
fun getY(): MutableFloat32x4 {
return y
}
fun getZ(): MutableFloat32x4 {
return z
}
fun getW(): MutableFloat32x4 {
return w
}
fun getRow(index: Int): MutableFloat32x4 {
when (index) {
0 -> return x
1 -> return y
2 -> return z
3 -> return w
}
return x
}
fun getCell(row: Int, column: Int): Float {
return MutableMatrixFloat32x4x4Utils._getCell(this, row, column)
}
val sumAll: Float
get() = MutableMatrixFloat32x4x4Utils._getSumAll(this)
fun setToMul44(a: MutableMatrixFloat32x4x4, b: MutableMatrixFloat32x4x4) {
MutableMatrixFloat32x4x4Utils._setToMul44(this, a, b)
}
}
|
apache-2.0
|
f94060c57d023fffafde159eb846aac4
| 20.960396 | 171 | 0.674335 | 2.491011 | false | false | false | false |
dataloom/conductor-client
|
src/main/kotlin/com/openlattice/data/storage/PostgresDataQueries.kt
|
1
|
32085
|
package com.openlattice.data.storage
import com.openlattice.IdConstants
import com.openlattice.analysis.SqlBindInfo
import com.openlattice.analysis.requests.Filter
import com.openlattice.data.storage.partitions.getPartition
import com.openlattice.edm.PostgresEdmTypeConverter
import com.openlattice.edm.type.PropertyType
import com.openlattice.postgres.*
import com.openlattice.postgres.DataTables.LAST_WRITE
import com.openlattice.postgres.PostgresColumn.*
import com.openlattice.postgres.PostgresDataTables.Companion.dataTableValueColumns
import com.openlattice.postgres.PostgresDataTables.Companion.getColumnDefinition
import com.openlattice.postgres.PostgresDataTables.Companion.getSourceDataColumnName
import com.openlattice.postgres.PostgresTable.DATA
import com.openlattice.postgres.PostgresTable.IDS
import java.sql.PreparedStatement
import java.util.*
/**
* This class is responsible for generating all the SQL for creating, reading, upated, and deleting entities.
* @author Matthew Tamayo-Rios <[email protected]>
*/
internal class PostgresDataQueries
const val VALUE = "value"
const val PROPERTIES = "properties"
val dataTableColumnsSql = PostgresDataTables.dataTableColumns.joinToString(",") { it.name }
// @formatter:off
val detailedValueColumnsSql =
"COALESCE( " + dataTableValueColumns.joinToString(",") {
"jsonb_agg(" +
"json_build_object(" +
"'$VALUE',${it.name}, " +
"'${ID_VALUE.name}', ${ORIGIN_ID.name}, " +
"'${LAST_WRITE.name}', ${LAST_WRITE.name}" +
")" +
") FILTER ( WHERE ${it.name} IS NOT NULL) "
} + ") as $PROPERTIES"
val valuesColumnsSql = "COALESCE( " + dataTableValueColumns.joinToString(",") {
"jsonb_agg(${it.name}) " +
"FILTER (WHERE ${it.name} IS NOT NULL)"
} + ") as $PROPERTIES"
// @formatter:on
val primaryKeyColumnNamesAsString = PostgresDataTables.buildDataTableDefinition().primaryKey.joinToString(
","
) { it.name }
/**
* Builds a preparable SQL query for reading filterable data.
*
* The first three columns om
* @return A preparable sql query to read the data to a ordered set of [SqlBinder] objects. The prepared query
* must be have the first three parameters bound separately from the [SqlBinder] objects. The parameters are as follows:
* 1. entity set ids (array)
* 2. entity key ids (array)
* 3. partition(s) (array)
*
*/
fun buildPreparableFiltersSql(
startIndex: Int,
propertyTypes: Map<UUID, PropertyType>,
propertyTypeFilters: Map<UUID, Set<Filter>>,
metadataOptions: Set<MetadataOption>,
linking: Boolean,
idsPresent: Boolean,
partitionsPresent: Boolean,
detailed: Boolean = false
): Pair<String, Set<SqlBinder>> {
val filtersClauses = buildPreparableFiltersClause(startIndex, propertyTypes, propertyTypeFilters)
val filtersClause = if (filtersClauses.first.isNotEmpty()) " AND ${filtersClauses.first} " else ""
val metadataOptionColumns = metadataOptions.associateWith(::mapOuterMetaDataToColumnSql)
val metadataOptionColumnsSql = metadataOptionColumns.values.joinToString("")
val innerGroupBy = if (linking) groupBy(ESID_ORIGINID_PART_PTID) else groupBy(ESID_EKID_PART_PTID)
val outerGroupBy = if (metadataOptions.contains(MetadataOption.ENTITY_KEY_IDS)) groupBy(ESID_EKID_PART_PTID) else groupBy(ESID_EKID_PART)
val linkingClause = if (linking) " AND ${ORIGIN_ID.name} != '${IdConstants.EMPTY_ORIGIN_ID.id}' " else ""
val innerSql = selectEntitiesGroupedByIdAndPropertyTypeId(
metadataOptions,
idsPresent = idsPresent,
partitionsPresent = partitionsPresent,
detailed = detailed,
linking = linking
) + linkingClause + filtersClause + innerGroupBy
val sql = "SELECT ${ENTITY_SET_ID.name},${ID_VALUE.name},${PARTITION.name}$metadataOptionColumnsSql," +
"jsonb_object_agg(${PROPERTY_TYPE_ID.name},$PROPERTIES) as $PROPERTIES " +
"FROM ($innerSql) entities $outerGroupBy"
return sql to filtersClauses.second
}
internal fun selectEntitiesGroupedByIdAndPropertyTypeId(
metadataOptions: Set<MetadataOption>,
idsPresent: Boolean = true,
partitionsPresent: Boolean = true,
entitySetsPresent: Boolean = true,
detailed: Boolean = false,
linking: Boolean = false
): String {
//Already have the comma prefix
val metadataOptionsSql = metadataOptions.joinToString("") { mapMetaDataToSelector(it) }
val columnsSql = if (detailed) detailedValueColumnsSql else valuesColumnsSql
val idColumn = if (linking) ORIGIN_ID.name else ID_VALUE.name
return "SELECT ${ENTITY_SET_ID.name},$idColumn as ${ID_VALUE.name},${PARTITION.name},${PROPERTY_TYPE_ID.name}$metadataOptionsSql,$columnsSql " +
"FROM ${DATA.name} ${optionalWhereClauses(idsPresent, partitionsPresent, entitySetsPresent, linking)}"
}
/**
* Returns the correspondent column name used for the metadata option with a comma prefix.
*/
private fun mapOuterMetaDataToColumnSql(metadataOption: MetadataOption): String {
return when (metadataOption) {
// TODO should be just last_write with comma prefix after empty rows are eliminated https://jira.openlattice.com/browse/LATTICE-2254
MetadataOption.LAST_WRITE -> ",max(${LAST_WRITE.name}) AS ${mapMetaDataToColumnName(metadataOption)}"
MetadataOption.ENTITY_KEY_IDS -> ",array_agg(${ORIGIN_ID.name}) as ${ENTITY_KEY_IDS_COL.name}"
else -> throw UnsupportedOperationException("No implementation yet for metadata option $metadataOption")
}
}
/**
* Returns the correspondent column name used for the metadata option.
*/
private fun mapMetaDataToColumnName(metadataOption: MetadataOption): String {
return when (metadataOption) {
MetadataOption.LAST_WRITE -> LAST_WRITE.name
MetadataOption.ENTITY_KEY_IDS -> ENTITY_KEY_IDS_COL.name
else -> throw UnsupportedOperationException("No implementation yet for metadata option $metadataOption")
}
}
/**
* Returns the select sql snippet for the requested metadata option.
*/
private fun mapMetaDataToSelector(metadataOption: MetadataOption): String {
return when (metadataOption) {
MetadataOption.LAST_WRITE -> ",max(${LAST_WRITE.name}) AS ${mapMetaDataToColumnName(metadataOption)}"
MetadataOption.ENTITY_KEY_IDS -> ",${ID_VALUE.name} as ${ORIGIN_ID.name}" //Adapter for queries for now.
else -> throw UnsupportedOperationException("No implementation yet for metadata option $metadataOption")
}
}
/*
* Creates a preparable query with the following clauses.
*/
private fun buildPreparableFiltersClause(
startIndex: Int,
propertyTypes: Map<UUID, PropertyType>,
propertyTypeFilters: Map<UUID, Set<Filter>>
): Pair<String, Set<SqlBinder>> {
val bindList = propertyTypeFilters.entries
.filter { (_, filters) -> filters.isEmpty() }
.flatMap { (propertyTypeId, filters) ->
val nCol = PostgresDataTables
.nonIndexedValueColumn(
PostgresEdmTypeConverter.map(propertyTypes.getValue(propertyTypeId).datatype)
)
val bCol = PostgresDataTables
.btreeIndexedValueColumn(
PostgresEdmTypeConverter.map(propertyTypes.getValue(propertyTypeId).datatype)
)
//Generate sql preparable sql fragments
var currentIndex = startIndex
val nFilterFragments = filters.map { filter ->
val bindDetails = buildBindDetails(currentIndex, propertyTypeId, filter, nCol.name)
currentIndex = bindDetails.nextIndex
bindDetails
}
val bFilterFragments = filters
.map { filter ->
val bindDetails = buildBindDetails(currentIndex, propertyTypeId, filter, bCol.name)
currentIndex = bindDetails.nextIndex
bindDetails
}
nFilterFragments + bFilterFragments
}
val sql = bindList.joinToString(" AND ") { "(${it.sql})" }
val bindInfo = bindList.flatMap { it.bindInfo }.toSet()
return sql to bindInfo
}
private fun buildBindDetails(
startIndex: Int,
propertyTypeId: UUID,
filter: Filter,
col: String
): BindDetails {
val bindInfo = linkedSetOf<SqlBinder>()
bindInfo.add(SqlBinder(SqlBindInfo(startIndex, propertyTypeId), ::doBind))
bindInfo.addAll(filter.bindInfo(startIndex).map { SqlBinder(it, ::doBind) })
return BindDetails(startIndex + bindInfo.size, bindInfo, "${PROPERTY_TYPE_ID.name} = ? AND " + filter.asSql(col))
}
@Suppress("UNCHECKED_CAST")
internal fun doBind(ps: PreparedStatement, info: SqlBindInfo) {
when (val v = info.value) {
is String -> ps.setString(info.bindIndex, v)
is Int -> ps.setInt(info.bindIndex, v)
is Long -> ps.setLong(info.bindIndex, v)
is Boolean -> ps.setBoolean(info.bindIndex, v)
is Short -> ps.setShort(info.bindIndex, v)
is java.sql.Array -> ps.setArray(info.bindIndex, v)
//TODO: Fix this bustedness.
is Collection<*> -> {
val array = when (val elem = v.first()!!) {
is String -> PostgresArrays.createTextArray(ps.connection, v as Collection<String>)
is Int -> PostgresArrays.createIntArray(ps.connection, v as Collection<Int>)
is Long -> PostgresArrays.createLongArray(ps.connection, v as Collection<Long>)
is Boolean -> PostgresArrays.createBooleanArray(ps.connection, v as Collection<Boolean>)
is Short -> PostgresArrays.createShortArray(ps.connection, v as Collection<Short>)
else -> throw IllegalArgumentException(
"Collection with elements of ${elem.javaClass} are not " +
"supported in filters"
)
}
ps.setArray(info.bindIndex, array)
}
else -> ps.setObject(info.bindIndex, v)
}
}
internal val ESID_EKID_PART = "${ENTITY_SET_ID.name},${ID_VALUE.name},${PARTITION.name}"
internal val ESID_EKID_PART_PTID = "$ESID_EKID_PART,${PROPERTY_TYPE_ID.name}"
internal val ESID_ORIGINID_PART_PTID = "${ENTITY_SET_ID.name},${ORIGIN_ID.name},${PARTITION.name},${PROPERTY_TYPE_ID.name}"
internal fun groupBy(columns: String): String {
return "GROUP BY ($columns)"
}
/**
* Preparable SQL that selects entities across multiple entity sets grouping by id and property type id from the [DATA]
* table with the following bind order:
*
* 1. entity set ids (array)
* 2. entity key ids (array)
* 3. partition (array)
*
*/
fun optionalWhereClauses(
idsPresent: Boolean = true,
partitionsPresent: Boolean = true,
entitySetsPresent: Boolean = true,
linking: Boolean = false
): String {
val entitySetClause = if (entitySetsPresent) "${ENTITY_SET_ID.name} = ANY(?)" else ""
val idsColumn = if (linking) ORIGIN_ID.name else ID_VALUE.name
val idsClause = if (idsPresent) "$idsColumn = ANY(?)" else ""
val partitionClause = if (partitionsPresent) "${PARTITION.name} = ANY(?)" else ""
val versionsClause = "${VERSION.name} > 0 "
val optionalClauses = listOf(entitySetClause, idsClause, partitionClause, versionsClause).filter { it.isNotBlank() }
return "WHERE ${optionalClauses.joinToString(" AND ")}"
}
fun optionalWhereClausesSingleEdk(
idPresent: Boolean = true,
partitionsPresent: Boolean = true,
entitySetPresent: Boolean = true
): String {
val entitySetClause = if (entitySetPresent) "${ENTITY_SET_ID.name} = ?" else ""
val idsClause = if (idPresent) "${ID_VALUE.name} = ?" else ""
val partitionClause = if (partitionsPresent) "${PARTITION.name} = ANY(?)" else ""
val versionsClause = "${VERSION.name} > 0 "
val optionalClauses = listOf(entitySetClause, idsClause, partitionClause, versionsClause).filter { it.isNotBlank() }
return "WHERE ${optionalClauses.joinToString(" AND ")}"
}
/**
* Preparable sql to lock entities in [IDS] table.
*
* This query will lock provided entities that have an assigned linking id in ID order.
*
* The bind order is the following:
*
* 1 - entity set id
*
* 2 - entity key id
*
* 3 - partition
*/
val lockEntitiesInIdsTable =
"SELECT 1 FROM ${IDS.name} " +
"WHERE ${ENTITY_SET_ID.name} = ? AND ${ID_VALUE.name} = ? AND ${PARTITION.name} = ? " +
"FOR UPDATE"
/**
* Preparable sql to lock entities in [IDS] table.
*
* This query will lock provided entities that have an assigned linking id in ID order.
*
* The bind order is the following:
*
* 1 - entity key ids
*
* 2 - partition
*/
val bulkLockEntitiesInIdsTable =
"SELECT 1 FROM ${IDS.name} " +
"WHERE ${ID_VALUE.name} = ANY(?) AND ${PARTITION.name} = ? " +
"ORDER BY ${ID_VALUE.name}" +
"FOR UPDATE"
/**
* Preparable sql to lock entities in [IDS] table.
*
* This query will lock provided entities that have an assigned linking id in ID order.
*
* The bind order is the following:
*
* 1 - entity set id
*
* 2 - entity key ids
*
* 3 - partition
*/
val lockLinkedEntitiesInIdsTable =
"SELECT 1 FROM ${IDS.name} " +
"WHERE ${ENTITY_SET_ID.name} = ? AND ${ID_VALUE.name} = ANY(?) AND ${PARTITION.name} = ? AND LINKING_ID IS NOT NULL " +
"ORDER BY ${ID_VALUE.name} " +
"FOR UPDATE"
/**
* Preparable sql to upsert entities in [IDS] table.
*
* It sets a positive version and updates last write to current time.
*
* The bind order is the following:
*
* 1 - versions
*
* 2 - version
*
* 3 - version
*
* 4 - entity set id
*
* 5 - entity key ids
*
* 6 - partition
*/
// @formatter:off
val upsertEntitiesSql = "UPDATE ${IDS.name} " +
"SET ${VERSIONS.name} = ${VERSIONS.name} || ?, " +
"${LAST_WRITE.name} = now(), " +
"${VERSION.name} = CASE " +
"WHEN abs(${IDS.name}.${VERSION.name}) <= abs(?) THEN ? " +
"ELSE ${IDS.name}.${VERSION.name} " +
"END " +
"WHERE ${ENTITY_SET_ID.name} = ? AND ${ID_VALUE.name} = ANY(?) AND ${PARTITION.name} = ? "
// @formatter:on
/**
* Preparable sql to update an entity in the [IDS] table.
*
* It sets a positive version and updates last write to current time.
*
* The bind order is the following:
*
* 1 - versions
*
* 2 - version
*
* 3 - version
*
* 4 - entity set id
*
* 5 - entity key id
*
* 6 - partition
*/
// @formatter:off
val updateEntitySql = "UPDATE ${IDS.name} " +
"SET ${VERSIONS.name} = ${VERSIONS.name} || ?, " +
"${LAST_WRITE.name} = now(), " +
"${VERSION.name} = CASE " +
"WHEN abs(${IDS.name}.${VERSION.name}) <= abs(?) THEN ? " +
"ELSE ${IDS.name}.${VERSION.name} " +
"END " +
"WHERE ${ENTITY_SET_ID.name} = ? AND ${ID_VALUE.name} = ? AND ${PARTITION.name} = ? "
// @formatter:on
/**
* Preparable SQL that upserts a version and sets last write to current datetime for all entities in a given entity set
* in [IDS] table.
*
* The following bind order is expected:
*
* 1. version
* 2. version
* 3. version
* 4. entity set id
* 5. partition
*/
// @formatter:off
internal val updateVersionsForEntitySet = "UPDATE ${IDS.name} " +
"SET " +
"${VERSIONS.name} = ${VERSIONS.name} || ARRAY[?], " +
"${VERSION.name} = " +
"CASE " +
"WHEN abs(${IDS.name}.${VERSION.name}) <= abs(?) " +
"THEN ? " +
"ELSE ${IDS.name}.${VERSION.name} " +
"END, " +
"${LAST_WRITE.name} = 'now()' " +
"WHERE ${ENTITY_SET_ID.name} = ? " +
"AND ${PARTITION.name} = ? "
// @formatter:on
/**
* Preparable SQL that upserts a version and sets last write to current datetime for all entities in a given entity set
* in [IDS] table.
*
* The following bind order is expected:
*
* 1. version
* 2. version
* 3. version
* 4. entity set id
* 5. partition
* 6. entity key ids (uuid array)
*/
internal val updateVersionsForEntitiesInEntitySet = "$updateVersionsForEntitySet " +
"AND ${ID_VALUE.name} = ANY(?) "
/**
* Preparable SQL that zeroes out the version and sets last write to current datetime for all entities in a given
* entity set in [IDS] table.
*
* The following bind order is expected:
*
* 1. entity set id
* 2. partition
*/
// @formatter:off
internal val zeroVersionsForEntitySet = "UPDATE ${IDS.name} " +
"SET " +
"${VERSIONS.name} = ${VERSIONS.name} || ARRAY[0]::bigint[], " +
"${VERSION.name} = 0, " +
"${LAST_WRITE.name} = 'now()' " +
"WHERE " +
"${ENTITY_SET_ID.name} = ? AND " +
"${PARTITION.name} = ? "
// @formatter:on
/**
* Preparable SQL that zeroes out the version and sets last write to current datetime for all entities in a given
* entity set in [IDS] table.
*
* The following bind order is expected:
*
* 1. entity set id
* 2. partition
* 3. id (uuid array)
*/
internal val zeroVersionsForEntitiesInEntitySet = "$zeroVersionsForEntitySet AND ${ID.name} = ANY(?) "
/**
* Preparable SQL that updates a version and sets last write to current datetime for all properties in a given entity
* set in [DATA] table.
*
* The following bind order is expected:
*
* 1. version
* 2. version
* 3. version
* 4. entity set id
* 5. partitions (int array)
*/
// @formatter:off
internal val updateVersionsForPropertiesInEntitySet = "UPDATE ${DATA.name} " +
"SET " +
"${VERSIONS.name} = ${VERSIONS.name} || ARRAY[?], " +
"${VERSION.name} = " +
"CASE " +
"WHEN abs(${DATA.name}.${VERSION.name}) <= abs(?) " +
"THEN ? " +
"ELSE ${DATA.name}.${VERSION.name} " +
"END, " +
"${LAST_WRITE.name} = 'now()' " +
"WHERE ${ENTITY_SET_ID.name} = ? " +
"AND ${PARTITION.name} = ANY(?) "
// @formatter:on
/**
* Preparable SQL that updates a version and sets last write to current datetime for all properties in a given entity
* set in [DATA] table.
*
* The following bind order is expected:
*
* 1. version
* 2. version
* 3. version
* 4. entity set id
* 5. partition(s) (int array)
* 6. property type ids
*/
internal val updateVersionsForPropertyTypesInEntitySet = "$updateVersionsForPropertiesInEntitySet " +
"AND ${PROPERTY_TYPE_ID.name} = ANY(?)"
/**
* Preparable SQL that updates a version and sets last write to current datetime for all properties in a given entity
* set in [DATA] table.
*
* The following bind order is expected:
*
* 1. version
* 2. version
* 3. version
* 4. entity set id
* 5. partition(s) (int array)
* 6. property type ids
* 7. entity key ids
* IF LINKING checks against ORIGIN_ID
* ELSE checks against ID column
*/
fun updateVersionsForPropertyTypesInEntitiesInEntitySet(linking: Boolean = false): String {
val idsSql = if (linking) {
"AND ${ORIGIN_ID.name} = ANY(?)"
} else {
"AND ${ID_VALUE.name} = ANY(?)"
}
return "$updateVersionsForPropertyTypesInEntitySet $idsSql "
}
/**
* Preparable SQL updates a version and sets last write to current datetime for all property values in a given entity
* set in [DATA] table.
*
* The following bind order is expected:
*
* 1. version
* 2. version
* 3. version
* 4. entity set id
* 5. partitions
* 6. property type ids
* 7. entity key ids (if linking: linking ids)
* {origin ids}: only if linking
* 8. hash
*/
internal fun updateVersionsForPropertyValuesInEntitiesInEntitySet(linking: Boolean = false): String {
return "${updateVersionsForPropertyTypesInEntitiesInEntitySet(linking)} AND ${HASH.name} = ? "
}
/**
* Preparable SQL that updates a version and sets last write to current datetime for all properties in a given linked
* entity set in [DATA] table.
*
* Update set:
* 1. VERSION: system.currentTime
* 2. VERSION: system.currentTime
* 3. VERSION: system.currentTime
*
* Where :
* 4. ENTITY_SET: entity set id
* 5. PARTITION: partition(s) (array)
* 6. ID_VALUE: linking id
* 7. ORIGIN_ID: entity key id
*/
val tombstoneLinkForEntity = "$updateVersionsForPropertiesInEntitySet " +
"AND ${ID_VALUE.name} = ? " +
"AND ${ORIGIN_ID.name} = ? "
/**
* Preparable SQL deletes a given property in a given entity set in [DATA]
*
* The following bind order is expected:
*
* 1. entity set id
* 2. property type id
*/
internal val deletePropertyInEntitySet = "DELETE FROM ${DATA.name} WHERE ${ENTITY_SET_ID.name} = ? AND ${PROPERTY_TYPE_ID.name} = ? "
/**
* Preparable SQL deletes all entity ids a given entity set in [IDS]
*
* The following bind order is expected:
*
* 1. entity set id
*/
internal val deleteEntitySetEntityKeys = "DELETE FROM ${IDS.name} WHERE ${ENTITY_SET_ID.name} = ? "
/**
* Preparable SQL that deletes selected property values of entities and their linking entities in a given entity set
* in [DATA] table.
*
* The following bind order is expected:
*
* 1. entity set id
* 2. entity key ids (non-linking entities, ID column)
* 3. entity key ids (linking entities, ORIGIN_ID column)
* 4. partition
* 5. property type ids
*/
// @formatter:off
internal val deletePropertiesOfEntitiesInEntitySet =
"DELETE FROM ${DATA.name} " +
"WHERE ${ENTITY_SET_ID.name} = ? AND " +
"( ${ID_VALUE.name} = ANY( ? ) OR ${ORIGIN_ID.name} = ANY( ? ) ) AND " +
"${PARTITION.name} = ? AND " +
"${PROPERTY_TYPE_ID.name} = ANY( ? ) "
// @formatter:on
/**
* Preparable SQL that deletes all property values and entity key id of entities and their linking entities in a given
* entity set in [DATA] table.
*
* The following bind order is expected:
*
* 1. entity set id
* 2. entity key ids (non-linking entities, ID column)
* 3. entity key ids (linking entities, ORIGIN_ID column)
* 4. partition
*/
internal val deleteEntitiesInEntitySet =
"DELETE FROM ${DATA.name} " +
"WHERE ${ENTITY_SET_ID.name} = ? AND " +
"( ${ID_VALUE.name} = ANY( ? ) OR ${ORIGIN_ID.name} = ANY( ? ) ) AND " +
"${PARTITION.name} = ? "
/**
* Preparable SQL deletes all entities in a given entity set in [IDS]
*
* The following bind order is expected:
*
* 1. entity set id
* 2. entity key ids
* 3. partition
*/
// @formatter:off
internal val deleteEntityKeys =
"$deleteEntitySetEntityKeys AND " +
"${ID.name} = ANY(?) AND " +
"${PARTITION.name} = ? "
// @formatter:on
/**
* Selects a text properties from entity sets with the following bind order:
* 1. entity set ids (array)
* 2. property type ids (array)
*
*/
internal val selectEntitySetTextProperties = "SELECT COALESCE(${getSourceDataColumnName(
PostgresDatatype.TEXT, IndexType.NONE
)},${getSourceDataColumnName(PostgresDatatype.TEXT, IndexType.BTREE)}) AS ${getMergedDataColumnName(
PostgresDatatype.TEXT
)} " +
"FROM ${DATA.name} " +
"WHERE (${getSourceDataColumnName(
PostgresDatatype.TEXT, IndexType.NONE
)} IS NOT NULL OR ${getSourceDataColumnName(PostgresDatatype.TEXT, IndexType.BTREE)} IS NOT NULL) AND " +
"${ENTITY_SET_ID.name} = ANY(?) AND ${PROPERTY_TYPE_ID.name} = ANY(?) "
/**
* Selects a text properties from specific entities with the following bind order:
* 1. entity set ids (array)
* 2. property type ids (array)
* 3. entity key ids (array)
*/
internal val selectEntitiesTextProperties = "$selectEntitySetTextProperties AND ${ID_VALUE.name} = ANY(?)"
/**
* Builds the list of partitions for a given set of entity key ids.
* @param entityKeyIds The entity key ids whose partitions will be retrieved.
* @param partitions The partitions to select from.
* @return A list of partitions.
*/
fun getPartitionsInfo(entityKeyIds: Set<UUID>, partitions: List<Int>): List<Int> {
return entityKeyIds.map { entityKeyId ->
getPartition(
entityKeyId, partitions
)
}
}
/**
* Builds a mapping of entity key id to partition.
*
* @param entityKeyIds The entity key ids whose partitions will be retrieved.
* @param partitions The partitions to select from.
*
* @return A map of entity key ids to partitions.
*/
@Deprecated("Unused")
fun getPartitionsInfoMap(entityKeyIds: Set<UUID>, partitions: List<Int>): Map<UUID, Int> {
return entityKeyIds.associateWith { entityKeyId ->
getPartition(
entityKeyId, partitions
)
}
}
fun getMergedDataColumnName(datatype: PostgresDatatype): String {
return "v_${datatype.name}"
}
/**
* This function generates preparable sql with the following bind order:
*
* 1. ENTITY_SET_ID
* 2. ID_VALUE
* 3. PARTITION
* 4. PROPERTY_TYPE_ID
* 5. HASH
* LAST_WRITE = now()
* 6. VERSION,
* 7. VERSIONS
* 8. Value Column
*/
fun upsertPropertyValueSql(propertyType: PropertyType): String {
val insertColumn = getColumnDefinition(propertyType.postgresIndexType, propertyType.datatype)
val metadataColumnsSql = listOf(
ENTITY_SET_ID,
ID_VALUE,
PARTITION,
PROPERTY_TYPE_ID,
HASH,
LAST_WRITE,
VERSION,
VERSIONS
).joinToString(",") { it.name }
return "INSERT INTO ${DATA.name} ($metadataColumnsSql,${insertColumn.name}) " +
"VALUES (?,?,?,?,?,now(),?,?,?) " +
"ON CONFLICT ($primaryKeyColumnNamesAsString) " +
"DO UPDATE SET " +
"${VERSIONS.name} = ${DATA.name}.${VERSIONS.name} || EXCLUDED.${VERSIONS.name}, " +
"${LAST_WRITE.name} = GREATEST(${DATA.name}.${LAST_WRITE.name},EXCLUDED.${LAST_WRITE.name}), " +
"${ORIGIN_ID.name} = EXCLUDED.${ORIGIN_ID.name}, " +
"${VERSION.name} = CASE " +
"WHEN abs(${DATA.name}.${VERSION.name}) <= EXCLUDED.${VERSION.name} " +
"THEN EXCLUDED.${VERSION.name} " +
"ELSE ${DATA.name}.${VERSION.name} " +
"END"
}
/**
*
* UPDATE DATA:
* 1. Set ORIGIN_ID: linkingID
* 2. where ENTITY_SET_ID: uuid
* 3. and ID_VALUE: UUID
* 4. and PARTITION: int
*/
fun updateLinkingId(): String {
return """
UPDATE ${DATA.name} SET ${ORIGIN_ID.name} = ?
WHERE ${ENTITY_SET_ID.name} = ? AND ${ID_VALUE.name} = ? AND ${PARTITION.name} = ANY(?)
""".trimIndent()
}
/**
* Used to C(~RUD~) a link from linker
* This function generates preparable sql with the following bind order:
*
* Insert into:
* 1. ID_VALUE: linkingId
* 2. VERSION: system.currentTime
*
* Select ƒrom where:
* 3. ENTITY_SET: entity set id
* 4. ID_VALUE: entity key id
* 5. PARTITION: partition(s) (array)
*
*/
fun createOrUpdateLinkFromEntity(): String {
val existingColumnsUpdatedForLinking = PostgresDataTables.dataTableColumns.joinToString(",") {
when (it) {
VERSION, ID_VALUE -> "?"
ORIGIN_ID -> ID_VALUE.name
LAST_WRITE -> "now()"
else -> it.name
}
}
// @formatter:off
return "INSERT INTO ${DATA.name} ($dataTableColumnsSql) " +
"SELECT $existingColumnsUpdatedForLinking " +
"FROM ${DATA.name} " +
"${optionalWhereClausesSingleEdk(idPresent = true, partitionsPresent = true, entitySetPresent = true)} " +
"ON CONFLICT ($primaryKeyColumnNamesAsString) " +
"DO UPDATE SET " +
"${VERSIONS.name} = ${DATA.name}.${VERSIONS.name} || EXCLUDED.${VERSIONS.name}, " +
"${LAST_WRITE.name} = GREATEST(${DATA.name}.${LAST_WRITE.name},EXCLUDED.${LAST_WRITE.name}), " +
"${ORIGIN_ID.name} = EXCLUDED.${ORIGIN_ID.name}, " +
"${VERSION.name} = CASE " +
"WHEN abs(${DATA.name}.${VERSION.name}) <= EXCLUDED.${VERSION.name} " +
"THEN EXCLUDED.${VERSION.name} " +
"ELSE ${DATA.name}.${VERSION.name} " +
"END"
// @formatter:on
}
/* For materialized views */
/**
* This function generates preparable sql for selecting property values columnar for a given entity set.
* Bind order is the following:
* 1. entity set ids (uuid array)
* 2. partitions (int array)
*/
fun selectPropertyTypesOfEntitySetColumnar(
authorizedPropertyTypes: Map<UUID, PropertyType>,
linking: Boolean
): String {
val idColumnsList = listOf(ENTITY_SET_ID.name, ID.name, ENTITY_KEY_IDS_COL.name)
val (entitySetData, _) = buildPreparableFiltersSql(
3,
authorizedPropertyTypes,
mapOf(),
EnumSet.of(MetadataOption.ENTITY_KEY_IDS),
linking,
idsPresent = false,
partitionsPresent = true
)
val selectColumns = (idColumnsList +
(authorizedPropertyTypes.map { selectPropertyColumn(it.value) }))
.joinToString()
val groupByColumns = idColumnsList.joinToString()
val selectArrayColumns = (idColumnsList +
(authorizedPropertyTypes.map { selectPropertyArray(it.value) }))
.joinToString()
return "SELECT $selectArrayColumns FROM (SELECT $selectColumns FROM ($entitySetData) as entity_set_data) as grouped_data GROUP BY ($groupByColumns)"
}
/**
* Partitioning selector requires an unambiguous data column called partitions to exist in the query to correcly compute partitions.
*/
fun getPartitioningSelector(
idColumn: PostgresColumnDefinition
) = getPartitioningSelector(idColumn.name)
/**
* Partitioning selector requires an unambiguous data column called partitions to exist in the query to correcly compute partitions.
*/
fun getPartitioningSelector(
idColumn: String
) = "partitions[ 1 + ((array_length(partitions,1) + (('x'||right(${idColumn}::text,8))::bit(32)::int % array_length(partitions,1))) % array_length(partitions,1))]"
/**
* SQL that given an array of partitions, their length, and a uuid column [idColumn] selects a partition from the
* array of partitions using the lower order 32 bits of the uuid.
*
* It does this by converting the uuid to text, taking the right-most 8 characters, prepending an x so that it will be interpreted as hex,
* casts it to 32 bit string, cast those 32 bits as an int, then uses the size of partition to compute the one-based index
* in the array. We do the mod twice to make sure that it is the positive remainder.
*
* 1. partitions (array)
* 2. array length ( partitions )
* 3. array length ( partitions )
* 4. array length ( partitions )
*
* @param idColumn
*/
fun getDirectPartitioningSelector(
idColumn: String
) = "(?)[ 1 + ((? + (('x'||right(${idColumn}::text,8))::bit(32)::int % ?)) % ?)]"
private fun selectPropertyColumn(propertyType: PropertyType): String {
val dataType = PostgresEdmTypeConverter.map(propertyType.datatype).sql()
val propertyColumnName = propertyColumnName(propertyType)
return "jsonb_array_elements_text($PROPERTIES -> '${propertyType.id}')::$dataType AS $propertyColumnName"
}
private fun selectPropertyArray(propertyType: PropertyType): String {
val propertyColumnName = propertyColumnName(propertyType)
return if (propertyType.isMultiValued) {
"array_agg($propertyColumnName) FILTER (WHERE $propertyColumnName IS NOT NULL) as $propertyColumnName"
} else {
"(array_agg($propertyColumnName))[1] FILTER (WHERE $propertyColumnName IS NOT NULL) as $propertyColumnName"
}
}
private fun propertyColumnName(propertyType: PropertyType): String {
return DataTables.quote(propertyType.type.fullQualifiedNameAsString)
}
|
gpl-3.0
|
fd12037dada8635d4b8daf59dbf3a922
| 34.768116 | 163 | 0.640381 | 3.928974 | false | false | false | false |
maksym-lukianenko/commerce-store
|
EStore/Core/src/main/kotlin/com/estore/commerce/pricing/entity/PriceList.kt
|
1
|
569
|
package com.estore.commerce.pricing.entity
import java.io.Serializable
import java.util.*
import javax.persistence.*
@Entity
@Table(name = "PRICE_LIST")
class PriceList : Serializable {
@Id
lateinit var id: String
@Column(name = "NAME", nullable = false)
lateinit var name: String
@OneToOne(optional = false)
@JoinColumn(name = "BASE_PRICE_LIST_ID")
lateinit var basePriceList: PriceList
@Column(name = "LOCALE", nullable = false)
lateinit var locale: Locale
override fun toString() = "PriceList(id='$id', name='$name')"
}
|
mit
|
56271d82e6f52ee66b80fe0619a27be3
| 21.8 | 65 | 0.68717 | 3.718954 | false | false | false | false |
blackbbc/Tucao
|
app/src/main/kotlin/me/sweetll/tucao/di/service/ApiConfig.kt
|
1
|
4341
|
package me.sweetll.tucao.di.service
import io.reactivex.Observable
import io.reactivex.functions.Function
import java.util.concurrent.TimeUnit
object ApiConfig {
const val API_KEY = "25tids8f1ew1821ed"
const val PROTOCOL = "https"
const val BASE_URL = "www.tucao.in"
const val BASE_RAW_API_URL = "$PROTOCOL://$BASE_URL/"
const val BASE_JSON_API_URL = "$PROTOCOL://$BASE_URL/api_v2/"
const val BASE_XML_API_URL = "$PROTOCOL://$BASE_URL/"
/*
* Json
*/
const val LIST_API_URL = "list.php"
const val SEARCH_API_URL = "search.php"
const val VIEW_API_URL = "view.php"
const val RANK_API_URL = "rank.php"
const val REPLY_API_URL = "$PROTOCOL://$BASE_URL/index.php?m=comment&c=index&a=ajax"
const val UPDATE_API_URL = "http://45.63.54.11:12450/api/app-portal/version"
/*
* Drrr
*/
const val CREATE_POST_API_URL = "http://45.63.54.11:13450/comment/create"
const val POSTS_API_URL = "http://45.63.54.11:13450/comments"
const val CREATE_REPLY_API_URL = "http://45.63.54.11:13450/reply/create/{commentId}"
const val REPLIES_API_URL = "http://45.63.54.11:13450/replies/{commentId}"
const val CREATE_VOTE_API_URL = "http://45.63.54.11:13450/vote/{commentId}"
/*
* XML
*/
const val PLAY_URL_API_URL = "$PROTOCOL://api.tucao.one/api/playurl"
const val DANMU_API_URL = "$PROTOCOL://$BASE_URL/index.php?m=mukio&c=index&a=init"
/*
* Raw
*/
const val INDEX_URL = "/"
const val LIST_URL = "list/{tid}/"
const val BGM_URL = "bgm/{year}/{month}/"
const val SEND_DANMU_URL = "index.php?m=mukio&c=index&a=post"
const val COMMENT_URL = "index.php?m=comment&c=index&a=init&hot=0&iframe=1"
const val SEND_COMMENT_URL = "index.php?m=comment&c=index&a=post"
const val READ_MESSAGE_LIST_URL = "index.php?m=message&c=index&a=inbox"
const val READ_MESSAGE_DETAIL_URL = "index.php?m=message&c=index&a=read"
const val REPLY_MESSAGE_URL = "index.php?m=message&c=index&a=reply"
const val SEND_MESSAGE_URL = "index.php?m=message&c=index&a=send"
const val USER_INFO_URL = "api.php?op=user"
const val CODE_URL = "api.php?op=checkcode&code_len=4&font_size=14&width=446&height=40"
const val LOGIN_URL = "index.php?m=member&c=index&a=login"
const val LOGOUT_URL = "index.php?m=member&c=index&a=logout&forward=&siteid=1"
const val REGISTER_URL = "index.php?m=member&c=index&a=register&siteid=1"
const val PERSONAL_URL = "index.php?m=member&c=index"
const val USER_URL = "play/u{userid}/"
const val SPACE_URL = "index.php?m=member&c=space"
const val SUPPORT_URL = "index.php?m=comment&c=index&a=support&format=json"
const val SEND_REPLY_URL = "index.php?m=comment&c=index&a=post&replyuid=undefined"
const val CHANGE_INFORMATION_URL = "index.php?m=member&c=index&a=account_manage_info&t=account"
const val CHANGE_PASSWORD_URL = "index.php?m=member&c=index&a=account_manage_password&t=account"
const val FORGOT_PASSWORD_URL = "index.php?m=member&c=index&a=public_forget_password&siteid=1"
const val CHECK_USERNAME_URL = "index.php?clientid=username&m=member&c=index&a=public_checkname_ajax"
const val CHECK_NICKNAME_URL = "index.php?clientid=nickname&m=member&c=index&a=public_checknickname_ajax"
const val CHECK_EMAIL_URL = "index.php?clientid=email&m=member&c=index&a=public_checkemail_ajax"
const val MANAGE_AVATAR_URL = "index.php?m=member&c=index&a=account_manage_avatar&t=account"
const val UPLOAD_AVATAR_URL = "phpsso_server/index.php?m=phpsso&c=index&a=uploadavatar&auth_data=v=1&appid=1"
fun generatePlayerId(hid: String, part: Int) = "11-$hid-1-$part"
class RetryWithDelay(val maxRetries: Int = 3, val delayMillis: Long = 2000L) : Function<Observable<in Throwable>, Observable<*>> {
var retryCount = 0
override fun apply(observable: Observable<in Throwable>): Observable<*> = observable
.flatMap { throwable ->
if (++retryCount < maxRetries) {
Observable.timer(delayMillis, TimeUnit.MILLISECONDS)
} else {
Observable.error(throwable as Throwable)
}
}
}
}
|
mit
|
52be07579bb6c15a2b156bc83c47ef87
| 46.184783 | 134 | 0.648468 | 3.048455 | false | false | false | false |
googlearchive/android-RecyclerView
|
kotlinApp/app/src/main/java/com/example/android/common/logger/LogWrapper.kt
|
3
|
2458
|
/*
* Copyright (C) 2012 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.common.logger
import android.util.Log
/**
* Helper class which wraps Android's native Log utility in the Logger interface. This way
* normal DDMS output can be one of the many targets receiving and outputting logs simultaneously.
*/
class LogWrapper : LogNode {
// For piping: The next node to receive Log data after this one has done its work.
var next: LogNode? = null
/**
* Prints data out to the console using Android's native log mechanism.
* @param priority Log level of the data being logged. Verbose, Error, etc.
* @param tag Tag for for the log data. Can be used to organize log statements.
* @param msg The actual message to be logged. The actual message to be logged.
* @param tr If an exception was thrown, this can be sent along for the logging facilities
* to extract and print useful information.
*/
override fun println(priority: Int, tag: String?, msg: String?, tr: Throwable?) {
var msg = msg
// There actually are log methods that don't take a msg parameter. For now,
// if that's the case, just convert null to the empty string and move on.
var useMsg: String? = msg
if (useMsg == null) {
useMsg = ""
}
// If an exception was provided, convert that exception to a usable string and attach
// it to the end of the msg method.
if (tr != null) {
msg += "\n$Log.getStackTraceString(tr)"
}
// This is functionally identical to Log.x(tag, useMsg);
// For instance, if priority were Log.VERBOSE, this would be the same as Log.v(tag, useMsg)
Log.println(priority, tag, useMsg)
// If this isn't the last node in the chain, move things along.
next?.println(priority, tag, msg, tr)
}
}
|
apache-2.0
|
2d950d9db9491632edf3b776a62981d8
| 39.966667 | 99 | 0.672905 | 4.173175 | false | false | false | false |
kohesive/kovert
|
core/src/main/kotlin/uy/kohesive/kovert/core/SimpleTypes.kt
|
1
|
1583
|
package uy.kohesive.kovert.core
import uy.klutter.reflect.erasedType
import java.math.BigDecimal
import java.time.*
import java.time.temporal.Temporal
import java.util.*
import kotlin.reflect.KClass
import kotlin.reflect.KType
import kotlin.reflect.jvm.jvmErasure
fun isSimpleDataType(type: Class<out Any>) =
type.isPrimitive || knownSimpleTypes.any { type.isAssignableFrom(it) } || simpleTypeNames.contains(type.name)
// fun <T: Any> isSimpleDataType(type: KClass<T>) = isSimpleDataType(type.java.erasedType())
fun isSimpleDataType(type: KType) = isSimpleDataType(type.jvmErasure.java)
fun isEnum(type: KType) = type.erasedType().isEnum
@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
val knownSimpleTypes = listOf<KClass<out Any>>(
Boolean::class,
Number::class,
String::class,
Date::class,
java.lang.Byte::class,
java.lang.Short::class,
java.lang.Integer::class,
java.lang.Long::class,
java.lang.Float::class,
java.lang.Double::class,
BigDecimal::class,
Temporal::class,
OffsetDateTime::class,
ZonedDateTime::class,
LocalDate::class,
LocalDateTime::class,
Clock::class,
Instant::class,
Period::class,
Year::class,
YearMonth::class,
MonthDay::class,
ZoneId::class,
ZoneOffset::class,
LocalTime::class,
OffsetTime::class
)
.map {
listOf(it.javaPrimitiveType, it.javaObjectType)
}
.flatten()
.filterNotNull()
.toMutableList()
internal val simpleTypeNames = setOf("byte", "char", "short", "int", "long", "float", "double", "string", "boolean")
|
mit
|
83b23fdc9e05347482f52841160bf5a8
| 26.77193 | 116 | 0.699937 | 3.724706 | false | false | false | false |
pdvrieze/ProcessManager
|
ProcessEngine/core/src/jvmTest/kotlin/nl/adaptivity/process/engine/spek/InstanceSupport.kt
|
1
|
8122
|
/*
* 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/>.
*/
package nl.adaptivity.process.engine.spek
import net.devrieze.util.Handle
import net.devrieze.util.security.SecureObject
import net.devrieze.util.writer
import nl.adaptivity.process.engine.*
import nl.adaptivity.process.engine.processModel.CompositeInstance
import nl.adaptivity.process.engine.processModel.NodeInstanceState
import nl.adaptivity.process.engine.processModel.ProcessNodeInstance
import nl.adaptivity.process.processModel.EndNode
import nl.adaptivity.process.processModel.StartNode
import nl.adaptivity.process.util.Identified
import nl.adaptivity.xmlutil.XmlStreaming
import nl.adaptivity.xmlutil.serialization.XML
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Assertions.assertTrue
/**
* Created by pdvrieze on 15/01/17.
*/
interface InstanceSupport {
val transaction: StubProcessTransaction
val engine: ProcessEngine<StubProcessTransaction, *>
fun ProcessInstance.allChildren(): Sequence<ProcessNodeInstance<*>> {
return transitiveChildren([email protected])
}
fun ProcessInstance.trace(filter: (ProcessNodeInstance<*>)->Boolean) = trace(transaction, filter)
val ProcessInstance.trace: Trace get() = trace(transaction)
fun ProcessInstance.toDebugString():String {
return toDebugString([email protected])
}
fun ProcessInstance.assertTracePossible(trace: Trace) {
assertTracePossible(transaction, trace)
}
fun TraceElement.getNodeInstance(hInstance: Handle<SecureObject<ProcessInstance>>): ProcessNodeInstance<*>? {
val instance = transaction.readableEngineData.instance(hInstance).withPermission()
return getNodeInstance(transaction, instance)
}
}
fun ProcessInstance.transitiveChildren(transaction: StubProcessTransaction): Sequence<ProcessNodeInstance<*>> {
return childNodes.asSequence().flatMap {
when (val child = it.withPermission()) {
is CompositeInstance ->
if (child.hChildInstance.isValid) {
sequenceOf(child) +
transaction.readableEngineData
.instance(child.hChildInstance)
.withPermission().transitiveChildren(transaction)
} else {
sequenceOf(child)
}
else -> sequenceOf(child)
}
}.filter { it.state != NodeInstanceState.SkippedInvalidated }
}
fun ProcessInstance.toDebugString(transaction: StubProcessTransaction): String {
fun StringBuilder.appendChildNodeState(processInstance: ProcessInstance) {
processInstance.childNodes.asSequence()
.map { it.withPermission() }
.sortedBy { it.handle }
.joinTo(this) {
when (val inst = it.withPermission()) {
is CompositeInstance -> when {
!inst.hChildInstance.isValid ->
"${inst.node.id}[${inst.entryNo}]:(<Not started>) = ${inst.state}"
else -> {
val childStatus = buildString {
appendChildNodeState(
transaction.readableEngineData.instance(inst.hChildInstance).withPermission()
)
}
"${inst.node.id}[${inst.entryNo}]:($childStatus) = ${inst.state}"
}
}
else -> "${inst.node.id}[${inst.entryNo}]:${inst.state}"
}
}
}
return buildString {
append("process(")
append(processModel.rootModel.name)
name?.let {
append(", instance: ")
append(it)
}
append('[').append(handle).append("] - ").append(state)
append(", allnodes: [")
appendChildNodeState(this@toDebugString)
appendLine("])\n\nModel:")
XmlStreaming.newWriter(this.writer()).use { XML.encodeToWriter(it, processModel.rootModel) }
appendLine("\n")
}
}
fun ProcessInstance.findChild(transaction: StubProcessTransaction, id: String) = transitiveChildren(transaction).firstOrNull { it.node.id==id }
fun ProcessInstance.findChild(transaction: StubProcessTransaction, id: Identified) = findChild(transaction, id.id)
fun ProcessInstance.trace(transaction: StubProcessTransaction,
filter: (ProcessNodeInstance<*>) -> Boolean): Sequence<TraceElement> {
return transitiveChildren(transaction)
.map { it.withPermission() }
.filter(filter)
.sortedBy { handle.handleValue }
.map { TraceElement(it.node.id, it.entryNo) }
}
fun ProcessInstance.trace(transaction: StubProcessTransaction): Array<TraceElement> {
return trace(transaction) { true }
.toList()
.toTypedArray()
}
fun ProcessInstance.assertTracePossible(transaction: StubProcessTransaction,
trace: Trace) {
val nonSeenChildNodes = this.childNodes.asSequence()
.map(SecureObject<ProcessNodeInstance<*>>::withPermission)
.filter { it.state.isFinal &&
! (it.state.isSkipped || it.state == NodeInstanceState.AutoCancelled)
}
.toMutableSet()
var nonFinal: ProcessNodeInstance<*>? = null
for(traceElementPos in trace.indices) {
val traceElement = trace[traceElementPos]
val nodeInstance = traceElement.getNodeInstance(transaction, this)?.takeIf { it.state.isFinal }
if (nodeInstance != null) {
if(nonFinal!=null) {
kfail("Found gap in the trace [${trace.joinToString()}]#$traceElementPos before node: $nodeInstance - ${toDebugString(transaction)}")
}
nonSeenChildNodes.remove(nodeInstance)
} else {
nonFinal = nodeInstance
}
}
if (! state.isFinal) {
for (otherChild in nonSeenChildNodes.toList()) {
if (otherChild.node is StartNode) {
val successors = getDirectSuccessors(transaction.readableEngineData, otherChild)
.map { getChildNodeInstance(it) }
if (successors.all { it.state.isActive && it.state!=NodeInstanceState.Started }) {
nonSeenChildNodes.remove(otherChild)
}
}
}
}
if (nonSeenChildNodes.isNotEmpty()) {
kfail("All actual child nodes should be in the full trace or skipped. Nodes that were not seen: [${nonSeenChildNodes.joinToString()}]" )
}
}
fun ProcessInstance.assertComplete(transaction: StubProcessTransaction, vararg nodeIds: String) {
val complete = transitiveChildren(transaction)
.filter { it.state.isFinal && it.node is EndNode }
.mapNotNull { nodeInstance ->
assertTrue(nodeInstance.state.isFinal) {
"The node instance state should be final (but is ${nodeInstance.state})"
}
assertTrue(nodeInstance.node is EndNode, "Completion nodes should be EndNodes")
if (nodeInstance.state.isSkipped) null else nodeInstance.node.id
}.sorted().toList()
Assertions.assertEquals(nodeIds.sorted(), complete) {
"The list of completed nodes does not match (Expected: [${nodeIds.joinToString()}], " +
"found: [${complete.joinToString()}], ${this.toDebugString(transaction)})"
}
}
|
lgpl-3.0
|
1520dc86e38cdd34efa776f7a48f0859
| 39.81407 | 149 | 0.644053 | 4.878078 | false | false | false | false |
kikermo/Things-Audio-Renderer
|
renderer/src/main/java/org/kikermo/thingsaudio/renderer/di/AppModule.kt
|
1
|
4126
|
package org.kikermo.thingsaudio.renderer.di
import android.app.Application
import android.content.Context
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import dagger.Module
import dagger.Provides
import io.reactivex.Observable
import io.reactivex.subjects.BehaviorSubject
import io.reactivex.subjects.PublishSubject
import org.kikermo.thingsaudio.core.api.ReceiverRepository
import org.kikermo.thingsaudio.core.model.PlayState
import org.kikermo.thingsaudio.core.model.RepeatMode
import org.kikermo.thingsaudio.core.model.Track
import org.kikermo.thingsaudio.core.rx.RxSchedulers
import org.kikermo.thingsaudio.core.rx.RxSchedulersImpl
import org.kikermo.thingsaudio.renderer.ThingsReceiverApplication
import org.kikermo.thingsaudio.renderer.api.PlayerControlActions
import org.kikermo.thingsaudio.renderer.api.ReceiverRepositoryImp
import javax.inject.Singleton
@Module
class AppModule(val thingsReceiverApplication: ThingsReceiverApplication) {
@Provides
@Singleton
fun provideApp() = thingsReceiverApplication
@Provides
@Singleton
fun provideContext(application: Application): Context {
return application
}
@Provides
@Singleton
fun provideRxScheduler(): RxSchedulers {
return RxSchedulersImpl()
}
@Provides
@Singleton
fun providesRepository(trackUpdatesObservable: Observable<Track>,
playPositionsObservable: Observable<Int>,
playStateObservable: Observable<PlayState>,
playerControlActionsSubject: PublishSubject<PlayerControlActions>,
repeatModeBehaviourSubject: BehaviorSubject<RepeatMode>,
rxSchedulers: RxSchedulers
): ReceiverRepository {
return ReceiverRepositoryImp(trackUpdatesObservable = trackUpdatesObservable,
playPositionObservable = playPositionsObservable,
playStateObservable = playStateObservable,
playerControlActionsSubject = playerControlActionsSubject,
repeatModeBehaviourSubject = repeatModeBehaviourSubject,
rxSchedulers = rxSchedulers)
}
@Provides
@Singleton
fun provideTrackBehaviourSubject(): BehaviorSubject<Track> = BehaviorSubject.create()
@Provides
@Singleton
fun providePlayPositionSubject(): BehaviorSubject<Int> = BehaviorSubject.create()
@Provides
@Singleton
fun providePlayStateBehaviourSubject(): BehaviorSubject<PlayState> = BehaviorSubject.create()
@Provides
@Singleton
fun providePlayerControlActionsSubject(): PublishSubject<PlayerControlActions> = PublishSubject.create()
@Provides
@Singleton
fun provideTrack(trackBehaviorSubject: BehaviorSubject<Track>): Observable<Track> = trackBehaviorSubject
@Provides
@Singleton
fun providePlayPositionObservable(playPositionBehaviorSubject: BehaviorSubject<Int>): Observable<Int> =
playPositionBehaviorSubject
@Provides
@Singleton
fun providePlayState(playStateBehaviorSubject: BehaviorSubject<PlayState>): Observable<PlayState> =
playStateBehaviorSubject
@Provides
@Singleton
fun providePlayerControlActionsObservable(playerControlActionsSubject: PublishSubject<PlayerControlActions>)
: Observable<PlayerControlActions> = playerControlActionsSubject
@Provides
@Singleton
fun provideTrackListBehaviourSubject(): BehaviorSubject<List<Track>> = BehaviorSubject.createDefault(listOf())
@Provides
@Singleton
fun provideTrackListObservable(trackListBehaviourSubject: BehaviorSubject<List<Track>>): Observable<List<Track>> =
trackListBehaviourSubject
@Provides
@Singleton
fun provideRepeatModeObservable(repeatModeBehaviourSubject: BehaviorSubject<RepeatMode>): Observable<RepeatMode> =
repeatModeBehaviourSubject
@Provides
@Singleton
fun providesRepeatModeBehaviourSubject(): BehaviorSubject<RepeatMode> = BehaviorSubject.createDefault(RepeatMode.DISABLED)
@Provides
@Singleton
fun provideGson(): Gson = GsonBuilder().create()
}
|
gpl-3.0
|
8fc5215444c23c439d85f9ae4a5af619
| 34.878261 | 126 | 0.758362 | 5.249364 | false | false | false | false |
deianvn/misc
|
vfu/course_3/android/CurrencyConverter/app/src/main/java/bg/vfu/rizov/currencyconverter/main/converter/ConverterFragment.kt
|
1
|
2471
|
package bg.vfu.rizov.currencyconverter.main.converter
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import bg.vfu.rizov.currencyconverter.R
import bg.vfu.rizov.currencyconverter.main.BaseFragment
import bg.vfu.rizov.currencyconverter.main.MainViewModel
import bg.vfu.rizov.currencyconverter.main.selection.SelectionFragment
import bg.vfu.rizov.currencyconverter.model.Currency
import kotlinx.android.synthetic.main.fragment_converter.*
import org.koin.android.viewmodel.ext.android.sharedViewModel
class ConverterFragment : BaseFragment() {
private val mainViewModel by sharedViewModel<MainViewModel>()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_converter, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
editButton.setOnClickListener { showFragment(SelectionFragment()) }
val currencies = mainViewModel.currencies.value ?: return
val converterAdapter =
ConverterAdapter(currencies) { currency: Currency? ->
if (currency != null) {
currentCurrencyText.visibility = View.VISIBLE
currentCurrencyInput.visibility = View.VISIBLE
currentCurrencyText.text = currency.code
currentCurrencyInput.text.clear()
} else {
currentCurrencyText.visibility = View.GONE
currentCurrencyInput.visibility = View.GONE
}
mainViewModel.storeCurrencies()
}
currencyConverterList.apply {
setHasFixedSize(true)
layoutManager = LinearLayoutManager(context)
adapter = converterAdapter
}
currentCurrencyInput.addTextChangedListener(
object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
val number = try {
s.toString().toDouble()
} catch (e: Throwable) {
0.0
}
converterAdapter.notifyValueChanged(number)
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
}
})
}
}
|
apache-2.0
|
709f99fc8238a15fee3ace46f08cb130
| 32.849315 | 94 | 0.716714 | 4.77027 | false | false | false | false |
LanternPowered/LanternServer
|
src/main/kotlin/org/lanternpowered/server/cause/EmptyCauseStack.kt
|
1
|
2794
|
/*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.cause
import org.lanternpowered.api.Lantern
import org.lanternpowered.api.cause.Cause
import org.lanternpowered.api.cause.CauseContext
import org.lanternpowered.api.cause.CauseContextKey
import org.lanternpowered.api.cause.CauseStack
import org.lanternpowered.api.cause.causeOf
import org.lanternpowered.api.cause.emptyCauseContext
import org.lanternpowered.api.util.optional.emptyOptional
import java.util.Optional
import kotlin.reflect.KClass
internal object EmptyCauseStack : CauseStack {
private val obj = Any()
private val cause by lazy { causeOf(Lantern.game) }
private val frame = object : CauseStack.Frame {
override fun close() {}
override fun getCurrentCause(): Cause = cause
override fun getCurrentContext(): CauseContext = emptyCauseContext()
override fun pushCause(obj: Any): CauseStack.Frame = this
override fun popCause(): Any = obj
override fun <T : Any> addContext(key: CauseContextKey<T>, value: T) = this
override fun <T : Any> removeContext(key: CauseContextKey<T>): Optional<T> = emptyOptional()
}
override fun getCurrentCause(): Cause = cause
override fun getCurrentContext(): CauseContext = emptyCauseContext()
override fun pushCause(obj: Any): CauseStack = this
override fun popCause(): Any = obj
override fun popCauses(n: Int) {}
override fun peekCause(): Any = obj
override fun pushCauseFrame() = frame
override fun popCauseFrame(handle: org.spongepowered.api.event.CauseStackManager.StackFrame) {}
override fun <T : Any> first(target: Class<T>): Optional<T> = emptyOptional()
override fun <T : Any> first(target: KClass<T>): T? = null
override fun <T : Any> last(target: Class<T>): Optional<T> = emptyOptional()
override fun <T : Any> last(target: KClass<T>): T? = null
override fun containsType(target: Class<*>): Boolean = false
override fun containsType(target: KClass<*>): Boolean = false
override fun contains(any: Any): Boolean = false
override fun <T : Any> addContext(key: CauseContextKey<T>, value: T): EmptyCauseStack = this
override fun <T : Any> getContext(key: CauseContextKey<T>): Optional<T> = emptyOptional()
override fun <T : Any> removeContext(key: CauseContextKey<T>): Optional<T> = emptyOptional()
override fun <T : Any> get(key: CauseContextKey<T>): T? = null
override fun <T : Any> set(key: CauseContextKey<T>, value: T) {}
}
|
mit
|
e937aafb14e3d05161de06e026f9ada3
| 43.349206 | 100 | 0.714388 | 3.918654 | false | false | false | false |
ursjoss/scipamato
|
core/core-web/src/test/kotlin/ch/difty/scipamato/core/web/code/CodeListPageTest.kt
|
1
|
6845
|
package ch.difty.scipamato.core.web.code
import ch.difty.scipamato.core.entity.CodeClass
import ch.difty.scipamato.core.entity.code.CodeDefinition
import ch.difty.scipamato.core.entity.code.CodeTranslation
import ch.difty.scipamato.core.web.common.BasePageTest
import de.agilecoders.wicket.core.markup.html.bootstrap.button.BootstrapAjaxButton
import de.agilecoders.wicket.extensions.markup.html.bootstrap.form.select.BootstrapSelect
import de.agilecoders.wicket.extensions.markup.html.bootstrap.table.BootstrapDefaultDataTable
import io.mockk.confirmVerified
import io.mockk.every
import io.mockk.verify
import org.apache.wicket.markup.html.form.Form
import org.apache.wicket.markup.html.link.Link
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Test
@Suppress("PrivatePropertyName", "VariableNaming")
internal class CodeListPageTest : BasePageTest<CodeListPage>() {
private val cc1 = CodeClass(1, "cc1", "d1")
private val cc2 = CodeClass(2, "cc2", "d2")
private val ct1_de = CodeTranslation(1, "de", "Name1", "a comment", 1)
private val ct1_en = CodeTranslation(2, "en", "name1", null, 1)
private val ct1_fr = CodeTranslation(3, "fr", "nom1", null, 1)
private val cd1 = CodeDefinition("1A", "de", cc1, 1, false, 1, ct1_de, ct1_en, ct1_fr)
private val ct2_en = CodeTranslation(5, "en", "name2", null, 1)
private val ct2_fr = CodeTranslation(6, "fr", "nom2", null, 1)
private val ct2_de = CodeTranslation(4, "de", "Name2", null, 1)
private val cd2 = CodeDefinition("2A", "de", cc2, 2, true, 1, ct2_de, ct2_en, ct2_fr)
private val results: List<CodeDefinition> = listOf(cd1, cd2)
@Suppress("LocalVariableName")
override fun setUpHook() {
every { codeServiceMock.countByFilter(any()) } returns results.size
every { codeServiceMock.getCodeClass1("en_us") } returns cc1
every { codeServiceMock.findPageOfEntityDefinitions(any(), any()) } returns results.iterator()
every { codeClassServiceMock.find(any()) } returns listOf(cc1, cc2)
}
@AfterEach
fun tearDown() {
confirmVerified(codeServiceMock)
}
override fun makePage(): CodeListPage = CodeListPage(null)
override val pageClass: Class<CodeListPage>
get() = CodeListPage::class.java
override fun assertSpecificComponents() {
assertFilterForm("filterPanel:filterForm")
val headers = arrayOf("Code", "Translations", "Sort", "Scope")
val row1 = arrayOf("1A", "DE: 'Name1'; EN: 'name1'; FR: 'nom1'".replace("'", "'"), "1", "Public")
val row2 = arrayOf("2A", "DE: 'Name2'; EN: 'name2'; FR: 'nom2'".replace("'", "'"), "2", "Internal")
assertResultTable("resultPanel:results", headers, row1, row2)
verify { codeServiceMock.getCodeClass1("en_us") }
verify { codeServiceMock.countByFilter(any()) }
verify { codeServiceMock.findPageOfEntityDefinitions(any(), any()) }
}
@Suppress("SameParameterValue")
private fun assertFilterForm(b: String) {
tester.assertComponent(b, Form::class.java)
tester.assertLabel("$b:codeClassLabel", "Code Class")
tester.assertComponent("$b:codeClass", BootstrapSelect::class.java)
assertLabeledTextField(b, "name")
assertLabeledTextField(b, "comment")
tester.assertComponent("$b:newCode", BootstrapAjaxButton::class.java)
}
@Suppress("SameParameterValue")
private fun assertResultTable(b: String, labels: Array<String>, vararg rows: Array<String>) {
tester.assertComponent(b, BootstrapDefaultDataTable::class.java)
assertHeaderColumns(b, labels)
assertTableValuesOfRows(b, 1, COLUMN_ID_WITH_LINK, *rows)
}
private fun assertHeaderColumns(b: String, labels: Array<String>) {
labels.withIndex().forEach { (idx, label) ->
val p = "$b:topToolbars:toolbars:2:headers:${idx + 1}:header:orderByLink:header_body:label"
tester.assertLabel(p, label)
}
}
@Suppress("SameParameterValue")
private fun assertTableValuesOfRows(b: String, rowStartIdx: Int, colIdxAsLink: Int?, vararg rows: Array<String>) {
colIdxAsLink?.let { id ->
tester.assertComponent("$b:body:rows:$rowStartIdx:cells:$id:cell:link", Link::class.java)
}
var rowIdx = rowStartIdx
rows.forEach { row ->
var colIdx = 1
row.forEach { value ->
tester.assertLabel(
"$b:body:rows:$rowIdx:cells:$colIdx:cell${if (colIdxAsLink != null && colIdx++ == colIdxAsLink) ":link:label" else ""}",
value
)
}
rowIdx++
}
}
@Test
fun clickingOnCodeTitle_forwardsToCodeEditPage_withModelLoaded() {
tester.startPage(pageClass)
tester.clickLink("resultPanel:results:body:rows:1:cells:$COLUMN_ID_WITH_LINK:cell:link")
tester.assertRenderedPage(CodeEditPage::class.java)
// verify the codes were loaded into the target page
tester.assertModelValue("form:translationsPanel:translations:1:name", "Name1")
tester.assertModelValue("form:translationsPanel:translations:2:name", "name1")
tester.assertModelValue("form:translationsPanel:translations:3:name", "nom1")
verify { codeServiceMock.getCodeClass1("en_us") }
verify { codeServiceMock.countByFilter(any()) }
verify { codeServiceMock.findPageOfEntityDefinitions(any(), any()) }
}
@Suppress("LocalVariableName")
@Test
fun clickingNewCode_forwardsToCodeEditPage() {
val ct_en = CodeTranslation(1, "en", "ct_en", null, 1)
val kd = CodeDefinition("1A", "en", cc1, 1, false, 1, ct_en)
every { codeServiceMock.newUnpersistedCodeDefinition() } returns kd
tester.startPage(pageClass)
tester.assertRenderedPage(pageClass)
val formTester = tester.newFormTester("filterPanel:filterForm")
formTester.submit("newCode")
tester.assertRenderedPage(CodeEditPage::class.java)
verify { codeServiceMock.getCodeClass1("en_us") }
verify { codeServiceMock.countByFilter(any()) }
verify { codeServiceMock.findPageOfEntityDefinitions(any(), any()) }
verify { codeServiceMock.newUnpersistedCodeDefinition() }
}
@Test
fun changingCodeClass_refreshesResultPanel() {
tester.startPage(pageClass)
tester.executeAjaxEvent("filterPanel:filterForm:codeClass", "change")
tester.assertComponentOnAjaxResponse("resultPanel")
verify { codeServiceMock.getCodeClass1("en_us") }
verify(exactly = 2) { codeServiceMock.countByFilter(any()) }
verify(exactly = 2) { codeServiceMock.findPageOfEntityDefinitions(any(), any()) }
}
companion object {
private const val COLUMN_ID_WITH_LINK = 2
}
}
|
bsd-3-clause
|
a6a202eea3c82c778ec46451e21c87f8
| 44.331126 | 140 | 0.674507 | 3.882587 | false | true | false | false |
SimonVT/cathode
|
cathode-sync/src/main/java/net/simonvt/cathode/actions/user/SyncEpisodesRatings.kt
|
1
|
3835
|
/*
* Copyright (C) 2014 Simon Vig Therkildsen
*
* 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 net.simonvt.cathode.actions.user
import android.content.ContentProviderOperation
import android.content.Context
import net.simonvt.cathode.actions.CallAction
import net.simonvt.cathode.actions.user.SyncEpisodesRatings.Params
import net.simonvt.cathode.api.entity.RatingItem
import net.simonvt.cathode.api.service.SyncService
import net.simonvt.cathode.common.database.forEach
import net.simonvt.cathode.common.database.getLong
import net.simonvt.cathode.provider.DatabaseContract.EpisodeColumns
import net.simonvt.cathode.provider.ProviderSchematic.Episodes
import net.simonvt.cathode.provider.batch
import net.simonvt.cathode.provider.helper.EpisodeDatabaseHelper
import net.simonvt.cathode.provider.helper.SeasonDatabaseHelper
import net.simonvt.cathode.provider.helper.ShowDatabaseHelper
import net.simonvt.cathode.provider.query
import net.simonvt.cathode.settings.TraktTimestamps
import retrofit2.Call
import javax.inject.Inject
class SyncEpisodesRatings @Inject constructor(
private val context: Context,
private val showHelper: ShowDatabaseHelper,
private val seasonHelper: SeasonDatabaseHelper,
private val episodeHelper: EpisodeDatabaseHelper,
private val syncService: SyncService
) : CallAction<Params, List<RatingItem>>() {
override fun key(params: Params): String = "SyncEpisodesRatings"
override fun getCall(params: Params): Call<List<RatingItem>> = syncService.getEpisodeRatings()
override suspend fun handleResponse(params: Params, response: List<RatingItem>) {
val ops = arrayListOf<ContentProviderOperation>()
val episodeIds = mutableListOf<Long>()
val episodes = context.contentResolver.query(
Episodes.EPISODES,
arrayOf(EpisodeColumns.ID),
EpisodeColumns.RATED_AT + ">0"
)
episodes.forEach { cursor -> episodeIds.add(cursor.getLong(EpisodeColumns.ID)) }
episodes.close()
for (rating in response) {
val seasonNumber = rating.episode!!.season!!
val episodeNumber = rating.episode!!.number!!
val showTraktId = rating.show!!.ids.trakt!!
val showResult = showHelper.getIdOrCreate(showTraktId)
val showId = showResult.showId
val seasonResult = seasonHelper.getIdOrCreate(showId, seasonNumber)
val seasonId = seasonResult.id
val episodeResult = episodeHelper.getIdOrCreate(showId, seasonId, episodeNumber)
val episodeId = episodeResult.id
episodeIds.remove(episodeId)
val op = ContentProviderOperation.newUpdate(Episodes.withId(episodeId))
.withValue(EpisodeColumns.USER_RATING, rating.rating)
.withValue(EpisodeColumns.RATED_AT, rating.rated_at.timeInMillis)
.build()
ops.add(op)
}
for (episodeId in episodeIds) {
val op = ContentProviderOperation.newUpdate(Episodes.withId(episodeId))
.withValue(EpisodeColumns.USER_RATING, 0)
.withValue(EpisodeColumns.RATED_AT, 0)
.build()
ops.add(op)
}
context.contentResolver.batch(ops)
if (params.userActivityTime > 0L) {
TraktTimestamps.getSettings(context)
.edit()
.putLong(TraktTimestamps.EPISODE_RATING, params.userActivityTime)
.apply()
}
}
data class Params(val userActivityTime: Long = 0L)
}
|
apache-2.0
|
2a3e6b1a4beb5c2413652a4ed56ca4f6
| 36.23301 | 96 | 0.754368 | 4.418203 | false | false | false | false |
googlecodelabs/watchnext-for-movie-tv-episodes
|
step_4_completed/src/main/java/com/android/tv/reference/castconnect/CastMediaLoadCommandCallback.kt
|
8
|
4513
|
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tv.reference.castconnect
import android.app.Application
import com.android.tv.reference.repository.VideoRepository
import com.android.tv.reference.repository.VideoRepositoryFactory
import com.android.tv.reference.shared.datamodel.Video
import com.google.android.gms.cast.MediaError
import com.google.android.gms.cast.MediaInfo
import com.google.android.gms.cast.MediaLoadRequestData
import com.google.android.gms.cast.tv.media.MediaException
import com.google.android.gms.cast.tv.media.MediaLoadCommandCallback
import com.google.android.gms.tasks.Task
import com.google.android.gms.tasks.Tasks
import timber.log.Timber
/**
* MediaLoadCommandCallback.onLoad() is invoked when the MediaManager detects the intent is a
* load request, this method receives the load request's data and converts it to a video object.
* Once converted, the video is played by the local player. The MediaManager is then updated
* with the MediaLoadRequest and broadcasts the MediaStatus to the connected senders.
*
* The load request's data comes from the sender app, such as the mobile or web complimentary apps
* and thus the data contract should be already defined most likely would be sharing the same data
* catalogue. The load request data is a media info object and as long as that object is populated
* with the right fields, this receiver part would remain the same. What varies is the actual data
* values in the MediaInfo fields.
*/
class CastMediaLoadCommandCallback(
var onLoaded: (Video, MediaLoadRequestData) -> Unit,
private val application: Application
) :
MediaLoadCommandCallback() {
override fun onLoad(
senderId: String?,
mediaLoadRequestData: MediaLoadRequestData?
): Task<MediaLoadRequestData> {
return if (mediaLoadRequestData == null) {
// Throw MediaException to indicate load failure.
Tasks.forException(
MediaException(
MediaError.Builder()
.setDetailedErrorCode(MediaError.DetailedErrorCode.LOAD_FAILED)
.setReason(MediaError.ERROR_REASON_INVALID_REQUEST)
.build()
)
)
} else {
Tasks.call {
var videoToPlay = convertLoadRequestToVideo(
mediaLoadRequestData, VideoRepositoryFactory.getVideoRepository(application)
)
if (videoToPlay != null) {
onLoaded(videoToPlay, mediaLoadRequestData)
} else {
Timber.w("Failed to convert cast load request to application-specific video")
}
mediaLoadRequestData
}
}
}
/**
* Retrieve the appropriate application-specific content or media object from the MediaInfo
* object that is passed from the sender application. The format of fields populated in the
* MediaInfo object follow a defined contract that is decided between the sender and the
* receiver, and is specific to each application so as to be able to identify the appropriate
* content at the receiver's end. The contentId parameter is an application-specific unique
* identifier for the content that is used here. Several other parameters of MediaInfo class can
* also be used to provide information such as contentUrl, duration, metadata, tracks and
* breaks. For more details on the available parameters, refer to the following link -
* https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.MediaInfo
*/
fun convertLoadRequestToVideo(
mediaLoadRequestData: MediaLoadRequestData,
videoRepository: VideoRepository
): Video? {
val mediaInfo: MediaInfo = mediaLoadRequestData.mediaInfo ?: return null
return videoRepository.getVideoById(mediaInfo.contentId)
}
}
|
apache-2.0
|
0e2a5a620a1eb58a642d6b4f07f3e5fd
| 45.525773 | 100 | 0.710835 | 4.750526 | false | false | false | false |
Geobert/radis
|
app/src/main/kotlin/fr/geobert/radis/MainActivity.kt
|
1
|
20070
|
package fr.geobert.radis
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.res.Configuration
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.widget.DrawerLayout
import android.support.v7.app.ActionBarDrawerToggle
import android.util.Log
import android.view.MenuItem
import android.view.View
import android.widget.*
import com.crashlytics.android.Crashlytics
import fr.geobert.radis.db.AccountTable
import fr.geobert.radis.db.DbContentProvider
import fr.geobert.radis.db.DbHelper
import fr.geobert.radis.service.InstallRadisServiceReceiver
import fr.geobert.radis.service.OnRefreshReceiver
import fr.geobert.radis.tools.*
import fr.geobert.radis.ui.*
import fr.geobert.radis.ui.drawer.NavDrawerItem
import fr.geobert.radis.ui.drawer.NavDrawerListAdapter
import fr.geobert.radis.ui.editor.AccountEditor
import fr.geobert.radis.ui.editor.OperationEditor
import fr.geobert.radis.ui.editor.ScheduledOperationEditor
import io.fabric.sdk.android.Fabric
import java.util.*
class MainActivity : BaseActivity(), UpdateDisplayInterface {
private val mDrawerLayout by lazy { findViewById(R.id.drawer_layout) as DrawerLayout }
private val mDrawerList by lazy { findViewById(R.id.left_drawer) as ListView }
private val mOnRefreshReceiver by lazy { OnRefreshReceiver(this) }
private val handler: FragmentHandler by lazy { FragmentHandler(this) }
val mAccountSpinner: Spinner by lazy { findViewById(R.id.account_spinner) as Spinner }
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
private val mDrawerToggle: ActionBarDrawerToggle by lazy {
object : ActionBarDrawerToggle(this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
mToolbar,
R.string.navigation_drawer_open, /* "open drawer" description for accessibility */
R.string.navigation_drawer_close /* "close drawer" description for accessibility */) {
override fun onDrawerClosed(drawerView: View?) {
invalidateOptionsMenu() // calls onPrepareOptionsMenu()
}
override fun onDrawerOpened(drawerView: View?) {
invalidateOptionsMenu() // calls onPrepareOptionsMenu()
}
}
}
private var mActiveFragment: BaseFragment? = null
private var mFirstStart = true
private var mPrevFragment: BaseFragment? = null
private var mActiveFragmentId = -1
private var mPrevFragmentId: Int = 0
protected fun findOrCreateFragment(c: Class<out BaseFragment>, fragmentId: Int): Fragment? {
var fragment: Fragment?
val fragmentManager = supportFragmentManager
fragment = fragmentManager.findFragmentByTag(c.name)
when (fragment) {
null -> {
try {
return updateFragmentRefs(c.newInstance(), fragmentId)
} catch (e: InstantiationException) {
e.printStackTrace()
} catch (e: IllegalAccessException) {
e.printStackTrace()
}
return null
}
else -> {
updateFragmentRefs(fragment, fragmentId)
mDrawerLayout.closeDrawer(mDrawerList)
fragmentManager.popBackStack(c.name, 0)
return null
}
}
}
protected fun updateFragmentRefs(fragment: Fragment, id: Int): Fragment {
val f = fragment as BaseFragment
mPrevFragment = mActiveFragment
mActiveFragment = f
mPrevFragmentId = mActiveFragmentId
mActiveFragmentId = id
mDrawerList.setItemChecked(mActiveFragmentId, true)
return fragment
}
private inner class FragmentHandler(private var activity: MainActivity) : PauseHandler() {
override fun processMessage(act: Activity, message: Message) {
var fragment: Fragment? = null
val fragmentManager: FragmentManager = activity.supportFragmentManager
when (message.what) {
OP_LIST -> fragment = findOrCreateFragment(OperationListFragment::class.java, message.what)
SCH_OP_LIST -> fragment = findOrCreateFragment(ScheduledOpListFragment::class.java, message.what)
STATISTICS -> fragment = findOrCreateFragment(StatisticsListFragment::class.java, message.what)
CREATE_ACCOUNT -> {
AccountEditor.callMeForResult(activity, AccountEditor.NO_ACCOUNT)
mDrawerList.setItemChecked(mActiveFragmentId, true)
}
EDIT_ACCOUNT -> {
AccountEditor.callMeForResult(activity, getCurrentAccountId())
mDrawerList.setItemChecked(mActiveFragmentId, true)
}
DELETE_ACCOUNT -> {
val account = mAccountManager.getCurrentAccount(activity)
OperationListFragment.DeleteAccountConfirmationDialog.newInstance(account.id, account.name).
show(fragmentManager, "delAccount")
mDrawerList.setItemChecked(mActiveFragmentId, true)
}
PREFERENCES -> {
val i = Intent(activity, ConfigEditor::class.java)
activity.startActivityForResult(i, 70)
mDrawerList.setItemChecked(mActiveFragmentId, true)
}
SAVE_ACCOUNT -> {
Tools.AdvancedDialog.newInstance(SAVE_ACCOUNT, activity).show(fragmentManager, "backup")
mDrawerList.setItemChecked(mActiveFragmentId, true)
}
RESTORE_ACCOUNT -> {
Tools.AdvancedDialog.newInstance(RESTORE_ACCOUNT, activity).show(fragmentManager, "restore")
mDrawerList.setItemChecked(mActiveFragmentId, true)
}
PROCESS_SCH -> {
Tools.AdvancedDialog.newInstance(PROCESS_SCH, activity).show(fragmentManager, "process_scheduling")
mDrawerList.setItemChecked(mActiveFragmentId, true)
}
RECOMPUTE_ACCOUNT -> {
AccountTable.consolidateSums(activity, activity.getCurrentAccountId())
MainActivity.refreshAccountList(activity)
mDrawerList.setItemChecked(mActiveFragmentId, true)
}
EXPORT_CSV -> {
ExporterActivity.callMe(activity)
mDrawerList.setItemChecked(mActiveFragmentId, true)
}
else -> Log.d(TAG, "Undeclared fragment")
}
val tmp = fragment
if (tmp != null) {
val f = tmp as BaseFragment
fragmentManager.beginTransaction().setCustomAnimations(R.anim.enter_from_right, R.anim.zoom_exit,
R.anim.enter_from_left, R.anim.zoom_exit).replace(R.id.content_frame, f,
f.getName()).addToBackStack(f.getName()).commit()
}
mDrawerLayout.closeDrawer(mDrawerList)
}
}
private fun cleanDatabaseIfTestingMode() {
// if run by robotium, delete database, can't do it from robotium test, it leads to crash
// see http://stackoverflow.com/questions/12125656/robotium-testing-failed-because-of-deletedatabase
if (TEST_MODE) {
DBPrefsManager.getInstance(this).resetAll()
val client = contentResolver
.acquireContentProviderClient("fr.geobert.radis.db")
val provider = client.localContentProvider as DbContentProvider
provider.deleteDatabase(this)
client.release()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initShortDate(this)
if (!BuildConfig.DEBUG)
Fabric.with(this, Crashlytics())
setContentView(R.layout.activity_main)
Tools.checkDebugMode(this)
cleanDatabaseIfTestingMode()
mToolbar.title = ""
registerReceiver(mOnRefreshReceiver, IntentFilter(Tools.INTENT_REFRESH_NEEDED))
registerReceiver(mOnRefreshReceiver, IntentFilter(INTENT_UPDATE_ACC_LIST))
initAccountStuff()
initDrawer()
installRadisTimer()
}
override fun onPostCreate(savedInstanceState: Bundle?) {
super.onPostCreate(savedInstanceState)
mDrawerToggle.syncState()
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
mDrawerToggle.onConfigurationChanged(newConfig)
}
override fun onBackPressed() {
if (supportFragmentManager.backStackEntryCount <= 1) {
finish()
} else {
mActiveFragment = mPrevFragment
mActiveFragmentId = mPrevFragmentId
mDrawerList.setItemChecked(mActiveFragmentId, true)
super.onBackPressed()
}
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
// Pass the event to ActionBarDrawerToggle, if it returns
// true, then it has handled the app icon touch event
return mDrawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item)
}
private fun setUpDrawerToggle() {
// Defer code dependent on restoration of previous instance state.
// NB: required for the drawer indicator to show up!
mDrawerLayout.setDrawerListener(mDrawerToggle)
mDrawerLayout.post({ mDrawerToggle.syncState() })
}
fun displayFragment(fragmentId: Int, id: Long) {
if (fragmentId != mActiveFragmentId || mActiveFragment == null) {
val msg = Message()
msg.what = fragmentId
msg.obj = id
handler.sendMessage(msg)
}
}
override fun onPause() {
super.onPause()
handler.pause()
}
override fun onResume() {
super.onResume()
// nothing to do here, required by Android
}
override fun onResumeFragments() {
Log.d(TAG, "onResumeFragments:$mActiveFragment")
mActiveFragment?.setupIcon()
DBPrefsManager.getInstance(this).fillCache(this, {
Log.d(TAG, "pref cache ok")
consolidateDbIfNeeded()
mAccountManager.fetchAllAccounts(false, {
Log.d(TAG, "all accounts fetched")
processAccountList(true)
mAccountSpinner.setSelection(mAccountManager.getCurrentAccountPosition(this))
super.onResumeFragments()
})
handler.resume(this)
})
}
override fun onDestroy() {
super.onDestroy()
unregisterReceiver(mOnRefreshReceiver)
}
fun onAccountEditFinished(requestCode: Int, result: Int) {
Log.d(TAG, "onAccountEditFinished: $result")
if (result == Activity.RESULT_OK) {
mAccountManager.fetchAllAccounts(true, {
mAccountManager.refreshConfig(this, mAccountManager.getCurrentAccountId(this)) // need to be done before setQuickAddVisibility
val f = mActiveFragment
if (mActiveFragmentId == OP_LIST && f is OperationListFragment) {
f.refreshQuickAdd()
}
processAccountList(requestCode == AccountEditor.ACCOUNT_CREATOR)
})
} else if (result == Activity.RESULT_CANCELED) {
if (mAccountManager.mAccountAdapter.count == 0) {
finish()
}
}
}
private fun processAccountList(create: Boolean) {
Log.d(TAG, "processAccountList: count:${mAccountManager.mAccountAdapter.count}, create:$create")
if (mAccountManager.mAccountAdapter.count == 0) {
// no account, try restore database
if (!TEST_MODE) {
if (!DbHelper.restoreDatabase(this)) {
// no account and no backup, open create account
AccountEditor.callMeForResult(this, AccountEditor.NO_ACCOUNT, true)
} else {
val msg = StringBuilder()
msg.append(getString(R.string.backup_found)).append('\n').append(getString(R.string.restarting))
Toast.makeText(this, msg, Toast.LENGTH_LONG).show()
Handler().postDelayed({ Tools.restartApp(this) }, 500)
}
} else {
AccountEditor.callMeForResult(this, AccountEditor.NO_ACCOUNT, true)
}
} else {
if (mActiveFragmentId == -1) {
displayFragment(OP_LIST, (-1).toLong())
} else {
displayFragment(mActiveFragmentId, getCurrentAccountId())
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
Log.d(TAG, "onActivityResult : " + requestCode);
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
AccountEditor.ACCOUNT_EDITOR, AccountEditor.ACCOUNT_CREATOR -> onAccountEditFinished(requestCode, resultCode)
ScheduledOperationEditor.ACTIVITY_SCH_OP_CREATE, ScheduledOperationEditor.ACTIVITY_SCH_OP_EDIT,
ScheduledOperationEditor.ACTIVITY_SCH_OP_CONVERT -> {
if (mActiveFragment == null) {
findOrCreateFragment(if (mActiveFragmentId == OP_LIST) OperationListFragment::class.java else
ScheduledOpListFragment::class.java, mActiveFragmentId)
}
mActiveFragment?.onOperationEditorResult(requestCode, resultCode, data)
}
OperationEditor.OPERATION_EDITOR, OperationEditor.OPERATION_CREATOR -> {
if (mActiveFragment == null) {
findOrCreateFragment(OperationListFragment::class.java, OP_LIST)
}
mActiveFragment?.onOperationEditorResult(requestCode, resultCode, data)
mAccountManager.backupCurAccountId()
updateAccountList()
}
else -> {
updateDisplay(null)
}
}
}
private fun consolidateDbIfNeeded() {
val prefs = DBPrefsManager.getInstance(this)
val needConsolidate = prefs.getBoolean(fr.geobert.radis.service.RadisService.CONSOLIDATE_DB, false)
if (needConsolidate) {
fr.geobert.radis.service.RadisService.acquireStaticLock(this)
this.startService(Intent(this, fr.geobert.radis.service.RadisService::class.java))
}
}
private fun initAccountStuff() {
mAccountSpinner.adapter = mAccountManager.mAccountAdapter
this.setActionBarListNavCbk(object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(p0: AdapterView<out Adapter>?) {
}
override fun onItemSelected(p0: AdapterView<out Adapter>?, p1: View?, p2: Int, itemId: Long) {
val frag = mActiveFragment
if (frag != null && frag.isAdded) {
frag.onAccountChanged(itemId)
}
}
})
}
fun updateAccountList() {
mAccountManager.fetchAllAccounts(true, {
onFetchAllAccountCbk()
})
}
private fun onFetchAllAccountCbk() {
processAccountList(false)
}
private fun initDrawer() {
setUpDrawerToggle()
val navDrawerItems = ArrayList<NavDrawerItem>()
navDrawerItems.add(NavDrawerItem(getString(R.string.operations)))
navDrawerItems.add(NavDrawerItem(getString(R.string.op_list), R.drawable.op_list_48))
navDrawerItems.add(NavDrawerItem(getString(R.string.scheduled_ops), R.drawable.sched_48))
navDrawerItems.add(NavDrawerItem(getString(R.string.statistics), R.drawable.stat_48))
navDrawerItems.add(NavDrawerItem(getString(R.string.accounts)))
navDrawerItems.add(NavDrawerItem(getString(R.string.create_account), R.drawable.new_account_48))
navDrawerItems.add(NavDrawerItem(getString(R.string.account_edit), R.drawable.edit_48))
navDrawerItems.add(NavDrawerItem(getString(R.string.delete_account), R.drawable.trash_48))
navDrawerItems.add(NavDrawerItem(getString(R.string.advanced)))
navDrawerItems.add(NavDrawerItem(getString(R.string.preferences), 0)) // TODO icon
navDrawerItems.add(NavDrawerItem(getString(R.string.backup_db), 0))
navDrawerItems.add(NavDrawerItem(getString(R.string.restore_db), 0))
navDrawerItems.add(NavDrawerItem(getString(R.string.process_scheduled_transactions), 0))
navDrawerItems.add(NavDrawerItem(getString(R.string.recompute_account_sums), 0))
navDrawerItems.add(NavDrawerItem(getString(R.string.export_csv), 0))
mDrawerList.adapter = NavDrawerListAdapter(applicationContext, navDrawerItems)
mDrawerList.onItemClickListener = object : AdapterView.OnItemClickListener {
override fun onItemClick(adapterView: AdapterView<*>, view: View, i: Int, l: Long) {
displayFragment(i, getCurrentAccountId())
}
}
}
private fun installRadisTimer() {
if (mFirstStart) {
val i = Intent(this, InstallRadisServiceReceiver::class.java)
i.action = Tools.INTENT_RADIS_STARTED
sendBroadcast(i) // install radis timer
fr.geobert.radis.service.RadisService.callMe(this) // call service once
mFirstStart = false
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putInt("activeFragId", mActiveFragmentId)
outState.putInt("prevFragId", mPrevFragmentId)
}
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
mActiveFragmentId = savedInstanceState.getInt("activeFragId")
mPrevFragmentId = savedInstanceState.getInt("prevFragId")
DBPrefsManager.getInstance(this).fillCache(this, {
initAccountStuff()
if (mAccountManager.mAccountAdapter.isEmpty) {
updateDisplay(null)
}
})
}
fun setActionBarListNavCbk(callback: AdapterView.OnItemSelectedListener?) {
mAccountSpinner.onItemSelectedListener = callback
}
fun getCurrentAccountId(): Long {
return mAccountManager.getCurrentAccountId(this)
}
override fun updateDisplay(intent: Intent?) {
Log.d(TAG, "updateDisplay")
mAccountManager.fetchAllAccounts(true, {
processAccountList(true)
val f = mActiveFragment
if (f != null && f.isAdded) {
f.updateDisplay(intent)
}
})
}
private val TAG = "MainActivity"
companion object {
var TEST_MODE: Boolean = false
val INTENT_UPDATE_OP_LIST: String = "fr.geobert.radis.UPDATE_OP_LIST"
val INTENT_UPDATE_ACC_LIST: String = "fr.geobert.radis.UPDATE_ACC_LIST"
// used for FragmentHandler
val OP_LIST: Int = 1
val SCH_OP_LIST: Int = 2
val STATISTICS: Int = 3
val CREATE_ACCOUNT: Int = 5
val EDIT_ACCOUNT: Int = 6
val DELETE_ACCOUNT: Int = 7
val PREFERENCES: Int = 9
val SAVE_ACCOUNT: Int = 10
val RESTORE_ACCOUNT: Int = 11
val PROCESS_SCH: Int = 12
val RECOMPUTE_ACCOUNT: Int = 13
val EXPORT_CSV: Int = 14
fun refreshAccountList(ctx: Context) {
val intent = Intent(INTENT_UPDATE_ACC_LIST)
ctx.sendBroadcast(intent)
}
}
}
|
gpl-2.0
|
78348d18a496ffd71691ce3659d88cd4
| 40.381443 | 142 | 0.632586 | 5.008735 | false | false | false | false |
lettuce-io/lettuce-core
|
src/main/kotlin/io/lettuce/core/api/coroutines/RedisScriptingCoroutinesCommandsImpl.kt
|
1
|
3845
|
/*
* Copyright 2020-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 io.lettuce.core.api.coroutines
import io.lettuce.core.ExperimentalLettuceCoroutinesApi
import io.lettuce.core.FlushMode
import io.lettuce.core.ScriptOutputType
import io.lettuce.core.api.reactive.RedisScriptingReactiveCommands
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.reactive.asFlow
import kotlinx.coroutines.reactive.awaitFirstOrNull
/**
* Coroutine executed commands (based on reactive commands) for Scripting. [Lua scripts][java.lang.String] are encoded by using the configured
* [charset][io.lettuce.core.ClientOptions#getScriptCharset()].
*
* @param <K> Key type.
* @param <V> Value type.
* @author Mikhael Sokolov
* @since 6.0
*
* @generated by io.lettuce.apigenerator.CreateKotlinCoroutinesReactiveImplementation
*/
@ExperimentalLettuceCoroutinesApi
internal class RedisScriptingCoroutinesCommandsImpl<K : Any, V : Any>(internal val ops: RedisScriptingReactiveCommands<K, V>) : RedisScriptingCoroutinesCommands<K, V> {
override suspend fun <T> eval(script: String, type: ScriptOutputType, vararg keys: K): T? = ops.eval<T>(script, type, *keys).awaitFirstOrNull()
override suspend fun <T> eval(script: ByteArray, type: ScriptOutputType, vararg keys: K): T? = ops.eval<T>(script, type, *keys).awaitFirstOrNull()
override suspend fun <T> eval(script: String, type: ScriptOutputType, keys: Array<K>, vararg values: V): T? = ops.eval<T>(script, type, keys, *values).awaitFirstOrNull()
override suspend fun <T> eval(script: ByteArray, type: ScriptOutputType, keys: Array<K>, vararg values: V): T? = ops.eval<T>(script, type, keys, *values).awaitFirstOrNull()
override suspend fun <T> evalReadOnly(
script: ByteArray,
type: ScriptOutputType,
keys: Array<K>,
vararg values: V
): T? = ops.evalReadOnly<T>(script, type, keys, *values).awaitFirstOrNull()
override suspend fun <T> evalsha(digest: String, type: ScriptOutputType, vararg keys: K): T? = ops.evalsha<T>(digest, type, *keys).awaitFirstOrNull()
override suspend fun <T> evalsha(digest: String, type: ScriptOutputType, keys: Array<K>, vararg values: V): T? = ops.evalsha<T>(digest, type, keys, *values).awaitFirstOrNull()
override suspend fun <T> evalshaReadOnly(
digest: String,
type: ScriptOutputType,
keys: Array<K>,
vararg values: V
): T? = ops.evalshaReadOnly<T>(digest, type, keys, *values).awaitFirstOrNull()
override suspend fun scriptExists(vararg digests: String): List<Boolean> = ops.scriptExists(*digests).asFlow().toList()
override suspend fun scriptFlush(): String? = ops.scriptFlush().awaitFirstOrNull()
override suspend fun scriptFlush(flushMode: FlushMode): String? = ops.scriptFlush(flushMode).awaitFirstOrNull()
override suspend fun scriptKill(): String? = ops.scriptKill().awaitFirstOrNull()
override suspend fun scriptLoad(script: String): String? = ops.scriptLoad(script).awaitFirstOrNull()
override suspend fun scriptLoad(script: ByteArray): String? = ops.scriptLoad(script).awaitFirstOrNull()
override suspend fun digest(script: String): String = ops.digest(script)
override suspend fun digest(script: ByteArray): String = ops.digest(script)
}
|
apache-2.0
|
61a52d0efbeca560db9cf3aa69e4346c
| 44.235294 | 179 | 0.736541 | 4.081741 | false | false | false | false |
android/animation-samples
|
Motion/app/src/main/java/com/example/android/motion/demo/loading/LoadingActivity.kt
|
1
|
3916
|
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.motion.demo.loading
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.core.view.WindowCompat
import androidx.recyclerview.widget.RecyclerView
import androidx.transition.Fade
import androidx.transition.Transition
import androidx.transition.TransitionListenerAdapter
import androidx.transition.TransitionManager
import com.example.android.motion.R
import com.example.android.motion.demo.FAST_OUT_SLOW_IN
import com.example.android.motion.demo.LARGE_EXPAND_DURATION
import com.example.android.motion.demo.plusAssign
import com.example.android.motion.demo.transitionSequential
import com.example.android.motion.ui.EdgeToEdge
/**
* Shows a list of cheeses. We use the Paging Library to load the list.
*/
class LoadingActivity : AppCompatActivity() {
private val viewModel: LoadingViewModel by viewModels()
private lateinit var list: RecyclerView
private val fade = transitionSequential {
duration = LARGE_EXPAND_DURATION
interpolator = FAST_OUT_SLOW_IN
this += Fade(Fade.OUT)
this += Fade(Fade.IN)
addListener(object : TransitionListenerAdapter() {
override fun onTransitionEnd(transition: Transition) {
if (savedItemAnimator != null) {
list.itemAnimator = savedItemAnimator
}
}
})
}
private val placeholderAdapter = PlaceholderAdapter()
private val cheeseAdapter = CheeseAdapter()
private var savedItemAnimator: RecyclerView.ItemAnimator? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.loading_activity)
val toolbar: Toolbar = findViewById(R.id.toolbar)
list = findViewById(R.id.list)
setSupportActionBar(toolbar)
WindowCompat.setDecorFitsSystemWindows(window, false)
EdgeToEdge.setUpAppBar(findViewById(R.id.app_bar), toolbar)
EdgeToEdge.setUpScrollingContent(list)
// Show the initial placeholders.
// See the ViewHolder implementation for how to create the loading animation.
list.adapter = placeholderAdapter
viewModel.cheeses.observe(this) { cheeses ->
if (list.adapter != cheeseAdapter) {
list.adapter = cheeseAdapter
savedItemAnimator = list.itemAnimator
list.itemAnimator = null
TransitionManager.beginDelayedTransition(list, fade)
}
cheeseAdapter.submitData(lifecycle, cheeses)
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.loading, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.action_refresh -> {
TransitionManager.beginDelayedTransition(list, fade)
list.adapter = placeholderAdapter
viewModel.refresh()
true
}
else -> super.onOptionsItemSelected(item)
}
}
}
|
apache-2.0
|
a75c9ad8d25a77d5b9f83e110f2f8aed
| 35.943396 | 85 | 0.699438 | 4.864596 | false | false | false | false |
ansman/okhttp
|
okhttp/src/main/kotlin/okhttp3/internal/http1/HeadersReader.kt
|
7
|
1445
|
/*
* Copyright (C) 2012 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 okhttp3.internal.http1
import okhttp3.Headers
import okio.BufferedSource
/**
* Parse all headers delimited by "\r\n" until an empty line. This throws if headers exceed 256 KiB.
*/
class HeadersReader(val source: BufferedSource) {
private var headerLimit = HEADER_LIMIT.toLong()
/** Read a single line counted against the header size limit. */
fun readLine(): String {
val line = source.readUtf8LineStrict(headerLimit)
headerLimit -= line.length.toLong()
return line
}
/** Reads headers or trailers. */
fun readHeaders(): Headers {
val result = Headers.Builder()
while (true) {
val line = readLine()
if (line.isEmpty()) break
result.addLenient(line)
}
return result.build()
}
companion object {
private const val HEADER_LIMIT = 256 * 1024
}
}
|
apache-2.0
|
a9e77c4662edc0a18932420f77aa65dc
| 29.104167 | 100 | 0.704498 | 4.140401 | false | false | false | false |
NextFaze/dev-fun
|
devfun-invoke-view-colorpicker/src/main/java/com/nextfaze/devfun/invoke/view/colorpicker/Module.kt
|
1
|
1601
|
package com.nextfaze.devfun.invoke.view.colorpicker
import android.content.Context
import android.util.AttributeSet
import android.view.View
import com.google.auto.service.AutoService
import com.nextfaze.devfun.core.AbstractDevFunModule
import com.nextfaze.devfun.core.DevFunModule
import com.nextfaze.devfun.invoke.Parameter
import com.nextfaze.devfun.invoke.ParameterViewFactoryProvider
import com.nextfaze.devfun.invoke.view.ColorPicker
import com.nextfaze.devfun.invoke.view.WithValue
import com.nextfaze.devfun.view.ViewFactory
import com.nextfaze.devfun.view.viewFactory
import com.rarepebble.colorpicker.ColorPickerView
@AutoService(DevFunModule::class)
internal class DevInvokeViewColorPicker : AbstractDevFunModule() {
override fun init(context: Context) {
devFun.parameterViewFactories += ColorPickerParameterViewProvider
}
override fun dispose() {
devFun.parameterViewFactories -= ColorPickerParameterViewProvider
}
}
private object ColorPickerParameterViewProvider : ParameterViewFactoryProvider {
override fun get(parameter: Parameter): ViewFactory<View>? =
when {
parameter.type == Int::class && parameter.annotations.any { it is ColorPicker } -> viewFactory(R.layout.df_invoke_view_colorpicker)
else -> null
}
}
private class ParameterColorPickerViewForInt @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) :
ColorPickerView(context, attrs),
WithValue<Int> {
override var value: Int
get() = this.color
set(value) {
color = value
}
}
|
apache-2.0
|
673fc57e08e54901e59bca25e1ff67f3
| 34.577778 | 143 | 0.761399 | 4.386301 | false | false | false | false |
kozalosev/DeskChan-Launcher
|
src/main/kotlin/info/deskchan/launcher/Helpers.kt
|
1
|
1903
|
package info.deskchan.launcher
import java.io.FileNotFoundException
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Path
import java.util.jar.JarFile
import java.util.zip.ZipException
fun getExecFilePath(rootDirPath: Path): Path {
val extension = if (onWindows) ".exe" else ""
return rootDirPath.resolve("bin/$APPLICATION_NAME$extension")
}
fun setAutorunUp(execFilePath: Path) {
execFilePath.toFile().setExecutable(true)
getAutorunManager(APPLICATION_NAME, execFilePath).setAutorunUp()
}
fun resetAutorun(execFilePath: Path) {
getAutorunManager(APPLICATION_NAME, execFilePath).resetAutorun()
}
fun copyLauncherTo(path: Path) {
val allFiles = env.rootDirPath.toFile().listFiles()
val coreFile = allFiles.filter { file -> file.name == "$CORE_FILENAME.jar" }
val exeFiles = allFiles
.filter { file -> file.extension == "exe" }
.filter {
val jar = try {
JarFile(it)
} catch (e: ZipException) {
null
}
jar?.manifest?.mainAttributes?.getValue("Launcher-Module") != null
}
val exeFileNames = exeFiles.map { it.nameWithoutExtension }
val shFiles = allFiles
.filter { file -> file.extension.isEmpty() }
.filter { file -> exeFileNames.contains(file.name) }
(coreFile + exeFiles + shFiles).forEach {
val newFile = path.resolve(it.name).toFile()
it.copyTo(newFile, overwrite = true)
}
}
@Throws(IOException::class)
fun launchApplication(execFilePath: Path) {
execFilePath.toFile().setExecutable(true)
if (Files.isExecutable(execFilePath)) {
ProcessBuilder(execFilePath.toString()).start()
} else {
throw FileNotFoundException()
}
}
fun exitProcess(status: ExitStatus): Nothing = kotlin.system.exitProcess(status.code)
|
lgpl-3.0
|
80cf6e58fdd19e581d5044c386822199
| 31.254237 | 85 | 0.658434 | 4.066239 | false | false | false | false |
RedstonerServer/Parcels
|
src/main/kotlin/io/dico/parcels2/util/math/Vec3d.kt
|
1
|
1838
|
package io.dico.parcels2.util.math
import org.bukkit.Location
import kotlin.math.sqrt
data class Vec3d(
val x: Double,
val y: Double,
val z: Double
) {
constructor(loc: Location) : this(loc.x, loc.y, loc.z)
operator fun plus(o: Vec3d) = Vec3d(x + o.x, y + o.y, z + o.z)
operator fun plus(o: Vec3i) = Vec3d(x + o.x, y + o.y, z + o.z)
operator fun minus(o: Vec3d) = Vec3d(x - o.x, y - o.y, z - o.z)
operator fun minus(o: Vec3i) = Vec3d(x - o.x, y - o.y, z - o.z)
infix fun addX(o: Double) = Vec3d(x + o, y, z)
infix fun addY(o: Double) = Vec3d(x, y + o, z)
infix fun addZ(o: Double) = Vec3d(x, y, z + o)
infix fun withX(o: Double) = Vec3d(o, y, z)
infix fun withY(o: Double) = Vec3d(x, o, z)
infix fun withZ(o: Double) = Vec3d(x, y, o)
fun add(ox: Double, oy: Double, oz: Double) = Vec3d(x + ox, y + oy, z + oz)
fun toVec3i() = Vec3i(x.floor(), y.floor(), z.floor())
fun distanceSquared(o: Vec3d): Double {
val dx = o.x - x
val dy = o.y - y
val dz = o.z - z
return dx * dx + dy * dy + dz * dz
}
fun distance(o: Vec3d) = sqrt(distanceSquared(o))
operator fun get(dimension: Dimension) =
when (dimension) {
Dimension.X -> x
Dimension.Y -> y
Dimension.Z -> z
}
fun with(dimension: Dimension, value: Double) =
when (dimension) {
Dimension.X -> withX(value)
Dimension.Y -> withY(value)
Dimension.Z -> withZ(value)
}
fun add(dimension: Dimension, value: Double) =
when (dimension) {
Dimension.X -> addX(value)
Dimension.Y -> addY(value)
Dimension.Z -> addZ(value)
}
fun copyInto(loc: Location) {
loc.x = x
loc.y = y
loc.z = z
}
}
|
gpl-2.0
|
8a4b692398215d0b1ac3e5a9d2550d7d
| 29.147541 | 79 | 0.532644 | 2.840804 | false | false | false | false |
nextcloud/android
|
app/src/main/java/com/nextcloud/ui/fileactions/FileActionsBottomSheet.kt
|
1
|
12306
|
/*
* Nextcloud Android client application
*
* @author Álvaro Brey
* Copyright (C) 2022 Álvaro Brey
* Copyright (C) 2022 Nextcloud GmbH
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.nextcloud.ui.fileactions
import android.content.Context
import android.content.res.ColorStateList
import android.graphics.Typeface
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.text.style.StyleSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.annotation.IdRes
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.os.bundleOf
import androidx.core.view.isVisible
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.setFragmentResult
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ViewModelProvider
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.nextcloud.android.common.ui.theme.utils.ColorRole
import com.nextcloud.client.account.CurrentAccountProvider
import com.nextcloud.client.di.Injectable
import com.nextcloud.client.di.ViewModelFactory
import com.owncloud.android.R
import com.owncloud.android.databinding.FileActionsBottomSheetBinding
import com.owncloud.android.databinding.FileActionsBottomSheetItemBinding
import com.owncloud.android.datamodel.FileDataStorageManager
import com.owncloud.android.datamodel.OCFile
import com.owncloud.android.datamodel.ThumbnailsCacheManager
import com.owncloud.android.lib.resources.files.model.FileLockType
import com.owncloud.android.ui.activity.ComponentsGetter
import com.owncloud.android.utils.DisplayUtils
import com.owncloud.android.utils.DisplayUtils.AvatarGenerationListener
import com.owncloud.android.utils.theme.ViewThemeUtils
import javax.inject.Inject
class FileActionsBottomSheet private constructor() : BottomSheetDialogFragment(), Injectable {
@Inject
lateinit var viewThemeUtils: ViewThemeUtils
@Inject
lateinit var vmFactory: ViewModelFactory
@Inject
lateinit var currentUserProvider: CurrentAccountProvider
@Inject
lateinit var storageManager: FileDataStorageManager
lateinit var viewModel: FileActionsViewModel
private var _binding: FileActionsBottomSheetBinding? = null
private val binding
get() = _binding!!
lateinit var componentsGetter: ComponentsGetter
private val thumbnailAsyncTasks = mutableListOf<ThumbnailsCacheManager.ThumbnailGenerationTask>()
interface ResultListener {
fun onResult(@IdRes actionId: Int)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
viewModel = ViewModelProvider(this, vmFactory)[FileActionsViewModel::class.java]
_binding = FileActionsBottomSheetBinding.inflate(inflater, container, false)
viewModel.uiState.observe(viewLifecycleOwner, this::handleState)
viewModel.clickActionId.observe(viewLifecycleOwner) { id ->
dispatchActionClick(id)
}
viewModel.load(requireArguments(), componentsGetter)
return binding.root
}
private fun handleState(
state: FileActionsViewModel.UiState
) {
toggleLoadingOrContent(state)
when (state) {
is FileActionsViewModel.UiState.LoadedForSingleFile -> {
loadFileThumbnail(state.titleFile)
if (state.lockInfo != null) {
displayLockInfo(state.lockInfo)
}
displayActions(state.actions)
displayTitle(state.titleFile)
}
is FileActionsViewModel.UiState.LoadedForMultipleFiles -> {
setMultipleFilesThumbnail()
displayActions(state.actions)
displayTitle(state.fileCount)
}
FileActionsViewModel.UiState.Loading -> {}
FileActionsViewModel.UiState.Error -> {
context?.let {
Toast.makeText(it, R.string.error_file_actions, Toast.LENGTH_SHORT).show()
}
dismissAllowingStateLoss()
}
}
}
private fun loadFileThumbnail(titleFile: OCFile?) {
titleFile?.let {
DisplayUtils.setThumbnail(
it,
binding.thumbnailLayout.thumbnail,
currentUserProvider.user,
storageManager,
thumbnailAsyncTasks,
false,
context,
binding.thumbnailLayout.thumbnailShimmer,
null,
viewThemeUtils
)
}
}
private fun setMultipleFilesThumbnail() {
context?.let {
val drawable = viewThemeUtils.platform.tintDrawable(it, R.drawable.file_multiple, ColorRole.PRIMARY)
binding.thumbnailLayout.thumbnail.setImageDrawable(drawable)
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
override fun onAttach(context: Context) {
super.onAttach(context)
require(context is ComponentsGetter) {
"Context is not a ComponentsGetter"
}
this.componentsGetter = context
}
fun setResultListener(
fragmentManager: FragmentManager,
lifecycleOwner: LifecycleOwner,
listener: ResultListener
): FileActionsBottomSheet {
fragmentManager.setFragmentResultListener(REQUEST_KEY, lifecycleOwner) { _, result ->
@IdRes val actionId = result.getInt(RESULT_KEY_ACTION_ID, -1)
if (actionId != -1) {
listener.onResult(actionId)
}
}
return this
}
private fun toggleLoadingOrContent(state: FileActionsViewModel.UiState) {
if (state is FileActionsViewModel.UiState.Loading) {
binding.bottomSheetLoading.isVisible = true
binding.bottomSheetContent.isVisible = false
viewThemeUtils.platform.colorCircularProgressBar(binding.bottomSheetLoading)
} else {
binding.bottomSheetLoading.isVisible = false
binding.bottomSheetContent.isVisible = true
}
}
private fun displayActions(
actions: List<FileAction>
) {
actions.forEach { action ->
val view = inflateActionView(action)
binding.fileActionsList.addView(view)
}
}
private fun displayTitle(titleFile: OCFile?) {
val decryptedFileName = titleFile?.decryptedFileName
if (decryptedFileName != null) {
decryptedFileName.let {
binding.title.text = it
}
} else {
binding.title.isVisible = false
}
}
private fun displayLockInfo(lockInfo: FileActionsViewModel.LockInfo) {
val view = FileActionsBottomSheetItemBinding.inflate(layoutInflater, binding.fileActionsList, false)
.apply {
val textColor = ColorStateList.valueOf(resources.getColor(R.color.secondary_text_color, null))
root.isClickable = false
text.setTextColor(textColor)
text.text = getLockedByText(lockInfo)
if (lockInfo.lockedUntil != null) {
textLine2.text = getLockedUntilText(lockInfo)
textLine2.isVisible = true
}
if (lockInfo.lockType != FileLockType.COLLABORATIVE) {
showLockAvatar(lockInfo)
}
}
binding.fileActionsList.addView(view.root)
}
private fun FileActionsBottomSheetItemBinding.showLockAvatar(lockInfo: FileActionsViewModel.LockInfo) {
val listener = object : AvatarGenerationListener {
override fun avatarGenerated(avatarDrawable: Drawable?, callContext: Any?) {
icon.setImageDrawable(avatarDrawable)
}
override fun shouldCallGeneratedCallback(tag: String?, callContext: Any?): Boolean {
return false
}
}
DisplayUtils.setAvatar(
currentUserProvider.user,
lockInfo.lockedBy,
listener,
resources.getDimension(R.dimen.list_item_avatar_icon_radius),
resources,
this,
requireContext()
)
}
private fun getLockedByText(lockInfo: FileActionsViewModel.LockInfo): CharSequence {
val resource = when (lockInfo.lockType) {
FileLockType.COLLABORATIVE -> R.string.locked_by_app
else -> R.string.locked_by
}
return DisplayUtils.createTextWithSpan(
getString(resource, lockInfo.lockedBy),
lockInfo.lockedBy,
StyleSpan(Typeface.BOLD)
)
}
private fun getLockedUntilText(lockInfo: FileActionsViewModel.LockInfo): CharSequence {
val relativeTimestamp = DisplayUtils.getRelativeTimestamp(context, lockInfo.lockedUntil!!, true)
return getString(R.string.lock_expiration_info, relativeTimestamp)
}
private fun displayTitle(fileCount: Int) {
binding.title.text = resources.getQuantityString(R.plurals.file_list__footer__file, fileCount, fileCount)
}
private fun inflateActionView(action: FileAction): View {
val itemBinding = FileActionsBottomSheetItemBinding.inflate(layoutInflater, binding.fileActionsList, false)
.apply {
root.setOnClickListener {
viewModel.onClick(action)
}
text.setText(action.title)
if (action.icon != null) {
val drawable =
viewThemeUtils.platform.tintDrawable(
requireContext(),
AppCompatResources.getDrawable(requireContext(), action.icon)!!
)
icon.setImageDrawable(drawable)
}
}
return itemBinding.root
}
private fun dispatchActionClick(id: Int?) {
if (id != null) {
setFragmentResult(REQUEST_KEY, bundleOf(RESULT_KEY_ACTION_ID to id))
parentFragmentManager.clearFragmentResultListener(REQUEST_KEY)
dismiss()
}
}
companion object {
private const val REQUEST_KEY = "REQUEST_KEY_ACTION"
private const val RESULT_KEY_ACTION_ID = "RESULT_KEY_ACTION_ID"
@JvmStatic
@JvmOverloads
fun newInstance(
file: OCFile,
isOverflow: Boolean,
@IdRes
additionalToHide: List<Int>? = null
): FileActionsBottomSheet {
return newInstance(1, listOf(file), isOverflow, additionalToHide)
}
@JvmStatic
@JvmOverloads
fun newInstance(
numberOfAllFiles: Int,
files: Collection<OCFile>,
isOverflow: Boolean,
@IdRes
additionalToHide: List<Int>? = null
): FileActionsBottomSheet {
return FileActionsBottomSheet().apply {
val argsBundle = bundleOf(
FileActionsViewModel.ARG_ALL_FILES_COUNT to numberOfAllFiles,
FileActionsViewModel.ARG_FILES to ArrayList<OCFile>(files),
FileActionsViewModel.ARG_IS_OVERFLOW to isOverflow
)
additionalToHide?.let {
argsBundle.putIntArray(FileActionsViewModel.ARG_ADDITIONAL_FILTER, additionalToHide.toIntArray())
}
arguments = argsBundle
}
}
}
}
|
gpl-2.0
|
1a001a48e651c188a4141a0a2924ca2b
| 35.402367 | 117 | 0.649057 | 5.145964 | false | false | false | false |
MimiReader/mimi-reader
|
mimi-app/src/main/java/com/emogoth/android/phone/mimi/view/gallery/GalleryGrid.kt
|
1
|
7409
|
package com.emogoth.android.phone.mimi.view.gallery
import android.content.Context
import android.util.AttributeSet
import android.util.LongSparseArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.TextView
import androidx.appcompat.widget.AppCompatImageView
import androidx.core.util.contains
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.emogoth.android.phone.mimi.R
import com.emogoth.android.phone.mimi.app.MimiApplication
import com.emogoth.android.phone.mimi.util.GlideApp
import com.emogoth.android.phone.mimi.util.MimiPrefs
import com.emogoth.android.phone.mimi.util.MimiUtil
import com.emogoth.android.phone.mimi.viewmodel.GalleryItem
import java.util.*
import kotlin.collections.ArrayList
class GalleryGrid @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0)
: FrameLayout(context, attrs, defStyleAttr) {
companion object {
const val MODE_OPEN = 0
const val MODE_SELECT = 1
}
private val grid: RecyclerView by lazy { RecyclerView(context) }
private var adapter: GalleryGridItemAdapter? = null
var itemSelected: ((GalleryItem, Boolean) -> (Unit))? = null
var multipleItemsSelected: ((List<GalleryItem>) -> (Unit))? = null
var itemClicked: ((View, GalleryItem) -> (Unit))? = null
// @State
var mode = MODE_OPEN
set(value) {
field = value
adapter?.mode = value
adapter?.notifyDataSetChanged()
}
// @State
var position: Int = 0
get() {
val lm: GridLayoutManager = grid.layoutManager as GridLayoutManager
return lm.findFirstCompletelyVisibleItemPosition()
}
set(value) {
field = value
grid.post { grid.layoutManager?.scrollToPosition(value) }
}
var items: List<GalleryItem> = Collections.emptyList()
set(value) {
field = value
adapter = GalleryGridItemAdapter(value)
adapter?.selectedChange = { item, selected ->
itemSelected?.invoke(item, selected)
}
adapter?.itemClicked = { view: View, item: GalleryItem ->
itemClicked?.invoke(view, item)
}
grid.adapter = adapter
}
init {
id = R.id.gallery2_grid
val landscape = resources.getBoolean(R.bool.is_landscape)
val rows = if (landscape) 3 else 2
grid.layoutManager = GridLayoutManager(context, rows)
addView(grid)
}
fun selectItems(all: Boolean) {
adapter?.selectItems(all)
multipleItemsSelected?.invoke(getSelectedItems())
}
fun invertSelection() {
adapter?.invertSelection()
multipleItemsSelected?.invoke(getSelectedItems())
}
fun getSelectedItems(): List<GalleryItem> {
return adapter?.getSelectedItems() ?: Collections.emptyList()
}
}
class GalleryGridItemAdapter(val items: List<GalleryItem>) : RecyclerView.Adapter<GalleryGridItemViewHolder>() {
private val preloadEnabled: Boolean = MimiPrefs.preloadEnabled(MimiApplication.instance)
var mode = GalleryGrid.MODE_OPEN
private val selectedItemMap = LongSparseArray<Boolean>()
var selectedChange: ((GalleryItem, Boolean) -> (Unit))? = null
var itemClicked: ((View, GalleryItem) -> (Unit))? = null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GalleryGridItemViewHolder {
val inflater = LayoutInflater.from(parent.context)
val view = inflater.inflate(R.layout.gallery_grid_item, parent, false)
return GalleryGridItemViewHolder(view, preloadEnabled)
}
override fun getItemCount(): Int {
return items.size
}
fun selectItems(all: Boolean) {
for (item in items) {
selectedItemMap.put(item.id, all)
}
notifyDataSetChanged()
}
fun invertSelection() {
for (item in items) {
if (selectedItemMap.contains(item.id)) {
val selected = !selectedItemMap[item.id]
selectedItemMap.put(item.id, selected)
} else {
selectedItemMap.put(item.id, true)
}
}
notifyDataSetChanged()
}
fun getSelectedItems(): List<GalleryItem> {
val list = ArrayList<GalleryItem>(items.size)
for (item in items) {
if (selectedItemMap.contains(item.id) && selectedItemMap[item.id] == true) {
list.add(item)
}
}
return list
}
override fun onBindViewHolder(holder: GalleryGridItemViewHolder, position: Int) {
val item = items[position]
val selected = selectedItemMap[item.id] ?: false
holder.bind(items[position], mode, selected)
holder.selectionChange = {
selectedItemMap.put(item.id, it)
selectedChange?.invoke(item, it)
mode = GalleryGrid.MODE_SELECT
}
holder.itemClicked = {
itemClicked?.invoke(holder.itemView, item)
}
}
fun setItems(items: List<GalleryItem>) {
if (this.items is ArrayList) {
this.items.clear()
this.items.addAll(items)
notifyDataSetChanged()
}
throw IllegalStateException("Items cannot be modified")
}
}
class GalleryGridItemViewHolder(private val root: View, private val preloadEnabled: Boolean) : RecyclerView.ViewHolder(root) {
private val thumbView: AppCompatImageView = this.root.findViewById(R.id.gallery_thumbnail)
private val selectedView: View = this.root.findViewById(R.id.selected)
private val fileSizeText: TextView = this.root.findViewById(R.id.file_size)
private val fileExtText: TextView = this.root.findViewById(R.id.file_ext)
private val number: TextView = this.root.findViewById(R.id.item_number)
var selected: Boolean = false
set(value) {
field = value
selectedView.visibility = if (value) View.VISIBLE else View.GONE
}
var mode = GalleryGrid.MODE_OPEN
var selectionChange: ((Boolean) -> (Unit))? = null
var itemClicked: ((GalleryItem) -> (Unit))? = null
fun bind(item: GalleryItem, mode: Int, itemSelected: Boolean) {
val useThumbnail = (item.downloadUrl.endsWith("webm") || item.size >= 400000) || !preloadEnabled
val url = if (useThumbnail) item.thumbnailUrl else item.downloadUrl
GlideApp.with(root)
.load(url)
.optionalCenterCrop()
.into(thumbView)
.clearOnDetach()
this.selected = itemSelected
fileSizeText.text = MimiUtil.humanReadableByteCount(item.size.toLong(), true)
fileExtText.text = item.ext.substring(1).toUpperCase()
number.text = (layoutPosition + 1).toString()
root.setOnClickListener {
if (mode == GalleryGrid.MODE_SELECT) {
this.selected = !this.selected
selectionChange?.invoke(this.selected)
} else {
itemClicked?.invoke(item)
}
}
root.setOnLongClickListener {
this.selected = !this.selected
selectionChange?.invoke(this.selected)
return@setOnLongClickListener true
}
}
}
|
apache-2.0
|
2db473824f4ad65b032cb02a85a12720
| 32.529412 | 126 | 0.646916 | 4.548189 | false | false | false | false |
oboehm/jfachwert
|
src/main/kotlin/de/jfachwert/net/ChatAccount.kt
|
1
|
5509
|
/*
* Copyright (c) 2017-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 orimplied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* (c)reated 19.08.17 by oliver ([email protected])
*/
package de.jfachwert.net
import com.fasterxml.jackson.annotation.JsonCreator
import com.fasterxml.jackson.databind.annotation.JsonSerialize
import de.jfachwert.KFachwert
import de.jfachwert.pruefung.exception.LocalizedIllegalArgumentException
import de.jfachwert.util.ToFachwertSerializer
import org.apache.commons.lang3.StringUtils
import java.util.*
/**
* Die Klasse ChatAccount steht fuer einen Account bei einem der uebleichen
* Chat-Dienst wie ICQ, Skype oder Jabber.
*
* @author oliver ([email protected])
* @since 0.4 (08.08.2017)
*/
@JsonSerialize(using = ToFachwertSerializer::class)
open class ChatAccount(val chatDienst: ChatDienst, private val dienstName: String?, account: String) : KFachwert {
/**
* Liefert den Account-Namen zurueck.
*
* @return z.B. "[email protected]"
*/
val account: String
/**
* Zerlegt den uebergebenen String in seine Einzelteile, um damit den
* ChatAccount zu instanziieren. Bei der Zerlegung wird folgeden Heuristik
* angwendet:
*
* * zuserst kommt der Dienst, gefolgt von einem Doppelpunkt,
* * danach kommt der Name bzw. Account.
*
* @param chatAccount z.B. "Twitter: oboehm"
*/
constructor(chatAccount: String) : this(split(chatAccount)) {}
private constructor(values: Array<String>) : this(ChatDienst.of(values[0]), values[0], values[1]) {}
/**
* Erzeugt einen neuen ChatAccount aus der uebergebenen Map.
*
* @param map mit den einzelnen Elementen fuer "chatDienst", "dienstName"
* und "account".
*/
@JsonCreator
constructor(map: Map<String, String>) : this(ChatDienst.of(map["chatDienst"]), map["dienstName"], map["account"]!!) {
}
/**
* Instanziiert einen Chat-Account.
*
* @param dienst z.B. "ICQ"
* @param account z.B. 211349835 fuer ICQ
*/
constructor(dienst: String, account: String) : this(ChatDienst.of(dienst), dienst, account) {}
/**
* Instanziiert eine Chat-Account.
*
* @param dienst z.B. "ICQ"
* @param account z.B. 211349835 fuer ICQ
*/
constructor(dienst: ChatDienst, account: String) : this(dienst, null, account) {}
init {
this.account = chatDienst.validator.verify(account)
}
/**
* Liefert den Dienst zum Account zurueck.
*
* @return z.B. "Jabber"
*/
fun getDienstName(): String {
return if (chatDienst == ChatDienst.SONSTIGER) {
dienstName!!
} else {
chatDienst.toString()
}
}
/**
* Beim Vergleich ignorieren wir Gross- und Kleinschreibung, weil das
* vermutlich keine Rolle spielen duerfte. Zumindest ist mir kein
* Chat-Dienst bekannt, wo zwischen Gross- und Kleinschreibung
* unterschieden wird.
*
* @param other der andere Chat-Account
* @return true oder false
*/
override fun equals(other: Any?): Boolean {
if (other !is ChatAccount) {
return false
}
return getDienstName().equals(other.getDienstName(), ignoreCase = true) &&
account.equals(other.account, ignoreCase = true)
}
/**
* Die Hashcode-Implementierung stuetzt sich nur auf den Account ab.
*
* @return hashcode
*/
override fun hashCode(): Int {
return account.hashCode()
}
/**
* Ausgabe des Chat-Accounts zusammen mit der Dienstbezeichnung.
*
* @return z.B. "Jabber: [email protected]"
*/
override fun toString(): String {
return getDienstName() + ": " + account
}
/**
* Liefert die einzelnen Attribute eines ChatAccounts als Map.
*
* @return Attribute als Map
*/
override fun toMap(): Map<String, Any> {
val map: MutableMap<String, Any> = HashMap()
map["chatDienst"] = chatDienst
map["dienstName"] = getDienstName()
map["account"] = account
return map
}
companion object {
private val WEAK_CACHE = WeakHashMap<String, ChatAccount>()
/** Null-Konstante fuer Initialisierungen. */
@JvmField
val NULL = ChatAccount(ChatDienst.SONSTIGER, "", "")
private fun split(value: String): Array<String> {
val splitted = StringUtils.trimToEmpty(value).split(":\\s+".toPattern()).toTypedArray()
if (splitted.size != 2) {
throw LocalizedIllegalArgumentException(value, "chat_service")
}
return splitted
}
/**
* Liefert einen Chat-Account.
*
* @param name z.B. "Twitter: oboehm"
* @return Chat-Account
*/
@JvmStatic
fun of(name: String): ChatAccount {
return WEAK_CACHE.computeIfAbsent(name) { chatAccount: String -> ChatAccount(chatAccount) }
}
}
}
|
apache-2.0
|
84db3481f6c181a40c697d8d19aabeb4
| 29.441989 | 121 | 0.633146 | 3.588925 | false | false | false | false |
martin-nordberg/KatyDOM
|
Katydid-VDOM-JS/src/main/kotlin/i/katydid/vdom/elements/embedded/KatydidVideo.kt
|
1
|
5765
|
//
// (C) Copyright 2018-2019 Martin E. Nordberg III
// Apache 2.0 License
//
package i.katydid.vdom.elements.embedded
import i.katydid.vdom.builders.KatydidEmbeddedContentBuilderImpl
import i.katydid.vdom.builders.KatydidFlowContentBuilderImpl
import i.katydid.vdom.builders.KatydidPhrasingContentBuilderImpl
import i.katydid.vdom.elements.KatydidHtmlElementImpl
import o.katydid.vdom.builders.media.KatydidMediaEmbeddedContentBuilder
import o.katydid.vdom.builders.media.KatydidMediaFlowContentBuilder
import o.katydid.vdom.builders.media.KatydidMediaPhrasingContentBuilder
import o.katydid.vdom.types.ECorsSetting
import o.katydid.vdom.types.EDirection
import o.katydid.vdom.types.EPreloadHint
//---------------------------------------------------------------------------------------------------------------------
/**
* Virtual node for a `<video>` element.
*/
internal class KatydidVideo<Msg>
: KatydidHtmlElementImpl<Msg> {
constructor(
embeddedContent: KatydidEmbeddedContentBuilderImpl<Msg>,
selector: String?,
key: Any?,
accesskey: Char?,
autoplay: Boolean?,
contenteditable: Boolean?,
controls: Boolean?,
crossorigin: ECorsSetting?,
dir: EDirection?,
draggable: Boolean?,
height: Int?,
hidden: Boolean?,
lang: String?,
loop: Boolean?,
muted: Boolean?,
poster: String?,
preload: EPreloadHint?,
spellcheck: Boolean?,
src: String?,
style: String?,
tabindex: Int?,
title: String?,
translate: Boolean?,
width: Int?,
defineContent: KatydidMediaEmbeddedContentBuilder<Msg>.() -> Unit
) : super(selector, key, accesskey, contenteditable, dir, draggable,
hidden, lang, spellcheck, style, tabindex, title, translate) {
embeddedContent.contentRestrictions.confirmMediaElementAllowed()
setBooleanAttribute("autoplay", autoplay)
setBooleanAttribute("controls", controls)
setAttribute("crossorigin", crossorigin?.toHtmlString())
setNumberAttribute("height", height)
setBooleanAttribute("loop", loop)
setBooleanAttribute("muted", muted)
setAttribute("poster", poster)
setAttribute("preload", preload?.toHtmlString())
setAttribute("src", src)
setNumberAttribute("width", width)
embeddedContent.mediaEmbeddedContent(this, src == null).defineContent()
this.freeze()
}
constructor(
flowContent: KatydidFlowContentBuilderImpl<Msg>,
selector: String?,
key: Any?,
accesskey: Char?,
autoplay: Boolean?,
contenteditable: Boolean?,
controls: Boolean?,
crossorigin: ECorsSetting?,
dir: EDirection?,
draggable: Boolean?,
height: Int?,
hidden: Boolean?,
lang: String?,
loop: Boolean?,
muted: Boolean?,
poster: String?,
preload: EPreloadHint?,
spellcheck: Boolean?,
src: String?,
style: String?,
tabindex: Int?,
title: String?,
translate: Boolean?,
width: Int?,
defineContent: KatydidMediaFlowContentBuilder<Msg>.() -> Unit
) : super(selector, key, accesskey, contenteditable, dir, draggable,
hidden, lang, spellcheck, style, tabindex, title, translate) {
flowContent.contentRestrictions.confirmMediaElementAllowed()
setBooleanAttribute("autoplay", autoplay)
setBooleanAttribute("controls", controls)
setAttribute("crossorigin", crossorigin?.toHtmlString())
setNumberAttribute("height", height)
setBooleanAttribute("loop", loop)
setBooleanAttribute("muted", muted)
setAttribute("poster", poster)
setAttribute("preload", preload?.toHtmlString())
setAttribute("src", src)
setNumberAttribute("width", width)
flowContent.mediaFlowContent(this, src == null).defineContent()
this.freeze()
}
constructor(
phrasingContent: KatydidPhrasingContentBuilderImpl<Msg>,
selector: String?,
key: Any?,
accesskey: Char?,
autoplay: Boolean?,
contenteditable: Boolean?,
controls: Boolean?,
crossorigin: ECorsSetting?,
dir: EDirection?,
draggable: Boolean?,
height: Int?,
hidden: Boolean?,
lang: String?,
loop: Boolean?,
muted: Boolean?,
poster: String?,
preload: EPreloadHint?,
spellcheck: Boolean?,
src: String?,
style: String?,
tabindex: Int?,
title: String?,
translate: Boolean?,
width: Int?,
defineContent: KatydidMediaPhrasingContentBuilder<Msg>.() -> Unit
) : super(selector, key, accesskey, contenteditable, dir, draggable,
hidden, lang, spellcheck, style, tabindex, title, translate) {
phrasingContent.contentRestrictions.confirmMediaElementAllowed()
setBooleanAttribute("autoplay", autoplay)
setBooleanAttribute("controls", controls)
setAttribute("crossorigin", crossorigin?.toHtmlString())
setNumberAttribute("height", height)
setBooleanAttribute("loop", loop)
setBooleanAttribute("muted", muted)
setAttribute("poster", poster)
setAttribute("preload", preload?.toHtmlString())
setAttribute("src", src)
setNumberAttribute("width", width)
phrasingContent.mediaPhrasingContent(this, src == null).defineContent()
this.freeze()
}
////
override val nodeName = "VIDEO"
}
//---------------------------------------------------------------------------------------------------------------------
|
apache-2.0
|
bb42920d8c67f8f55aa34a3a85615634
| 31.755682 | 119 | 0.617693 | 5.323176 | false | false | false | false |
chromeos/vulkanphotobooth
|
app/src/main/java/dev/hadrosaur/vulkanphotobooth/ImageUtils.kt
|
1
|
3913
|
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.hadrosaur.vulkanphotobooth
import android.content.Intent
import android.hardware.camera2.CameraCharacteristics
import android.net.Uri
import android.os.Environment
import android.util.SparseIntArray
import android.view.Surface
import android.widget.Toast
import dev.hadrosaur.vulkanphotobooth.MainActivity.Companion.PHOTOS_DIR
import dev.hadrosaur.vulkanphotobooth.MainActivity.Companion.logd
import java.io.File
import java.text.SimpleDateFormat
import java.util.*
/**
* Various image and ImageReader utilities
*/
/**
* Generate a timestamp to append to saved filenames.
*/
fun generateTimestamp(): String {
val sdf = SimpleDateFormat("yyyy_MM_dd_HH_mm_ss_SSS", Locale.US)
return sdf.format(Date())
}
/**
* Ensure photos directory exists and return path
*/
fun checkPhotosDirectory() : String {
val photosDir = File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
PHOTOS_DIR)
if (!photosDir.exists()) {
val createSuccess = photosDir.mkdir()
if (!createSuccess) {
logd("Photo storage directory DCIM/" + PHOTOS_DIR + " creation failed!!")
} else {
logd("Photo storage directory DCIM/" + PHOTOS_DIR + " did not exist. Created.")
}
}
return photosDir.path
}
/**
* Generate a file path for a GIF file made up of VulkanPhotoBooth + timestamp + .gif
*/
fun generateGifFilepath() : String {
// Create photos directory if needed
checkPhotosDirectory()
val gifFilepath = File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
File.separatorChar + PHOTOS_DIR + File.separatorChar +
"VulkanPhotoBooth" + generateTimestamp() + ".gif")
return gifFilepath.path
}
/**
* Delete all the photos in the default PHOTOS_DIR
*/
fun deleteAllPhotos(activity: MainActivity) {
val photosDir = File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
PHOTOS_DIR)
if (photosDir.exists()) {
for (photo in photosDir.listFiles())
photo.delete()
// Files are deleted, let media scanner know
val scannerIntent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
scannerIntent.data = Uri.fromFile(photosDir)
activity.sendBroadcast(scannerIntent)
activity.runOnUiThread {
Toast.makeText(activity, "All photos deleted", Toast.LENGTH_SHORT).show()
}
logd("All photos in storage directory DCIM/" + PHOTOS_DIR + " deleted.")
}
}
/**
* Calculate rotation needed to save jpg file in the correct orientation
*/
fun getOrientation(params: CameraParams, rotation: Int): Int {
val orientations = SparseIntArray()
orientations.append(Surface.ROTATION_0, 90)
orientations.append(Surface.ROTATION_90, 0)
orientations.append(Surface.ROTATION_180, 270)
orientations.append(Surface.ROTATION_270, 180)
logd("Orientation: sensor: " +
params.characteristics?.get(CameraCharacteristics.SENSOR_ORIENTATION) +
" and current rotation: " + orientations.get(rotation))
val sensorRotation: Int =
params.characteristics?.get(CameraCharacteristics.SENSOR_ORIENTATION) ?: 0
return (orientations.get(rotation) + sensorRotation + 270) % 360
}
|
apache-2.0
|
9b2d703291841a9a86cb802166b372e2
| 31.338843 | 91 | 0.706363 | 4.234848 | false | false | false | false |
panpf/sketch
|
sketch/src/main/java/com/github/panpf/sketch/drawable/internal/AnimatableDrawableWrapper.kt
|
1
|
6440
|
/*
* Copyright (C) 2022 panpf <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.panpf.sketch.drawable.internal
import android.annotation.SuppressLint
import android.graphics.drawable.Animatable
import android.graphics.drawable.Animatable2
import android.graphics.drawable.Drawable
import android.os.Build.VERSION
import android.os.Build.VERSION_CODES
import android.os.Handler
import android.os.Looper
import androidx.appcompat.graphics.drawable.DrawableWrapper
import androidx.vectordrawable.graphics.drawable.Animatable2Compat
import com.github.panpf.sketch.util.requiredMainThread
/**
* Provide unified Callback support for Animatable2, Animatable2Compat, Animatable
*/
@SuppressLint("RestrictedApi")
open class AnimatableDrawableWrapper constructor(
private val animatableDrawable: Drawable,
) : DrawableWrapper(animatableDrawable), Animatable2Compat {
private var callbacks: MutableList<Animatable2Compat.AnimationCallback>? = null
private var callbackMap: HashMap<Animatable2Compat.AnimationCallback, Animatable2.AnimationCallback>? =
null
private val handler by lazy { Handler(Looper.getMainLooper()) }
init {
require(animatableDrawable is Animatable) {
"animatableDrawable must implement the Animatable"
}
}
override fun registerAnimationCallback(callback: Animatable2Compat.AnimationCallback) {
requiredMainThread() // Consistent with AnimatedImageDrawable
when {
VERSION.SDK_INT >= VERSION_CODES.M && animatableDrawable is Animatable2 -> {
val callbackMap = callbackMap
?: HashMap<Animatable2Compat.AnimationCallback, Animatable2.AnimationCallback>().apply {
[email protected] = this
}
if (callbackMap[callback] == null) {
val proxyCallback = object : Animatable2.AnimationCallback() {
override fun onAnimationStart(drawable: Drawable?) {
callback.onAnimationStart(drawable)
}
override fun onAnimationEnd(drawable: Drawable?) {
callback.onAnimationEnd(drawable)
}
}
callbackMap[callback] = proxyCallback
animatableDrawable.registerAnimationCallback(proxyCallback)
}
}
animatableDrawable is Animatable2Compat -> {
animatableDrawable.registerAnimationCallback(callback)
}
else -> {
val callbacks = callbacks
?: mutableListOf<Animatable2Compat.AnimationCallback>().apply {
[email protected] = this
}
if (!callbacks.contains(callback)) {
callbacks.add(callback)
}
}
}
}
override fun unregisterAnimationCallback(callback: Animatable2Compat.AnimationCallback): Boolean =
when {
VERSION.SDK_INT >= VERSION_CODES.M && animatableDrawable is Animatable2 -> {
callbackMap?.get(callback)
?.let { animatableDrawable.unregisterAnimationCallback(it) } == true
}
animatableDrawable is Animatable2Compat -> {
animatableDrawable.unregisterAnimationCallback(callback)
}
else -> {
callbacks?.remove(callback) == true
}
}
override fun clearAnimationCallbacks() {
when {
VERSION.SDK_INT >= VERSION_CODES.M && animatableDrawable is Animatable2 -> {
callbackMap?.clear()
animatableDrawable.clearAnimationCallbacks()
}
animatableDrawable is Animatable2Compat -> {
animatableDrawable.clearAnimationCallbacks()
}
else -> {
callbacks?.clear()
}
}
}
override fun start() {
val animatableDrawable = animatableDrawable as Animatable
if (animatableDrawable.isRunning) {
return
}
animatableDrawable.start()
val callbacks = callbacks
if (callbacks != null && !(VERSION.SDK_INT >= VERSION_CODES.M && animatableDrawable is Animatable2) && animatableDrawable !is Animatable2Compat) {
handler.post {
for (callback in callbacks) {
callback.onAnimationStart(this)
}
}
}
}
override fun stop() {
val animatableDrawable = animatableDrawable as Animatable
if (!animatableDrawable.isRunning) {
return
}
animatableDrawable.stop()
val callbacks = callbacks
if (callbacks != null && !(VERSION.SDK_INT >= VERSION_CODES.M && animatableDrawable is Animatable2) && animatableDrawable !is Animatable2Compat) {
handler.post {
for (callback in callbacks) {
callback.onAnimationEnd(this)
}
}
}
}
override fun isRunning(): Boolean {
val animatableDrawable = animatableDrawable
if (animatableDrawable !is Animatable) {
throw IllegalArgumentException("Drawable must implement the Animatable interface")
}
return animatableDrawable.isRunning
}
@SuppressLint("RestrictedApi")
override fun mutate(): AnimatableDrawableWrapper {
val mutateDrawable = wrappedDrawable.mutate()
return if (mutateDrawable !== wrappedDrawable) {
AnimatableDrawableWrapper(mutateDrawable)
} else {
this
}
}
override fun toString(): String = "AnimatableDrawableWrapper($animatableDrawable)"
}
|
apache-2.0
|
9933bbbe695ecd169e5c1b42fb425876
| 37.801205 | 154 | 0.623447 | 5.508982 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.