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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
jwren/intellij-community
|
plugins/kotlin/groovy/src/org/jetbrains/kotlin/idea/groovy/GroovyGradleBuildScriptSupport.kt
|
1
|
22659
|
// 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.groovy
import com.intellij.openapi.module.Module
import com.intellij.openapi.roots.DependencyScope
import com.intellij.openapi.roots.ExternalLibraryDescriptor
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.jetbrains.kotlin.cli.common.arguments.CliArgumentStringBuilder.buildArgumentString
import org.jetbrains.kotlin.cli.common.arguments.CliArgumentStringBuilder.replaceLanguageFeature
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.idea.compiler.configuration.IdeKotlinVersion
import org.jetbrains.kotlin.idea.configuration.*
import org.jetbrains.kotlin.idea.extensions.gradle.*
import org.jetbrains.kotlin.idea.groovy.inspections.DifferentKotlinGradleVersionInspection
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.idea.util.projectStructure.module
import org.jetbrains.kotlin.idea.util.reformatted
import org.jetbrains.kotlin.psi.psiUtil.getChildrenOfType
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.plugins.groovy.lang.psi.GroovyFile
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrApplicationStatement
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrAssignmentExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression
import org.jetbrains.plugins.groovy.lang.psi.api.util.GrStatementOwner
object GroovyGradleBuildScriptSupport : GradleBuildScriptSupport {
override fun createManipulator(
file: PsiFile,
preferNewSyntax: Boolean,
versionProvider: GradleVersionProvider
): GroovyBuildScriptManipulator? {
if (file !is GroovyFile) {
return null
}
return GroovyBuildScriptManipulator(file, preferNewSyntax, versionProvider)
}
override fun createScriptBuilder(file: PsiFile): SettingsScriptBuilder<*>? {
return if (file is GroovyFile) GroovySettingsScriptBuilder(file) else null
}
}
class GroovyBuildScriptManipulator(
override val scriptFile: GroovyFile,
override val preferNewSyntax: Boolean,
private val versionProvider: GradleVersionProvider
) : GradleBuildScriptManipulator<GroovyFile> {
override fun isApplicable(file: PsiFile) = file is GroovyFile
private val gradleVersion = versionProvider.fetchGradleVersion(scriptFile)
override fun isConfiguredWithOldSyntax(kotlinPluginName: String): Boolean {
val fileText = runReadAction { scriptFile.text }
return containsDirective(fileText, getApplyPluginDirective(kotlinPluginName)) &&
fileText.contains("org.jetbrains.kotlin") &&
fileText.contains("kotlin-stdlib")
}
override fun isConfigured(kotlinPluginExpression: String): Boolean {
val fileText = runReadAction { scriptFile.text }
val pluginsBlockText = runReadAction { scriptFile.getBlockByName("plugins")?.text ?: "" }
return (containsDirective(pluginsBlockText, kotlinPluginExpression)) &&
fileText.contains("org.jetbrains.kotlin") &&
fileText.contains("kotlin-stdlib")
}
override fun configureModuleBuildScript(
kotlinPluginName: String,
kotlinPluginExpression: String,
stdlibArtifactName: String,
version: IdeKotlinVersion,
jvmTarget: String?
): Boolean {
val oldText = scriptFile.text
val useNewSyntax = useNewSyntax(kotlinPluginName, gradleVersion, versionProvider)
if (useNewSyntax) {
scriptFile
.getPluginsBlock()
.addLastExpressionInBlockIfNeeded("$kotlinPluginExpression version '$version'")
scriptFile.getRepositoriesBlock().apply {
val repository = getRepositoryForVersion(version)
val gradleFacade = KotlinGradleFacade.instance
if (repository != null && gradleFacade != null) {
scriptFile.module?.getBuildScriptSettingsPsiFile()?.let {
with(gradleFacade.getManipulator(it)) {
addPluginRepository(repository)
addMavenCentralPluginRepository()
addPluginRepository(DEFAULT_GRADLE_PLUGIN_REPOSITORY)
}
}
}
}
} else {
val applyPluginDirective = getGroovyApplyPluginDirective(kotlinPluginName)
if (!containsDirective(scriptFile.text, applyPluginDirective)) {
val apply = GroovyPsiElementFactory.getInstance(scriptFile.project).createExpressionFromText(applyPluginDirective)
val applyStatement = getApplyStatement(scriptFile)
if (applyStatement != null) {
scriptFile.addAfter(apply, applyStatement)
} else {
val anchorBlock = scriptFile.getBlockByName("plugins") ?: scriptFile.getBlockByName("buildscript")
if (anchorBlock != null) {
scriptFile.addAfter(apply, anchorBlock.parent)
} else {
scriptFile.addAfter(apply, scriptFile.statements.lastOrNull() ?: scriptFile.firstChild)
}
}
}
}
scriptFile.getRepositoriesBlock().apply {
addRepository(version)
addMavenCentralIfMissing()
}
scriptFile.getDependenciesBlock().apply {
addExpressionOrStatementInBlockIfNeeded(
getGroovyDependencySnippet(stdlibArtifactName, !useNewSyntax, gradleVersion),
isStatement = false,
isFirst = false
)
}
if (jvmTarget != null) {
changeKotlinTaskParameter(scriptFile, "jvmTarget", jvmTarget, forTests = false)
changeKotlinTaskParameter(scriptFile, "jvmTarget", jvmTarget, forTests = true)
}
return scriptFile.text != oldText
}
override fun configureProjectBuildScript(kotlinPluginName: String, version: IdeKotlinVersion): Boolean {
if (useNewSyntax(kotlinPluginName, gradleVersion, versionProvider)) return false
val oldText = scriptFile.text
scriptFile.apply {
getBuildScriptBlock().apply {
addFirstExpressionInBlockIfNeeded(VERSION.replace(VERSION_TEMPLATE, version.rawVersion))
}
getBuildScriptRepositoriesBlock().apply {
addRepository(version)
addMavenCentralIfMissing()
}
getBuildScriptDependenciesBlock().apply {
addLastExpressionInBlockIfNeeded(CLASSPATH)
}
}
return oldText != scriptFile.text
}
override fun changeLanguageFeatureConfiguration(
feature: LanguageFeature,
state: LanguageFeature.State,
forTests: Boolean
): PsiElement? {
if (usesNewMultiplatform()) {
state.assertApplicableInMultiplatform()
val kotlinBlock = scriptFile.getKotlinBlock()
val sourceSetsBlock = kotlinBlock.getSourceSetsBlock()
val allBlock = sourceSetsBlock.getBlockOrCreate("all")
allBlock.addLastExpressionInBlockIfNeeded("languageSettings.enableLanguageFeature(\"${feature.name}\")")
return allBlock.statements.lastOrNull()
}
val kotlinVersion = DifferentKotlinGradleVersionInspection.getKotlinPluginVersion(scriptFile)
val featureArgumentString = feature.buildArgumentString(state, kotlinVersion)
val parameterName = "freeCompilerArgs"
return addOrReplaceKotlinTaskParameter(
scriptFile,
parameterName,
"[\"$featureArgumentString\"]",
forTests
) { insideKotlinOptions ->
val prefix = if (insideKotlinOptions) "kotlinOptions." else ""
val newText = text.replaceLanguageFeature(
feature,
state,
kotlinVersion,
prefix = "$prefix$parameterName = [",
postfix = "]"
)
replaceWithStatementFromText(newText)
}
}
override fun changeLanguageVersion(version: String, forTests: Boolean): PsiElement? =
changeKotlinTaskParameter(scriptFile, "languageVersion", version, forTests)
override fun changeApiVersion(version: String, forTests: Boolean): PsiElement? =
changeKotlinTaskParameter(scriptFile, "apiVersion", version, forTests)
override fun addKotlinLibraryToModuleBuildScript(
targetModule: Module?,
scope: DependencyScope,
libraryDescriptor: ExternalLibraryDescriptor
) {
val dependencyString = String.format(
"%s \"%s:%s:%s\"",
scope.toGradleCompileScope(scriptFile.isAndroidModule()),
libraryDescriptor.libraryGroupId,
libraryDescriptor.libraryArtifactId,
libraryDescriptor.maxVersion
)
if (targetModule != null && usesNewMultiplatform()) {
scriptFile
.getKotlinBlock()
.getSourceSetsBlock()
.getBlockOrCreate(targetModule.name.takeLastWhile { it != '.' })
.getDependenciesBlock()
.addLastExpressionInBlockIfNeeded(dependencyString)
} else {
scriptFile.getDependenciesBlock().apply {
addLastExpressionInBlockIfNeeded(dependencyString)
}
}
}
override fun getKotlinStdlibVersion(): String? {
val versionProperty = "\$kotlin_version"
scriptFile.getBlockByName("buildScript")?.let {
if (it.text.contains("ext.kotlin_version = ")) {
return versionProperty
}
}
val dependencies = scriptFile.getBlockByName("dependencies")?.statements
val stdlibArtifactPrefix = "org.jetbrains.kotlin:kotlin-stdlib:"
dependencies?.forEach { dependency ->
val dependencyText = dependency.text
val startIndex = dependencyText.indexOf(stdlibArtifactPrefix) + stdlibArtifactPrefix.length
val endIndex = dependencyText.length - 1
if (startIndex != -1 && endIndex != -1) {
return dependencyText.substring(startIndex, endIndex)
}
}
return null
}
private fun addPluginRepositoryExpression(expression: String) {
scriptFile
.getBlockOrPrepend("pluginManagement")
.getBlockOrCreate("repositories")
.addLastExpressionInBlockIfNeeded(expression)
}
override fun addMavenCentralPluginRepository() {
addPluginRepositoryExpression("mavenCentral()")
}
override fun addPluginRepository(repository: RepositoryDescription) {
addPluginRepositoryExpression(repository.toGroovyRepositorySnippet())
}
override fun addResolutionStrategy(pluginId: String) {
scriptFile
.getBlockOrPrepend("pluginManagement")
.getBlockOrCreate("resolutionStrategy")
.getBlockOrCreate("eachPlugin")
.addLastStatementInBlockIfNeeded(
"""
if (requested.id.id == "$pluginId") {
useModule("org.jetbrains.kotlin:kotlin-gradle-plugin:${'$'}{requested.version}")
}
""".trimIndent()
)
}
private fun GrClosableBlock.addParameterAssignment(
parameterName: String,
defaultValue: String,
replaceIt: GrStatement.(Boolean) -> GrStatement
) {
statements.firstOrNull { stmt ->
(stmt as? GrAssignmentExpression)?.lValue?.text == parameterName
}?.let { stmt ->
stmt.replaceIt(false)
} ?: addLastExpressionInBlockIfNeeded("$parameterName = $defaultValue")
}
private fun String.extractTextFromQuotes(quoteCharacter: Char): String? {
val quoteIndex = indexOf(quoteCharacter)
if (quoteIndex != -1) {
val lastQuoteIndex = lastIndexOf(quoteCharacter)
return if (lastQuoteIndex > quoteIndex) substring(quoteIndex + 1, lastQuoteIndex) else null
}
return null
}
private fun String.extractTextFromQuotes(): String = extractTextFromQuotes('\'') ?: extractTextFromQuotes('"') ?: this
private fun addOrReplaceKotlinTaskParameter(
gradleFile: GroovyFile,
parameterName: String,
defaultValue: String,
forTests: Boolean,
replaceIt: GrStatement.(Boolean) -> GrStatement
): PsiElement? {
if (usesNewMultiplatform()) {
val kotlinBlock = gradleFile.getKotlinBlock()
val kotlinTargets = kotlinBlock.getBlockOrCreate("targets")
val targetNames = mutableListOf<String>()
fun GrStatement.handleTarget(targetExpectedText: String) {
if (this is GrMethodCallExpression && invokedExpression.text == targetExpectedText) {
val targetNameArgument = argumentList.expressionArguments.getOrNull(1)?.text
if (targetNameArgument != null) {
targetNames += targetNameArgument.extractTextFromQuotes()
}
}
}
for (target in kotlinTargets.statements) {
target.handleTarget("fromPreset")
}
for (target in kotlinBlock.statements) {
target.handleTarget("targets.fromPreset")
}
val configureBlock = kotlinTargets.getBlockOrCreate("configure")
val factory = GroovyPsiElementFactory.getInstance(kotlinTargets.project)
val argumentList = factory.createArgumentListFromText(
targetNames.joinToString(prefix = "([", postfix = "])", separator = ", ")
)
configureBlock.getStrictParentOfType<GrMethodCallExpression>()!!.argumentList.replaceWithArgumentList(argumentList)
val kotlinOptions = configureBlock.getBlockOrCreate("tasks.getByName(compilations.main.compileKotlinTaskName).kotlinOptions")
kotlinOptions.addParameterAssignment(parameterName, defaultValue, replaceIt)
return kotlinOptions.parent.parent
}
val kotlinBlock: GrClosableBlock =
if (gradleFile.isAndroidModule() && gradleFile.getBlockByName("android") != null) {
gradleFile.getBlockOrCreate("tasks.withType(org.jetbrains.kotlin.gradle.tasks.${if (forTests) "KotlinTest" else "KotlinCompile"}).all")
} else {
gradleFile.getBlockOrCreate(if (forTests) "compileTestKotlin" else "compileKotlin")
}
for (stmt in kotlinBlock.statements) {
if ((stmt as? GrAssignmentExpression)?.lValue?.text == "kotlinOptions.$parameterName") {
return stmt.replaceIt(true)
}
}
kotlinBlock.getBlockOrCreate("kotlinOptions").addParameterAssignment(parameterName, defaultValue, replaceIt)
return kotlinBlock.parent
}
private fun changeKotlinTaskParameter(
gradleFile: GroovyFile,
parameterName: String,
parameterValue: String,
forTests: Boolean
): PsiElement? {
return addOrReplaceKotlinTaskParameter(
gradleFile, parameterName, "\"$parameterValue\"", forTests
) { insideKotlinOptions ->
if (insideKotlinOptions) {
replaceWithStatementFromText("kotlinOptions.$parameterName = \"$parameterValue\"")
} else {
replaceWithStatementFromText("$parameterName = \"$parameterValue\"")
}
}
}
private fun getGroovyDependencySnippet(
artifactName: String,
withVersion: Boolean,
gradleVersion: GradleVersionInfo
): String {
val configuration = gradleVersion.scope("implementation", versionProvider)
return "$configuration \"org.jetbrains.kotlin:$artifactName${if (withVersion) ":\$kotlin_version" else ""}\""
}
private fun getApplyPluginDirective(pluginName: String) = "apply plugin: '$pluginName'"
private fun containsDirective(fileText: String, directive: String): Boolean {
return fileText.contains(directive)
|| fileText.contains(directive.replace("\"", "'"))
|| fileText.contains(directive.replace("'", "\""))
}
private fun getApplyStatement(file: GroovyFile): GrApplicationStatement? =
file.getChildrenOfType<GrApplicationStatement>().find { it.invokedExpression.text == "apply" }
private fun GrClosableBlock.addRepository(version: IdeKotlinVersion): Boolean {
val repository = getRepositoryForVersion(version)
val snippet = when {
repository != null -> repository.toGroovyRepositorySnippet()
!isRepositoryConfigured(text) -> "$MAVEN_CENTRAL\n"
else -> return false
}
return addLastExpressionInBlockIfNeeded(snippet)
}
private fun GroovyFile.isAndroidModule() = module?.getBuildSystemType() == BuildSystemType.AndroidGradle
private fun GrStatementOwner.getBuildScriptBlock() = getBlockOrCreate("buildscript") { newBlock ->
val pluginsBlock = getBlockByName("plugins") ?: return@getBlockOrCreate false
addBefore(newBlock, pluginsBlock.parent)
true
}
private fun GrStatementOwner.getBuildScriptRepositoriesBlock(): GrClosableBlock =
getBuildScriptBlock().getRepositoriesBlock()
private fun GrStatementOwner.getBuildScriptDependenciesBlock(): GrClosableBlock =
getBuildScriptBlock().getDependenciesBlock()
private fun GrClosableBlock.addMavenCentralIfMissing(): Boolean =
if (!isRepositoryConfigured(text)) addLastExpressionInBlockIfNeeded(MAVEN_CENTRAL) else false
private fun GrStatementOwner.getRepositoriesBlock() = getBlockOrCreate("repositories")
private fun GrStatementOwner.getDependenciesBlock(): GrClosableBlock = getBlockOrCreate("dependencies")
private fun GrStatementOwner.getKotlinBlock(): GrClosableBlock = getBlockOrCreate("kotlin")
private fun GrStatementOwner.getSourceSetsBlock(): GrClosableBlock = getBlockOrCreate("sourceSets")
private fun GrClosableBlock.addOrReplaceExpression(snippet: String, predicate: (GrStatement) -> Boolean) {
statements.firstOrNull(predicate)?.let { stmt ->
stmt.replaceWithStatementFromText(snippet)
return
}
addLastExpressionInBlockIfNeeded(snippet)
}
private fun getGroovyApplyPluginDirective(pluginName: String) = "apply plugin: '$pluginName'"
private fun GrStatement.replaceWithStatementFromText(snippet: String): GrStatement {
val newStatement = GroovyPsiElementFactory.getInstance(project).createExpressionFromText(snippet)
newStatement.reformatted()
return replaceWithStatement(newStatement)
}
companion object {
private const val VERSION_TEMPLATE = "\$VERSION$"
private val VERSION = String.format("ext.kotlin_version = '%s'", VERSION_TEMPLATE)
private const val GRADLE_PLUGIN_ID = "kotlin-gradle-plugin"
private val CLASSPATH = "classpath \"$KOTLIN_GROUP_ID:$GRADLE_PLUGIN_ID:\$kotlin_version\""
private fun PsiElement.getBlockByName(name: String): GrClosableBlock? {
return getChildrenOfType<GrMethodCallExpression>()
.filter { it.closureArguments.isNotEmpty() }
.find { it.invokedExpression.text == name }
?.let { it.closureArguments[0] }
}
fun GrStatementOwner.getBlockOrCreate(
name: String,
customInsert: GrStatementOwner.(newBlock: PsiElement) -> Boolean = { false }
): GrClosableBlock {
var block = getBlockByName(name)
if (block == null) {
val factory = GroovyPsiElementFactory.getInstance(project)
val newBlock = factory.createExpressionFromText("$name{\n}\n")
if (!customInsert(newBlock)) {
addAfter(newBlock, statements.lastOrNull() ?: firstChild)
}
block = getBlockByName(name)!!
}
return block
}
fun GrStatementOwner.getBlockOrPrepend(name: String) = getBlockOrCreate(name) { newBlock ->
addAfter(newBlock, null)
true
}
fun GrStatementOwner.getPluginsBlock() = getBlockOrCreate("plugins") { newBlock ->
addAfter(newBlock, getBlockByName("buildscript"))
true
}
fun GrClosableBlock.addLastExpressionInBlockIfNeeded(expressionText: String): Boolean =
addExpressionOrStatementInBlockIfNeeded(expressionText, isStatement = false, isFirst = false)
fun GrClosableBlock.addLastStatementInBlockIfNeeded(expressionText: String): Boolean =
addExpressionOrStatementInBlockIfNeeded(expressionText, isStatement = true, isFirst = false)
private fun GrClosableBlock.addFirstExpressionInBlockIfNeeded(expressionText: String): Boolean =
addExpressionOrStatementInBlockIfNeeded(expressionText, isStatement = false, isFirst = true)
private fun GrClosableBlock.addExpressionOrStatementInBlockIfNeeded(text: String, isStatement: Boolean, isFirst: Boolean): Boolean {
if (statements.any { StringUtil.equalsIgnoreWhitespaces(it.text, text) }) return false
val psiFactory = GroovyPsiElementFactory.getInstance(project)
val newStatement = if (isStatement) psiFactory.createStatementFromText(text) else psiFactory.createExpressionFromText(text)
newStatement.reformatted()
if (!isFirst && statements.isNotEmpty()) {
val lastStatement = statements[statements.size - 1]
if (lastStatement != null) {
addAfter(newStatement, lastStatement)
}
} else {
if (firstChild != null) {
addAfter(newStatement, firstChild)
}
}
return true
}
}
}
|
apache-2.0
|
a9d9f703d6a8df6ed4fd581d5a9c64ae
| 42.912791 | 151 | 0.66115 | 5.997618 | false | false | false | false |
jwren/intellij-community
|
plugins/markdown/core/src/org/intellij/plugins/markdown/extensions/common/plantuml/PlantUMLCodeGeneratingProvider.kt
|
1
|
3151
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.plugins.markdown.extensions.common.plantuml
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.registry.Registry
import org.intellij.markdown.ast.ASTNode
import org.intellij.plugins.markdown.MarkdownBundle
import org.intellij.plugins.markdown.extensions.MarkdownCodeFenceCacheableProvider
import org.intellij.plugins.markdown.extensions.MarkdownExtensionWithDownloadableFiles
import org.intellij.plugins.markdown.extensions.MarkdownExtensionWithDownloadableFiles.FileEntry
import org.intellij.plugins.markdown.ui.preview.html.MarkdownCodeFencePluginCacheCollector
import org.jetbrains.annotations.ApiStatus
import java.io.File
import java.io.IOException
@ApiStatus.Internal
class PlantUMLCodeGeneratingProvider(
collector: MarkdownCodeFencePluginCacheCollector? = null
): MarkdownCodeFenceCacheableProvider(collector), MarkdownExtensionWithDownloadableFiles {
override val externalFiles: Iterable<String>
get() = ownFiles
override val filesToDownload: Iterable<FileEntry>
get() = dowloadableFiles
override fun isApplicable(language: String): Boolean {
return isEnabled && isAvailable && (language == "puml" || language == "plantuml")
}
override fun generateHtml(language: String, raw: String, node: ASTNode): String {
val key = getUniqueFile(language, raw, "png").toFile()
cacheDiagram(key, raw)
collector?.addAliveCachedFile(this, key)
return "<img src=\"${key.toURI()}\"/>"
}
override val displayName: String
get() = MarkdownBundle.message("markdown.extensions.plantuml.display.name")
override val description: String
get() = MarkdownBundle.message("markdown.extensions.plantuml.description")
override val id: String = "PlantUMLLanguageExtension"
override fun beforeCleanup() {
PlantUMLJarManager.getInstance().dropCache()
}
private fun cacheDiagram(path: File, text: String) {
if (!path.exists()) {
generateDiagram(text, path)
}
}
@Throws(IOException::class)
private fun generateDiagram(text: CharSequence, diagramPath: File) {
var innerText: String = text.toString().trim()
if (!innerText.startsWith("@startuml")) {
innerText = "@startuml\n$innerText"
}
if (!innerText.endsWith("@enduml")) {
innerText += "\n@enduml"
}
FileUtil.createParentDirs(diagramPath)
storeDiagram(innerText, diagramPath)
}
companion object {
const val jarFilename = "plantuml.jar"
private val ownFiles = listOf(jarFilename)
private val dowloadableFiles = listOf(FileEntry(jarFilename) { Registry.stringValue("markdown.plantuml.download.link") })
private fun storeDiagram(source: String, file: File) {
try {
file.outputStream().buffered().use { PlantUMLJarManager.getInstance().generateImage(source, it) }
} catch (exception: Exception) {
thisLogger().warn("Cannot save diagram PlantUML diagram. ", exception)
}
}
}
}
|
apache-2.0
|
97cfce5224dd5c362228e42a97ebc66a
| 37.426829 | 158 | 0.75246 | 4.298772 | false | false | false | false |
jwren/intellij-community
|
plugins/kotlin/uast/uast-kotlin/src/org/jetbrains/uast/kotlin/internal/kotlinInternalUastUtils.kt
|
1
|
29158
|
// 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.uast.kotlin
import com.intellij.openapi.diagnostic.Attachment
import com.intellij.openapi.diagnostic.ControlFlowException
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.psi.*
import com.intellij.psi.impl.cache.TypeInfo
import com.intellij.psi.impl.compiled.ClsTypeElementImpl
import com.intellij.psi.impl.compiled.SignatureParsing
import com.intellij.psi.impl.compiled.StubBuildingVisitor
import com.intellij.psi.util.PsiTypesUtil
import com.intellij.util.SmartList
import org.jetbrains.kotlin.asJava.*
import org.jetbrains.kotlin.backend.jvm.serialization.DisabledDescriptorMangler.signatureString
import org.jetbrains.kotlin.builtins.isBuiltinFunctionalTypeOrSubtype
import org.jetbrains.kotlin.codegen.signature.BothSignatureWriter
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.annotations.AnnotationArgumentVisitor
import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor
import org.jetbrains.kotlin.descriptors.impl.EnumEntrySyntheticClassDescriptor
import org.jetbrains.kotlin.descriptors.impl.TypeAliasConstructorDescriptor
import org.jetbrains.kotlin.descriptors.synthetic.SyntheticMemberDescriptor
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.load.java.lazy.descriptors.LazyJavaPackageFragment
import org.jetbrains.kotlin.load.java.sam.SamAdapterDescriptor
import org.jetbrains.kotlin.load.kotlin.KotlinJvmBinaryPackageSourceElement
import org.jetbrains.kotlin.load.kotlin.TypeMappingMode
import org.jetbrains.kotlin.metadata.ProtoBuf
import org.jetbrains.kotlin.metadata.deserialization.getExtensionOrNull
import org.jetbrains.kotlin.metadata.jvm.JvmProtoBuf
import org.jetbrains.kotlin.metadata.jvm.deserialization.JvmMemberSignature
import org.jetbrains.kotlin.metadata.jvm.deserialization.JvmProtoBufUtil
import org.jetbrains.kotlin.name.StandardClassIds
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.parents
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.ImportedFromObjectCallableDescriptor
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.inference.model.TypeVariableTypeConstructor
import org.jetbrains.kotlin.resolve.calls.model.ArgumentMatch
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.calls.tower.NewResolvedCallImpl
import org.jetbrains.kotlin.resolve.calls.util.isFakePsiElement
import org.jetbrains.kotlin.resolve.constants.*
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.references.ReferenceAccess
import org.jetbrains.kotlin.resolve.sam.SamConstructorDescriptor
import org.jetbrains.kotlin.resolve.source.getPsi
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedCallableMemberDescriptor
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedClassDescriptor
import org.jetbrains.kotlin.synthetic.SamAdapterExtensionFunctionDescriptor
import org.jetbrains.kotlin.synthetic.SyntheticJavaPropertyDescriptor
import org.jetbrains.kotlin.type.MapPsiToAsmDesc
import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.types.typeUtil.builtIns
import org.jetbrains.kotlin.types.typeUtil.contains
import org.jetbrains.kotlin.types.typeUtil.isInterface
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import org.jetbrains.uast.*
import org.jetbrains.uast.kotlin.internal.KotlinUastTypeMapper
import org.jetbrains.uast.kotlin.psi.UastDescriptorLightMethod
import org.jetbrains.uast.kotlin.psi.UastFakeLightMethod
import org.jetbrains.uast.kotlin.psi.UastFakeLightPrimaryConstructor
import java.text.StringCharacterIterator
val kotlinUastPlugin: UastLanguagePlugin by lz {
UastLanguagePlugin.getInstances().find { it.language == KotlinLanguage.INSTANCE }
?: KotlinUastLanguagePlugin()
}
internal fun KotlinType.toPsiType(
source: UElement?,
element: KtElement,
typeOwnerKind: TypeOwnerKind,
boxed: Boolean
): PsiType =
toPsiType(source?.getParentOfType<UDeclaration>(false)?.javaPsi as? PsiModifierListOwner, element, typeOwnerKind, boxed)
internal fun KotlinType.toPsiType(
containingLightDeclaration: PsiModifierListOwner?,
context: KtElement,
typeOwnerKind: TypeOwnerKind,
boxed: Boolean
): PsiType {
if (this.isError) return UastErrorType
(constructor.declarationDescriptor as? TypeAliasDescriptor)?.let { typeAlias ->
return typeAlias.expandedType.toPsiType(containingLightDeclaration, context, typeOwnerKind, boxed)
}
if (contains { type -> type.constructor is TypeVariableTypeConstructor }) {
return UastErrorType
}
(constructor.declarationDescriptor as? TypeParameterDescriptor)?.let { typeParameter ->
(typeParameter.containingDeclaration.toSource()?.getMaybeLightElement() as? PsiTypeParameterListOwner)
?.typeParameterList?.typeParameters?.getOrNull(typeParameter.index)
?.let { return PsiTypesUtil.getClassType(it) }
return CommonSupertypes.commonSupertype(typeParameter.upperBounds)
.toPsiType(containingLightDeclaration, context, typeOwnerKind, boxed)
}
if (arguments.isEmpty()) {
val typeFqName = this.constructor.declarationDescriptor?.fqNameSafe
fun PsiPrimitiveType.orBoxed() = if (boxed) getBoxedType(context) else this
val psiType = when (typeFqName) {
StandardClassIds.Int.asSingleFqName() -> PsiType.INT.orBoxed()
StandardClassIds.Long.asSingleFqName() -> PsiType.LONG.orBoxed()
StandardClassIds.Short.asSingleFqName() -> PsiType.SHORT.orBoxed()
StandardClassIds.Boolean.asSingleFqName() -> PsiType.BOOLEAN.orBoxed()
StandardClassIds.Byte.asSingleFqName() -> PsiType.BYTE.orBoxed()
StandardClassIds.Char.asSingleFqName() -> PsiType.CHAR.orBoxed()
StandardClassIds.Double.asSingleFqName() -> PsiType.DOUBLE.orBoxed()
StandardClassIds.Float.asSingleFqName() -> PsiType.FLOAT.orBoxed()
StandardClassIds.Unit.asSingleFqName() -> {
if (typeOwnerKind == TypeOwnerKind.DECLARATION && context is KtNamedFunction)
PsiType.VOID.orBoxed()
else null
}
StandardClassIds.String.asSingleFqName() -> PsiType.getJavaLangString(context.manager, context.resolveScope)
else -> {
when (val typeConstructor = this.constructor) {
is IntegerValueTypeConstructor ->
TypeUtils.getDefaultPrimitiveNumberType(typeConstructor)
.toPsiType(containingLightDeclaration, context, typeOwnerKind, boxed)
is IntegerLiteralTypeConstructor ->
typeConstructor.getApproximatedType().toPsiType(containingLightDeclaration, context, typeOwnerKind, boxed)
else -> null
}
}
}
if (psiType != null) return psiType.annotate(buildAnnotationProvider(this, containingLightDeclaration ?: context))
}
if (this.containsLocalTypes()) return UastErrorType
val project = context.project
val languageVersionSettings = project.getService(KotlinUastResolveProviderService::class.java)
.getLanguageVersionSettings(context)
val signatureWriter = BothSignatureWriter(BothSignatureWriter.Mode.TYPE)
val typeMappingMode = if (boxed) TypeMappingMode.GENERIC_ARGUMENT_UAST else TypeMappingMode.DEFAULT_UAST
val approximatedType =
TypeApproximator(this.builtIns, languageVersionSettings).approximateDeclarationType(this, true)
KotlinUastTypeMapper.mapType(approximatedType, signatureWriter, typeMappingMode)
val signature = StringCharacterIterator(signatureWriter.toString())
val javaType = SignatureParsing.parseTypeString(signature, StubBuildingVisitor.GUESSING_MAPPER)
val typeInfo = TypeInfo.fromString(javaType, false)
val typeText = TypeInfo.createTypeText(typeInfo) ?: return UastErrorType
val psiTypeParent: PsiElement = containingLightDeclaration ?: context
if (psiTypeParent.containingFile == null) {
Logger.getInstance("org.jetbrains.uast.kotlin.KotlinInternalUastUtils")
.error(
"initialising ClsTypeElementImpl with null-file parent = $psiTypeParent (of ${psiTypeParent.javaClass}) " +
"containing class = ${psiTypeParent.safeAs<PsiMethod>()?.containingClass}, " +
"containing lightDeclaration = $containingLightDeclaration (of ${containingLightDeclaration?.javaClass}), " +
"context = $context (of ${context.javaClass})"
)
}
return ClsTypeElementImpl(psiTypeParent, typeText, '\u0000').type
}
private fun renderAnnotation(annotation: AnnotationDescriptor): String? {
val fqn = annotation.fqName?.asString() ?: return null
val valueArguments = annotation.allValueArguments
val valueesList = SmartList<String>().apply {
for ((k, v) in valueArguments.entries) {
add("${k.identifier} = ${renderConstantValue(v)}")
}
}
return "@$fqn(${valueesList.joinToString(", ")})"
}
private fun renderConstantValue(value: ConstantValue<*>?): String? = value?.accept(object : AnnotationArgumentVisitor<String?, String?> {
override fun visitLongValue(value: LongValue, data: String?): String = value.value.toString()
override fun visitIntValue(value: IntValue, data: String?): String = value.value.toString()
override fun visitErrorValue(value: ErrorValue?, data: String?): String? = null
override fun visitShortValue(value: ShortValue, data: String?): String = value.value.toString()
override fun visitByteValue(value: ByteValue, data: String?): String = value.value.toString()
override fun visitDoubleValue(value: DoubleValue, data: String?): String = value.value.toString()
override fun visitFloatValue(value: FloatValue, data: String?): String = value.value.toString()
override fun visitBooleanValue(value: BooleanValue, data: String?): String = value.value.toString()
override fun visitCharValue(value: CharValue, data: String?): String = "'${value.value}'"
override fun visitStringValue(value: StringValue, data: String?): String = "\"${value.value}\""
override fun visitNullValue(value: NullValue?, data: String?): String = "null"
override fun visitEnumValue(value: EnumValue, data: String?): String =
value.value.run { first.asSingleFqName().asString() + "." + second.asString() }
override fun visitArrayValue(value: ArrayValue, data: String?): String =
value.value.mapNotNull { renderConstantValue(it) }.joinToString(", ", "{", "}")
override fun visitAnnotationValue(value: AnnotationValue, data: String?): String? = renderAnnotation(value.value)
override fun visitKClassValue(value: KClassValue, data: String?): String = value.value.toString() + ".class"
override fun visitUByteValue(value: UByteValue, data: String?): String = value.value.toString()
override fun visitUShortValue(value: UShortValue, data: String?): String = value.value.toString()
override fun visitUIntValue(value: UIntValue, data: String?): String = value.value.toString()
override fun visitULongValue(value: ULongValue, data: String?): String = value.value.toString()
}, null)
private fun buildAnnotationProvider(ktType: KotlinType, context: PsiElement): TypeAnnotationProvider {
val result = SmartList<PsiAnnotation>()
val psiElementFactory = PsiElementFactory.getInstance(context.project)
for (annotation in ktType.annotations) {
val annotationText = renderAnnotation(annotation) ?: continue
try {
result.add(psiElementFactory.createAnnotationFromText(annotationText, context))
} catch (e: Exception) {
if (e is ControlFlowException) throw e
Logger.getInstance("org.jetbrains.uast.kotlin.KotlinInternalUastUtils")
.error("failed to create annotation from text", e, Attachment("annotationText.txt", annotationText))
}
}
if (result.isEmpty()) return TypeAnnotationProvider.EMPTY
return TypeAnnotationProvider.Static.create(result.toArray(PsiAnnotation.EMPTY_ARRAY))
}
internal fun KtTypeReference?.toPsiType(source: UElement, boxed: Boolean = false): PsiType {
if (this == null) return UastErrorType
return (analyze()[BindingContext.TYPE, this] ?: return UastErrorType).toPsiType(source, this, this.typeOwnerKind, boxed)
}
@Suppress("NAME_SHADOWING")
internal fun KtElement.analyze(): BindingContext {
if (!canAnalyze()) return BindingContext.EMPTY
return project.getService(KotlinUastResolveProviderService::class.java)
?.getBindingContextIfAny(this) ?: BindingContext.EMPTY
}
internal fun KtExpression.getExpectedType(): KotlinType? = analyze()[BindingContext.EXPECTED_EXPRESSION_TYPE, this]
internal fun KtTypeReference.getType(): KotlinType? = analyze()[BindingContext.TYPE, this]
internal fun KotlinType.getFunctionalInterfaceType(
source: UElement,
element: KtElement,
typeOwnerKind: TypeOwnerKind,
): PsiType? =
takeIf { it.isInterface() && !it.isBuiltinFunctionalTypeOrSubtype }?.toPsiType(source, element, typeOwnerKind, false)
internal fun KotlinULambdaExpression.getFunctionalInterfaceType(): PsiType? {
val parent = sourcePsi.parent
if (parent is KtBinaryExpressionWithTypeRHS)
return parent.right?.getType()?.getFunctionalInterfaceType(this, sourcePsi, parent.right!!.typeOwnerKind)
if (parent is KtValueArgument) run {
val callExpression = parent.parents.take(2).firstIsInstanceOrNull<KtCallExpression>() ?: return@run
val resolvedCall = callExpression.getResolvedCall(callExpression.analyze()) ?: return@run
// NewResolvedCallImpl can be used as a marker meaning that this code is working under *new* inference
if (resolvedCall is NewResolvedCallImpl) {
val samConvertedArgument = resolvedCall.getExpectedTypeForSamConvertedArgument(parent)
// Same as if in old inference we would get SamDescriptor
if (samConvertedArgument != null) {
val type = getTypeByArgument(resolvedCall, parent) ?: return@run
return type.getFunctionalInterfaceType(this, sourcePsi, callExpression.typeOwnerKind)
}
}
val candidateDescriptor = resolvedCall.candidateDescriptor as? SyntheticMemberDescriptor<*> ?: return@run
when (candidateDescriptor) {
is SamConstructorDescriptor ->
return candidateDescriptor.returnType?.getFunctionalInterfaceType(this, sourcePsi, callExpression.typeOwnerKind)
is SamAdapterDescriptor<*>, is SamAdapterExtensionFunctionDescriptor -> {
val type = getTypeByArgument(resolvedCall, parent) ?: return@run
return type.getFunctionalInterfaceType(this, sourcePsi, callExpression.typeOwnerKind)
}
}
}
return sourcePsi.getExpectedType()?.getFunctionalInterfaceType(this, sourcePsi, sourcePsi.typeOwnerKind)
}
internal fun resolveToPsiMethod(context: KtElement): PsiMethod? =
context.getResolvedCall(context.analyze())?.resultingDescriptor?.let { resolveToPsiMethod(context, it) }
internal fun resolveToPsiMethod(
context: KtElement,
descriptor: DeclarationDescriptor,
source: PsiElement? = descriptor.toSource()
): PsiMethod? {
if (descriptor is TypeAliasConstructorDescriptor) {
return resolveToPsiMethod(context, descriptor.underlyingConstructorDescriptor)
}
// For synthetic members in enum classes, `source` points to their containing enum class.
if (source is KtClass && source.isEnum() && descriptor is SimpleFunctionDescriptor) {
val lightClass = source.toLightClass() ?: return null
lightClass.methods.find { it.name == descriptor.name.identifier }?.let { return it }
}
// Default primary constructor
if (descriptor is ConstructorDescriptor && descriptor.isPrimary
&& source is KtClassOrObject && source.primaryConstructor == null
&& source.secondaryConstructors.isEmpty()
) {
val lightClass = source.toLightClass() ?: return null
lightClass.constructors.firstOrNull()?.let { return it }
if (source.isLocal) {
return UastFakeLightPrimaryConstructor(source, lightClass)
}
return null
}
return when (source) {
is KtFunction ->
if (source.isLocal)
getContainingLightClass(source)?.let { UastFakeLightMethod(source, it) }
else // UltraLightMembersCreator.createMethods() returns nothing for JVM-invisible methods, so fake it if we get null here
LightClassUtil.getLightClassMethod(source) ?: getContainingLightClass(source)?.let { UastFakeLightMethod(source, it) }
is PsiMethod -> source
null -> resolveDeserialized(context, descriptor) as? PsiMethod
else -> null
}
}
internal fun resolveToClassIfConstructorCallImpl(ktCallElement: KtCallElement, source: UElement): PsiElement? =
when (val resultingDescriptor = ktCallElement.getResolvedCall(ktCallElement.analyze())?.descriptorForResolveViaConstructor()) {
is ConstructorDescriptor -> {
ktCallElement.calleeExpression?.let { resolveToDeclarationImpl(it, resultingDescriptor.constructedClass) }
}
is SamConstructorDescriptor -> {
(resultingDescriptor.returnType
?.getFunctionalInterfaceType(source, ktCallElement, ktCallElement.typeOwnerKind) as? PsiClassType)?.resolve()
}
else -> null
}
// In new inference, SAM constructor is substituted with a function descriptor, so we use candidate descriptor to preserve behavior
private fun ResolvedCall<*>.descriptorForResolveViaConstructor(): CallableDescriptor? {
return if (this is NewResolvedCallImpl) candidateDescriptor else resultingDescriptor
}
internal fun resolveToDeclarationImpl(sourcePsi: KtExpression): PsiElement? =
when (sourcePsi) {
is KtSimpleNameExpression ->
sourcePsi.analyze()[BindingContext.REFERENCE_TARGET, sourcePsi]
?.let { resolveToDeclarationImpl(sourcePsi, it) }
else ->
sourcePsi.getResolvedCall(sourcePsi.analyze())?.resultingDescriptor
?.let { descriptor -> resolveToDeclarationImpl(sourcePsi, descriptor) }
}
fun resolveToDeclarationImpl(sourcePsi: KtExpression, declarationDescriptor: DeclarationDescriptor): PsiElement? {
declarationDescriptor.toSource()?.getMaybeLightElement(sourcePsi)?.let { return it }
@Suppress("NAME_SHADOWING")
var declarationDescriptor = declarationDescriptor
if (declarationDescriptor is ImportedFromObjectCallableDescriptor<*>) {
declarationDescriptor = declarationDescriptor.callableFromObject
}
if (declarationDescriptor is SyntheticJavaPropertyDescriptor) {
declarationDescriptor = when (sourcePsi.readWriteAccess()) {
ReferenceAccess.WRITE, ReferenceAccess.READ_WRITE ->
declarationDescriptor.setMethod ?: declarationDescriptor.getMethod
ReferenceAccess.READ -> declarationDescriptor.getMethod
}
}
if (declarationDescriptor is PackageViewDescriptor) {
return JavaPsiFacade.getInstance(sourcePsi.project).findPackage(declarationDescriptor.fqName.asString())
}
resolveToPsiClass({ sourcePsi.toUElement() }, declarationDescriptor, sourcePsi)?.let {
return if (declarationDescriptor is EnumEntrySyntheticClassDescriptor) {
// An enum entry, a subtype of enum class, is resolved to the enclosing enum class if the mapped type is used.
// However, the expected resolution result is literally the enum entry, not the enum class.
// From the resolved enum class (as PsiClass), we can search for the enum entry (as PsiField).
it.findFieldByName(declarationDescriptor.name.asString(), false)
} else it
}
if (declarationDescriptor is DeclarationDescriptorWithSource) {
declarationDescriptor.source.getPsi()?.takeIf { it.isValid }?.let { it.getMaybeLightElement() ?: it }?.let { return it }
}
if (declarationDescriptor is ValueParameterDescriptor) {
val parentDeclaration = resolveToDeclarationImpl(sourcePsi, declarationDescriptor.containingDeclaration)
if (parentDeclaration is PsiClass && parentDeclaration.isAnnotationType) {
parentDeclaration.findMethodsByName(declarationDescriptor.name.asString(), false).firstOrNull()?.let { return it }
}
}
if (declarationDescriptor is CallableMemberDescriptor && declarationDescriptor.kind == CallableMemberDescriptor.Kind.FAKE_OVERRIDE) {
declarationDescriptor.overriddenDescriptors.asSequence()
.mapNotNull { resolveToDeclarationImpl(sourcePsi, it) }
.firstOrNull()
?.let { return it }
}
resolveDeserialized(sourcePsi, declarationDescriptor, sourcePsi.readWriteAccess())?.let { return it }
return null
}
private fun resolveContainingDeserializedClass(context: KtElement, memberDescriptor: DeserializedCallableMemberDescriptor): PsiClass? {
return when (val containingDeclaration = memberDescriptor.containingDeclaration) {
is LazyJavaPackageFragment -> {
val binaryPackageSourceElement = containingDeclaration.source as? KotlinJvmBinaryPackageSourceElement ?: return null
val containingBinaryClass = binaryPackageSourceElement.getContainingBinaryClass(memberDescriptor) ?: return null
val containingClassQualifiedName = containingBinaryClass.classId.asSingleFqName().asString()
JavaPsiFacade.getInstance(context.project).findClass(containingClassQualifiedName, context.resolveScope) ?: return null
}
is DeserializedClassDescriptor -> {
val declaredPsiType = containingDeclaration.defaultType.toPsiType(
null as PsiModifierListOwner?,
context,
TypeOwnerKind.DECLARATION,
boxed = false
)
(declaredPsiType as? PsiClassType)?.resolve() ?: return null
}
else -> return null
}
}
private fun resolveToPsiClass(uElement: () -> UElement?, declarationDescriptor: DeclarationDescriptor, context: KtElement): PsiClass? =
when (declarationDescriptor) {
is ConstructorDescriptor -> declarationDescriptor.returnType
is ClassDescriptor -> declarationDescriptor.defaultType
is TypeParameterDescriptor -> declarationDescriptor.defaultType
is TypeAliasDescriptor -> declarationDescriptor.expandedType
else -> null
}?.toPsiType(uElement.invoke(), context, TypeOwnerKind.DECLARATION, boxed = true).let { PsiTypesUtil.getPsiClass(it) }
private fun DeclarationDescriptor.toSource(): PsiElement? {
return try {
DescriptorToSourceUtils.getEffectiveReferencedDescriptors(this)
.asSequence()
.mapNotNull { DescriptorToSourceUtils.getSourceFromDescriptor(it) }
.find { it.isValid }
} catch (e: ProcessCanceledException) {
throw e
} catch (e: Exception) {
Logger.getInstance("DeclarationDescriptor.toSource").error(e)
null
}
}
private fun resolveDeserialized(
context: KtElement,
descriptor: DeclarationDescriptor,
accessHint: ReferenceAccess? = null
): PsiModifierListOwner? {
if (descriptor !is DeserializedCallableMemberDescriptor) return null
val psiClass = resolveContainingDeserializedClass(context, descriptor) ?: return null
val proto = descriptor.proto
val nameResolver = descriptor.nameResolver
val typeTable = descriptor.typeTable
return when (proto) {
is ProtoBuf.Function -> {
psiClass.getMethodBySignature(
JvmProtoBufUtil.getJvmMethodSignature(proto, nameResolver, typeTable)
?: getMethodSignatureFromDescriptor(context, descriptor)
) ?: UastDescriptorLightMethod(descriptor as SimpleFunctionDescriptor, psiClass, context) // fake Java-invisible methods
}
is ProtoBuf.Constructor -> {
val signature = JvmProtoBufUtil.getJvmConstructorSignature(proto, nameResolver, typeTable)
?: getMethodSignatureFromDescriptor(context, descriptor)
?: return null
psiClass.constructors.firstOrNull { it.matchesDesc(signature.desc) }
}
is ProtoBuf.Property -> {
JvmProtoBufUtil.getJvmFieldSignature(proto, nameResolver, typeTable, false)
?.let { signature -> psiClass.fields.firstOrNull { it.name == signature.name } }
?.let { return it }
val propertySignature = proto.getExtensionOrNull(JvmProtoBuf.propertySignature)
if (propertySignature != null) {
with(propertySignature) {
when {
hasSetter() && accessHint?.isWrite == true -> setter // treat += etc. as write as was done elsewhere
hasGetter() && accessHint?.isRead != false -> getter
else -> null // it should have been handled by the previous case
}
}?.let { methodSignature ->
psiClass.getMethodBySignature(
nameResolver.getString(methodSignature.name),
if (methodSignature.hasDesc()) nameResolver.getString(methodSignature.desc) else null
)
}?.let { return it }
} else if (proto.hasName()) {
// Property without a Property signature, looks like a @JvmField
val name = nameResolver.getString(proto.name)
psiClass.fields
.firstOrNull { it.name == name }
?.let { return it }
}
getMethodSignatureFromDescriptor(context, descriptor)
?.let { signature -> psiClass.getMethodBySignature(signature) }
?.let { return it }
}
else -> null
}
}
private fun PsiClass.getMethodBySignature(methodSignature: JvmMemberSignature?) = methodSignature?.let { signature ->
getMethodBySignature(signature.name, signature.desc)
}
private fun PsiClass.getMethodBySignature(name: String, descr: String?) =
methods.firstOrNull { method -> method.name == name && descr?.let { method.matchesDesc(it) } ?: true }
private fun PsiMethod.matchesDesc(desc: String) = desc == buildString {
parameterList.parameters.joinTo(this, separator = "", prefix = "(", postfix = ")") { MapPsiToAsmDesc.typeDesc(it.type) }
append(MapPsiToAsmDesc.typeDesc(returnType ?: PsiType.VOID))
}
private fun getMethodSignatureFromDescriptor(context: KtElement, descriptor: CallableDescriptor): JvmMemberSignature? {
fun PsiType.raw() = (this as? PsiClassType)?.rawType() ?: PsiPrimitiveType.getUnboxedType(this) ?: this
fun KotlinType.toPsiType() = toPsiType(null as PsiModifierListOwner?, context, TypeOwnerKind.DECLARATION, boxed = false).raw()
val originalDescriptor = descriptor.original
val receiverType = originalDescriptor.extensionReceiverParameter?.type?.toPsiType()
val parameterTypes = listOfNotNull(receiverType) + originalDescriptor.valueParameters.map { it.type.toPsiType() }
val returnType = originalDescriptor.returnType?.toPsiType() ?: PsiType.VOID
if (parameterTypes.any { !it.isValid } || !returnType.isValid) {
return null
}
val desc = parameterTypes.joinToString("", prefix = "(", postfix = ")") { MapPsiToAsmDesc.typeDesc(it) } +
MapPsiToAsmDesc.typeDesc(returnType)
return JvmMemberSignature.Method(descriptor.name.asString(), desc)
}
private fun KotlinType.containsLocalTypes(visited: MutableSet<KotlinType> = hashSetOf()): Boolean {
if (!visited.add(this)) return false
val typeDeclarationDescriptor = this.constructor.declarationDescriptor
if (typeDeclarationDescriptor is ClassDescriptor && DescriptorUtils.isLocal(typeDeclarationDescriptor)) {
return true
}
return arguments.any { !it.isStarProjection && it.type.containsLocalTypes(visited) }
|| constructor.supertypes.any { it.containsLocalTypes(visited) }
}
private fun getTypeByArgument(
resolvedCall: ResolvedCall<*>,
argument: ValueArgument
): KotlinType? {
val parameterInfo = (resolvedCall.getArgumentMapping(argument) as? ArgumentMatch)?.valueParameter ?: return null
return parameterInfo.type
}
|
apache-2.0
|
46da19d6d8144ceacbf98614523c426e
| 51.067857 | 158 | 0.727005 | 5.235769 | false | false | false | false |
jwren/intellij-community
|
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/search/ideaExtensions/KotlinDeclarationScopeOptimizer.kt
|
1
|
2804
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.search.ideaExtensions
import com.intellij.lang.jvm.JvmModifier
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiModifierListOwner
import com.intellij.psi.search.*
import com.intellij.psi.util.parentsOfType
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.idea.search.excludeKotlinSources
import org.jetbrains.kotlin.idea.search.fileScope
import org.jetbrains.kotlin.idea.util.psiPackage
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.psiUtil.isPrivate
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class KotlinDeclarationScopeOptimizer : ScopeOptimizer {
override fun getRestrictedUseScope(element: PsiElement): SearchScope? {
val declaration = element.unwrapped?.safeAs<KtDeclaration>() ?: return null
val isPrivateDeclaration = declaration.isPrivate() ||
element.safeAs<PsiModifierListOwner>()?.hasModifier(JvmModifier.PRIVATE) == true
val privateClass = declaration.parentsOfType<KtClassOrObject>(withSelf = true).find(KtClassOrObject::isPrivate)
if (privateClass == null && !isPrivateDeclaration) return null
val containingFile = declaration.containingKtFile
val fileScope = containingFile.fileScope()
if (declaration !is KtClassOrObject && isPrivateDeclaration || privateClass?.isTopLevel() != true) return fileScope
// it is possible to create new kotlin private class from java - so have to look up in the same module as well
val minimalScope = findModuleOrLibraryScope(containingFile) ?: element.useScope
val scopeWithoutKotlin = minimalScope.excludeKotlinSources(containingFile.project)
val psiPackage = containingFile.psiPackage
val jvmScope = if (psiPackage != null && scopeWithoutKotlin is GlobalSearchScope)
PackageScope.packageScope(psiPackage, /* includeSubpackages = */ false, scopeWithoutKotlin)
else
scopeWithoutKotlin
return fileScope.union(jvmScope)
}
}
private fun findModuleOrLibraryScope(file: KtFile): GlobalSearchScope? {
val project = file.project
val projectFileIndex = ProjectFileIndex.SERVICE.getInstance(project)
val virtualFile = file.virtualFile ?: return null
val moduleScope = projectFileIndex.getModuleForFile(virtualFile)?.moduleScope
return when {
moduleScope != null -> moduleScope
projectFileIndex.isInLibrary(virtualFile) -> ProjectScope.getLibrariesScope(project)
else -> null
}
}
|
apache-2.0
|
9ec2c00ec7116588f0e00f2bc4d3b2ac
| 49.089286 | 123 | 0.765335 | 5.007143 | false | false | false | false |
jwren/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeToMutableCollectionFix.kt
|
1
|
4806
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.core.replaced
import org.jetbrains.kotlin.idea.project.builtIns
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.resolve.calls.util.getType
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.KotlinType
class ChangeToMutableCollectionFix(property: KtProperty, private val type: String) : KotlinQuickFixAction<KtProperty>(property) {
override fun getText() = KotlinBundle.message("fix.change.to.mutable.type", "Mutable$type")
override fun getFamilyName() = text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val property = element ?: return
val context = property.analyze(BodyResolveMode.PARTIAL)
val type = property.initializer?.getType(context) ?: return
applyFix(property, type)
editor?.caretModel?.moveToOffset(property.endOffset)
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction<KtProperty>? {
val element = Errors.NO_SET_METHOD.cast(diagnostic).psiElement as? KtArrayAccessExpression ?: return null
val arrayExpr = element.arrayExpression ?: return null
val context = arrayExpr.analyze(BodyResolveMode.PARTIAL)
val type = arrayExpr.getType(context) ?: return null
if (!type.isReadOnlyListOrMap(element.builtIns)) return null
val property = arrayExpr.mainReference?.resolve() as? KtProperty ?: return null
if (!isApplicable(property)) return null
val typeName = type.constructor.declarationDescriptor?.name?.asString() ?: return null
return ChangeToMutableCollectionFix(property, typeName)
}
private fun KotlinType.isReadOnlyListOrMap(builtIns: KotlinBuiltIns): Boolean {
val leftDefaultType = constructor.declarationDescriptor?.defaultType ?: return false
return leftDefaultType in listOf(builtIns.list.defaultType, builtIns.map.defaultType)
}
fun isApplicable(property: KtProperty): Boolean {
return property.isLocal && property.initializer != null
}
fun applyFix(property: KtProperty, type: KotlinType) {
val initializer = property.initializer ?: return
val fqName = initializer.resolveToCall()?.resultingDescriptor?.fqNameOrNull()?.asString()
val psiFactory = KtPsiFactory(property)
val mutableOf = mutableConversionMap[fqName]
if (mutableOf != null) {
(initializer as? KtCallExpression)?.calleeExpression?.replaced(psiFactory.createExpression(mutableOf)) ?: return
} else {
val builtIns = property.builtIns
val toMutable = when (type.constructor) {
builtIns.list.defaultType.constructor -> "toMutableList"
builtIns.set.defaultType.constructor -> "toMutableSet"
builtIns.map.defaultType.constructor -> "toMutableMap"
else -> null
} ?: return
val dotQualifiedExpression = initializer.replaced(
psiFactory.createExpressionByPattern("($0).$1()", initializer, toMutable)
) as KtDotQualifiedExpression
val receiver = dotQualifiedExpression.receiverExpression
val deparenthesize = KtPsiUtil.deparenthesize(dotQualifiedExpression.receiverExpression)
if (deparenthesize != null && receiver != deparenthesize) receiver.replace(deparenthesize)
}
property.typeReference?.also { it.replace(psiFactory.createType("Mutable${it.text}")) }
}
private const val COLLECTIONS = "kotlin.collections"
private val mutableConversionMap = mapOf(
"$COLLECTIONS.listOf" to "mutableListOf",
"$COLLECTIONS.setOf" to "mutableSetOf",
"$COLLECTIONS.mapOf" to "mutableMapOf"
)
}
}
|
apache-2.0
|
46acfa5e40d1b24da8390736296f7bce
| 51.25 | 158 | 0.699334 | 5.322259 | false | false | false | false |
jwren/intellij-community
|
platform/remote-core/src/credentialStore/CredentialAttributes.kt
|
1
|
3326
|
// 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.credentialStore
import com.intellij.openapi.util.NlsSafe
import com.intellij.util.text.nullize
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.Contract
const val SERVICE_NAME_PREFIX = "IntelliJ Platform"
/**
* The combined name of your service and name of service that requires authentication.
*
* Can be specified in:
* * reverse-DNS format: `com.apple.facetime: registrationV1`
* * prefixed human-readable format: `IntelliJ Platform Settings Repository — github.com`, where `IntelliJ Platform` is a required prefix. **You must always use this prefix**.
*/
fun generateServiceName(subsystem: String, key: String) = "$SERVICE_NAME_PREFIX $subsystem — $key"
/**
* Consider using [generateServiceName] to generate [serviceName].
*
* [requestor] is deprecated (never use it in a new code).
*/
data class CredentialAttributes(
val serviceName: String,
val userName: String? = null,
val requestor: Class<*>? = null,
val isPasswordMemoryOnly: Boolean = false,
val cacheDeniedItems: Boolean = true
) {
@JvmOverloads
constructor(serviceName: String,
userName: String? = null,
requestor: Class<*>? = null,
isPasswordMemoryOnly: Boolean = false)
: this(serviceName, userName, requestor, isPasswordMemoryOnly, true)
}
/**
* Pair of user and password.
*
* @param user Account name ("John") or path to SSH key file ("/Users/john/.ssh/id_rsa").
* @param password Can be empty.
*/
class Credentials(@NlsSafe user: String?, @NlsSafe val password: OneTimeString? = null) {
constructor(@NlsSafe user: String?, @NlsSafe password: String?) : this(user, password?.let(::OneTimeString))
constructor(@NlsSafe user: String?, password: CharArray?) : this(user, password?.let { OneTimeString(it) })
constructor(@NlsSafe user: String?, password: ByteArray?) : this(user, password?.let { OneTimeString(password) })
val userName = user.nullize()
@NlsSafe
fun getPasswordAsString() = password?.toString()
override fun equals(other: Any?) = other is Credentials && userName == other.userName && password == other.password
override fun hashCode() = (userName?.hashCode() ?: 0) * 37 + (password?.hashCode() ?: 0)
override fun toString() = "userName: $userName, password size: ${password?.length ?: 0}"
companion object {
val ACCESS_TO_KEY_CHAIN_DENIED = Credentials(null, null as OneTimeString?)
val CANNOT_UNLOCK_KEYCHAIN = Credentials(null, null as OneTimeString?)
}
}
/** @deprecated Use [CredentialAttributes] instead. */
@Deprecated("Never use it in a new code.")
@ApiStatus.ScheduledForRemoval
@Suppress("FunctionName", "DeprecatedCallableAddReplaceWith")
fun CredentialAttributes(requestor: Class<*>, userName: String?) = CredentialAttributes(requestor.name, userName, requestor)
@Contract("null -> false")
fun Credentials?.isFulfilled() = this != null && userName != null && !password.isNullOrEmpty()
@Contract("null -> false")
fun Credentials?.hasOnlyUserName() = this != null && userName != null && password.isNullOrEmpty()
fun Credentials?.isEmpty() = this == null || (userName == null && password.isNullOrEmpty())
|
apache-2.0
|
deb50abb4caac16978401ff97fa40d6b
| 39.52439 | 175 | 0.720349 | 4.221093 | false | false | false | false |
jwren/intellij-community
|
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/ClassToObjectPromotionConversion.kt
|
6
|
3256
|
// 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.nj2k.conversions
import com.intellij.psi.PsiClass
import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext
import org.jetbrains.kotlin.nj2k.declarationList
import org.jetbrains.kotlin.nj2k.getCompanion
import org.jetbrains.kotlin.nj2k.psi
import org.jetbrains.kotlin.nj2k.tree.*
class ClassToObjectPromotionConversion(context: NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) {
override fun applyToElement(element: JKTreeElement): JKTreeElement {
if (element is JKClass && element.classKind == JKClass.ClassKind.CLASS) {
val companion = element.getCompanion() ?: return recurse(element)
val allDeclarationsMatches = element.declarationList.all {
when (it) {
is JKKtPrimaryConstructor -> it.parameters.isEmpty() && it.block.statements.isEmpty()
is JKKtInitDeclaration ->
it.block.statements.all { statement ->
when (statement) {
is JKDeclarationStatement -> statement.declaredStatements.isEmpty()
else -> false
}
}
is JKClass -> true
else -> false
}
}
if (allDeclarationsMatches && !element.hasInheritors()) {
companion.invalidate()
element.invalidate()
return recurse(
JKClass(
element.name,
element.inheritance,
JKClass.ClassKind.OBJECT,
element.typeParameterList,
companion.classBody.also { body ->
body.handleDeclarationsModifiers()
body.declarations += element.classBody.declarations.filter {
//TODO preserve order
it is JKClass && it.classKind != JKClass.ClassKind.COMPANION
}.map { it.detached(element.classBody) }
},
element.annotationList,
element.otherModifierElements,
element.visibilityElement,
JKModalityModifierElement(Modality.FINAL)
).withFormattingFrom(element)
)
}
}
return recurse(element)
}
private fun JKClassBody.handleDeclarationsModifiers() {
for (declaration in declarations) {
if (declaration !is JKVisibilityOwner) continue
if (declaration.visibility == Visibility.PROTECTED) {
//in old j2k it is internal. should it be private instead?
declaration.visibility = Visibility.INTERNAL
}
}
}
private fun JKClass.hasInheritors(): Boolean {
val psi = psi<PsiClass>() ?: return false
return context.converter.converterServices.oldServices.referenceSearcher.hasInheritors(psi)
}
}
|
apache-2.0
|
7aed338c098acd5e01599bd1d0fbfcba
| 42.426667 | 120 | 0.559582 | 5.856115 | false | false | false | false |
DSteve595/Put.io
|
app/src/main/java/com/stevenschoen/putionew/PutioTransfersService.kt
|
1
|
2737
|
package com.stevenschoen.putionew
import android.app.Service
import android.content.Intent
import android.os.Binder
import android.os.IBinder
import com.stevenschoen.putionew.model.responses.TransfersListResponse
import com.stevenschoen.putionew.model.transfers.PutioTransfer
import io.reactivex.Observable
import io.reactivex.Single
import io.reactivex.disposables.Disposable
import io.reactivex.subjects.BehaviorSubject
import java.util.*
import java.util.concurrent.TimeUnit
class PutioTransfersService : Service() {
private val binder = TransfersServiceBinder()
private var stopTask: TimerTask? = null
inner class TransfersServiceBinder : Binder() {
val service: PutioTransfersService
get() = this@PutioTransfersService
}
private val utils by lazy {
(application as PutioApplication).putioUtils
}
private val transfersSubject = BehaviorSubject.create<List<PutioTransfer>>()
val transfers: Observable<List<PutioTransfer>>
get() = transfersSubject
private lateinit var transfersRefreshObservable: Observable<TransfersListResponse>
private var transfersRefreshSubscription: Disposable? = null
override fun onCreate() {
super.onCreate()
val transfersFetchObservable = Single.defer {
utils!!.restInterface.transfers()
}
transfersRefreshObservable = transfersFetchObservable
.retryWhen { it.delay(5, TimeUnit.SECONDS) }
.repeatWhen { it.delay(8, TimeUnit.SECONDS) }
.toObservable()
startRefreshing()
}
private fun startRefreshing() {
stopRefreshing()
transfersRefreshSubscription = transfersRefreshObservable
.subscribe { response ->
val responseTransfers = response.transfers.reversed()
val oldTransfers = transfersSubject.value
if (oldTransfers == null || oldTransfers != responseTransfers) {
transfersSubject.onNext(responseTransfers)
}
}
}
private fun stopRefreshing() {
transfersRefreshSubscription?.let {
it.dispose()
transfersRefreshSubscription = null
}
}
fun refreshNow() = startRefreshing()
override fun onStartCommand(intent: Intent, flags: Int, startId: Int) = Service.START_NOT_STICKY
override fun onBind(intent: Intent): IBinder? {
if (stopTask != null) stopTask!!.cancel()
return binder
}
override fun onRebind(intent: Intent) {
super.onRebind(intent)
if (stopTask != null) stopTask!!.cancel()
}
override fun onUnbind(intent: Intent): Boolean {
stopTask = object : TimerTask() {
override fun run() {
stopSelf()
}
}
Timer().schedule(stopTask, 5000)
return true
}
override fun onDestroy() {
stopRefreshing()
super.onDestroy()
}
}
|
mit
|
ff505cd20019e8ca351dae9cae4adbe1
| 26.37 | 98 | 0.716113 | 4.561667 | false | false | false | false |
lytefast/flex-input
|
flexinput/src/main/java/com/lytefast/flexinput/adapters/FileListAdapter.kt
|
1
|
9534
|
package com.lytefast.flexinput.adapters
import android.animation.AnimatorInflater
import android.animation.AnimatorSet
import android.content.ContentResolver
import android.net.Uri
import android.os.AsyncTask
import android.provider.MediaStore
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.MimeTypeMap
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.facebook.drawee.backends.pipeline.Fresco
import com.facebook.drawee.view.SimpleDraweeView
import com.lytefast.flexinput.R
import com.lytefast.flexinput.model.Attachment
import com.lytefast.flexinput.utils.FileUtils.getFileSize
import com.lytefast.flexinput.utils.FileUtils.toAttachment
import com.lytefast.flexinput.utils.SelectionCoordinator
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import java.io.File
import java.util.*
/**
* [RecyclerView.Adapter] that knows how to display files from the media store.
*
* @author Sam Shih
*/
class FileListAdapter(private val contentResolver: ContentResolver,
selectionCoordinator: SelectionCoordinator<*, Attachment<File>>)
: RecyclerView.Adapter<FileListAdapter.ViewHolder>() {
private val selectionCoordinator: SelectionCoordinator<*, in Attachment<File>> =
selectionCoordinator.bind(this)
private var files: List<Attachment<File>> = listOf()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.view_file_item, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) =
holder.bind(files[position])
override fun onBindViewHolder(holder: ViewHolder, position: Int, payloads: MutableList<Any>) {
payloads
.firstOrNull { it is SelectionCoordinator.SelectionEvent<*> }
?.let { it as? SelectionCoordinator.SelectionEvent<*> }
?.also {
holder.setSelected(it.isSelected, isAnimationRequested = true)
return
}
super.onBindViewHolder(holder, position, payloads)
}
override fun getItemCount(): Int = files.size
suspend fun load(root: File) = withContext(Dispatchers.IO) {
val files = flattenFileList(root)
files.sortWith(
compareByDescending<Attachment<File>> { it.lastModified }
.then(compareBy { it.uri })
)
withContext(Dispatchers.Main) {
[email protected] = files
[email protected]()
}
}
@Suppress("MemberVisibilityCanBePrivate")
open inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val shrinkAnim: AnimatorSet
private val growAnim: AnimatorSet
protected var thumbIv: SimpleDraweeView = itemView.findViewById(R.id.thumb_iv)
protected var typeIv: ImageView = itemView.findViewById(R.id.type_iv)
protected var fileNameTv: TextView = itemView.findViewById(R.id.file_name_tv)
protected var fileSubtitleTv: TextView = itemView.findViewById(R.id.file_subtitle_tv)
private var attachmentFile: Attachment<File>? = null
init {
this.itemView.isClickable = true
this.itemView.setOnClickListener {
setSelected(selectionCoordinator.toggleItem(attachmentFile, adapterPosition), true)
}
//region Perf: Load animations once
this.shrinkAnim = AnimatorInflater.loadAnimator(
itemView.context, R.animator.selection_shrink) as AnimatorSet
this.shrinkAnim.setTarget(thumbIv)
this.growAnim = AnimatorInflater.loadAnimator(
itemView.context, R.animator.selection_grow) as AnimatorSet
this.growAnim.setTarget(thumbIv)
//endregion
}
fun bind(fileAttachment: Attachment<File>) {
this.attachmentFile = fileAttachment
setSelected(selectionCoordinator.isSelected(fileAttachment, adapterPosition), false)
val file = fileAttachment.data
if (file != null) {
fileNameTv.text = file.name
fileSubtitleTv.text = file.getFileSize()
} else {
fileNameTv.text = null
fileSubtitleTv.text = null
}
// Set defaults
thumbIv.setImageURI(null as Uri?, thumbIv.context)
typeIv.visibility = View.GONE
val mimeType = file?.getMimeType()
if (mimeType.isNullOrEmpty()) return
thumbIv.setImageURI(Uri.fromFile(file), thumbIv.context)
when {
mimeType.startsWith("image") -> {
typeIv.setImageResource(R.drawable.ic_image_24dp)
typeIv.visibility = View.VISIBLE
bindThumbIvWithImage(file)
}
mimeType.startsWith("video") -> {
typeIv.setImageResource(R.drawable.ic_movie_24dp)
typeIv.visibility = View.VISIBLE
bindThumbIvWithImage(file)
}
mimeType.startsWith("audio") -> {
typeIv.setImageResource(R.drawable.ic_audio_24dp)
typeIv.visibility = View.VISIBLE
bindThumbIvWithImage(file)
}
}
}
private fun bindThumbIvWithImage(file: File) {
contentResolver.query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
arrayOf(MediaStore.Images.Media._ID, MediaStore.Images.Media.MINI_THUMB_MAGIC),
"${MediaStore.Images.Media.DATA}=?",
arrayOf(file.path), null/* sortOrder */)
?.use { cursor ->
if (!cursor.moveToFirst()) return
val imageId = cursor.getLong(0)
val thumbMagic = cursor.getLong(1)
if (thumbMagic == 0L) {
// Force thumbnail generation
val genThumb = MediaStore.Images.Thumbnails.getThumbnail(
contentResolver, imageId, MediaStore.Images.Thumbnails.MINI_KIND, null)
genThumb?.recycle()
}
contentResolver.query(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
arrayOf(MediaStore.Images.Thumbnails._ID),
"${MediaStore.Images.Thumbnails.IMAGE_ID}=?",
arrayOf(java.lang.Long.toString(imageId)),
null)
?.use { thumbnailCursor ->
if (!thumbnailCursor.moveToFirst()) return
val thumbId = thumbnailCursor.getString(0)
thumbIv.controller = Fresco.newDraweeControllerBuilder()
.setOldController(thumbIv.controller)
.setUri(Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, thumbId))
.setTapToRetryEnabled(true)
.build()
}
}
}
fun setSelected(isSelected: Boolean, isAnimationRequested: Boolean) {
itemView.isSelected = isSelected
fun scaleImage(animation: AnimatorSet) {
animation.start()
if (!isAnimationRequested) {
animation.end()
}
}
if (isSelected) {
if (thumbIv.scaleX == 1.0f) scaleImage(shrinkAnim)
} else {
if (thumbIv.scaleX != 1.0f) scaleImage(growAnim)
}
}
}
private fun File.getMimeType(): String? {
var type: String? = null
val fileName = this.name
val extension = fileName.substring(fileName.lastIndexOf('.') + 1)
if (!TextUtils.isEmpty(extension)) {
type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension)
}
return type
}
private fun flattenFileList(parentDir: File): MutableList<Attachment<File>> {
fun File.getFileList() = listFiles()?.asSequence() ?: emptySequence()
val flattenedFileList = ArrayList<Attachment<File>>()
val files = LinkedList<File>()
files.addAll(parentDir.getFileList())
while (!files.isEmpty()) {
val file = files.remove()
if (file.isHidden) {
continue
}
if (file.isDirectory) {
files.addAll(file.getFileList())
} else {
flattenedFileList.add(file.toAttachment())
}
}
return flattenedFileList
}
private val Attachment<File>.lastModified
get() = data?.lastModified() ?: 0
private class FileLoaderTask(val adapter: FileListAdapter) : AsyncTask<File, Boolean, List<Attachment<File>>>() {
override fun doInBackground(vararg rootFiles: File): List<Attachment<File>> {
val files = flattenFileList(rootFiles[0])
files.sortWith(
compareByDescending<Attachment<File>> { it.lastModified }
.then(compareBy { it.uri })
)
return files
}
override fun onPostExecute(files: List<Attachment<File>>) {
this.adapter.files = files
this.adapter.notifyDataSetChanged()
}
private fun flattenFileList(parentDir: File): MutableList<Attachment<File>> {
fun File.getFileList() = listFiles()?.asSequence() ?: emptySequence()
val flattenedFileList = ArrayList<Attachment<File>>()
val files = LinkedList<File>()
files.addAll(parentDir.getFileList())
while (!files.isEmpty()) {
val file = files.remove()
if (file.isHidden) {
continue
}
if (file.isDirectory) {
files.addAll(file.getFileList())
} else {
flattenedFileList.add(file.toAttachment())
}
}
return flattenedFileList
}
private val Attachment<File>.lastModified
get() = data?.lastModified() ?: 0
}
}
|
mit
|
1c4a4147a9610b7c5eceb18f11d9e77a
| 32.107639 | 115 | 0.667506 | 4.608023 | false | false | false | false |
androidx/androidx
|
compose/foundation/foundation/src/androidAndroidTest/kotlin/androidx/compose/foundation/text/selection/SelectionHandlesTest.kt
|
3
|
10514
|
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.foundation.text.selection
import android.graphics.Bitmap
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.view.PixelCopy
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import androidx.activity.compose.setContent
import androidx.annotation.RequiresApi
import androidx.compose.foundation.TestActivity
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.text.style.ResolvedTextDirection
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.MediumTest
import androidx.test.filters.SdkSuppress
import androidx.test.filters.SmallTest
import com.google.common.truth.Truth.assertThat
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
@MediumTest
@RunWith(AndroidJUnit4::class)
class SelectionHandlesTest {
@Suppress("DEPRECATION")
@get:Rule
val rule = androidx.test.rule.ActivityTestRule(TestActivity::class.java)
private lateinit var activity: TestActivity
private val HANDLE_COLOR = Color(0xFF4286F4)
// Due to the rendering effect of captured bitmap from activity, if we want the pixels from the
// corners, we need a little bit offset from the edges of the bitmap.
private val OFFSET_FROM_EDGE = 5
private val selectionLtrHandleDirection = Selection(
start = Selection.AnchorInfo(
direction = ResolvedTextDirection.Ltr,
offset = 0,
selectableId = 0
),
end = Selection.AnchorInfo(
direction = ResolvedTextDirection.Ltr,
offset = 0,
selectableId = 0
),
handlesCrossed = false
)
private val selectionRtlHandleDirection = Selection(
start = Selection.AnchorInfo(
direction = ResolvedTextDirection.Ltr,
offset = 0,
selectableId = 0
),
end = Selection.AnchorInfo(
direction = ResolvedTextDirection.Ltr,
offset = 0,
selectableId = 0
),
handlesCrossed = true
)
@Before
fun setup() {
activity = rule.activity
activity.hasFocusLatch.await(5, TimeUnit.SECONDS)
}
@Test
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.O)
fun StartSelectionHandle_left_pointing() {
rule.runOnUiThreadIR {
activity.setContent {
DefaultSelectionHandle(
modifier = Modifier,
isStartHandle = true,
direction = selectionLtrHandleDirection.start.direction,
handlesCrossed = selectionLtrHandleDirection.handlesCrossed
)
}
}
val bitmap = rule.waitAndScreenShot()
val pixelLeftTop = bitmap.getPixel(OFFSET_FROM_EDGE, OFFSET_FROM_EDGE)
val pixelRightTop = bitmap.getPixel(bitmap.width - OFFSET_FROM_EDGE, OFFSET_FROM_EDGE)
assertThat(pixelLeftTop).isNotEqualTo(HANDLE_COLOR.toArgb())
assertThat(pixelRightTop).isEqualTo(HANDLE_COLOR.toArgb())
}
@Test
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.O)
fun StartSelectionHandle_right_pointing() {
rule.runOnUiThreadIR {
activity.setContent {
DefaultSelectionHandle(
modifier = Modifier,
isStartHandle = true,
direction = selectionRtlHandleDirection.start.direction,
handlesCrossed = selectionRtlHandleDirection.handlesCrossed
)
}
}
val bitmap = rule.waitAndScreenShot()
val pixelLeftTop = bitmap.getPixel(OFFSET_FROM_EDGE, OFFSET_FROM_EDGE)
val pixelRightTop = bitmap.getPixel(bitmap.width - OFFSET_FROM_EDGE, OFFSET_FROM_EDGE)
assertThat(pixelLeftTop).isEqualTo(HANDLE_COLOR.toArgb())
assertThat(pixelRightTop).isNotEqualTo(HANDLE_COLOR.toArgb())
}
@Test
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.O)
fun EndSelectionHandle_right_pointing() {
rule.runOnUiThreadIR {
activity.setContent {
DefaultSelectionHandle(
modifier = Modifier,
isStartHandle = false,
direction = selectionLtrHandleDirection.end.direction,
handlesCrossed = selectionLtrHandleDirection.handlesCrossed
)
}
}
val bitmap = rule.waitAndScreenShot()
val pixelLeftTop = bitmap.getPixel(OFFSET_FROM_EDGE, OFFSET_FROM_EDGE)
val pixelRightTop = bitmap.getPixel(bitmap.width - OFFSET_FROM_EDGE, OFFSET_FROM_EDGE)
assertThat(pixelLeftTop).isEqualTo(HANDLE_COLOR.toArgb())
assertThat(pixelRightTop).isNotEqualTo(HANDLE_COLOR.toArgb())
}
@Test
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.O)
fun EndSelectionHandle_left_pointing() {
rule.runOnUiThreadIR {
activity.setContent {
DefaultSelectionHandle(
modifier = Modifier,
isStartHandle = false,
direction = selectionRtlHandleDirection.end.direction,
handlesCrossed = selectionRtlHandleDirection.handlesCrossed
)
}
}
val bitmap = rule.waitAndScreenShot()
val pixelLeftTop = bitmap.getPixel(OFFSET_FROM_EDGE, OFFSET_FROM_EDGE)
val pixelRightTop = bitmap.getPixel(bitmap.width - OFFSET_FROM_EDGE, OFFSET_FROM_EDGE)
assertThat(pixelLeftTop).isNotEqualTo(HANDLE_COLOR.toArgb())
assertThat(pixelRightTop).isEqualTo(HANDLE_COLOR.toArgb())
}
@Test
@SmallTest
fun isHandleLtrDirection_ltr_handles_not_cross_return_true() {
assertThat(
isHandleLtrDirection(direction = ResolvedTextDirection.Ltr, areHandlesCrossed = false)
).isTrue()
}
@Test
@SmallTest
fun isHandleLtrDirection_ltr_handles_cross_return_false() {
assertThat(
isHandleLtrDirection(direction = ResolvedTextDirection.Ltr, areHandlesCrossed = true)
).isFalse()
}
@Test
@SmallTest
fun isHandleLtrDirection_rtl_handles_not_cross_return_false() {
assertThat(
isHandleLtrDirection(direction = ResolvedTextDirection.Rtl, areHandlesCrossed = false)
).isFalse()
}
@Test
@SmallTest
fun isHandleLtrDirection_rtl_handles_cross_return_true() {
assertThat(
isHandleLtrDirection(direction = ResolvedTextDirection.Rtl, areHandlesCrossed = true)
).isTrue()
}
}
@Suppress("DEPRECATION")
// We only need this because IR compiler doesn't like converting lambdas to Runnables
private fun androidx.test.rule.ActivityTestRule<*>.runOnUiThreadIR(block: () -> Unit) {
val runnable = Runnable { block() }
runOnUiThread(runnable)
}
@Suppress("DEPRECATION")
fun androidx.test.rule.ActivityTestRule<*>.findAndroidComposeView(): ViewGroup {
val contentViewGroup = activity.findViewById<ViewGroup>(android.R.id.content)
return findAndroidComposeView(contentViewGroup)!!
}
fun findAndroidComposeView(parent: ViewGroup): ViewGroup? {
for (index in 0 until parent.childCount) {
val child = parent.getChildAt(index)
if (child is ViewGroup) {
if (child is ComposeView)
return child
else {
val composeView = findAndroidComposeView(child)
if (composeView != null) {
return composeView
}
}
}
}
return null
}
@Suppress("DEPRECATION")
@RequiresApi(Build.VERSION_CODES.O)
fun androidx.test.rule.ActivityTestRule<*>.waitAndScreenShot(
forceInvalidate: Boolean = true
): Bitmap = waitAndScreenShot(findAndroidComposeView(), forceInvalidate)
class DrawCounterListener(private val view: View) :
ViewTreeObserver.OnPreDrawListener {
val latch = CountDownLatch(5)
override fun onPreDraw(): Boolean {
latch.countDown()
if (latch.count > 0) {
view.postInvalidate()
} else {
view.viewTreeObserver.removeOnPreDrawListener(this)
}
return true
}
}
@Suppress("DEPRECATION")
@RequiresApi(Build.VERSION_CODES.O)
fun androidx.test.rule.ActivityTestRule<*>.waitAndScreenShot(
view: View,
forceInvalidate: Boolean = true
): Bitmap {
val flushListener = DrawCounterListener(view)
val offset = intArrayOf(0, 0)
var handler: Handler? = null
runOnUiThread {
view.getLocationInWindow(offset)
if (forceInvalidate) {
view.viewTreeObserver.addOnPreDrawListener(flushListener)
view.invalidate()
}
handler = Handler(Looper.getMainLooper())
}
if (forceInvalidate) {
assertTrue("Drawing latch timed out", flushListener.latch.await(1, TimeUnit.SECONDS))
}
val width = view.width
val height = view.height
val dest =
Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val srcRect = android.graphics.Rect(0, 0, width, height)
srcRect.offset(offset[0], offset[1])
val latch = CountDownLatch(1)
var copyResult = 0
val onCopyFinished = PixelCopy.OnPixelCopyFinishedListener { result ->
copyResult = result
latch.countDown()
}
PixelCopy.request(activity.window, srcRect, dest, onCopyFinished, handler!!)
assertTrue("Pixel copy latch timed out", latch.await(1, TimeUnit.SECONDS))
assertEquals(PixelCopy.SUCCESS, copyResult)
return dest
}
|
apache-2.0
|
76557f2ce57e9bff4f3ed25ab3beb4f7
| 33.933555 | 99 | 0.668442 | 4.615452 | false | true | false | false |
djkovrik/YapTalker
|
app/src/main/java/com/sedsoftware/yaptalker/presentation/feature/news/NewsPresenter.kt
|
1
|
6977
|
package com.sedsoftware.yaptalker.presentation.feature.news
import com.arellomobile.mvp.InjectViewState
import com.sedsoftware.yaptalker.data.system.SchedulersProvider
import com.sedsoftware.yaptalker.domain.device.Settings
import com.sedsoftware.yaptalker.domain.interactor.BlacklistInteractor
import com.sedsoftware.yaptalker.domain.interactor.NewsInteractor
import com.sedsoftware.yaptalker.domain.interactor.VideoThumbnailsInteractor
import com.sedsoftware.yaptalker.presentation.base.BasePresenter
import com.sedsoftware.yaptalker.presentation.base.enums.lifecycle.PresenterLifecycle
import com.sedsoftware.yaptalker.presentation.base.enums.navigation.NavigationScreen
import com.sedsoftware.yaptalker.presentation.delegate.LinkBrowserDelegate
import com.sedsoftware.yaptalker.presentation.feature.news.adapter.NewsItemElementsClickListener
import com.sedsoftware.yaptalker.presentation.mapper.NewsModelMapper
import com.sedsoftware.yaptalker.presentation.model.base.NewsItemModel
import com.uber.autodispose.kotlin.autoDisposable
import io.reactivex.Observable
import io.reactivex.Single
import io.reactivex.SingleObserver
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import ru.terrakok.cicerone.Router
import timber.log.Timber
import javax.inject.Inject
@InjectViewState
class NewsPresenter @Inject constructor(
private val router: Router,
private val settings: Settings,
private val targetScreen: String,
private val newsInteractor: NewsInteractor,
private val videoThumbnailsInteractor: VideoThumbnailsInteractor,
private val blacklistInteractor: BlacklistInteractor,
private val newsModelMapper: NewsModelMapper,
private val linksDelegate: LinkBrowserDelegate,
private val schedulers: SchedulersProvider
) : BasePresenter<NewsView>(), NewsItemElementsClickListener {
private val displayedTopics = mutableSetOf<Int>()
private lateinit var currentNewsItem: NewsItemModel
private var nextPagesLoadingActive: Boolean = false
override fun onFirstViewAttach() {
super.onFirstViewAttach()
loadFirstPage()
}
override fun attachView(view: NewsView?) {
super.attachView(view)
viewState.updateCurrentUiState()
}
override fun onNewsItemClicked(forumId: Int, topicId: Int) {
router.navigateTo(NavigationScreen.CHOSEN_TOPIC_SCREEN, Triple(forumId, topicId, 0))
}
override fun onNewsItemLongClicked(item: NewsItemModel) {
currentNewsItem = item
viewState.showBlacklistRequest()
}
override fun onMediaPreviewClicked(url: String, directUrl: String, type: String, html: String, isVideo: Boolean) {
linksDelegate.checkVideoLink(directUrl)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe { viewState.showLoadingIndicator() }
.doFinally { viewState.hideLoadingIndicator() }
.autoDisposable(event(PresenterLifecycle.DESTROY))
.subscribe({ link: String ->
linksDelegate.browse(url, link, type, html, isVideo)
}, { e: Throwable ->
e.message?.let { viewState.showErrorMessage(it) }
})
}
fun addSelectedTopicToBlacklist() {
blacklistInteractor
.addTopicToBlacklist(currentNewsItem.title, currentNewsItem.topicId)
.observeOn(schedulers.ui())
.autoDisposable(event(PresenterLifecycle.DESTROY))
.subscribe({
Timber.i("Current topic added to blacklist.")
viewState.showTopicBlacklistedMessage()
viewState.removeBlacklistedTopicFromList(currentNewsItem)
}, { e: Throwable ->
e.message?.let { viewState.showErrorMessage(it) }
})
}
fun handleFabVisibility(diff: Int) {
when {
diff > 0 -> viewState.hideFab()
diff < 0 -> viewState.showFab()
}
}
fun requestThumbnail(videoUrl: String): Single<String> =
videoThumbnailsInteractor
.getThumbnail(videoUrl)
.observeOn(schedulers.ui())
fun loadFirstPage() {
val url = buildUrl()
nextPagesLoadingActive = false
newsInteractor
.getNewsPage(url)
.map(newsModelMapper)
.flatMapObservable { Observable.fromIterable(it) }
.toList()
.observeOn(schedulers.ui())
.doOnSubscribe { viewState.showLoadingIndicator() }
.doFinally { viewState.hideLoadingIndicator() }
.autoDisposable(event(PresenterLifecycle.DESTROY))
.subscribe(getNewsObserver())
}
fun loadNextPage() {
nextPagesLoadingActive = true
newsInteractor
.getNextNewsPage()
.map(newsModelMapper)
.flatMapObservable { Observable.fromIterable(it) }
.toList()
.observeOn(schedulers.ui())
.doOnSubscribe { viewState.showLoadingIndicator() }
.doFinally { viewState.hideLoadingIndicator() }
.autoDisposable(event(PresenterLifecycle.DESTROY))
.subscribe(getNewsObserver())
}
private fun getNewsObserver() =
object : SingleObserver<List<NewsItemModel>> {
override fun onSubscribe(d: Disposable) {
Timber.i("News page loading started.")
}
override fun onSuccess(items: List<NewsItemModel>) {
if (!nextPagesLoadingActive) {
viewState.clearNewsList()
displayedTopics.clear()
}
val loadedTopicIds = items.map { it.topicId }
val newTopics = items.filter { !displayedTopics.contains(it.topicId) }
displayedTopics.addAll(loadedTopicIds)
if (newTopics.isEmpty()) {
loadNextPage()
} else {
viewState.appendNewsItems(newTopics)
}
}
override fun onError(e: Throwable) {
e.message?.let { viewState.showErrorMessage(it) }
}
}
private fun buildUrl(): String {
val schema = if (settings.isHttpsEnabled()) "https://" else "http://"
val base = when (targetScreen) {
NavigationScreen.NEWS_SCREEN -> "www.yaplakal.com"
NavigationScreen.PICTURES_SCREEN -> "pics.yaplakal.com"
NavigationScreen.VIDEOS_SCREEN -> "video.yaplakal.com"
NavigationScreen.EVENTS_SCREEN -> "news.yaplakal.com"
NavigationScreen.AUTO_MOTO_SCREEN -> "auto.yaplakal.com"
NavigationScreen.ANIMALS_SCREEN -> "animals.yaplakal.com"
NavigationScreen.PHOTOBOMB_SCREEN -> "fotozhaba.yaplakal.com"
else -> "inkubator.yaplakal.com"
}
return "$schema$base"
}
}
|
apache-2.0
|
273f6d54f61a1c7d3a4befd8fc926943
| 38.642045 | 118 | 0.667766 | 4.934229 | false | false | false | false |
androidx/androidx
|
navigation/navigation-compose/src/main/java/androidx/navigation/compose/NavGraphBuilder.kt
|
3
|
4429
|
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.navigation.compose
import androidx.compose.runtime.Composable
import androidx.compose.ui.window.DialogProperties
import androidx.navigation.NamedNavArgument
import androidx.navigation.NavBackStackEntry
import androidx.navigation.NavDeepLink
import androidx.navigation.NavGraphBuilder
import androidx.navigation.get
/**
* Add the [Composable] to the [NavGraphBuilder]
*
* @param route route for the destination
* @param arguments list of arguments to associate with destination
* @param deepLinks list of deep links to associate with the destinations
* @param content composable for the destination
*/
public fun NavGraphBuilder.composable(
route: String,
arguments: List<NamedNavArgument> = emptyList(),
deepLinks: List<NavDeepLink> = emptyList(),
content: @Composable (NavBackStackEntry) -> Unit
) {
addDestination(
ComposeNavigator.Destination(provider[ComposeNavigator::class], content).apply {
this.route = route
arguments.forEach { (argumentName, argument) ->
addArgument(argumentName, argument)
}
deepLinks.forEach { deepLink ->
addDeepLink(deepLink)
}
}
)
}
/**
* Construct a nested [NavGraph]
*
* @sample androidx.navigation.compose.samples.NestedNavInGraphWithArgs
*
* @param startDestination the starting destination's route for this NavGraph
* @param route the destination's unique route
* @param arguments list of arguments to associate with destination
* @param deepLinks list of deep links to associate with the destinations
* @param builder the builder used to construct the graph
*/
public fun NavGraphBuilder.navigation(
startDestination: String,
route: String,
arguments: List<NamedNavArgument> = emptyList(),
deepLinks: List<NavDeepLink> = emptyList(),
builder: NavGraphBuilder.() -> Unit
) {
addDestination(
NavGraphBuilder(provider, startDestination, route).apply(builder).build().apply {
arguments.forEach { (argumentName, argument) ->
addArgument(argumentName, argument)
}
deepLinks.forEach { deepLink ->
addDeepLink(deepLink)
}
}
)
}
/**
* Add the [Composable] to the [NavGraphBuilder] that will be hosted within a
* [androidx.compose.ui.window.Dialog]. This is suitable only when this dialog represents
* a separate screen in your app that needs its own lifecycle and saved state, independent
* of any other destination in your navigation graph. For use cases such as `AlertDialog`,
* you should use those APIs directly in the [composable] destination that wants to show that
* dialog.
*
* @param route route for the destination
* @param arguments list of arguments to associate with destination
* @param deepLinks list of deep links to associate with the destinations
* @param dialogProperties properties that should be passed to [androidx.compose.ui.window.Dialog].
* @param content composable content for the destination that will be hosted within the Dialog
*/
public fun NavGraphBuilder.dialog(
route: String,
arguments: List<NamedNavArgument> = emptyList(),
deepLinks: List<NavDeepLink> = emptyList(),
dialogProperties: DialogProperties = DialogProperties(),
content: @Composable (NavBackStackEntry) -> Unit
) {
addDestination(
DialogNavigator.Destination(
provider[DialogNavigator::class],
dialogProperties,
content
).apply {
this.route = route
arguments.forEach { (argumentName, argument) ->
addArgument(argumentName, argument)
}
deepLinks.forEach { deepLink ->
addDeepLink(deepLink)
}
}
)
}
|
apache-2.0
|
afe2d12185d833a94be837d4994b50ba
| 35.908333 | 99 | 0.701287 | 4.883131 | false | false | false | false |
kivensolo/UiUsingListView
|
library/player/src/main/java/com/kingz/utils/AudioUtils.kt
|
1
|
8004
|
package com.kingz.utils
import android.content.Context
import android.media.AudioFormat
import android.media.AudioManager
import android.media.AudioRecord
import android.media.MediaRecorder
import android.os.Build
import com.kingz.library.audio.IAudioControl
/**
* @author zeke.wang
* @date 2020/6/19
* @maintainer zeke.wang
* @desc: 音频工具类,单例模式
*/
@Suppress("RedundantModalityModifier")
final class AudioUtils(context: Context): IAudioControl {
private val mContext: Context = context
/**
* 缓冲区字节大小
*/
private var bufferSizeInBytes = 0
/**
* 音频获取源
*/
private val audioSource = MediaRecorder.AudioSource.MIC
/**
* 设置音频采样率,44100是目前的标准,但是某些设备仍然支持22050,16000,11025
*/
private val sampleRateInHz = 44100
/**
* 设置音频的录制的声道CHANNEL_IN_STEREO为双声道,CHANNEL_CONFIGURATION_MONO为单声道
*/
private val channelConfig = AudioFormat.CHANNEL_IN_STEREO
/**
* 音频数据格式:PCM 16位每个样本。保证设备支持。PCM 8位每个样本。不一定能得到设备支持。
*/
private val audioFormat = AudioFormat.ENCODING_PCM_16BIT
private val instance: AudioUtils? = null
private var mAudioManager: AudioManager? = null
private var audioRate = 16
// Stream Music Max value.
private var mMusicMaxAudio: Int
private var audioFocusManager: AudioFocusManager? = null
companion object{
@Volatile
private var instance: AudioUtils? = null
fun getInstance(context:Context): AudioUtils{
val i = instance
if(i != null){ return i}
return synchronized(this){
val i2 = instance
if (i2 != null){
i2
} else{
val audioUtils = AudioUtils(context)
instance = audioUtils
audioUtils
}
}
}
}
init {
mAudioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager?
mMusicMaxAudio = mAudioManager!!.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
audioFocusManager = AudioFocusManager()
}
/**
* 判断是否有录音权限
* @return true | false
*/
fun hasAudioRecordPermission(): Boolean {
try {
bufferSizeInBytes = 0
bufferSizeInBytes = AudioRecord.getMinBufferSize(
sampleRateInHz,
channelConfig, audioFormat
)
val audioRecord = AudioRecord(
audioSource,
sampleRateInHz,
channelConfig,
audioFormat,
bufferSizeInBytes
)
//开始录制音频
try { // 防止某些手机崩溃,例如联想
audioRecord.startRecording()
} catch (e: IllegalStateException) {
e.printStackTrace()
}
/*
* 根据开始录音判断是否有录音权限
*/if (audioRecord.recordingState != AudioRecord.RECORDSTATE_RECORDING) {
return false
}
audioRecord.stop()
audioRecord.release()
} catch (ignored: Exception) {
}
return true
}
override fun mute(isMute: Boolean) {
setStreamMute(AudioManager.STREAM_MUSIC, isMute)
}
private fun setStreamMute(type: Int, isMute:Boolean) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mAudioManager?.adjustStreamVolume(type, AudioManager.ADJUST_UNMUTE, 0)
} else {
@Suppress("DEPRECATION")
mAudioManager?.setStreamMute(type, isMute)
}
}
override fun increase() {
increaseMusic()
}
override fun decrease() {
decreaseMusic()
}
@JvmOverloads
fun decreaseMusic(isFollowSystem:Boolean = false){
adjustStreamVolumeByType(AudioManager.STREAM_MUSIC,
AudioManager.ADJUST_LOWER, isFollowSystem)
}
@JvmOverloads
fun increaseMusic(isFollowSystem:Boolean = false){
adjustStreamVolumeByType(AudioManager.STREAM_MUSIC,
AudioManager.ADJUST_RAISE, isFollowSystem)
}
/**
* 根据类型调整音量+-
* @param streamType The stream type to adjust.
* @param isFollowSystem Is follow system v.
* @param direction The direction to adjust the volume.
*/
private fun adjustStreamVolumeByType(streamType: Int, direction: Int, isFollowSystem: Boolean){
setStreamMute(AudioManager.STREAM_MUSIC, false)
if (isFollowSystem || mMusicMaxAudio < audioRate) {
mAudioManager?.adjustStreamVolume(streamType, direction,
AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE)
} else {
mAudioManager?.setStreamVolume(streamType,
getTargetAudio(streamType, direction),
AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE
)
}
}
/**
* 获取目标类型指定方向的音量大小
*/
private fun getTargetAudio(type: Int, direction: Int): Int {
val currentAudioVolume = mAudioManager!!.getStreamVolume(type)
var targetAudio: Int
val rateValue = mMusicMaxAudio.div(audioRate)
return if(AudioManager.ADJUST_RAISE == direction){
targetAudio = currentAudioVolume + rateValue
if(mMusicMaxAudio - targetAudio < rateValue){
targetAudio = 100
}
if (targetAudio >= mMusicMaxAudio) mMusicMaxAudio else targetAudio
}else{
targetAudio = currentAudioVolume - rateValue
if (targetAudio < rateValue) {
targetAudio = 0
}
if (currentAudioVolume <= 0) 0 else targetAudio
}
}
fun setAudioRate(audioRate: Int) {
this.audioRate = audioRate
}
/**
* 获取当前音量
*/
fun getCurrAudio(audioType: Int): Int {
return mAudioManager!!.getStreamVolume(audioType)
}
/**
* 获取当前最大音量
*/
fun getMaxAudio(audioType: Int): Int {
return mAudioManager!!.getStreamMaxVolume(audioType)
}
/**
* 音频焦点控制器, 避免音视频声音并发问题
*/
inner class AudioFocusManager(
private var mFocuseChangeLsr: AudioManager.OnAudioFocusChangeListener ?= null
){
/**
* 请求音频焦点 设置监听
* @param onStart 音频焦点GAIN事件
* @param onPause 音频焦点LOSS事件
*/
fun getAudioFocusValue(context:Context, onStart:()->Unit, onPause:()->Unit):Int{
//Android 2.2开始(API8)才有音频焦点机制
if(mFocuseChangeLsr == null){
mFocuseChangeLsr = AudioManager.OnAudioFocusChangeListener {
when(it){
AudioManager.AUDIOFOCUS_GAIN,
AudioManager.AUDIOFOCUS_GAIN_TRANSIENT,
AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK -> {//播放操作
onStart()
}
AudioManager.AUDIOFOCUS_LOSS,
AudioManager.AUDIOFOCUS_LOSS_TRANSIENT,
AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> {//播放操作
onPause()
}
}
}
}
//下面两个常量参数试过很多 都无效,最终反编译了其他app才搞定,汗~
return mAudioManager?.requestAudioFocus(
mFocuseChangeLsr,
AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK,
AudioManager.AUDIOFOCUS_GAIN_TRANSIENT
)?: AudioManager.AUDIOFOCUS_REQUEST_FAILED
}
}
}
|
gpl-2.0
|
0fe87f8636fb38029f2bb0ad4a1e3c78
| 29.586066 | 99 | 0.582284 | 4.431116 | false | false | false | false |
siosio/intellij-community
|
plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/configuration/ui/KotlinConfigurationCheckerService.kt
|
1
|
3514
|
// 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.configuration.ui
import com.intellij.notification.NotificationDisplayType
import com.intellij.notification.NotificationsConfiguration
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.externalSystem.service.project.manage.ProjectDataImportListener
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.StartupActivity
import org.jetbrains.kotlin.idea.KotlinJvmBundle
import org.jetbrains.kotlin.idea.configuration.getModulesWithKotlinFiles
import org.jetbrains.kotlin.idea.configuration.notifyOutdatedBundledCompilerIfNecessary
import org.jetbrains.kotlin.idea.core.KotlinPluginDisposable
import org.jetbrains.kotlin.idea.project.getAndCacheLanguageLevelByDependencies
import org.jetbrains.kotlin.idea.util.application.getServiceSafe
import java.util.concurrent.atomic.AtomicInteger
class KotlinConfigurationCheckerStartupActivity : StartupActivity.Background {
override fun runActivity(project: Project) {
NotificationsConfiguration.getNotificationsConfiguration()
.register(
KotlinConfigurationCheckerService.CONFIGURE_NOTIFICATION_GROUP_ID,
NotificationDisplayType.STICKY_BALLOON, true
)
val connection = project.messageBus.connect(KotlinPluginDisposable.getInstance(project))
connection.subscribe(ProjectDataImportListener.TOPIC, ProjectDataImportListener {
notifyOutdatedBundledCompilerIfNecessary(project)
})
DumbService.getInstance(project).runWhenSmart {
KotlinConfigurationCheckerService.getInstance(project).performProjectPostOpenActions()
}
}
}
class KotlinConfigurationCheckerService(val project: Project) {
private val syncDepth = AtomicInteger()
fun performProjectPostOpenActions() {
val task = object : Task.Backgroundable(project, KotlinJvmBundle.message("configure.kotlin.language.settings"), false) {
override fun run(indicator: ProgressIndicator) {
val ktModules = getModulesWithKotlinFiles(project)
indicator.isIndeterminate = false
for ((idx, module) in ktModules.withIndex()) {
if (project.isDisposed) return
indicator.fraction = 1.0 * idx / ktModules.size
runReadAction {
if (module.isDisposed) return@runReadAction
indicator.text2 = KotlinJvmBundle.message("configure.kotlin.language.settings.0.module", module.name)
module.getAndCacheLanguageLevelByDependencies()
}
}
}
}
ProgressManager.getInstance().run(task)
}
val isSyncing: Boolean get() = syncDepth.get() > 0
fun syncStarted() {
syncDepth.incrementAndGet()
}
fun syncDone() {
syncDepth.decrementAndGet()
}
companion object {
const val CONFIGURE_NOTIFICATION_GROUP_ID = "Configure Kotlin in Project"
fun getInstance(project: Project): KotlinConfigurationCheckerService = project.getServiceSafe()
}
}
|
apache-2.0
|
10376c26bcee1567b6b36cf6d5d7846b
| 42.925 | 158 | 0.730222 | 5.260479 | false | true | false | false |
GunoH/intellij-community
|
platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/ArtifactEntityImpl.kt
|
2
|
17856
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.storage.bridgeEntities
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.SymbolicEntityId
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToAbstractOneChild
import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren
import com.intellij.workspaceModel.storage.impl.extractOneToOneChild
import com.intellij.workspaceModel.storage.impl.updateOneToAbstractOneChildOfParent
import com.intellij.workspaceModel.storage.impl.updateOneToManyChildrenOfParent
import com.intellij.workspaceModel.storage.impl.updateOneToOneChildOfParent
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Abstract
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class ArtifactEntityImpl(val dataSource: ArtifactEntityData) : ArtifactEntity, WorkspaceEntityBase() {
companion object {
internal val ROOTELEMENT_CONNECTION_ID: ConnectionId = ConnectionId.create(ArtifactEntity::class.java,
CompositePackagingElementEntity::class.java,
ConnectionId.ConnectionType.ABSTRACT_ONE_TO_ONE, true)
internal val CUSTOMPROPERTIES_CONNECTION_ID: ConnectionId = ConnectionId.create(ArtifactEntity::class.java,
ArtifactPropertiesEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_MANY, false)
internal val ARTIFACTOUTPUTPACKAGINGELEMENT_CONNECTION_ID: ConnectionId = ConnectionId.create(ArtifactEntity::class.java,
ArtifactOutputPackagingElementEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_ONE,
false)
val connections = listOf<ConnectionId>(
ROOTELEMENT_CONNECTION_ID,
CUSTOMPROPERTIES_CONNECTION_ID,
ARTIFACTOUTPUTPACKAGINGELEMENT_CONNECTION_ID,
)
}
override val name: String
get() = dataSource.name
override val artifactType: String
get() = dataSource.artifactType
override val includeInProjectBuild: Boolean get() = dataSource.includeInProjectBuild
override val outputUrl: VirtualFileUrl?
get() = dataSource.outputUrl
override val rootElement: CompositePackagingElementEntity?
get() = snapshot.extractOneToAbstractOneChild(ROOTELEMENT_CONNECTION_ID, this)
override val customProperties: List<ArtifactPropertiesEntity>
get() = snapshot.extractOneToManyChildren<ArtifactPropertiesEntity>(CUSTOMPROPERTIES_CONNECTION_ID, this)!!.toList()
override val artifactOutputPackagingElement: ArtifactOutputPackagingElementEntity?
get() = snapshot.extractOneToOneChild(ARTIFACTOUTPUTPACKAGINGELEMENT_CONNECTION_ID, this)
override val entitySource: EntitySource
get() = dataSource.entitySource
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(result: ArtifactEntityData?) : ModifiableWorkspaceEntityBase<ArtifactEntity, ArtifactEntityData>(
result), ArtifactEntity.Builder {
constructor() : this(ArtifactEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity ArtifactEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// After adding entity data to the builder, we need to unbind it and move the control over entity data to builder
// Builder may switch to snapshot at any moment and lock entity data to modification
this.currentEntityData = null
index(this, "outputUrl", this.outputUrl)
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isNameInitialized()) {
error("Field ArtifactEntity#name should be initialized")
}
if (!getEntityData().isArtifactTypeInitialized()) {
error("Field ArtifactEntity#artifactType should be initialized")
}
// Check initialization for list with ref type
if (_diff != null) {
if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CUSTOMPROPERTIES_CONNECTION_ID, this) == null) {
error("Field ArtifactEntity#customProperties should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(true, CUSTOMPROPERTIES_CONNECTION_ID)] == null) {
error("Field ArtifactEntity#customProperties should be initialized")
}
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as ArtifactEntity
if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource
if (this.name != dataSource.name) this.name = dataSource.name
if (this.artifactType != dataSource.artifactType) this.artifactType = dataSource.artifactType
if (this.includeInProjectBuild != dataSource.includeInProjectBuild) this.includeInProjectBuild = dataSource.includeInProjectBuild
if (this.outputUrl != dataSource?.outputUrl) this.outputUrl = dataSource.outputUrl
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData(true).entitySource = value
changedProperty.add("entitySource")
}
override var name: String
get() = getEntityData().name
set(value) {
checkModificationAllowed()
getEntityData(true).name = value
changedProperty.add("name")
}
override var artifactType: String
get() = getEntityData().artifactType
set(value) {
checkModificationAllowed()
getEntityData(true).artifactType = value
changedProperty.add("artifactType")
}
override var includeInProjectBuild: Boolean
get() = getEntityData().includeInProjectBuild
set(value) {
checkModificationAllowed()
getEntityData(true).includeInProjectBuild = value
changedProperty.add("includeInProjectBuild")
}
override var outputUrl: VirtualFileUrl?
get() = getEntityData().outputUrl
set(value) {
checkModificationAllowed()
getEntityData(true).outputUrl = value
changedProperty.add("outputUrl")
val _diff = diff
if (_diff != null) index(this, "outputUrl", value)
}
override var rootElement: CompositePackagingElementEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToAbstractOneChild(ROOTELEMENT_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true,
ROOTELEMENT_CONNECTION_ID)] as? CompositePackagingElementEntity
}
else {
this.entityLinks[EntityLink(true, ROOTELEMENT_CONNECTION_ID)] as? CompositePackagingElementEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*, *> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*, *>) {
value.entityLinks[EntityLink(false, ROOTELEMENT_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*, *> || value.diff != null)) {
_diff.updateOneToAbstractOneChildOfParent(ROOTELEMENT_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*, *>) {
value.entityLinks[EntityLink(false, ROOTELEMENT_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(true, ROOTELEMENT_CONNECTION_ID)] = value
}
changedProperty.add("rootElement")
}
// List of non-abstract referenced types
var _customProperties: List<ArtifactPropertiesEntity>? = emptyList()
override var customProperties: List<ArtifactPropertiesEntity>
get() {
// Getter of the list of non-abstract referenced types
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyChildren<ArtifactPropertiesEntity>(CUSTOMPROPERTIES_CONNECTION_ID,
this)!!.toList() + (this.entityLinks[EntityLink(true,
CUSTOMPROPERTIES_CONNECTION_ID)] as? List<ArtifactPropertiesEntity>
?: emptyList())
}
else {
this.entityLinks[EntityLink(true, CUSTOMPROPERTIES_CONNECTION_ID)] as? List<ArtifactPropertiesEntity> ?: emptyList()
}
}
set(value) {
// Setter of the list of non-abstract referenced types
checkModificationAllowed()
val _diff = diff
if (_diff != null) {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*, *> && (item_value as? ModifiableWorkspaceEntityBase<*, *>)?.diff == null) {
// Backref setup before adding to store
if (item_value is ModifiableWorkspaceEntityBase<*, *>) {
item_value.entityLinks[EntityLink(false, CUSTOMPROPERTIES_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(item_value)
}
}
_diff.updateOneToManyChildrenOfParent(CUSTOMPROPERTIES_CONNECTION_ID, this, value)
}
else {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*, *>) {
item_value.entityLinks[EntityLink(false, CUSTOMPROPERTIES_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
}
this.entityLinks[EntityLink(true, CUSTOMPROPERTIES_CONNECTION_ID)] = value
}
changedProperty.add("customProperties")
}
override var artifactOutputPackagingElement: ArtifactOutputPackagingElementEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToOneChild(ARTIFACTOUTPUTPACKAGINGELEMENT_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true,
ARTIFACTOUTPUTPACKAGINGELEMENT_CONNECTION_ID)] as? ArtifactOutputPackagingElementEntity
}
else {
this.entityLinks[EntityLink(true, ARTIFACTOUTPUTPACKAGINGELEMENT_CONNECTION_ID)] as? ArtifactOutputPackagingElementEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*, *> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*, *>) {
value.entityLinks[EntityLink(false, ARTIFACTOUTPUTPACKAGINGELEMENT_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*, *> || value.diff != null)) {
_diff.updateOneToOneChildOfParent(ARTIFACTOUTPUTPACKAGINGELEMENT_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*, *>) {
value.entityLinks[EntityLink(false, ARTIFACTOUTPUTPACKAGINGELEMENT_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(true, ARTIFACTOUTPUTPACKAGINGELEMENT_CONNECTION_ID)] = value
}
changedProperty.add("artifactOutputPackagingElement")
}
override fun getEntityClass(): Class<ArtifactEntity> = ArtifactEntity::class.java
}
}
class ArtifactEntityData : WorkspaceEntityData.WithCalculableSymbolicId<ArtifactEntity>() {
lateinit var name: String
lateinit var artifactType: String
var includeInProjectBuild: Boolean = false
var outputUrl: VirtualFileUrl? = null
fun isNameInitialized(): Boolean = ::name.isInitialized
fun isArtifactTypeInitialized(): Boolean = ::artifactType.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<ArtifactEntity> {
val modifiable = ArtifactEntityImpl.Builder(null)
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): ArtifactEntity {
return getCached(snapshot) {
val entity = ArtifactEntityImpl(this)
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun symbolicId(): SymbolicEntityId<*> {
return ArtifactId(name)
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return ArtifactEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return ArtifactEntity(name, artifactType, includeInProjectBuild, entitySource) {
this.outputUrl = [email protected]
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as ArtifactEntityData
if (this.entitySource != other.entitySource) return false
if (this.name != other.name) return false
if (this.artifactType != other.artifactType) return false
if (this.includeInProjectBuild != other.includeInProjectBuild) return false
if (this.outputUrl != other.outputUrl) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as ArtifactEntityData
if (this.name != other.name) return false
if (this.artifactType != other.artifactType) return false
if (this.includeInProjectBuild != other.includeInProjectBuild) return false
if (this.outputUrl != other.outputUrl) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + name.hashCode()
result = 31 * result + artifactType.hashCode()
result = 31 * result + includeInProjectBuild.hashCode()
result = 31 * result + outputUrl.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + name.hashCode()
result = 31 * result + artifactType.hashCode()
result = 31 * result + includeInProjectBuild.hashCode()
result = 31 * result + outputUrl.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
this.outputUrl?.let { collector.add(it::class.java) }
collector.sameForAllEntities = false
}
}
|
apache-2.0
|
f84775d1991e6f4c8d1a023d4627f287
| 41.923077 | 207 | 0.666107 | 5.467238 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/caches/resolve/ResolutionAnchorCacheService.kt
|
2
|
5331
|
// 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.caches.resolve
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.xmlb.XmlSerializerUtil
import org.jetbrains.kotlin.analyzer.ModuleInfo
import org.jetbrains.kotlin.caches.project.cacheByClassInvalidatingOnRootModifications
import org.jetbrains.kotlin.idea.caches.project.LibraryDependenciesCache
import org.jetbrains.kotlin.idea.caches.project.LibraryInfo
import org.jetbrains.kotlin.idea.caches.project.ModuleSourceInfo
import org.jetbrains.kotlin.idea.caches.project.getModuleInfosFromIdeaModel
import org.jetbrains.kotlin.idea.util.application.getService
import org.jetbrains.kotlin.progress.ProgressIndicatorAndCompilationCanceledStatus.checkCanceled
import org.jetbrains.kotlin.types.typeUtil.closure
import org.jetbrains.kotlin.utils.addToStdlib.cast
interface ResolutionAnchorCacheService {
val resolutionAnchorsForLibraries: Map<LibraryInfo, ModuleSourceInfo>
fun getDependencyResolutionAnchors(libraryInfo: LibraryInfo): Set<ModuleSourceInfo>
companion object {
val Default = object : ResolutionAnchorCacheService {
override val resolutionAnchorsForLibraries: Map<LibraryInfo, ModuleSourceInfo>
get() = emptyMap()
override fun getDependencyResolutionAnchors(libraryInfo: LibraryInfo): Set<ModuleSourceInfo> = emptySet()
}
fun getInstance(project: Project): ResolutionAnchorCacheService =
project.getService() ?: Default
}
}
@State(name = "KotlinIdeAnchorService", storages = [Storage("anchors.xml")])
class ResolutionAnchorCacheServiceImpl(val project: Project) :
ResolutionAnchorCacheService,
PersistentStateComponent<ResolutionAnchorCacheServiceImpl.State> {
data class State(
var moduleNameToAnchorName: Map<String, String> = emptyMap()
)
@JvmField
@Volatile
var myState: State = State()
override fun getState(): State = myState
override fun loadState(state: State) {
XmlSerializerUtil.copyBean(state, myState)
}
object ResolutionAnchorMappingCacheKey
object ResolutionAnchorDependenciesCacheKey
override val resolutionAnchorsForLibraries: Map<LibraryInfo, ModuleSourceInfo>
get() = project.cacheByClassInvalidatingOnRootModifications(ResolutionAnchorMappingCacheKey::class.java) {
mapResolutionAnchorForLibraries()
}
private val resolutionAnchorDependenciesCache: MutableMap<LibraryInfo, Set<ModuleSourceInfo>>
get() = project.cacheByClassInvalidatingOnRootModifications(ResolutionAnchorDependenciesCacheKey::class.java) {
ContainerUtil.createConcurrentWeakMap()
}
override fun getDependencyResolutionAnchors(libraryInfo: LibraryInfo): Set<ModuleSourceInfo> {
return resolutionAnchorDependenciesCache.getOrPut(libraryInfo) {
val allTransitiveLibraryDependencies = with(LibraryDependenciesCache.getInstance(project)) {
val (directDependenciesOnLibraries, _) = getLibrariesAndSdksUsedWith(libraryInfo)
directDependenciesOnLibraries.closure { libraryDependency ->
checkCanceled()
getLibrariesAndSdksUsedWith(libraryDependency).first
}
}
allTransitiveLibraryDependencies.mapNotNull { resolutionAnchorsForLibraries[it] }.toSet()
}
}
private fun associateModulesByNames(): Map<String, ModuleInfo> {
return getModuleInfosFromIdeaModel(project).associateBy { moduleInfo ->
checkCanceled()
when (moduleInfo) {
is LibraryInfo -> moduleInfo.library.name ?: "" // TODO: when does library have no name?
is ModuleSourceInfo -> moduleInfo.module.name
else -> moduleInfo.name.asString()
}
}
}
private fun mapResolutionAnchorForLibraries(): Map<LibraryInfo, ModuleSourceInfo> {
val modulesByNames: Map<String, ModuleInfo> = associateModulesByNames()
return myState.moduleNameToAnchorName.entries.mapNotNull { (libraryName, anchorName) ->
val library: LibraryInfo = modulesByNames[libraryName]?.takeIf { it is LibraryInfo }?.cast()
?: run {
logger.warn("Resolution anchor mapping key doesn't point to a known library: $libraryName. Skipping this anchor")
return@mapNotNull null
}
val anchor: ModuleSourceInfo = modulesByNames[anchorName]?.takeIf { it is ModuleSourceInfo }?.cast()
?: run {
logger.warn("Resolution anchor mapping value doesn't point to a source module: $anchorName. Skipping this anchor")
return@mapNotNull null
}
library to anchor
}.toMap()
}
companion object {
private val logger = logger<ResolutionAnchorCacheServiceImpl>()
}
}
|
apache-2.0
|
61e999359fbf8dc758bc894e1b4632bb
| 43.798319 | 158 | 0.722566 | 5.325674 | false | false | false | false |
smmribeiro/intellij-community
|
platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/changesHandler/CommonInjectedFileChangesHandler.kt
|
1
|
14776
|
// 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.psi.impl.source.tree.injected.changesHandler
import com.intellij.lang.injection.InjectedLanguageManager
import com.intellij.openapi.diagnostic.*
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.RangeMarker
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.util.*
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.*
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil
import com.intellij.psi.util.parents
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.NonNls
import java.util.*
import kotlin.Pair
import kotlin.math.max
import kotlin.math.min
open class CommonInjectedFileChangesHandler(
shreds: List<PsiLanguageInjectionHost.Shred>,
hostEditor: Editor,
fragmentDocument: Document,
injectedFile: PsiFile
) : BaseInjectedFileChangesHandler(hostEditor, fragmentDocument, injectedFile) {
protected val markers: MutableList<MarkersMapping> =
LinkedList<MarkersMapping>().apply {
addAll(getMarkersFromShreds(shreds))
}
protected fun getMarkersFromShreds(shreds: List<PsiLanguageInjectionHost.Shred>): List<MarkersMapping> {
val result = ArrayList<MarkersMapping>(shreds.size)
val smartPointerManager = SmartPointerManager.getInstance(myProject)
var currentOffsetInHostFile = -1
var currentOffsetInInjectedFile = -1
for (shred in shreds) {
val rangeMarker = fragmentMarkerFromShred(shred)
val rangeInsideHost = shred.rangeInsideHost
val host = shred.host ?: failAndReport("host should not be null", null, null)
val origMarker = myHostDocument.createRangeMarker(rangeInsideHost.shiftRight(host.textRange.startOffset))
val elementPointer = smartPointerManager.createSmartPsiElementPointer(host)
result.add(MarkersMapping(origMarker, rangeMarker, elementPointer))
origMarker.isGreedyToRight = true
rangeMarker.isGreedyToRight = true
if (origMarker.startOffset > currentOffsetInHostFile) {
origMarker.isGreedyToLeft = true
}
if (rangeMarker.startOffset > currentOffsetInInjectedFile) {
rangeMarker.isGreedyToLeft = true
}
currentOffsetInHostFile = origMarker.endOffset
currentOffsetInInjectedFile = rangeMarker.endOffset
}
return result
}
protected open fun rebuildMarkers(contextRange: TextRange) {
val psiDocumentManager = PsiDocumentManager.getInstance(myProject)
psiDocumentManager.commitDocument(myHostDocument)
val hostPsiFile = psiDocumentManager.getPsiFile(myHostDocument) ?: failAndReport("no psiFile $myHostDocument")
val injectedLanguageManager = InjectedLanguageManager.getInstance(myProject)
val newInjectedFile = getInjectionHostAtRange(hostPsiFile, contextRange)?.let { host ->
val injectionRange = run {
val hostRange = host.textRange
val contextRangeTrimmed = hostRange.intersection(contextRange) ?: hostRange
contextRangeTrimmed.shiftLeft(hostRange.startOffset)
}
injectedLanguageManager.getInjectedPsiFiles(host)
.orEmpty()
.asSequence()
.filter { (_, range) -> injectionRange.intersects(range) }
.mapNotNull { it.first as? PsiFile }
.firstOrNull()
}
LOG.debug { "newInjectedFile = $newInjectedFile" }
myInjectedFile = newInjectedFile ?: myInjectedFile
//some hostless shreds could exist for keeping guarded values
if (myInjectedFile.isValid) {
markers.forEach { it.dispose() }
markers.clear()
val hostfulShreds = InjectedLanguageUtil.getShreds(myInjectedFile).filter { it.host != null }
val markersFromShreds = getMarkersFromShreds(hostfulShreds)
markers.addAll(markersFromShreds)
}
else
LOG.error(
getReportException("failed to rebuildMarkers at range $contextRange due to invalid myInjectedFile, newInjectedFile = $newInjectedFile", null, null))
}
override fun isValid(): Boolean = myInjectedFile.isValid && markers.all { it.isValid() }
override fun commitToOriginal(e: DocumentEvent) {
val text = myFragmentDocument.text
LOG.debug { "commitToOriginal: $e text='${text.esclbr()}'" }
val map = markers.groupByTo(LinkedHashMap()) { it.host }
val documentManager = PsiDocumentManager.getInstance(myProject)
documentManager.commitDocument(myHostDocument) // commit here and after each manipulator update
var workingRange: TextRange? = null
for (host in map.keys) {
if (host == null) continue
val hostRange = host.textRange
val hostOffset = hostRange.startOffset
var currentHost = host;
val hostMarkers = map[host].orEmpty().reversed()
for ((hostMarker, fragmentMarker, _) in hostMarkers) {
val localInsideHost = ProperTextRange(hostMarker.startOffset - hostOffset, hostMarker.endOffset - hostOffset)
val localInsideFile = ProperTextRange(fragmentMarker.startOffset, fragmentMarker.endOffset)
currentHost!! // should never happen
// fixme we could optimize here and check if host text has been changed and update only really changed fragments, not all of them
if (localInsideFile.endOffset <= text.length && !localInsideFile.isEmpty) {
val decodedText = localInsideFile.substring(text)
currentHost = updateHostOrFail(currentHost, localInsideHost, decodedText, e)
}
else if (hostMarkers.size == 1 && text.isEmpty()) {
currentHost = updateHostOrFail(currentHost, localInsideHost, text, e)
}
else
continue
workingRange = workingRange union currentHost.contentRange
}
}
if (!markers.all { it.isValid() }) {
workingRange?.let { workingRange ->
LOG.logMarkers("before rebuild")
rebuildMarkers(workingRange)
LOG.logMarkers("after rebuild")
}
}
else
LOG.logMarkers("markers were not rebuilt")
}
private fun updateHostOrFail(currentHost: PsiLanguageInjectionHost,
localInsideHost: TextRange,
decodedText: String,
e: DocumentEvent?): PsiLanguageInjectionHost {
LOG.debug { "updating host '${currentHost.text?.esclbr()}' at $localInsideHost with '${decodedText.esclbr()}' " }
val updatedHost = updateHostElement(currentHost, localInsideHost, decodedText)
if (updatedHost == null)
failAndReport("Updating host returned null. Original host" + currentHost +
"; original text: " + currentHost.text +
"; updated range in host: " + localInsideHost +
"; decoded text to replace: " + decodedText.esclbr(), e)
LOG.debug { "updated host: '${updatedHost.text?.esclbr()}'" }
return updatedHost
}
@Deprecated("use updateHostElement", ReplaceWith("updateHostElement"))
@ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
protected fun updateInjectionHostElement(host: PsiLanguageInjectionHost,
insideHost: ProperTextRange,
content: String): PsiLanguageInjectionHost? {
return updateHostElement(host, insideHost, content)
}
protected open fun updateHostElement(host: PsiLanguageInjectionHost,
insideHost: TextRange,
content: String): PsiLanguageInjectionHost? {
return ElementManipulators.handleContentChange(host, insideHost, content)
}
override fun dispose() {
markers.forEach(MarkersMapping::dispose)
markers.clear()
super.dispose()
}
override fun handlesRange(range: TextRange): Boolean {
if (markers.isEmpty()) return false
val hostRange = TextRange.create(markers[0].hostMarker.startOffset,
markers[markers.size - 1].hostMarker.endOffset)
return range.intersects(hostRange)
}
protected fun fragmentMarkerFromShred(shred: PsiLanguageInjectionHost.Shred): RangeMarker {
if (!shred.innerRange.run { 0 <= startOffset && startOffset <= endOffset && endOffset <= myFragmentDocument.textLength }) {
LOG.error("fragment and host diverged: startOffset = ${shred.innerRange.startOffset}," +
" endOffset = ${shred.innerRange.endOffset}," +
" textLength = ${myFragmentDocument.textLength}",
Attachment("host", shred.host?.text?.esclbr() ?: "<null>"),
Attachment("fragment document", this.myFragmentDocument.text.esclbr()),
Attachment("markers", markers.joinToString("\n", transform = ::markerString))
)
}
return myFragmentDocument.createRangeMarker(shred.innerRange)
}
protected fun failAndReport(@NonNls message: String, e: DocumentEvent? = null, exception: Exception? = null): Nothing =
throw getReportException(message, e, exception)
protected fun getReportException(@NonNls message: String,
e: DocumentEvent?,
exception: Exception?): RuntimeExceptionWithAttachments =
RuntimeExceptionWithAttachments("${this.javaClass.simpleName}: $message (event = $e)," +
" myInjectedFile.isValid = ${myInjectedFile.isValid}, isValid = $isValid",
*listOfNotNull(
Attachment("hosts", markers.mapNotNullTo(LinkedHashSet()) { it.host }
.joinToString("\n\n") { it.text.esclbr() ?: "<null>" }),
Attachment("markers", markers.logMarkersRanges()),
Attachment("fragment document", this.myFragmentDocument.text.esclbr()),
exception?.let { Attachment("exception", it) }
).toTypedArray()
)
protected fun String.esclbr(): String = StringUtil.escapeLineBreak(this)
protected val RangeMarker.debugText: String
get() = "$range'${
try {
document.getText(range)
}
catch (e: IndexOutOfBoundsException) {
e.toString()
}
}'".esclbr()
protected fun Logger.logMarkers(title: String) {
this.debug { "logMarkers('$title'):${markers.size}\n" + markers.joinToString("\n", transform = ::markerString) }
}
protected fun markerString(m: MarkersMapping): String {
val (hostMarker, fragmentMarker, _) = m
return "${hostMarker.debugText}\t<-\t${fragmentMarker.debugText}"
}
protected fun Iterable<MarkersMapping>.logMarkersRanges(): String = joinToString("\n", transform = ::markerString)
protected fun String.substringVerbose(start: Int, cursor: Int): String = try {
substring(start, cursor)
}
catch (e: StringIndexOutOfBoundsException) {
failAndReport("can't get substring ($start, $cursor) of '${this}'[$length]", exception = e)
}
fun distributeTextToMarkers(affectedMarkers: List<MarkersMapping>,
affectedRange: TextRange,
limit: Int): List<Pair<MarkersMapping, String>> {
tailrec fun List<MarkersMapping>.nearestValidMarker(start: Int): MarkersMapping? {
val next = getOrNull(start) ?: return null
if (next.isValid()) return next
return nearestValidMarker(start + 1)
}
var cursor = 0
var remainder = 0
return affectedMarkers.indices.map { i ->
val marker = affectedMarkers[i]
val fragmentMarker = marker.fragmentMarker
marker to if (fragmentMarker.isValid) {
val start = max(cursor, fragmentMarker.startOffset) - remainder
remainder = 0
val text = fragmentMarker.document.text
val fragmentText = fragmentMarker.range.subSequence(text)
val lastEndOfLine = fragmentText.lastIndexOf("\n")
val nextValidMarker by lazy(LazyThreadSafetyMode.NONE) { affectedMarkers.nearestValidMarker(i + 1) }
cursor = if (lastEndOfLine != -1 && lastEndOfLine != fragmentText.length - 1 && nextValidMarker != null) {
remainder = fragmentText.length - lastEndOfLine - 1
max(cursor, fragmentMarker.startOffset + lastEndOfLine + 1)
}
else if (affectedLength(marker, affectedRange) == 0 && affectedLength(nextValidMarker, affectedRange) > 1)
nextValidMarker!!.fragmentMarker.startOffset
else
min(text.length, max(fragmentMarker.endOffset, limit))
text.substringVerbose(start, cursor)
}
else ""
}
}
}
@Deprecated("Use platform API", ReplaceWith("debug", "com.intellij.openapi.diagnostic"))
inline fun Logger.debug(message: () -> String) {
this.debug(null, message)
}
private val LOG = logger<CommonInjectedFileChangesHandler>()
data class MarkersMapping(val hostMarker: RangeMarker,
val fragmentMarker: RangeMarker,
val hostPointer: SmartPsiElementPointer<PsiLanguageInjectionHost>) {
val host: PsiLanguageInjectionHost? get() = hostPointer.element
val hostElementRange: TextRange? get() = hostPointer.range?.range
val fragmentRange: TextRange get() = fragmentMarker.range
fun isValid(): Boolean = hostMarker.isValid && fragmentMarker.isValid && hostPointer.element?.isValid == true
fun dispose() {
fragmentMarker.dispose()
hostMarker.dispose()
}
}
infix fun TextRange?.union(another: TextRange?) = another?.let { this?.union(it) ?: it } ?: this
inline val Segment.range: TextRange get() = TextRange.create(this)
inline val PsiLanguageInjectionHost.Shred.innerRange: TextRange
get() = TextRange.create(this.range.startOffset + this.prefix.length,
this.range.endOffset - this.suffix.length)
val PsiLanguageInjectionHost.contentRange
get() = ElementManipulators.getValueTextRange(this).shiftRight(textRange.startOffset)
private val PsiElement.withNextSiblings: Sequence<PsiElement>
get() = generateSequence(this) { it.nextSibling }
@ApiStatus.Internal
fun getInjectionHostAtRange(hostPsiFile: PsiFile, contextRange: Segment): PsiLanguageInjectionHost? =
hostPsiFile.findElementAt(contextRange.startOffset)?.withNextSiblings.orEmpty()
.takeWhile { it.textRange.startOffset <= contextRange.endOffset }
.flatMap { it.parents(true).take(3) }
.filterIsInstance<PsiLanguageInjectionHost>().firstOrNull()
private fun affectedLength(markersMapping: MarkersMapping?, affectedRange: TextRange): Int =
markersMapping?.fragmentRange?.let { affectedRange.intersection(it)?.length } ?: -1
|
apache-2.0
|
8e10bb667a761f94871b16d26e7c1373
| 42.979167 | 158 | 0.684962 | 5.053352 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/completion/src/org/jetbrains/kotlin/idea/completion/smart/LambdaSignatureItems.kt
|
2
|
4292
|
// 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.completion.smart
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.builtins.getValueParameterTypesFromFunctionType
import org.jetbrains.kotlin.builtins.isFunctionOrSuspendFunctionType
import org.jetbrains.kotlin.idea.completion.LambdaSignatureTemplates
import org.jetbrains.kotlin.idea.completion.suppressAutoInsertion
import org.jetbrains.kotlin.idea.core.ExpectedInfos
import org.jetbrains.kotlin.idea.core.fuzzyType
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.psi.KtBlockExpression
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtFunctionLiteral
import org.jetbrains.kotlin.psi.KtLambdaExpression
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.types.KotlinType
object LambdaSignatureItems {
fun addToCollection(
collection: MutableCollection<LookupElement>,
position: KtExpression,
bindingContext: BindingContext,
resolutionFacade: ResolutionFacade
) {
val block = position.parent as? KtBlockExpression ?: return
if (position != block.statements.first()) return
val functionLiteral = block.parent as? KtFunctionLiteral ?: return
if (functionLiteral.arrow != null) return
val literalExpression = functionLiteral.parent as KtLambdaExpression
val expectedFunctionTypes = ExpectedInfos(bindingContext, resolutionFacade, null).calculate(literalExpression)
.mapNotNull { it.fuzzyType?.type }
.filter { it.isFunctionOrSuspendFunctionType }
.toSet()
for (functionType in expectedFunctionTypes) {
if (functionType.getValueParameterTypesFromFunctionType().isEmpty()) continue
if (LambdaSignatureTemplates.explicitParameterTypesRequired(expectedFunctionTypes, functionType)) {
collection.add(
createLookupElement(
functionType,
LambdaSignatureTemplates.SignaturePresentation.NAMES_OR_TYPES,
explicitParameterTypes = true
)
)
} else {
collection.add(
createLookupElement(
functionType,
LambdaSignatureTemplates.SignaturePresentation.NAMES,
explicitParameterTypes = false
)
)
collection.add(
createLookupElement(
functionType,
LambdaSignatureTemplates.SignaturePresentation.NAMES_AND_TYPES,
explicitParameterTypes = true
)
)
}
}
}
private fun createLookupElement(
functionType: KotlinType,
signaturePresentation: LambdaSignatureTemplates.SignaturePresentation,
explicitParameterTypes: Boolean
): LookupElement {
val lookupString = LambdaSignatureTemplates.signaturePresentation(functionType, signaturePresentation)
val priority = if (explicitParameterTypes)
SmartCompletionItemPriority.LAMBDA_SIGNATURE_EXPLICIT_PARAMETER_TYPES
else
SmartCompletionItemPriority.LAMBDA_SIGNATURE
return LookupElementBuilder.create(lookupString)
.withInsertHandler { context, _ ->
val offset = context.startOffset
val placeholder = "{}"
context.document.replaceString(offset, context.tailOffset, placeholder)
LambdaSignatureTemplates.insertTemplate(
context,
TextRange(offset, offset + placeholder.length),
functionType,
explicitParameterTypes,
signatureOnly = true
)
}
.suppressAutoInsertion()
.assignSmartCompletionPriority(priority)
}
}
|
apache-2.0
|
edfcf83f3b671fc3956362e7b3fc729a
| 44.189474 | 158 | 0.663094 | 6.062147 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/core/src/org/jetbrains/kotlin/idea/core/psiModificationUtils.kt
|
1
|
27052
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.core
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiErrorElement
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.impl.source.codeStyle.CodeEditUtil
import com.intellij.psi.tree.IElementType
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.elementType
import com.intellij.psi.util.parentOfType
import org.jetbrains.kotlin.builtins.isFunctionOrSuspendFunctionType
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.diagnostics.Severity
import org.jetbrains.kotlin.extensions.DeclarationAttributeAltererExtension
import org.jetbrains.kotlin.idea.FrontendInternals
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.project.languageVersionSettings
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.resolve.frontendService
import org.jetbrains.kotlin.idea.resolve.getLanguageVersionSettings
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.idea.util.application.withPsiAttachment
import org.jetbrains.kotlin.idea.util.hasJvmFieldAnnotation
import org.jetbrains.kotlin.idea.util.isExpectDeclaration
import org.jetbrains.kotlin.idea.util.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.lexer.KtModifierKeywordToken
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.addRemoveModifier.MODIFIERS_ORDER
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.psi.typeRefHelpers.setReceiverTypeReference
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.OverridingUtil
import org.jetbrains.kotlin.resolve.calls.callUtil.getParameterForArgument
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.callUtil.getValueArgumentsInParentheses
import org.jetbrains.kotlin.resolve.calls.model.ArgumentMatch
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.sam.SamConversionOracle
import org.jetbrains.kotlin.resolve.sam.SamConversionResolver
import org.jetbrains.kotlin.resolve.sam.getFunctionTypeForPossibleSamType
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.isError
import org.jetbrains.kotlin.types.typeUtil.isTypeParameter
import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments
import org.jetbrains.kotlin.utils.SmartList
fun KtLambdaArgument.moveInsideParentheses(bindingContext: BindingContext): KtCallExpression {
val ktExpression = this.getArgumentExpression()
?: throw KotlinExceptionWithAttachments("no argument expression for $this")
.withPsiAttachment("lambdaExpression", this)
return moveInsideParenthesesAndReplaceWith(ktExpression, bindingContext)
}
fun KtLambdaArgument.moveInsideParenthesesAndReplaceWith(
replacement: KtExpression,
bindingContext: BindingContext
): KtCallExpression = moveInsideParenthesesAndReplaceWith(replacement, getLambdaArgumentName(bindingContext))
fun KtLambdaArgument.getLambdaArgumentName(bindingContext: BindingContext): Name? {
val callExpression = parent as KtCallExpression
val resolvedCall = callExpression.getResolvedCall(bindingContext)
return (resolvedCall?.getArgumentMapping(this) as? ArgumentMatch)?.valueParameter?.name
}
fun KtLambdaArgument.moveInsideParenthesesAndReplaceWith(
replacement: KtExpression,
functionLiteralArgumentName: Name?,
withNameCheck: Boolean = true,
): KtCallExpression {
val oldCallExpression = parent as KtCallExpression
val newCallExpression = oldCallExpression.copy() as KtCallExpression
val psiFactory = KtPsiFactory(project)
val argument =
if (withNameCheck && shouldLambdaParameterBeNamed(newCallExpression.getValueArgumentsInParentheses(), oldCallExpression)) {
psiFactory.createArgument(replacement, functionLiteralArgumentName)
} else {
psiFactory.createArgument(replacement)
}
val functionLiteralArgument = newCallExpression.lambdaArguments.firstOrNull()!!
val valueArgumentList = newCallExpression.valueArgumentList ?: psiFactory.createCallArguments("()")
valueArgumentList.addArgument(argument)
(functionLiteralArgument.prevSibling as? PsiWhiteSpace)?.delete()
if (newCallExpression.valueArgumentList != null) {
functionLiteralArgument.delete()
} else {
functionLiteralArgument.replace(valueArgumentList)
}
return oldCallExpression.replace(newCallExpression) as KtCallExpression
}
fun KtLambdaExpression.moveFunctionLiteralOutsideParenthesesIfPossible() {
val valueArgument = parentOfType<KtValueArgument>()?.takeIf {
KtPsiUtil.deparenthesize(it.getArgumentExpression()) == this
} ?: return
val valueArgumentList = valueArgument.parent as? KtValueArgumentList ?: return
val call = valueArgumentList.parent as? KtCallExpression ?: return
if (call.canMoveLambdaOutsideParentheses()) {
call.moveFunctionLiteralOutsideParentheses()
}
}
private fun shouldLambdaParameterBeNamed(args: List<ValueArgument>, callExpr: KtCallExpression): Boolean {
if (args.any { it.isNamed() }) return true
val callee = (callExpr.calleeExpression?.mainReference?.resolve() as? KtFunction) ?: return false
return if (callee.valueParameters.any { it.isVarArg }) true else callee.valueParameters.size - 1 > args.size
}
fun KtCallExpression.getLastLambdaExpression(): KtLambdaExpression? {
if (lambdaArguments.isNotEmpty()) return null
return valueArguments.lastOrNull()?.getArgumentExpression()?.unpackFunctionLiteral()
}
@OptIn(FrontendInternals::class)
fun KtCallExpression.canMoveLambdaOutsideParentheses(): Boolean {
if (getStrictParentOfType<KtDelegatedSuperTypeEntry>() != null) return false
val lastLambdaExpression = getLastLambdaExpression() ?: return false
val callee = calleeExpression
if (callee is KtNameReferenceExpression) {
val resolutionFacade = getResolutionFacade()
val samConversionTransformer = resolutionFacade.frontendService<SamConversionResolver>()
val samConversionOracle = resolutionFacade.frontendService<SamConversionOracle>()
val languageVersionSettings = resolutionFacade.getLanguageVersionSettings()
val newInferenceEnabled = languageVersionSettings.supportsFeature(LanguageFeature.NewInference)
val bindingContext = safeAnalyzeNonSourceRootCode(resolutionFacade, BodyResolveMode.PARTIAL_WITH_DIAGNOSTICS)
if (bindingContext.diagnostics.forElement(lastLambdaExpression).none { it.severity == Severity.ERROR }) {
val resolvedCall = getResolvedCall(bindingContext)
if (resolvedCall != null) {
val parameter = resolvedCall.getParameterForArgument(valueArguments.last()) ?: return false
val functionDescriptor = resolvedCall.resultingDescriptor as? FunctionDescriptor ?: return false
if (parameter != functionDescriptor.valueParameters.lastOrNull()) return false
return parameter.type.allowsMoveOutsideParentheses(samConversionTransformer, samConversionOracle, newInferenceEnabled)
}
}
val targets = bindingContext[BindingContext.REFERENCE_TARGET, callee]?.let { listOf(it) }
?: bindingContext[BindingContext.AMBIGUOUS_REFERENCE_TARGET, callee]
?: listOf()
val candidates = targets.filterIsInstance<FunctionDescriptor>()
val lambdaArgumentCount = valueArguments.count { it.getArgumentExpression()?.unpackFunctionLiteral() != null }
val referenceArgumentCount = valueArguments.count { it.getArgumentExpression() is KtCallableReferenceExpression }
// if there are functions among candidates but none of them have last function parameter then not show the intention
val areAllCandidatesWithoutLastFunctionParameter = candidates.none {
it.allowsMoveOfLastParameterOutsideParentheses(
lambdaArgumentCount + referenceArgumentCount,
samConversionTransformer,
samConversionOracle,
newInferenceEnabled
)
}
if (candidates.isNotEmpty() && areAllCandidatesWithoutLastFunctionParameter) return false
}
return true
}
private fun KotlinType.allowsMoveOutsideParentheses(
samConversionTransformer: SamConversionResolver,
samConversionOracle: SamConversionOracle,
newInferenceEnabled: Boolean
): Boolean {
// Fast-path
if (isFunctionOrSuspendFunctionType || isTypeParameter()) return true
// Also check if it can be SAM-converted
// Note that it is not necessary in OI, where we provide synthetic candidate descriptors with already
// converted types, but in NI it is performed by conversions, so we check it explicitly
// Also note that 'newInferenceEnabled' is essentially a micro-optimization, as there are no
// harm in just calling 'samConversionTransformer' on all candidates.
return newInferenceEnabled && samConversionTransformer.getFunctionTypeForPossibleSamType(this.unwrap(), samConversionOracle) != null
}
private fun FunctionDescriptor.allowsMoveOfLastParameterOutsideParentheses(
lambdaAndCallableReferencesInOriginalCallCount: Int,
samConversionTransformer: SamConversionResolver,
samConversionOracle: SamConversionOracle,
newInferenceEnabled: Boolean
): Boolean {
val params = valueParameters
val lastParamType = params.lastOrNull()?.type ?: return false
if (!lastParamType.allowsMoveOutsideParentheses(samConversionTransformer, samConversionOracle, newInferenceEnabled)) return false
val movableParametersOfCandidateCount = params.count {
it.type.allowsMoveOutsideParentheses(samConversionTransformer, samConversionOracle, newInferenceEnabled)
}
return movableParametersOfCandidateCount == lambdaAndCallableReferencesInOriginalCallCount
}
fun KtCallExpression.moveFunctionLiteralOutsideParentheses() {
assert(lambdaArguments.isEmpty())
val argumentList = valueArgumentList!!
val argument = argumentList.arguments.last()
val expression = argument.getArgumentExpression()!!
assert(expression.unpackFunctionLiteral() != null)
fun isWhiteSpaceOrComment(e: PsiElement) = e is PsiWhiteSpace || e is PsiComment
val prevComma = argument.siblings(forward = false, withItself = false).firstOrNull { it.elementType == KtTokens.COMMA }
val prevComments = (prevComma ?: argumentList.leftParenthesis)
?.siblings(forward = true, withItself = false)
?.takeWhile(::isWhiteSpaceOrComment)?.toList().orEmpty()
val nextComments = argumentList.rightParenthesis
?.siblings(forward = false, withItself = false)
?.takeWhile(::isWhiteSpaceOrComment)?.toList()?.reversed().orEmpty()
val psiFactory = KtPsiFactory(project)
val dummyCall = psiFactory.createExpression("foo() {}") as KtCallExpression
val functionLiteralArgument = dummyCall.lambdaArguments.single()
functionLiteralArgument.getArgumentExpression()?.replace(expression)
if (prevComments.any { it is PsiComment }) {
if (prevComments.firstOrNull() !is PsiWhiteSpace) this.add(psiFactory.createWhiteSpace())
prevComments.forEach { this.add(it) }
prevComments.forEach { if (it is PsiComment) it.delete() }
}
this.add(functionLiteralArgument)
if (nextComments.any { it is PsiComment }) {
nextComments.forEach { this.add(it) }
nextComments.forEach { if (it is PsiComment) it.delete() }
}
/* we should not remove empty parenthesis when callee is a call too - it won't parse */
if (argumentList.arguments.size == 1 && calleeExpression !is KtCallExpression) {
argumentList.delete()
} else {
argumentList.removeArgument(argument)
}
}
fun KtBlockExpression.appendElement(element: KtElement, addNewLine: Boolean = false): KtElement {
val rBrace = rBrace
val newLine = KtPsiFactory(this).createNewLine()
val anchor = if (rBrace == null) {
val lastChild = lastChild
lastChild as? PsiWhiteSpace ?: addAfter(newLine, lastChild)!!
} else {
rBrace.prevSibling!!
}
val addedElement = addAfter(element, anchor)!! as KtElement
if (addNewLine) {
addAfter(newLine, addedElement)
}
return addedElement
}
//TODO: git rid of this method
fun PsiElement.deleteElementAndCleanParent() {
val parent = parent
deleteElementWithDelimiters(this)
deleteChildlessElement(parent, this::class.java)
}
// Delete element if it doesn't contain children of a given type
private fun <T : PsiElement> deleteChildlessElement(element: PsiElement, childClass: Class<T>) {
if (PsiTreeUtil.getChildrenOfType<T>(element, childClass) == null) {
element.delete()
}
}
// Delete given element and all the elements separating it from the neighboring elements of the same class
private fun deleteElementWithDelimiters(element: PsiElement) {
val paramBefore = PsiTreeUtil.getPrevSiblingOfType(element, element.javaClass)
val from: PsiElement
val to: PsiElement
if (paramBefore != null) {
from = paramBefore.nextSibling
to = element
} else {
val paramAfter = PsiTreeUtil.getNextSiblingOfType(element, element.javaClass)
from = element
to = if (paramAfter != null) paramAfter.prevSibling else element
}
val parent = element.parent
parent.deleteChildRange(from, to)
}
fun PsiElement.deleteSingle() {
CodeEditUtil.removeChild(parent?.node ?: return, node ?: return)
}
fun KtClass.getOrCreateCompanionObject(): KtObjectDeclaration {
companionObjects.firstOrNull()?.let { return it }
return appendDeclaration(KtPsiFactory(this).createCompanionObject())
}
inline fun <reified T : KtDeclaration> KtClass.appendDeclaration(declaration: T): T {
val body = getOrCreateBody()
val anchor = PsiTreeUtil.skipSiblingsBackward(body.rBrace ?: body.lastChild!!, PsiWhiteSpace::class.java)
val newDeclaration = if (anchor?.nextSibling is PsiErrorElement) body.addBefore(declaration, anchor) else body.addAfter(declaration, anchor)
return newDeclaration as T
}
fun KtDeclaration.toDescriptor(): DeclarationDescriptor? {
if (this is KtScriptInitializer) {
return null
}
return resolveToDescriptorIfAny()
}
fun KtModifierListOwner.setVisibility(visibilityModifier: KtModifierKeywordToken, addImplicitVisibilityModifier: Boolean = false) {
if (this is KtDeclaration && !addImplicitVisibilityModifier) {
val defaultVisibilityKeyword = implicitVisibility()
if (visibilityModifier == defaultVisibilityKeyword) {
this.visibilityModifierType()?.let { removeModifier(it) }
return
}
}
addModifier(visibilityModifier)
}
fun KtDeclaration.implicitVisibility(): KtModifierKeywordToken? {
return when {
this is KtPropertyAccessor && isSetter && property.hasModifier(KtTokens.OVERRIDE_KEYWORD) -> {
(property.resolveToDescriptorIfAny() as? PropertyDescriptor)?.overriddenDescriptors?.forEach {
val visibility = it.setter?.visibility?.toKeywordToken()
if (visibility != null) return visibility
}
KtTokens.DEFAULT_VISIBILITY_KEYWORD
}
this is KtConstructor<*> -> {
// constructors cannot be declared in objects
val klass = getContainingClassOrObject() as? KtClass ?: return KtTokens.DEFAULT_VISIBILITY_KEYWORD
when {
klass.isEnum() -> KtTokens.PRIVATE_KEYWORD
klass.isSealed() ->
if (klass.languageVersionSettings.supportsFeature(LanguageFeature.SealedInterfaces)) KtTokens.PROTECTED_KEYWORD
else KtTokens.PRIVATE_KEYWORD
else -> KtTokens.DEFAULT_VISIBILITY_KEYWORD
}
}
hasModifier(KtTokens.OVERRIDE_KEYWORD) -> {
(resolveToDescriptorIfAny() as? CallableMemberDescriptor)
?.overriddenDescriptors
?.let { OverridingUtil.findMaxVisibility(it) }
?.toKeywordToken()
}
else -> {
KtTokens.DEFAULT_VISIBILITY_KEYWORD
}
}
}
fun KtModifierListOwner.canBePrivate(): Boolean {
if (modifierList?.hasModifier(KtTokens.ABSTRACT_KEYWORD) == true) return false
if (this.isAnnotationClassPrimaryConstructor()) return false
if (this is KtProperty && this.hasJvmFieldAnnotation()) return false
if (this is KtDeclaration) {
if (hasActualModifier() || isExpectDeclaration()) return false
val containingClassOrObject = containingClassOrObject ?: return true
if (containingClassOrObject is KtClass &&
(containingClassOrObject.isInterface() || containingClassOrObject.isAnnotation())
) {
return false
}
}
return true
}
fun KtModifierListOwner.canBeProtected(): Boolean {
val parent = when (this) {
is KtPropertyAccessor -> this.property.parent
else -> this.parent
}
return when (parent) {
is KtClassBody -> parent.parent is KtClass
is KtParameterList -> parent.parent is KtPrimaryConstructor
else -> false
}
}
fun KtModifierListOwner.canBeInternal(): Boolean {
if (containingClass()?.isInterface() == true) {
val objectDeclaration = getStrictParentOfType<KtObjectDeclaration>() ?: return false
if (objectDeclaration.isCompanion() && hasJvmFieldAnnotation()) return false
}
return !isAnnotationClassPrimaryConstructor()
}
private fun KtModifierListOwner.isAnnotationClassPrimaryConstructor(): Boolean =
this is KtPrimaryConstructor && (this.parent as? KtClass)?.hasModifier(KtTokens.ANNOTATION_KEYWORD) ?: false
fun KtClass.isInheritable(): Boolean {
return when (getModalityFromDescriptor()) {
KtTokens.ABSTRACT_KEYWORD, KtTokens.OPEN_KEYWORD, KtTokens.SEALED_KEYWORD -> true
else -> false
}
}
val KtParameter.isOverridable: Boolean
get() = hasValOrVar() && !isEffectivelyFinal
val KtProperty.isOverridable: Boolean
get() = !isTopLevel && !isEffectivelyFinal
private val KtDeclaration.isEffectivelyFinal: Boolean
get() = hasModifier(KtTokens.FINAL_KEYWORD) ||
!(hasModifier(KtTokens.OPEN_KEYWORD) || hasModifier(KtTokens.ABSTRACT_KEYWORD) || hasModifier(KtTokens.OVERRIDE_KEYWORD)) ||
containingClassOrObject?.isEffectivelyFinal == true
private val KtClassOrObject.isEffectivelyFinal: Boolean
get() = this is KtObjectDeclaration ||
this is KtClass && isEffectivelyFinal
private val KtClass.isEffectivelyFinal: Boolean
get() = hasModifier(KtTokens.FINAL_KEYWORD) ||
isData() ||
!(isSealed() || hasModifier(KtTokens.OPEN_KEYWORD) || hasModifier(KtTokens.ABSTRACT_KEYWORD))
fun KtDeclaration.isOverridable(): Boolean {
val parent = parent
if (!(parent is KtClassBody || parent is KtParameterList)) return false
val klass = if (parent.parent is KtPrimaryConstructor)
parent.parent.parent as? KtClass
else
parent.parent as? KtClass
if (klass == null || (!klass.isInheritable() && !klass.isEnum())) return false
if (this.hasModifier(KtTokens.PRIVATE_KEYWORD)) {
// 'private' is incompatible with 'open'
return false
}
return when (getModalityFromDescriptor()) {
KtTokens.ABSTRACT_KEYWORD, KtTokens.OPEN_KEYWORD -> true
else -> false
}
}
fun KtDeclaration.getModalityFromDescriptor(descriptor: DeclarationDescriptor? = resolveToDescriptorIfAny()): KtModifierKeywordToken? {
if (descriptor is MemberDescriptor) {
return mapModality(descriptor.modality)
}
return null
}
fun KtDeclaration.implicitModality(): KtModifierKeywordToken {
var predictedModality = predictImplicitModality()
val bindingContext = safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL)
val descriptor = bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, this] ?: return predictedModality
val containingDescriptor = descriptor.containingDeclaration ?: return predictedModality
val extensions = DeclarationAttributeAltererExtension.getInstances(this.project)
for (extension in extensions) {
val newModality = extension.refineDeclarationModality(
this,
descriptor as? ClassDescriptor,
containingDescriptor,
mapModalityToken(predictedModality),
isImplicitModality = true
)
if (newModality != null) {
predictedModality = mapModality(newModality)
}
}
return predictedModality
}
fun mapModality(accurateModality: Modality): KtModifierKeywordToken = when (accurateModality) {
Modality.FINAL -> KtTokens.FINAL_KEYWORD
Modality.SEALED -> KtTokens.SEALED_KEYWORD
Modality.OPEN -> KtTokens.OPEN_KEYWORD
Modality.ABSTRACT -> KtTokens.ABSTRACT_KEYWORD
}
private fun mapModalityToken(modalityToken: IElementType): Modality = when (modalityToken) {
KtTokens.FINAL_KEYWORD -> Modality.FINAL
KtTokens.SEALED_KEYWORD -> Modality.SEALED
KtTokens.OPEN_KEYWORD -> Modality.OPEN
KtTokens.ABSTRACT_KEYWORD -> Modality.ABSTRACT
else -> error("Unexpected modality keyword $modalityToken")
}
private fun KtDeclaration.predictImplicitModality(): KtModifierKeywordToken {
if (this is KtClassOrObject) {
if (this is KtClass && this.isInterface()) return KtTokens.ABSTRACT_KEYWORD
return KtTokens.FINAL_KEYWORD
}
val klass = containingClassOrObject ?: return KtTokens.FINAL_KEYWORD
if (hasModifier(KtTokens.OVERRIDE_KEYWORD)) {
if (klass.hasModifier(KtTokens.ABSTRACT_KEYWORD) ||
klass.hasModifier(KtTokens.OPEN_KEYWORD) ||
klass.hasModifier(KtTokens.SEALED_KEYWORD)
) {
return KtTokens.OPEN_KEYWORD
}
}
if (klass is KtClass && klass.isInterface() && !hasModifier(KtTokens.PRIVATE_KEYWORD)) {
return if (hasBody()) KtTokens.OPEN_KEYWORD else KtTokens.ABSTRACT_KEYWORD
}
return KtTokens.FINAL_KEYWORD
}
fun KtSecondaryConstructor.getOrCreateBody(): KtBlockExpression {
bodyExpression?.let { return it }
val delegationCall = getDelegationCall()
val anchor = if (delegationCall.isImplicit) valueParameterList else delegationCall
val newBody = KtPsiFactory(this).createEmptyBody()
return addAfter(newBody, anchor) as KtBlockExpression
}
fun KtParameter.dropDefaultValue() {
val from = equalsToken ?: return
val to = defaultValue ?: from
deleteChildRange(from, to)
}
fun dropEnclosingParenthesesIfPossible(expression: KtExpression): KtExpression {
val parent = expression.parent as? KtParenthesizedExpression ?: return expression
if (!KtPsiUtil.areParenthesesUseless(parent)) return expression
return parent.replaced(expression)
}
fun KtTypeParameterListOwner.addTypeParameter(typeParameter: KtTypeParameter): KtTypeParameter? {
typeParameterList?.let { return it.addParameter(typeParameter) }
val list = KtPsiFactory(this).createTypeParameterList("<X>")
list.parameters[0].replace(typeParameter)
val leftAnchor = when (this) {
is KtClass -> nameIdentifier
is KtNamedFunction -> funKeyword
is KtProperty -> valOrVarKeyword
is KtTypeAlias -> nameIdentifier
else -> null
} ?: return null
return (addAfter(list, leftAnchor) as KtTypeParameterList).parameters.first()
}
fun KtNamedFunction.getOrCreateValueParameterList(): KtParameterList {
valueParameterList?.let { return it }
val parameterList = KtPsiFactory(this).createParameterList("()")
val anchor = nameIdentifier ?: funKeyword!!
return addAfter(parameterList, anchor) as KtParameterList
}
fun KtCallableDeclaration.setType(type: KotlinType, shortenReferences: Boolean = true) {
if (type.isError) return
setType(IdeDescriptorRenderers.SOURCE_CODE.renderType(type), shortenReferences)
}
fun KtCallableDeclaration.setType(typeString: String, shortenReferences: Boolean = true) {
val typeReference = KtPsiFactory(project).createType(typeString)
setTypeReference(typeReference)
if (shortenReferences) {
ShortenReferences.DEFAULT.process(getTypeReference()!!)
}
}
fun KtCallableDeclaration.setReceiverType(type: KotlinType) {
if (type.isError) return
val typeReference = KtPsiFactory(project).createType(IdeDescriptorRenderers.SOURCE_CODE.renderType(type))
setReceiverTypeReference(typeReference)
ShortenReferences.DEFAULT.process(receiverTypeReference!!)
}
fun KtParameter.setDefaultValue(newDefaultValue: KtExpression): PsiElement {
defaultValue?.let { return it.replaced(newDefaultValue) }
val psiFactory = KtPsiFactory(this)
val eq = equalsToken ?: add(psiFactory.createEQ())
return addAfter(newDefaultValue, eq) as KtExpression
}
fun KtModifierList.appendModifier(modifier: KtModifierKeywordToken) {
add(KtPsiFactory(this).createModifier(modifier))
}
fun KtModifierList.normalize(): KtModifierList {
val psiFactory = KtPsiFactory(this)
return psiFactory.createEmptyModifierList().also { newList ->
val modifiers = SmartList<PsiElement>()
allChildren.forEach {
val elementType = it.node.elementType
when {
it is KtAnnotation || it is KtAnnotationEntry -> newList.add(it)
elementType is KtModifierKeywordToken -> {
if (elementType == KtTokens.DEFAULT_VISIBILITY_KEYWORD) return@forEach
if (elementType == KtTokens.FINALLY_KEYWORD && !hasModifier(KtTokens.OVERRIDE_KEYWORD)) return@forEach
modifiers.add(it)
}
}
}
modifiers.sortBy { MODIFIERS_ORDER.indexOf(it.node.elementType) }
modifiers.forEach { newList.add(it) }
}
}
fun KtBlockStringTemplateEntry.canDropBraces(): Boolean {
val expression = this.expression
return (expression is KtNameReferenceExpression || (expression is KtThisExpression && expression.labelQualifier == null))
&& canPlaceAfterSimpleNameEntry(nextSibling)
}
fun KtBlockStringTemplateEntry.dropBraces(): KtSimpleNameStringTemplateEntry {
val name = if (expression is KtThisExpression) {
KtTokens.THIS_KEYWORD.value
} else {
(expression as KtNameReferenceExpression).getReferencedNameElement().text
}
val newEntry = KtPsiFactory(this).createSimpleNameStringTemplateEntry(name)
return replaced(newEntry)
}
|
apache-2.0
|
b11c1bddf1fcae85e785bb1ce0d63909
| 41.670347 | 158 | 0.739539 | 5.303274 | false | false | false | false |
Cognifide/gradle-aem-plugin
|
src/main/kotlin/com/cognifide/gradle/aem/instance/tasks/InstanceBackup.kt
|
1
|
2060
|
package com.cognifide.gradle.aem.instance.tasks
import com.cognifide.gradle.aem.AemException
import com.cognifide.gradle.aem.common.instance.InstanceException
import com.cognifide.gradle.aem.common.tasks.LocalInstance
import com.cognifide.gradle.common.utils.Formats
import java.io.File
import org.gradle.api.tasks.Internal
import org.gradle.api.tasks.TaskAction
open class InstanceBackup : LocalInstance() {
private val manager get() = localInstanceManager.backup
/**
* Determines what need to be done (backup zipped and uploaded or something else).
*/
@Internal
var mode: Mode = Mode.of(aem.prop.string("instance.backup.mode") ?: Mode.ZIP_AND_UPLOAD.name)
@TaskAction
fun backup() {
when (mode) {
Mode.ZIP_ONLY -> zip()
Mode.ZIP_AND_UPLOAD -> {
val zip = zip()
upload(zip, false)
}
Mode.UPLOAD_ONLY -> {
val zip = manager.local ?: throw InstanceException("No instance backup to upload!")
upload(zip, true)
}
}
}
private fun zip(): File {
val file = manager.create(anyInstances)
manager.clean()
common.notifier.lifecycle("Instance(s) backed up", "File: ${file.name}, Size: ${Formats.fileSize(file)}")
return file
}
private fun upload(file: File, verbose: Boolean) {
val uploaded = manager.upload(file, verbose)
if (uploaded) {
common.notifier.lifecycle("Instance backup uploaded", "File: ${file.name}")
}
}
init {
description = "Turns off local instance(s), archives to ZIP file, then turns on again."
}
enum class Mode {
ZIP_ONLY,
ZIP_AND_UPLOAD,
UPLOAD_ONLY;
companion object {
fun of(name: String) = values().find { it.name.equals(name, true) }
?: throw AemException("Unsupported instance backup mode: $name")
}
}
companion object {
const val NAME = "instanceBackup"
}
}
|
apache-2.0
|
a46496a3a391aafbb163c170c4378073
| 29.294118 | 113 | 0.608252 | 4.212679 | false | false | false | false |
Cognifide/gradle-aem-plugin
|
src/main/kotlin/com/cognifide/gradle/aem/common/utils/JcrUtil.kt
|
1
|
1432
|
package com.cognifide.gradle.aem.common.utils
import com.cognifide.gradle.common.utils.formats.ISO8601
import java.util.*
import java.util.regex.Pattern
object JcrUtil {
fun date(date: Date = Date()): String = dateFormat(date)
fun dateParse(value: String): Date = ISO8601.parse(value).time
fun dateFormat(date: Calendar): String = ISO8601.format(date)
fun dateFormat(date: Date): String = dateFormat(dateToCalendar(date))
fun dateToCalendar(date: Date): Calendar = Calendar.getInstance().apply { time = date }
/**
* Converts e.g ':jcr:content' to '_jcr_content' (part of JCR path to be valid OS path).
*/
fun manglePath(path: String): String = when {
!path.contains("/") -> manglePathInternal("/$path").removePrefix("/")
else -> manglePathInternal(path)
}
private fun manglePathInternal(path: String): String {
var mangledPath = path
if (path.contains(":")) {
val matcher = MANGLE_NAMESPACE_PATTERN.matcher(path)
val buffer = StringBuffer()
while (matcher.find()) {
val namespace = matcher.group(1)
matcher.appendReplacement(buffer, "/_${namespace}_")
}
matcher.appendTail(buffer)
mangledPath = buffer.toString()
}
return mangledPath
}
private val MANGLE_NAMESPACE_PATTERN: Pattern = Pattern.compile("/([^:/]+):")
}
|
apache-2.0
|
263a33740df099f9857057d344e108e8
| 32.302326 | 92 | 0.627793 | 4.199413 | false | false | false | false |
vnesek/nmote-jwt-issuer
|
src/main/kotlin/com/nmote/jwti/web/GoogleLoginController.kt
|
1
|
2978
|
/*
* Copyright 2017. Vjekoslav Nesek
* 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.nmote.jwti.web
import com.fasterxml.jackson.databind.ObjectMapper
import com.github.scribejava.apis.openid.OpenIdOAuth2AccessToken
import com.github.scribejava.core.model.OAuthRequest
import com.github.scribejava.core.model.Verb
import com.github.scribejava.core.oauth.OAuth20Service
import com.nmote.jwti.config.GoogleAccount
import com.nmote.jwti.model.SocialAccount
import com.nmote.jwti.repository.AppRepository
import com.nmote.jwti.repository.UserRepository
import com.nmote.jwti.service.ScopeService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.CookieValue
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import javax.servlet.http.HttpServletResponse
@ConditionalOnBean(name = ["googleOAuthService"])
@Controller
@RequestMapping("/google")
class GoogleLoginController @Autowired
constructor(
@Qualifier("googleOAuthService") service: OAuth20Service,
objectMapper: ObjectMapper,
users: UserRepository,
apps: AppRepository,
tokens: TokenCache,
scopes: ScopeService
) : OAuthLoginController<OAuth20Service, OpenIdOAuth2AccessToken>(service, objectMapper, users, apps, tokens, scopes) {
@RequestMapping("callback")
fun callback(
@RequestParam code: String,
@CookieValue("authState") authState: String,
response: HttpServletResponse
): String {
val accessToken = service.getAccessToken(code) as OpenIdOAuth2AccessToken
return callback(accessToken, authState, response)
}
override fun getSocialAccount(accessToken: OpenIdOAuth2AccessToken): SocialAccount<*> {
val request = OAuthRequest(Verb.GET, "https://www.googleapis.com/oauth2/v3/userinfo")
service.signRequest(accessToken, request)
val response = service.execute(request)
val responseBody = response.body
val account = objectMapper.readValue(responseBody, GoogleAccount::class.java)
account.accessToken = accessToken
return account
}
override val authorizationUrl: String
get() = service.authorizationUrl
}
|
apache-2.0
|
908cf3c0f58400a1270bcc6ae819b01e
| 40.361111 | 119 | 0.771995 | 4.411852 | false | false | false | false |
hazuki0x0/YuzuBrowser
|
legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/action/ActionNameMap.kt
|
1
|
1444
|
/*
* Copyright (C) 2017-2021 Hazuki
*
* 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 jp.hazuki.yuzubrowser.legacy.action
import android.content.res.Resources
import androidx.collection.SparseArrayCompat
import androidx.collection.set
import jp.hazuki.yuzubrowser.legacy.R
class ActionNameMap(resources: Resources) {
private val names = SparseArrayCompat<String>()
init {
val actionList = resources.getStringArray(R.array.action_list)
val actionValues = resources.getIntArray(R.array.action_values)
require(actionList.size == actionValues.size)
for (i in actionList.indices) {
names[actionValues[i]] = actionList[i]
}
}
operator fun get(key: Int) = names[key]
operator fun get(action: Action?): String? {
return if (action == null || action.size == 0) {
null
} else {
get(action[0].id)
}
}
}
|
apache-2.0
|
2391650e29474908806cd0ae58778f25
| 30.391304 | 75 | 0.686288 | 4.137536 | false | false | false | false |
seventhroot/elysium
|
bukkit/rpk-selection-worldedit-bukkit/src/main/kotlin/com/rpkit/selection/bukkit/worldedit/selection/RPKWorldEditSelection.kt
|
1
|
4216
|
/*
* Copyright 2019 Ren Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.selection.bukkit.worldedit.selection
import com.rpkit.players.bukkit.profile.RPKMinecraftProfile
import com.rpkit.selection.bukkit.selection.RPKSelection
import com.sk89q.worldedit.IncompleteRegionException
import com.sk89q.worldedit.LocalSession
import com.sk89q.worldedit.bukkit.BukkitAdapter
import com.sk89q.worldedit.math.BlockVector3
import com.sk89q.worldedit.regions.selector.CuboidRegionSelector
import com.sk89q.worldedit.regions.selector.limit.PermissiveSelectorLimits
import org.bukkit.Bukkit
import org.bukkit.World
import org.bukkit.block.Block
import kotlin.math.floor
class RPKWorldEditSelection(
override var id: Int = 0,
override val minecraftProfile: RPKMinecraftProfile,
val session: LocalSession?
): RPKSelection {
override var point1: Block
get() {
return if (session == null) {
val world = Bukkit.getWorlds()[0]
world.getBlockAt(world.spawnLocation)
} else {
val world = BukkitAdapter.adapt(session.selectionWorld)
val primaryPosition = try {
session.getRegionSelector(session.selectionWorld).primaryPosition.toVector3()
} catch (exception: IncompleteRegionException) {
BukkitAdapter.adapt(world.spawnLocation).toVector()
}
world.getBlockAt(
floor(primaryPosition.x).toInt(),
floor(primaryPosition.y).toInt(),
floor(primaryPosition.z).toInt()
)
}
}
set(value) {
val selector = session?.getRegionSelector(BukkitAdapter.adapt(value.world))
selector?.selectPrimary(
BlockVector3.at(
value.x,
value.y,
value.z
),
PermissiveSelectorLimits.getInstance()
)
}
override var point2: Block
get() {
return if (session == null) {
val world = Bukkit.getWorlds()[0]
world.getBlockAt(world.spawnLocation)
} else {
val world = BukkitAdapter.adapt(session.selectionWorld)
val secondaryPosition = try {
(session.getRegionSelector(session.selectionWorld) as? CuboidRegionSelector)?.region?.pos2?.toVector3()
} catch (exception: IncompleteRegionException) {
null
} ?: BukkitAdapter.adapt(world.spawnLocation).toVector()
world.getBlockAt(
floor(secondaryPosition.x).toInt(),
floor(secondaryPosition.y).toInt(),
floor(secondaryPosition.z).toInt()
)
}
}
set(value) {
val selector = session?.getRegionSelector(BukkitAdapter.adapt(value.world))
selector?.selectPrimary(
BlockVector3.at(
value.x,
value.y,
value.z
),
PermissiveSelectorLimits.getInstance()
)
}
override var world: World
get() = BukkitAdapter.adapt(session?.selectionWorld) ?: Bukkit.getWorlds()[0]
set(value) {
}
override fun contains(block: Block): Boolean {
return session?.getSelection(session.selectionWorld)?.contains(BukkitAdapter.asBlockVector(block.location)) ?: false
}
}
|
apache-2.0
|
b8bee0df65d96148d9cab22f91237adc
| 36.990991 | 124 | 0.591082 | 4.796359 | false | false | false | false |
firebase/quickstart-android
|
auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/FirebaseUIFragment.kt
|
1
|
3832
|
package com.google.firebase.quickstart.auth.kotlin
import android.app.Activity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.firebase.ui.auth.AuthUI
import com.firebase.ui.auth.FirebaseAuthUIActivityResultContract
import com.firebase.ui.auth.data.model.FirebaseAuthUIAuthenticationResult
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
import com.google.firebase.quickstart.auth.BuildConfig
import com.google.firebase.quickstart.auth.R
import com.google.firebase.quickstart.auth.databinding.FragmentFirebaseUiBinding
/**
* Demonstrate authentication using the FirebaseUI-Android library. This fragment demonstrates
* using FirebaseUI for basic email/password sign in.
*
* For more information, visit https://github.com/firebase/firebaseui-android
*/
class FirebaseUIFragment : Fragment() {
private lateinit var auth: FirebaseAuth
private var _binding: FragmentFirebaseUiBinding? = null
private val binding: FragmentFirebaseUiBinding
get() = _binding!!
// Build FirebaseUI sign in intent. For documentation on this operation and all
// possible customization see: https://github.com/firebase/firebaseui-android
private val signInLauncher = registerForActivityResult(
FirebaseAuthUIActivityResultContract()
) { result -> this.onSignInResult(result)}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
_binding = FragmentFirebaseUiBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// Initialize Firebase Auth
auth = Firebase.auth
binding.signInButton.setOnClickListener { startSignIn() }
binding.signOutButton.setOnClickListener { signOut() }
}
override fun onStart() {
super.onStart()
updateUI(auth.currentUser)
}
private fun onSignInResult(result: FirebaseAuthUIAuthenticationResult) {
if (result.resultCode == Activity.RESULT_OK) {
// Sign in succeeded
updateUI(auth.currentUser)
} else {
// Sign in failed
Toast.makeText(context, "Sign In Failed", Toast.LENGTH_SHORT).show()
updateUI(null)
}
}
private fun startSignIn() {
val intent = AuthUI.getInstance().createSignInIntentBuilder()
.setIsSmartLockEnabled(!BuildConfig.DEBUG)
.setAvailableProviders(listOf(AuthUI.IdpConfig.EmailBuilder().build()))
.setLogo(R.mipmap.ic_launcher)
.build()
signInLauncher.launch(intent)
}
private fun updateUI(user: FirebaseUser?) {
if (user != null) {
// Signed in
binding.status.text = getString(R.string.firebaseui_status_fmt, user.email)
binding.detail.text = getString(R.string.id_fmt, user.uid)
binding.signInButton.visibility = View.GONE
binding.signOutButton.visibility = View.VISIBLE
} else {
// Signed out
binding.status.setText(R.string.signed_out)
binding.detail.text = null
binding.signInButton.visibility = View.VISIBLE
binding.signOutButton.visibility = View.GONE
}
}
private fun signOut() {
AuthUI.getInstance().signOut(requireContext())
updateUI(null)
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
|
apache-2.0
|
bd0975c91652df2a681b9255b7bbb42d
| 34.155963 | 115 | 0.695459 | 4.736712 | false | false | false | false |
joekickass/monday-madness
|
app/src/main/kotlin/com/joekickass/mondaymadness/model/Workout.kt
|
1
|
1487
|
package com.joekickass.mondaymadness.model
class Workout(private val queue: IntervalQueue, internal val timer: Timer = Timer(queue.time)) {
var onWorkRunning: () -> Unit = {}
var onWorkPaused: () -> Unit = {}
var onWorkFinished: () -> Unit = {}
var onRestRunning: () -> Unit = {}
var onRestPaused: () -> Unit = {}
var onRestFinished: () -> Unit = {}
var onWorkoutFinished: () -> Unit = {}
init {
timer.onRunning = { intervalRunning() }
timer.onPaused = { intervalPaused() }
timer.onFinished = { intervalFinished() }
}
fun start(): Workout {
timer.start()
return this
}
fun pause(): Workout {
timer.pause()
return this
}
private fun intervalRunning() {
when {
queue.work -> onWorkRunning()
queue.rest -> onRestRunning()
}
}
private fun intervalPaused() {
when {
queue.work -> onWorkPaused()
queue.rest -> onRestPaused()
}
}
private fun intervalFinished() {
when {
queue.work -> onWorkFinished()
queue.rest -> onRestFinished()
}
// Start new if there are any intervals left
if (queue.hasNextInterval()) {
queue.nextInterval()
timer.reset(queue.time)
start()
} else {
onWorkoutFinished()
}
}
val running: Boolean
get() = timer.running
}
|
apache-2.0
|
cce4ec4f787ecb9473251c5daf554bce
| 23.393443 | 96 | 0.529254 | 4.386431 | false | false | false | false |
dkhmelenko/Varis-Android
|
app-v3/src/main/java/com/khmelenko/lab/varis/network/retrofit/raw/RawClient.kt
|
2
|
2662
|
package com.khmelenko.lab.varis.network.retrofit.raw
import com.khmelenko.lab.varis.storage.AppSettings
import java.lang.reflect.Type
import io.reactivex.Single
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.ResponseBody
import retrofit2.Converter
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
/**
* Raw http client
*
* @author Dmytro Khmelenko ([email protected])
*/
class RawClient(private var retrofit: Retrofit, private val httpClient: OkHttpClient, appSettings: AppSettings) {
/**
* Gets Raw API service
*
* @return Raw API service
*/
lateinit var apiService: RawApiService
private set
init {
val travisUrl = appSettings.serverUrl
updateEndpoint(travisUrl)
}
/**
* Updates Travis endpoint
*
* @param newEndpoint New endpoint
*/
fun updateEndpoint(newEndpoint: String) {
retrofit = Retrofit.Builder()
.baseUrl(newEndpoint)
.addConverterFactory(object : Converter.Factory() {
override fun responseBodyConverter(type: Type?, annotations: Array<Annotation>?, retrofit: Retrofit?): Converter<ResponseBody, *>? {
return if (String::class.java == type) {
Converter<ResponseBody, String> { value -> value.string() }
} else null
}
})
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(httpClient)
.build()
apiService = retrofit.create(RawApiService::class.java)
}
/**
* Executes single request
*
* @param url URL for request
* @return Response
*/
fun singleRequest(url: String): Single<Response> {
val request = Request.Builder()
.url(url)
.build()
return Single.create { e ->
val response = httpClient.newCall(request).execute()
e.onSuccess(response)
}
}
/**
* Executes single request
*
* @param url URL for request
* @return String
*/
fun singleStringRequest(url: String): Single<String> {
val request = Request.Builder()
.url(url)
.build()
return Single.create { e ->
val response = httpClient.newCall(request).execute()
e.onSuccess(response.body()!!.string())
}
}
fun getLogUrl(jobId: Long?): String {
return String.format("%sjobs/%d/log", retrofit.baseUrl(), jobId)
}
}
|
apache-2.0
|
7ab49dadc086fc57fc35e3fff4f674c2
| 26.443299 | 152 | 0.59429 | 4.736655 | false | false | false | false |
j-selby/kotgb
|
core/src/main/kotlin/net/jselby/kotgb/cpu/interpreter/instructions/Loads.kt
|
1
|
24274
|
package net.jselby.kotgb.cpu.interpreter.instructions
import net.jselby.kotgb.Gameboy
import net.jselby.kotgb.cpu.CPU
import net.jselby.kotgb.cpu.Registers
/**
* Load instructions store values in registers or in RAM.
*/
// TODO: Sort this file
/**
* -- 8 bit loads. --
*/
/**
* **0x02** - *LD (bc),a* - Put a in \*bc
*/
val x02 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
gb.ram.writeByte(registers.bc.toLong() and 0xFFFF, registers.a)
/*Cycles: */ 8
}
/**
* **0x06** - *LD b,#* - Put # in b
*/
val x06 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.b = gb.ram.readByte(registers.pc.toLong()).toShort()
registers.pc++
/*Cycles: */ 8
}
/**
* **0x0A** - *LD a,(bc)* - Put \*bc in a
*/
val x0A : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.a = gb.ram.readByte(registers.bc.toLong() and 0xFFFF).toShort()
/*Cycles: */ 8
}
/**
* **0x0E** - *LD c,#* - Put # in c
*/
val x0E : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.c = gb.ram.readByte(registers.pc.toLong()).toShort()
registers.pc++
/*Cycles: */ 8
}
/**
* **0x12** - *LD (de),a* - Put a into \*de
*/
val x12 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
gb.ram.writeByte(registers.de.toLong() and 0xFFFF, registers.a)
/*Cycles: */ 8
}
/**
* **0x16** - *LD d,n* - Put n in d
*/
val x16 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.d = (gb.ram.readByte(registers.pc.toLong()).toInt() and 0xFF).toShort()
registers.pc++
/*Cycles: */ 8
}
/**
* **0x1A** - *LD a,(de)* - Put \*de into a
*/
val x1A : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.a = gb.ram.readByte((registers.de.toInt() and 0xFFFF).toLong()).toShort()
/*Cycles: */ 8
}
/**
* **0x1E** - *LD e,n* - Put n in e
*/
val x1E : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.e = (gb.ram.readByte(registers.pc.toLong()).toInt() and 0xFF).toShort()
registers.pc++
/*Cycles: */ 8
}
/**
* **0x22** - *LDI (hl),a* - Put a into \*hl. Increment hl.
*/
val x22 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
gb.ram.writeByte(registers.hl.toLong() and 0xFFFF, registers.a)
registers.hl++
/*Cycles: */ 8
}
/**
* **0x26** - *LD h,#* - Put # in h
*/
val x26 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.h = gb.ram.readByte(registers.pc.toLong()).toShort()
registers.pc++
/*Cycles: */ 8
}
/**
* **0x2A** - *LDI a,(hl)* - Put *hl into a. Increment hl.
*/
val x2A : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.a = gb.ram.readByte((registers.hl.toInt() and 0xFFFF).toLong()).toShort()
registers.hl++
/*Cycles: */ 8
}
/**
* **0x2E** - *LD l,#* - Put # in l
*/
val x2E : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.l = gb.ram.readByte(registers.pc.toLong()).toShort()
registers.pc++
/*Cycles: */ 8
}
/**
* **0x3A** - *LDD a,(hl)* - Put \*hl in a. Decrement hl.
*/
val x3A : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.a = gb.ram.readByte(registers.hl.toLong() and 0xFFFF).toShort()
registers.hl--
/*Cycles: */ 8
}
/**
* **0x32** - *LDD (hl),a* - Put a into \*hl. Decrement hl.
*/
val x32 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
gb.ram.writeByte(registers.hl.toLong() and 0xFFFF, registers.a)
registers.hl--
/*Cycles: */ 8
}
/**
* **0x36** - *LD (hl),n* - Put n in \*hl
*/
val x36 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
gb.ram.writeByte(registers.hl.toLong() and 0xFFFF, gb.ram.readByte(registers.pc.toLong()).toShort())
registers.pc++
/*Cycles: */ 12
}
/**
* **0x3E** - *LD a,#* - Put # in a
*/
val x3E : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.a = gb.ram.readByte(registers.pc.toLong()).toShort()
registers.pc++
/*Cycles: */ 8
}
/**
* **0x40** - *LD b,b* - Put b in b
*/
val x40 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.b = registers.b
/*Cycles: */ 4
}
/**
* **0x41** - *LD b,c* - Put c in b
*/
val x41 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.b = registers.c
/*Cycles: */ 4
}
/**
* **0x42** - *LD b,d* - Put d in b
*/
val x42 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.b = registers.d
/*Cycles: */ 4
}
/**
* **0x43** - *LD b,e* - Put e in b
*/
val x43 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.b = registers.e
/*Cycles: */ 4
}
/**
* **0x44** - *LD b,h* - Put h in b
*/
val x44 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.b = registers.h
/*Cycles: */ 4
}
/**
* **0x45** - *LD b,l* - Put l in b
*/
val x45 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.b = registers.l
/*Cycles: */ 4
}
/**
* **0x46** - *LD b,(hl)* - Put \*hl in b
*/
val x46 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.b = gb.ram.readByte(registers.hl.toLong() and 0xFFFF).toShort()
/*Cycles: */ 8
}
/**
* **0x47** - *LD b,a* - Put a in b
*/
val x47 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.b = registers.a
/*Cycles: */ 4
}
/**
* **0x48** - *LD c,b* - Put b in c
*/
val x48 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.c = registers.b
/*Cycles: */ 4
}
/**
* **0x49** - *LD c,c* - Put c in c
*/
val x49 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.c = registers.c
/*Cycles: */ 4
}
/**
* **0x4A** - *LD c,d* - Put d in c
*/
val x4A : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.c = registers.d
/*Cycles: */ 4
}
/**
* **0x4B** - *LD c,e* - Put e in c
*/
val x4B : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.c = registers.e
/*Cycles: */ 4
}
/**
* **0x4C** - *LD c,h* - Put h in c
*/
val x4C : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.c = registers.h
/*Cycles: */ 4
}
/**
* **0x4D** - *LD c,l* - Put l in c
*/
val x4D : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.c = registers.l
/*Cycles: */ 4
}
/**
* **0x4E** - *LD c,(hl)* - Put \*hl in c
*/
val x4E : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.c = gb.ram.readByte(registers.hl.toLong() and 0xFFFF)
/*Cycles: */ 8
}
/**
* **0x4F** - *LD c,a* - Put a in c
*/
val x4F : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.c = registers.a
/*Cycles: */ 4
}
/**
* **0x50** - *LD d,b* - Put b in d
*/
val x50 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.d = registers.b
/*Cycles: */ 4
}
/**
* **0x51** - *LD d,c* - Put c in d
*/
val x51 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.d = registers.c
/*Cycles: */ 4
}
/**
* **0x52** - *LD d,d* - Put d in d
*/
val x52 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.d = registers.d
/*Cycles: */ 4
}
/**
* **0x53** - *LD d,e* - Put e in d
*/
val x53 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.d = registers.e
/*Cycles: */ 4
}
/**
* **0x54** - *LD d,h* - Put h in d
*/
val x54 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.d = registers.h
/*Cycles: */ 4
}
/**
* **0x55** - *LD d,l* - Put l in d
*/
val x55 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.d = registers.l
/*Cycles: */ 4
}
/**
* **0x56** - *LD d,(hl)* - Put \*hl in d
*/
val x56 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.d = gb.ram.readByte(registers.hl.toLong() and 0xFFFF).toShort()
/*Cycles: */ 8
}
/**
* **0x57** - *LD d,a* - Put a in d
*/
val x57 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.d = registers.a
/*Cycles: */ 4
}
/**
* **0x58** - *LD e,b* - Put b in e
*/
val x58 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.e = registers.b
/*Cycles: */ 4
}
/**
* **0x59** - *LD e,c* - Put c in e
*/
val x59 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.e = registers.c
/*Cycles: */ 4
}
/**
* **0x5A** - *LD e,d* - Put d in e
*/
val x5A : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.e = registers.d
/*Cycles: */ 4
}
/**
* **0x5B** - *LD e,e* - Put e in e
*/
val x5B : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.e = registers.e
/*Cycles: */ 4
}
/**
* **0x5C** - *LD e,h* - Put h in e
*/
val x5C : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.e = registers.h
/*Cycles: */ 4
}
/**
* **0x5D** - *LD e,l* - Put l in e
*/
val x5D : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.e = registers.l
/*Cycles: */ 4
}
/**
* **0x5E** - *LD e,(hl)* - Put \*hl in e
*/
val x5E : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.e = gb.ram.readByte(registers.hl.toLong() and 0xFFFF).toShort()
/*Cycles: */ 8
}
/**
* **0x5F** - *LD e,a* - Put a in e
*/
val x5F : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.e = registers.a
/*Cycles: */ 4
}
/**
* **0x60** - *LD h,b* - Put b in h
*/
val x60 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.h = registers.b
/*Cycles: */ 4
}
/**
* **0x61** - *LD h,c* - Put c in h
*/
val x61 : (CPU, Registers, Gameboy) -> (Int) = {
cpu: CPU, registers: Registers, gb: Gameboy ->
registers.h = registers.c
/*Cycles: */ 4
}
/**
* **0x62** - *LD h,d* - Put d in h
*/
val x62 : (CPU, Registers, Gameboy) -> (Int) = {
cpu: CPU, registers: Registers, gb: Gameboy ->
registers.h = registers.d
/*Cycles: */ 4
}
/**
* **0x63** - *LD h,e* - Put e in h
*/
val x63 : (CPU, Registers, Gameboy) -> (Int) = {
cpu: CPU, registers: Registers, gb: Gameboy ->
registers.h = registers.e
/*Cycles: */ 4
}
/**
* **0x64** - *LD h,h* - Put h in h
*/
val x64 : (CPU, Registers, Gameboy) -> (Int) = {
cpu: CPU, registers: Registers, gb: Gameboy ->
registers.h = registers.h
/*Cycles: */ 4
}
/**
* **0x65** - *LD h,l* - Put l in h
*/
val x65 : (CPU, Registers, Gameboy) -> (Int) = {
cpu: CPU, registers: Registers, gb: Gameboy ->
registers.h = registers.l
/*Cycles: */ 4
}
/**
* **0x66** - *LD h,(hl)* - Put \*hl in h
*/
val x66 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.h = gb.ram.readByte(registers.hl.toLong() and 0xFFFF).toShort()
/*Cycles: */ 8
}
/**
* **0x67** - *LD h,a* - Put a in h
*/
val x67 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.h = registers.a
/*Cycles: */ 4
}
/**
* **0x68** - *LD l,b* - Put b in l
*/
val x68 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.l = registers.b
/*Cycles: */ 4
}
/**
* **0x69** - *LD l,c* - Put c in l
*/
val x69 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.l = registers.c
/*Cycles: */ 4
}
/**
* **0x6A** - *LD l,e* - Put d in l
*/
val x6A : (CPU, Registers, Gameboy) -> (Int) = {
cpu: CPU, registers: Registers, gb: Gameboy ->
registers.l = registers.d
/*Cycles: */ 4
}
/**
* **0x6B** - *LD l,e* - Put e in l
*/
val x6B : (CPU, Registers, Gameboy) -> (Int) = {
cpu: CPU, registers: Registers, gb: Gameboy ->
registers.l = registers.e
/*Cycles: */ 4
}
/**
* **0x6C** - *LD l,h* - Put h in l
*/
val x6C : (CPU, Registers, Gameboy) -> (Int) = {
cpu: CPU, registers: Registers, gb: Gameboy ->
registers.l = registers.h
/*Cycles: */ 4
}
/**
* **0x6D** - *LD l,l* - Put l in l
*/
val x6D : (CPU, Registers, Gameboy) -> (Int) = {
cpu: CPU, registers: Registers, gb: Gameboy ->
registers.l = registers.l
/*Cycles: */ 4
}
/**
* **0x6E** - *LD l,(hl)* - Put \*hl in l
*/
val x6E : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.l = gb.ram.readByte(registers.hl.toLong() and 0xFFFF).toShort()
/*Cycles: */ 8
}
/**
* **0x6F** - *LD l,a* - Put a in l
*/
val x6F : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.l = registers.a
/*Cycles: */ 4
}
/**
* **0x70** - *LD (hl),b* - Put b in \*hl
*/
val x70 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
gb.ram.writeByte(registers.hl.toLong() and 0xFFFF, registers.b)
/*Cycles: */ 8
}
/**
* **0x71** - *LD (hl),c* - Put c in \*hl
*/
val x71 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
gb.ram.writeByte(registers.hl.toLong() and 0xFFFF, registers.c)
/*Cycles: */ 8
}
/**
* **0x72** - *LD (hl),d* - Put d in \*hl
*/
val x72 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
gb.ram.writeByte(registers.hl.toLong() and 0xFFFF, registers.d)
/*Cycles: */ 8
}
/**
* **0x73** - *LD (hl),e* - Put e in \*hl
*/
val x73 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
gb.ram.writeByte(registers.hl.toLong() and 0xFFFF, registers.e)
/*Cycles: */ 8
}
/**
* **0x74** - *LD (hl),h* - Put h in \*hl
*/
val x74 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
gb.ram.writeByte(registers.hl.toLong() and 0xFFFF, registers.h)
/*Cycles: */ 8
}
/**
* **0x75** - *LD (hl),l* - Put l in \*hl
*/
val x75 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
gb.ram.writeByte(registers.hl.toLong() and 0xFFFF, registers.l)
/*Cycles: */ 8
}
/**
* **0x77** - *LD (hl),a* - Put a in \*hl
*/
val x77 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
gb.ram.writeByte(registers.hl.toLong() and 0xFFFF, registers.a)
/*Cycles: */ 8
}
/**
* **0x78** - *LD a,b* - Put b in a
*/
val x78 : (CPU, Registers, Gameboy) -> (Int) = {
cpu: CPU, registers: Registers, gb: Gameboy ->
registers.a = registers.b
/*Cycles: */ 4
}
/*
* **0x79** - *LD a,c* - Put c in a
*/
val x79 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.a = registers.c
/*Cycles: */ 4
}
/**
* **0x7A** - *LD a,d* - Put d in a
*/
val x7A : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.a = registers.d
/*Cycles: */ 4
}
/**
* **0x7B** - *LD a,e* - Put e in a
*/
val x7B : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.a = registers.e
/*Cycles: */ 4
}
/**
* **0x7C** - *LD a,h* - Put h in a
*/
val x7C : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.a = registers.h
/*Cycles: */ 4
}
/**
* **0x7D** - *LD a,l* - Put l in a
*/
val x7D : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.a = registers.l
/*Cycles: */ 4
}
/**
* **0x7E** - *LD a,(hl)* - Put \*hl in a
*/
val x7E : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.a = gb.ram.readByte(registers.hl.toLong() and 0xFFFF).toShort()
/*Cycles: */ 8
}
/**
* **0x7F** - *LD a,a* - Put a in a (so powerful, much processing)
*/
val x7F : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.a = registers.a
/*Cycles: */ 4
}
/**
* -- 16 bit loads. --
**/
/**
* **0x01** - *LD bc,nnnn* - Put nnnn in bc
*/
val x01 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.bc = gb.ram.readShortAsInt((registers.pc and 0xFFFF).toLong())
registers.pc += 2
/*Cycles: */ 12
}
/**
* **0x08** - *LD (nn),sp* - Put sp at n
*/
val x08 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
val pointer = gb.ram.readShortAsInt((registers.pc and 0xFFFF).toLong()) and 0xFFFF
gb.ram.writeShort(pointer.toLong(), registers.sp.toShort())
registers.pc += 2
/*Cycles: */ 20
}
/**
* **0x11** - *LD de,nn* - Put nn in de
*/
val x11 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.de = gb.ram.readShortAsInt(registers.pc.toLong())
registers.pc += 2
/*Cycles: */ 12
}
/**
* **0x21** - *LD hl,nnnn* - Put nnnn in hl
*/
val x21 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.hl = gb.ram.readShortAsInt(registers.pc.toLong())
registers.pc += 2
/*Cycles: */ 12
}
/**
* **0x31** - *LD sp,nn* - Put nn in sp
*/
val x31 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.sp = gb.ram.readShortAsInt(registers.pc.toLong())
registers.pc += 2
/*Cycles: */ 12
}
/**
* **0xC1** - *POP bc* - Pop stack element into bc
*/
val xC1 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.bc = gb.ram.readShortAsInt(registers.sp.toLong())
registers.sp += 2
/*Cycles: */ 12
}
/**
* **0xC5** - *PUSH bc* - Push bc onto the stack
*/
val xC5 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.sp -= 2
gb.ram.writeShort(registers.sp.toLong(), registers.bc.toShort())
/*Cycles: */ 16
}
/**
* **0xD1** - *POP de* - Pop stack element into de
*/
val xD1 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.de = gb.ram.readShortAsInt(registers.sp.toLong())
registers.sp += 2
/*Cycles: */ 12
}
/**
* **0xD5** - *PUSH de* - Push de onto the stack
*/
val xD5 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.sp -= 2
gb.ram.writeShort(registers.sp.toLong(), registers.de.toShort())
/*Cycles: */ 16
}
/**
* **0xE0** - *LDH (n),a* - Put a in memory address *($FF00+n)
*/
val xE0 : (CPU, Registers, Gameboy) -> (Int) = {
_, registers, gb ->
val value = (0xFF00 + getN(registers, gb)).toLong()
gb.ram.writeByte(value, registers.a)
/*Cycles: */ 12
}
/**
* **0xE1** - *POP hl* - Pop stack element into hl
*/
val xE1 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.hl = gb.ram.readShortAsInt(registers.sp.toLong())
registers.sp += 2
/*Cycles: */ 12
}
/**
* **0xE2** - *LD (c),a* - Put a in memory address *($FF00+c)
*/
val xE2 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
val value = (0xFF00 + (registers.c.toInt() and 0xFF)).toLong()
gb.ram.writeByte(value, registers.a)
/*Cycles: */ 8
}
/**
* **0xE5** - *PUSH hl* - Push hl onto the stack
*/
val xE5 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.sp -= 2
gb.ram.writeShort(registers.sp.toLong(), registers.hl.toShort())
/*Cycles: */ 16
}
/**
* **0xEA** - *LD (nn),a* - Put a in \*nn
*/
val xEA : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
// Read PC short
val value = gb.ram.readShortAsInt(registers.pc.toLong()) and 0xFFFF
registers.pc += 2
// Write it
gb.ram.writeByte(value.toLong(), registers.a)
/*Cycles: */ 16
}
/**
* **0xF0** - *LDH a,(n)* - Put memory address *($FF00+n) in A
*/
val xF0 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
val value = (0xFF00 + (gb.ram.readByte(registers.pc.toLong()).toInt()
and 0xFF)).toLong()
//println("New value: $value = ${gb.ram.readByte(value)}")
registers.a = gb.ram.readByte(value).toShort()
registers.pc++
/*Cycles: */ 12
}
/**
* **0xF1** - *POP af* - Pop stack element into af
*/
val xF1 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.af = gb.ram.readShortAsInt(registers.sp.toLong())
registers.sp += 2
/*Cycles: */ 12
}
/**
* **0xF2** - *LD a,(c)* - Put *($FF00+c) into a
*/
val xF2 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
val value = (0xFF00 + (registers.c.toInt() and 0xFF)).toLong()
registers.a = gb.ram.readByte(value)
/*Cycles: */ 8
}
/**
* **0xF5** - *PUSH af* - Push af onto the stack
*/
val xF5 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.sp -= 2
gb.ram.writeShort(registers.sp.toLong(), registers.af.toShort())
/*Cycles: */ 16
}
/**
* **0xF8** - *LDHL SP,n* - Put sp + n effective address into hl
*/
val xF8 : (CPU, Registers, Gameboy) -> (Int) = {
_, registers, gb ->
val prevValue = registers.sp
val curValue = gb.ram.readByte(registers.pc.toLong() and 0xFFFF).toInt()
registers.pc++
val result = prevValue + curValue
registers.hl = result
registers.flagZ = false
registers.flagN = false
registers.flagH = (prevValue xor curValue xor (result and 0xFFFF) and 0x10) == 0x10
registers.flagC = (prevValue xor curValue xor (result and 0xFFFF) and 0x100) == 0x100
/*Cycles: */ 12
}
/**
* **0xF9** - *LD sp,hl* - Put hl in sp
*/
val xF9 : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
registers.sp = registers.hl.toInt()
/*Cycles: */ 8
}
/**
* **0xFA** - *LD a,(nn)* - Read \*nn into a
*/
val xFA : (CPU, Registers, Gameboy) -> (Int) = {
cpu : CPU, registers : Registers, gb : Gameboy ->
// TODO: WTF?
registers.a = gb.ram.readByte((gb.ram.readShortAsInt(registers.pc.toLong()) and 0xFFFF).toLong())
registers.pc += 2
/*Cycles: */ 16
}
|
mit
|
b47b4c81d124afafa032b7182b6f5fc2
| 21.708138 | 104 | 0.547376 | 2.80527 | false | false | false | false |
rori-dev/lunchbox
|
backend-spring-kotlin/src/main/kotlin/lunchbox/domain/resolvers/LunchResolverSchweinestall.kt
|
1
|
2999
|
package lunchbox.domain.resolvers
import lunchbox.domain.models.LunchOffer
import lunchbox.domain.models.LunchProvider.SCHWEINESTALL
import lunchbox.util.date.DateValidator
import lunchbox.util.html.HtmlParser
import lunchbox.util.string.StringParser
import org.jsoup.nodes.Element
import org.springframework.stereotype.Component
import java.net.URL
import java.time.DayOfWeek
import java.time.LocalDate
/**
* Ermittelt Mittagsangebote für Schweinestall.
*/
@Component
class LunchResolverSchweinestall(
val dateValidator: DateValidator,
val htmlParser: HtmlParser
) : LunchResolver {
override val provider = SCHWEINESTALL
override fun resolve(): List<LunchOffer> =
resolve(provider.menuUrl)
fun resolve(url: URL): List<LunchOffer> {
val site = htmlParser.parse(url)
val sections = site.select("section")
val sectionsByWeek =
sections // Datum-Section und Offers-Section filtern und je Woche gruppieren
.filter { it.text().matches(Regex("""[-–0-9 .]+""")) || it.text().contains("€") }
.chunked(2)
.filter { it.size == 2 }
return sectionsByWeek.flatMap { (dateElem, offersElem) ->
resolveOffers(dateElem, offersElem)
}
}
private fun resolveOffers(dateElem: Element, offersElem: Element): List<LunchOffer> {
val monday: LocalDate = resolveMonday(dateElem) ?: return emptyList()
if (!dateValidator.isValid(monday)) return emptyList()
val tdsAsText = offersElem.select("td")
.map { it.text() }
return tdsAsText
.chunked(6) // 6 td sind ein Offer ...
.filter { it.size >= 4 } // ... nur die erste 4 enthalten Daten
.mapNotNull { (weekday, _, offerName, price) ->
resolveOffer(monday, weekday, offerName, price)
}
}
private fun resolveMonday(dateElem: Element): LocalDate? {
val dateString = dateElem.text().replace(" ", "")
val day = StringParser.parseLocalDate(dateString) ?: return null
return day.with(DayOfWeek.MONDAY)
}
private fun resolveOffer(
monday: LocalDate,
weekdayString: String,
nameString: String,
priceString: String
): LunchOffer? {
val weekday = Weekday.values().find { it.label == weekdayString } ?: return null
val day = monday.plusDays(weekday.order)
val price = StringParser.parseMoney(priceString) ?: return null
val name = cleanName(nameString)
val (title, description) = StringParser.splitOfferName(name, listOf(" auf ", " mit "))
return LunchOffer(0, title, description, day, price, emptySet(), provider.id)
}
private fun cleanName(nameString: String): String =
nameString
.trim()
.replace("\u0084", "") // merkwürdige Anführungszeichen rauswerfen
.replace("\u0093", "")
.replace("(", "")
.replace(")", "")
enum class Weekday(
val label: String,
val order: Long
) {
MONTAG("Montag", 0),
DIENSTAG("Dienstag", 1),
MITTWOCH("Mittwoch", 2),
DONNERSTAG("Donnerstag", 3),
FREITAG("Freitag", 4);
}
}
|
mit
|
9028dbaba9e8f8015215ce58dede602a
| 29.845361 | 90 | 0.680147 | 3.71677 | false | false | false | false |
FRC5333/2016-Stronghold
|
src/main/kotlin/frc/team5333/core/control/profiling/SplineSystem.kt
|
1
|
5464
|
package frc.team5333.core.control.profiling
import frc.team5333.core.Core
import frc.team5333.core.network.NetworkHub
/**
* Spline and Motion Profiling generation subsystem. All values are in Metric Units unless otherwise stated. Not your
* silly 'Freedom Units' like feet, inches and dick size.
*
* Motion Profiling is a way for the Robot to accurately move from point a to point b in a smooth, nice motion using
* spline fitting. This means our robot cha chas real smooth
*
* Something to note: Motion Profiles are created such that the 'y' position is the center of the Drive Base in terms
* of distance between Track Axis (i.e. half way between left and right tracks on the base). The 'x' position is determined
* as the rearmost axle of the drive base
*
* @author Jaci
*/
enum class SplineSystem {
INSTANCE;
class Waypoint(var x:Double, var y:Double, var angle:Double)
class Segment(var x:Double, var y:Double, var position:Double, var velocity:Double, var acceleration:Double, var jerk:Double, var heading:Double) {
constructor(seg: Segment) : this(seg.x, seg.y, seg.position, seg.velocity, seg.acceleration, seg.jerk, seg.heading)
}
class Trajectory(var segments: Array<Segment>) {
fun copy(): Trajectory {
var newTraj = Trajectory(segments)
newTraj.segments = newTraj.segments.map { Segment(it) }.toTypedArray()
return newTraj
}
fun getLength(): Int = segments.size
fun get(i: Int): Segment = segments.get(i)
fun set(i: Int, seg: Segment) = segments.set(i, seg)
}
fun generateTrajectoryPairs(points: Array<out Waypoint>): Pair<Trajectory, Trajectory> {
return createTrajectoryPair(generateCentralTrajectory(points), Core.config.getDouble("motion.wheelbase_width", 0.633294))
}
fun generateCentralTrajectory(points: Array<out Waypoint>): Trajectory {
writeToCoprocessor(Core.config.getFloat("motion.max_velocity", 1.2f),
Core.config.getFloat("motion.max_acceleration", 2.0f), points)
return readFromCoprocessor()
}
fun writeToCoprocessor(max_velocity: Float, max_acceleration: Float, points: Array<out Waypoint>) {
var hub = NetworkHub.INSTANCE
NetworkHub.INSTANCE.waitFor(NetworkHub.PROCESSORS.SPLINES)
var sock = NetworkHub.PROCESSORS.SPLINES.active!!
var out = sock.outputStream
out.write(hub.intToBytes(0xAB)) // Negotiation Byte
out.write(hub.floatToBytes(max_velocity))
out.write(hub.floatToBytes(max_acceleration))
out.write(hub.intToBytes(points.size))
points.forEach {
out.write(hub.floatToBytes(it.x.toFloat()))
out.write(hub.floatToBytes(it.y.toFloat()))
out.write(hub.floatToBytes(it.angle.toFloat()))
}
}
fun readFromCoprocessor(): Trajectory {
var hub = NetworkHub.INSTANCE
var sock = NetworkHub.PROCESSORS.SPLINES.active!!
var inp = sock.inputStream
while (true) {
if (hub.readInt(inp) == 0xBA) {
// Negotiation Byte
var len = hub.readInt(inp)
var segments = arrayOfNulls<Segment>(len)
for (i in 0..len - 1) {
var x = hub.readFloat(inp).toDouble()
var y = hub.readFloat(inp).toDouble()
var pos = hub.readFloat(inp).toDouble()
var vel = hub.readFloat(inp).toDouble()
var acc = hub.readFloat(inp).toDouble()
var jerk = hub.readFloat(inp).toDouble()
var head = hub.readFloat(inp).toDouble()
segments.set(i, Segment(x, y, pos, vel, acc, jerk, head))
}
sock.close()
return Trajectory(segments.map { it!! }.toTypedArray())
}
}
}
fun createTrajectoryPair(original: Trajectory, width: Double): Pair<Trajectory, Trajectory> {
var out = Pair(original.copy(), original.copy())
var w = width / 2
for (i in 0..original.getLength() - 1) {
var seg = original.get(i)
var ca = Math.cos(seg.heading)
var sa = Math.sin(seg.heading)
var seg1 = out.first.get(i)
seg1.x = seg.x - (w * sa)
seg1.y = seg.y + (w * ca)
if (i > 0) {
var last = out.first.get(i - 1)
var distance = Math.sqrt((seg1.x - last.x) * (seg1.x - last.x) + (seg1.y - last.y) * (seg1.y - last.y))
seg1.position = last.position + distance
seg1.velocity = distance / 0.05
seg1.acceleration = (seg1.velocity - last.velocity) / 0.05
seg1.jerk = (seg1.acceleration - last.acceleration) / 0.05
}
var seg2 = out.second.get(i)
seg2.x = seg.x + (w * sa)
seg2.y = seg.y - (w * ca)
if (i > 0) {
var last = out.second.get(i - 1)
var distance = Math.sqrt((seg2.x - last.x) * (seg2.x - last.x) + (seg2.y - last.y) * (seg2.y - last.y))
seg2.position = last.position + distance
seg2.velocity = distance / 0.05
seg2.acceleration = (seg2.velocity - last.velocity) / 0.05
seg2.jerk = (seg2.acceleration - last.acceleration) / 0.05
}
}
return out
}
}
|
mit
|
07b28dcf42f732a5d25319e32d929bf5
| 39.481481 | 151 | 0.590227 | 3.635396 | false | false | false | false |
reid112/Reidit
|
app/src/main/java/ca/rjreid/reidit/ui/main/MainPresenter.kt
|
1
|
2497
|
package ca.rjreid.reidit.ui.main
import android.os.Bundle
import ca.rjreid.reidit.data.DataManager
import ca.rjreid.reidit.data.model.FrontPageTypes
import ca.rjreid.reidit.data.model.Post
import ca.rjreid.reidit.data.model.PostsHolder
import ca.rjreid.reidit.data.model.TimeFilters
import com.evernote.android.state.State
import com.evernote.android.state.StateSaver
import io.reactivex.disposables.CompositeDisposable
import javax.inject.Inject
class MainPresenter @Inject constructor(private var view: MainView, private var dataManager: DataManager) {
//region Variables
private val compositeDisposable = CompositeDisposable()
//endregion
//region State Variables
@State var after: String = ""
@State var currentFrontPageType = FrontPageTypes.TOP
@State var currentTimeFilter = TimeFilters.DAY
//endregion
//region Commands
fun saveInstanceState(outState: Bundle?) {
outState?.let {
StateSaver.saveInstanceState(this, it)
}
}
fun restoreInstanceState(savedInstanceState: Bundle?) {
StateSaver.restoreInstanceState(this, savedInstanceState)
}
fun fetchFrontPage() {
fetchFrontPage(currentFrontPageType, currentTimeFilter)
}
fun fetchFrontPage(frontPageType: FrontPageTypes, timeFilter: TimeFilters) {
currentFrontPageType = frontPageType
currentTimeFilter = timeFilter
compositeDisposable.add(
dataManager
.fetchFrontPage(frontPageType, timeFilter, after)
.subscribe(
{ displayPosts(it) },
{ showError(it) }
))
}
fun refresh() {
view.isRefreshing(true)
view.clearPosts()
after = ""
fetchFrontPage(currentFrontPageType, currentTimeFilter)
}
fun destroy() = compositeDisposable.clear()
//endregion
//region Click Helpers
fun postClick(post: Post) = view.showPostDetails(post)
fun upVoteClick(post: Post) {
}
fun downVoteClick(post: Post) {
}
fun commentClick(post: Post) = view.showPostComments(post)
//endregion
//region Helpers
private fun displayPosts(response: PostsHolder) {
after = response.postsData.after ?: ""
view.updatePosts(response.postsData.postHolders)
}
private fun showError(throwable: Throwable) = view.showError(throwable.localizedMessage)
//endregion
}
|
apache-2.0
|
ba6f50d7ffa4e51a579aaa074a267902
| 27.386364 | 107 | 0.673608 | 4.47491 | false | false | false | false |
iarchii/trade_app
|
app/src/main/java/xyz/thecodeside/tradeapp/helpers/NumberFormatter.kt
|
1
|
1003
|
package xyz.thecodeside.tradeapp.helpers
import java.text.DecimalFormat
import java.text.NumberFormat
import java.util.*
object NumberFormatter{
private val DEFAULT_DECIMALS = 2
private val percentFormatter by lazy {
val df = NumberFormat.getNumberInstance(Locale.getDefault()) as DecimalFormat
df.maximumFractionDigits = DEFAULT_DECIMALS
df.minimumFractionDigits = DEFAULT_DECIMALS
df.negativePrefix = "- "
df.positivePrefix = "+ "
df.negativeSuffix = "%"
df.positiveSuffix = "%"
df
}
fun formatPercent(value: Float): String? = percentFormatter.format(value)
fun format(value: Float, decimals : Int = DEFAULT_DECIMALS): String? {
val normalFormatter =
NumberFormat.getNumberInstance(Locale.getDefault()) as DecimalFormat
normalFormatter.maximumFractionDigits = decimals
normalFormatter.minimumFractionDigits = decimals
return normalFormatter.format(value)
}
}
|
apache-2.0
|
931e1efd9866e832e96922557e13483d
| 30.375 | 85 | 0.694915 | 4.99005 | false | false | false | false |
etesync/android
|
app/src/main/java/com/etesync/syncadapter/ui/importlocal/ImportActivity.kt
|
1
|
5791
|
package com.etesync.syncadapter.ui.importlocal
import android.accounts.Account
import android.app.Activity
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.view.*
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.Fragment
import com.etesync.syncadapter.R
import com.etesync.syncadapter.model.CollectionInfo
import com.etesync.syncadapter.ui.BaseActivity
class ImportActivity : BaseActivity(), SelectImportMethod, DialogInterface {
private lateinit var account: Account
protected lateinit var info: CollectionInfo
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
title = getString(R.string.import_dialog_title)
account = intent.extras!!.getParcelable(EXTRA_ACCOUNT)!!
info = intent.extras!!.getSerializable(EXTRA_COLLECTION_INFO) as CollectionInfo
if (savedInstanceState == null)
supportFragmentManager.beginTransaction()
.add(android.R.id.content, ImportActivity.SelectImportFragment())
.commit()
}
override fun importFile() {
supportFragmentManager.beginTransaction()
.add(ImportFragment.newInstance(account, info), null)
.commit()
}
override fun importAccount() {
if (info.enumType == CollectionInfo.Type.CALENDAR) {
supportFragmentManager.beginTransaction()
.replace(android.R.id.content,
LocalCalendarImportFragment.newInstance(account, info.uid!!))
.addToBackStack(LocalCalendarImportFragment::class.java.name)
.commit()
} else if (info.enumType == CollectionInfo.Type.ADDRESS_BOOK) {
supportFragmentManager.beginTransaction()
.replace(android.R.id.content,
LocalContactImportFragment.newInstance(account, info.uid!!))
.addToBackStack(LocalContactImportFragment::class.java.name)
.commit()
}
title = getString(R.string.import_select_account)
}
private fun popBackStack() {
if (!supportFragmentManager.popBackStackImmediate()) {
finish()
} else {
title = getString(R.string.import_dialog_title)
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
popBackStack()
return true
}
return false
}
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
if (keyCode == KeyEvent.KEYCODE_BACK) {
popBackStack()
return true
}
return super.onKeyDown(keyCode, event)
}
override fun cancel() {
finish()
}
override fun dismiss() {
finish()
}
class SelectImportFragment : Fragment() {
private var mSelectImportMethod: SelectImportMethod? = null
override fun onAttach(context: Context) {
super.onAttach(context)
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mSelectImportMethod = activity as SelectImportMethod
} catch (e: ClassCastException) {
throw ClassCastException(activity.toString() + " must implement MyInterface ")
}
}
override fun onAttach(activity: Activity) {
super.onAttach(activity)
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mSelectImportMethod = activity as SelectImportMethod?
} catch (e: ClassCastException) {
throw ClassCastException(activity.toString() + " must implement MyInterface ")
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val v = inflater.inflate(R.layout.import_actions_list, container, false)
var card = v.findViewById<View>(R.id.import_file)
var img = card.findViewById<View>(R.id.action_icon) as ImageView
var text = card.findViewById<View>(R.id.action_text) as TextView
img.setImageResource(R.drawable.ic_file_white)
text.setText(R.string.import_button_file)
card.setOnClickListener { mSelectImportMethod!!.importFile() }
card = v.findViewById(R.id.import_account)
img = card.findViewById<View>(R.id.action_icon) as ImageView
text = card.findViewById<View>(R.id.action_text) as TextView
img.setImageResource(R.drawable.ic_account_circle_white)
text.setText(R.string.import_button_local)
card.setOnClickListener { mSelectImportMethod!!.importAccount() }
if ((activity as ImportActivity).info.enumType == CollectionInfo.Type.TASKS) {
card.visibility = View.GONE
}
return v
}
}
companion object {
val EXTRA_ACCOUNT = "account"
val EXTRA_COLLECTION_INFO = "collectionInfo"
fun newIntent(context: Context, account: Account, info: CollectionInfo): Intent {
val intent = Intent(context, ImportActivity::class.java)
intent.putExtra(ImportActivity.EXTRA_ACCOUNT, account)
intent.putExtra(ImportActivity.EXTRA_COLLECTION_INFO, info)
return intent
}
}
}
|
gpl-3.0
|
62e094f59f89b15d2be3ad52aefae79f
| 35.421384 | 120 | 0.633051 | 5.062063 | false | false | false | false |
LorittaBot/Loritta
|
web/embed-editor/embed-renderer/src/main/kotlin/net/perfectdreams/loritta/embededitor/data/DiscordEmbed.kt
|
1
|
1364
|
package net.perfectdreams.loritta.embededitor.data
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class DiscordEmbed(
val title: String? = null,
val description: String? = null,
val color: Int? = null,
val image: EmbedUrl? = null,
val thumbnail: EmbedUrl? = null,
val footer: Footer? = null,
val author: Author? = null,
val fields: List<Field> = listOf()
) {
companion object {
const val MAX_FIELD_OBJECTS = 25
const val MAX_DESCRIPTION_LENGTH = 2048
const val MAX_FIELD_NAME_LENGTH = 256
const val MAX_FIELD_VALUE_LENGTH = 1024
const val MAX_FOOTER_TEXT_VALUE_LENGTH = 2048
const val MAX_AUTHOR_NAME_LENGTH = 256
}
@Serializable
data class EmbedUrl(
val url: String
)
@Serializable
data class Field(
val name: String,
val value: String,
val inline: Boolean = false
)
@Serializable
data class Footer(
val text: String,
@SerialName("icon_url")
val iconUrl: String? = null
)
@Serializable
data class Author(
val name: String,
val url: String? = null,
@SerialName("icon_url")
val iconUrl: String? = null
)
}
|
agpl-3.0
|
1dec390c92f65fbc222224984690e7d1
| 25.25 | 53 | 0.585044 | 4.414239 | false | false | false | false |
cketti/okhttp
|
okhttp/src/test/java/okhttp3/internal/concurrent/TaskRunnerTest.kt
|
1
|
20133
|
/*
* Copyright (C) 2019 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.internal.concurrent
import java.util.concurrent.RejectedExecutionException
import okhttp3.TestLogHandler
import org.assertj.core.api.Assertions.assertThat
import org.junit.Assert.fail
import org.junit.Rule
import org.junit.Test
class TaskRunnerTest {
@Rule @JvmField val testLogHandler = TestLogHandler(TaskRunner::class.java)
private val taskFaker = TaskFaker()
private val taskRunner = taskFaker.taskRunner
private val log = mutableListOf<String>()
private val redQueue = taskRunner.newQueue()
private val blueQueue = taskRunner.newQueue()
private val greenQueue = taskRunner.newQueue()
@Test fun executeDelayed() {
redQueue.execute("task", 100.µs) {
log += "run@${taskFaker.nanoTime}"
}
taskFaker.advanceUntil(0.µs)
assertThat(log).containsExactly()
taskFaker.advanceUntil(99.µs)
assertThat(log).containsExactly()
taskFaker.advanceUntil(100.µs)
assertThat(log).containsExactly("run@100000")
taskFaker.assertNoMoreTasks()
assertThat(testLogHandler.takeAll()).containsExactly(
"FINE: Q10000 scheduled after 100 µs: task",
"FINE: Q10000 starting : task",
"FINE: Q10000 finished run in 0 µs: task"
)
}
@Test fun executeRepeated() {
val delays = mutableListOf(50.µs, 150.µs, -1L)
redQueue.schedule("task", 100.µs) {
log += "run@${taskFaker.nanoTime}"
return@schedule delays.removeAt(0)
}
taskFaker.advanceUntil(0.µs)
assertThat(log).containsExactly()
taskFaker.advanceUntil(100.µs)
assertThat(log).containsExactly("run@100000")
taskFaker.advanceUntil(150.µs)
assertThat(log).containsExactly("run@100000", "run@150000")
taskFaker.advanceUntil(299.µs)
assertThat(log).containsExactly("run@100000", "run@150000")
taskFaker.advanceUntil(300.µs)
assertThat(log).containsExactly("run@100000", "run@150000", "run@300000")
taskFaker.assertNoMoreTasks()
assertThat(testLogHandler.takeAll()).containsExactly(
"FINE: Q10000 scheduled after 100 µs: task",
"FINE: Q10000 starting : task",
"FINE: Q10000 run again after 50 µs: task",
"FINE: Q10000 finished run in 0 µs: task",
"FINE: Q10000 starting : task",
"FINE: Q10000 run again after 150 µs: task",
"FINE: Q10000 finished run in 0 µs: task",
"FINE: Q10000 starting : task",
"FINE: Q10000 finished run in 0 µs: task"
)
}
/** Repeat with a delay of 200 but schedule with a delay of 50. The schedule wins. */
@Test fun executeScheduledEarlierReplacesRepeatedLater() {
val task = object : Task("task") {
val schedules = mutableListOf(50.µs)
val delays = mutableListOf(200.µs, -1)
override fun runOnce(): Long {
log += "run@${taskFaker.nanoTime}"
if (schedules.isNotEmpty()) {
redQueue.schedule(this, schedules.removeAt(0))
}
return delays.removeAt(0)
}
}
redQueue.schedule(task, 100.µs)
taskFaker.advanceUntil(0.µs)
assertThat(log).isEmpty()
taskFaker.advanceUntil(100.µs)
assertThat(log).containsExactly("run@100000")
taskFaker.advanceUntil(150.µs)
assertThat(log).containsExactly("run@100000", "run@150000")
taskFaker.assertNoMoreTasks()
assertThat(testLogHandler.takeAll()).containsExactly(
"FINE: Q10000 scheduled after 100 µs: task",
"FINE: Q10000 starting : task",
"FINE: Q10000 scheduled after 50 µs: task",
"FINE: Q10000 already scheduled : task",
"FINE: Q10000 finished run in 0 µs: task",
"FINE: Q10000 starting : task",
"FINE: Q10000 finished run in 0 µs: task"
)
}
/** Schedule with a delay of 200 but repeat with a delay of 50. The repeat wins. */
@Test fun executeRepeatedEarlierReplacesScheduledLater() {
val task = object : Task("task") {
val schedules = mutableListOf(200.µs)
val delays = mutableListOf(50.µs, -1L)
override fun runOnce(): Long {
log += "run@${taskFaker.nanoTime}"
if (schedules.isNotEmpty()) {
redQueue.schedule(this, schedules.removeAt(0))
}
return delays.removeAt(0)
}
}
redQueue.schedule(task, 100.µs)
taskFaker.advanceUntil(0.µs)
assertThat(log).isEmpty()
taskFaker.advanceUntil(100.µs)
assertThat(log).containsExactly("run@100000")
taskFaker.advanceUntil(150.µs)
assertThat(log).containsExactly("run@100000", "run@150000")
taskFaker.assertNoMoreTasks()
assertThat(testLogHandler.takeAll()).containsExactly(
"FINE: Q10000 scheduled after 100 µs: task",
"FINE: Q10000 starting : task",
"FINE: Q10000 scheduled after 200 µs: task",
"FINE: Q10000 run again after 50 µs: task",
"FINE: Q10000 finished run in 0 µs: task",
"FINE: Q10000 starting : task",
"FINE: Q10000 finished run in 0 µs: task"
)
}
@Test fun cancelReturnsTruePreventsNextExecution() {
redQueue.execute("task", 100.µs) {
log += "run@${taskFaker.nanoTime}"
}
taskFaker.advanceUntil(0.µs)
assertThat(log).isEmpty()
redQueue.cancelAll()
taskFaker.advanceUntil(99.µs)
assertThat(log).isEmpty()
taskFaker.assertNoMoreTasks()
assertThat(testLogHandler.takeAll()).containsExactly(
"FINE: Q10000 scheduled after 100 µs: task",
"FINE: Q10000 canceled : task"
)
}
@Test fun cancelReturnsFalseDoesNotCancel() {
redQueue.schedule(object : Task("task", cancelable = false) {
override fun runOnce(): Long {
log += "run@${taskFaker.nanoTime}"
return -1L
}
}, 100.µs)
taskFaker.advanceUntil(0.µs)
assertThat(log).isEmpty()
redQueue.cancelAll()
taskFaker.advanceUntil(99.µs)
assertThat(log).isEmpty()
taskFaker.advanceUntil(100.µs)
assertThat(log).containsExactly("run@100000")
taskFaker.assertNoMoreTasks()
assertThat(testLogHandler.takeAll()).containsExactly(
"FINE: Q10000 scheduled after 100 µs: task",
"FINE: Q10000 starting : task",
"FINE: Q10000 finished run in 0 µs: task"
)
}
@Test fun cancelWhileExecutingPreventsRepeat() {
redQueue.schedule("task", 100.µs) {
log += "run@${taskFaker.nanoTime}"
redQueue.cancelAll()
return@schedule 100.µs
}
taskFaker.advanceUntil(0.µs)
assertThat(log).isEmpty()
taskFaker.advanceUntil(100.µs)
assertThat(log).containsExactly("run@100000")
taskFaker.assertNoMoreTasks()
assertThat(testLogHandler.takeAll()).containsExactly(
"FINE: Q10000 scheduled after 100 µs: task",
"FINE: Q10000 starting : task",
"FINE: Q10000 finished run in 0 µs: task"
)
}
@Test fun cancelWhileExecutingDoesNothingIfTaskDoesNotRepeat() {
redQueue.execute("task", 100.µs) {
log += "run@${taskFaker.nanoTime}"
redQueue.cancelAll()
}
taskFaker.advanceUntil(0.µs)
assertThat(log).isEmpty()
taskFaker.advanceUntil(100.µs)
assertThat(log).containsExactly("run@100000")
taskFaker.assertNoMoreTasks()
assertThat(testLogHandler.takeAll()).containsExactly(
"FINE: Q10000 scheduled after 100 µs: task",
"FINE: Q10000 starting : task",
"FINE: Q10000 finished run in 0 µs: task"
)
}
@Test fun cancelWhileExecutingDoesNotStopUncancelableTask() {
redQueue.schedule(object : Task("task", cancelable = false) {
val delays = mutableListOf(50.µs, -1L)
override fun runOnce(): Long {
log += "run@${taskFaker.nanoTime}"
redQueue.cancelAll()
return delays.removeAt(0)
}
}, 100.µs)
taskFaker.advanceUntil(0.µs)
assertThat(log).isEmpty()
taskFaker.advanceUntil(100.µs)
assertThat(log).containsExactly("run@100000")
taskFaker.advanceUntil(150.µs)
assertThat(log).containsExactly("run@100000", "run@150000")
taskFaker.assertNoMoreTasks()
assertThat(testLogHandler.takeAll()).containsExactly(
"FINE: Q10000 scheduled after 100 µs: task",
"FINE: Q10000 starting : task",
"FINE: Q10000 run again after 50 µs: task",
"FINE: Q10000 finished run in 0 µs: task",
"FINE: Q10000 starting : task",
"FINE: Q10000 finished run in 0 µs: task"
)
}
@Test fun interruptingCoordinatorAttemptsToCancelsAndSucceeds() {
redQueue.execute("task", 100.µs) {
log += "run@${taskFaker.nanoTime}"
}
taskFaker.advanceUntil(0.µs)
assertThat(log).isEmpty()
taskFaker.interruptCoordinatorThread()
taskFaker.advanceUntil(0.µs)
assertThat(log).isEmpty()
taskFaker.assertNoMoreTasks()
assertThat(testLogHandler.takeAll()).containsExactly(
"FINE: Q10000 scheduled after 100 µs: task",
"FINE: Q10000 canceled : task"
)
}
@Test fun interruptingCoordinatorAttemptsToCancelsAndFails() {
redQueue.schedule(object : Task("task", cancelable = false) {
override fun runOnce(): Long {
log += "run@${taskFaker.nanoTime}"
return -1L
}
}, 100.µs)
taskFaker.advanceUntil(0.µs)
assertThat(log).isEmpty()
taskFaker.interruptCoordinatorThread()
taskFaker.advanceUntil(0.µs)
assertThat(log).isEmpty()
taskFaker.advanceUntil(100.µs)
assertThat(log).containsExactly("run@100000")
taskFaker.assertNoMoreTasks()
assertThat(testLogHandler.takeAll()).containsExactly(
"FINE: Q10000 scheduled after 100 µs: task",
"FINE: Q10000 starting : task",
"FINE: Q10000 finished run in 0 µs: task"
)
}
/** Inspect how many runnables have been enqueued. If none then we're truly sequential. */
@Test fun singleQueueIsSerial() {
redQueue.execute("task one", 100.µs) {
log += "one:run@${taskFaker.nanoTime} parallel=${taskFaker.isParallel}"
}
redQueue.execute("task two", 100.µs) {
log += "two:run@${taskFaker.nanoTime} parallel=${taskFaker.isParallel}"
}
redQueue.execute("task three", 100.µs) {
log += "three:run@${taskFaker.nanoTime} parallel=${taskFaker.isParallel}"
}
taskFaker.advanceUntil(0.µs)
assertThat(log).isEmpty()
taskFaker.advanceUntil(100.µs)
assertThat(log).containsExactly(
"one:run@100000 parallel=false",
"two:run@100000 parallel=false",
"three:run@100000 parallel=false"
)
taskFaker.assertNoMoreTasks()
assertThat(testLogHandler.takeAll()).containsExactly(
"FINE: Q10000 scheduled after 100 µs: task one",
"FINE: Q10000 scheduled after 100 µs: task two",
"FINE: Q10000 scheduled after 100 µs: task three",
"FINE: Q10000 starting : task one",
"FINE: Q10000 finished run in 0 µs: task one",
"FINE: Q10000 starting : task two",
"FINE: Q10000 finished run in 0 µs: task two",
"FINE: Q10000 starting : task three",
"FINE: Q10000 finished run in 0 µs: task three"
)
}
/** Inspect how many runnables have been enqueued. If non-zero then we're truly parallel. */
@Test fun differentQueuesAreParallel() {
redQueue.execute("task one", 100.µs) {
log += "one:run@${taskFaker.nanoTime} parallel=${taskFaker.isParallel}"
}
blueQueue.execute("task two", 100.µs) {
log += "two:run@${taskFaker.nanoTime} parallel=${taskFaker.isParallel}"
}
greenQueue.execute("task three", 100.µs) {
log += "three:run@${taskFaker.nanoTime} parallel=${taskFaker.isParallel}"
}
taskFaker.advanceUntil(0.µs)
assertThat(log).isEmpty()
taskFaker.advanceUntil(100.µs)
assertThat(log).containsExactly(
"one:run@100000 parallel=true",
"two:run@100000 parallel=true",
"three:run@100000 parallel=true"
)
taskFaker.assertNoMoreTasks()
assertThat(testLogHandler.takeAll()).containsExactly(
"FINE: Q10000 scheduled after 100 µs: task one",
"FINE: Q10001 scheduled after 100 µs: task two",
"FINE: Q10002 scheduled after 100 µs: task three",
"FINE: Q10000 starting : task one",
"FINE: Q10000 finished run in 0 µs: task one",
"FINE: Q10001 starting : task two",
"FINE: Q10001 finished run in 0 µs: task two",
"FINE: Q10002 starting : task three",
"FINE: Q10002 finished run in 0 µs: task three"
)
}
/** Test the introspection method [TaskQueue.scheduledTasks]. */
@Test fun scheduledTasks() {
redQueue.execute("task one", 100.µs) {
// Do nothing.
}
redQueue.execute("task two", 200.µs) {
// Do nothing.
}
assertThat(redQueue.scheduledTasks.toString()).isEqualTo("[task one, task two]")
assertThat(testLogHandler.takeAll()).containsExactly(
"FINE: Q10000 scheduled after 100 µs: task one",
"FINE: Q10000 scheduled after 200 µs: task two"
)
}
/**
* We don't track the active task in scheduled tasks. This behavior might be a mistake, but it's
* cumbersome to implement properly because the active task might be a cancel.
*/
@Test fun scheduledTasksDoesNotIncludeRunningTask() {
val task = object : Task("task one") {
val schedules = mutableListOf(200.µs)
override fun runOnce(): Long {
if (schedules.isNotEmpty()) {
redQueue.schedule(this, schedules.removeAt(0)) // Add it at the end also.
}
log += "scheduledTasks=${redQueue.scheduledTasks}"
return -1L
}
}
redQueue.schedule(task, 100.µs)
redQueue.execute("task two", 200.µs) {
log += "scheduledTasks=${redQueue.scheduledTasks}"
}
taskFaker.advanceUntil(100.µs)
assertThat(log).containsExactly(
"scheduledTasks=[task two, task one]"
)
taskFaker.advanceUntil(200.µs)
assertThat(log).containsExactly(
"scheduledTasks=[task two, task one]",
"scheduledTasks=[task one]"
)
taskFaker.advanceUntil(300.µs)
assertThat(log).containsExactly(
"scheduledTasks=[task two, task one]",
"scheduledTasks=[task one]",
"scheduledTasks=[]"
)
taskFaker.assertNoMoreTasks()
assertThat(testLogHandler.takeAll()).containsExactly(
"FINE: Q10000 scheduled after 100 µs: task one",
"FINE: Q10000 scheduled after 200 µs: task two",
"FINE: Q10000 starting : task one",
"FINE: Q10000 scheduled after 200 µs: task one",
"FINE: Q10000 finished run in 0 µs: task one",
"FINE: Q10000 starting : task two",
"FINE: Q10000 finished run in 0 µs: task two",
"FINE: Q10000 starting : task one",
"FINE: Q10000 finished run in 0 µs: task one"
)
}
/**
* The runner doesn't hold references to its queues! Otherwise we'd need a mechanism to clean them
* up when they're no longer needed and that's annoying. Instead the task runner only tracks which
* queues have work scheduled.
*/
@Test fun activeQueuesContainsOnlyQueuesWithScheduledTasks() {
redQueue.execute("task one", 100.µs) {
// Do nothing.
}
blueQueue.execute("task two", 200.µs) {
// Do nothing.
}
taskFaker.advanceUntil(0.µs)
assertThat(taskRunner.activeQueues()).containsExactly(redQueue, blueQueue)
taskFaker.advanceUntil(100.µs)
assertThat(taskRunner.activeQueues()).containsExactly(blueQueue)
taskFaker.advanceUntil(200.µs)
assertThat(taskRunner.activeQueues()).isEmpty()
taskFaker.assertNoMoreTasks()
assertThat(testLogHandler.takeAll()).containsExactly(
"FINE: Q10000 scheduled after 100 µs: task one",
"FINE: Q10001 scheduled after 200 µs: task two",
"FINE: Q10000 starting : task one",
"FINE: Q10000 finished run in 0 µs: task one",
"FINE: Q10001 starting : task two",
"FINE: Q10001 finished run in 0 µs: task two"
)
}
@Test fun taskNameIsUsedForThreadNameWhenRunning() {
redQueue.execute("lucky task") {
log += "run threadName:${Thread.currentThread().name}"
}
taskFaker.advanceUntil(0.µs)
assertThat(log).containsExactly("run threadName:lucky task")
taskFaker.assertNoMoreTasks()
assertThat(testLogHandler.takeAll()).containsExactly(
"FINE: Q10000 scheduled after 0 µs: lucky task",
"FINE: Q10000 starting : lucky task",
"FINE: Q10000 finished run in 0 µs: lucky task"
)
}
@Test fun shutdownSuccessfullyCancelsScheduledTasks() {
redQueue.execute("task", 100.µs) {
log += "run@${taskFaker.nanoTime}"
}
taskFaker.advanceUntil(0.µs)
assertThat(log).isEmpty()
redQueue.shutdown()
taskFaker.advanceUntil(99.µs)
assertThat(log).isEmpty()
taskFaker.assertNoMoreTasks()
assertThat(testLogHandler.takeAll()).containsExactly(
"FINE: Q10000 scheduled after 100 µs: task",
"FINE: Q10000 canceled : task"
)
}
@Test fun shutdownFailsToCancelsScheduledTasks() {
redQueue.schedule(object : Task("task", false) {
override fun runOnce(): Long {
log += "run@${taskFaker.nanoTime}"
return 50.µs
}
}, 100.µs)
taskFaker.advanceUntil(0.µs)
assertThat(log).isEmpty()
redQueue.shutdown()
taskFaker.advanceUntil(99.µs)
assertThat(log).isEmpty()
taskFaker.advanceUntil(100.µs)
assertThat(log).containsExactly("run@100000")
taskFaker.assertNoMoreTasks()
assertThat(testLogHandler.takeAll()).containsExactly(
"FINE: Q10000 scheduled after 100 µs: task",
"FINE: Q10000 starting : task",
"FINE: Q10000 finished run in 0 µs: task"
)
}
@Test fun scheduleDiscardsTaskWhenShutdown() {
redQueue.shutdown()
redQueue.execute("task", 100.µs) {
// Do nothing.
}
taskFaker.assertNoMoreTasks()
assertThat(testLogHandler.takeAll()).containsExactly(
"FINE: Q10000 schedule canceled (queue is shutdown): task"
)
}
@Test fun scheduleThrowsWhenShutdown() {
redQueue.shutdown()
try {
redQueue.schedule(object : Task("task", cancelable = false) {
override fun runOnce(): Long {
return -1L
}
}, 100.µs)
fail()
} catch (_: RejectedExecutionException) {
}
taskFaker.assertNoMoreTasks()
assertThat(testLogHandler.takeAll()).containsExactly(
"FINE: Q10000 schedule failed (queue is shutdown): task"
)
}
@Test fun idleLatch() {
redQueue.execute("task") {
log += "run@${taskFaker.nanoTime}"
}
val idleLatch = redQueue.idleLatch()
assertThat(idleLatch.count).isEqualTo(1)
taskFaker.advanceUntil(0.µs)
assertThat(log).containsExactly("run@0")
assertThat(idleLatch.count).isEqualTo(0)
}
@Test fun multipleCallsToIdleLatchReturnSameInstance() {
redQueue.execute("task") {
log += "run@${taskFaker.nanoTime}"
}
val idleLatch1 = redQueue.idleLatch()
val idleLatch2 = redQueue.idleLatch()
assertThat(idleLatch2).isSameAs(idleLatch1)
}
private val Int.µs: Long
get() = this * 1_000L
}
|
apache-2.0
|
6d1653808d53add83b92303807b0eb7e
| 29.654908 | 100 | 0.642067 | 3.847353 | false | true | false | false |
gatheringhallstudios/MHGenDatabase
|
app/src/main/java/com/ghstudios/android/features/armorsetbuilder/list/ASBSetAddDialogFragment.kt
|
1
|
4450
|
package com.ghstudios.android.features.armorsetbuilder.list
import android.app.Activity
import android.app.AlertDialog
import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.DialogFragment
import android.view.LayoutInflater
import android.view.WindowManager
import android.widget.ArrayAdapter
import android.widget.EditText
import android.widget.Spinner
import com.ghstudios.android.AssetLoader
import com.ghstudios.android.data.classes.ASBSet
import com.ghstudios.android.data.classes.Rank
import com.ghstudios.android.mhgendatabase.R
import com.ghstudios.android.util.applyArguments
import com.ghstudios.android.util.sendDialogResult
/**
* Dialog used to add or edit an ASBSet or Session.
*/
class ASBSetAddDialogFragment : DialogFragment() {
companion object {
private const val ARG_ID = "id"
private const val ARG_NAME = "name"
private const val ARG_RANK = "rank"
private const val ARG_HUNTER_TYPE = "hunter_type"
@JvmStatic fun newInstance(): ASBSetAddDialogFragment {
val f = ASBSetAddDialogFragment()
f.isEditing = false
return f
}
@JvmStatic fun newInstance(set: ASBSet)
= newInstance(set.id, set.name, set.rank, set.hunterType)
@JvmStatic fun newInstance(id: Long, name: String, rank: Rank, hunterType: Int): ASBSetAddDialogFragment {
val f = ASBSetAddDialogFragment().applyArguments {
putLong(ARG_ID, id)
putString(ARG_NAME, name)
putInt(ARG_RANK, rank.value)
putInt(ARG_HUNTER_TYPE, hunterType)
}
f.isEditing = true
return f
}
}
private var isEditing: Boolean = false
private fun sendResult(resultCode: Int, name: String, rank: Rank, hunterType: Int) {
val i = Intent()
if (isEditing) {
i.putExtra(ASBSetListFragment.EXTRA_ASB_SET_ID, arguments!!.getLong(ARG_ID))
}
i.putExtra(ASBSetListFragment.EXTRA_ASB_SET_NAME, name)
i.putExtra(ASBSetListFragment.EXTRA_ASB_SET_RANK, rank.value)
i.putExtra(ASBSetListFragment.EXTRA_ASB_SET_HUNTER_TYPE, hunterType)
sendDialogResult(resultCode, i)
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val inflater = LayoutInflater.from(context)
val view = inflater.inflate(R.layout.dialog_asb_set_add, null)
val nameInput = view.findViewById<EditText>(R.id.name_text)
val rankSpinner = view.findViewById<Spinner>(R.id.spinner_rank)
val hunterTypeSpinner = view.findViewById<Spinner>(R.id.spinner_hunter_type)
val ranks = Rank.all
val rankStrings = ranks.map { AssetLoader.localizeRank(it) }.toTypedArray()
rankSpinner.adapter = ArrayAdapter<String>(context!!, R.layout.view_spinner_item, rankStrings).apply {
setDropDownViewResource(R.layout.view_spinner_dropdown_item)
}
hunterTypeSpinner.adapter = ArrayAdapter.createFromResource(context!!, R.array.hunter_type, R.layout.view_spinner_item).apply {
setDropDownViewResource(R.layout.view_spinner_dropdown_item)
}
if (isEditing) {
val selectedRank = Rank.from(arguments?.getInt(ARG_RANK) ?: -1)
nameInput.setText(arguments?.getString(ARG_NAME) ?: "")
rankSpinner.setSelection(ranks.indexOf(selectedRank))
hunterTypeSpinner.setSelection(arguments!!.getInt(ARG_HUNTER_TYPE))
}
val d = AlertDialog.Builder(activity)
.setTitle(if (!isEditing) R.string.dialog_title_add_asb_set else R.string.dialog_title_edit_asb_set)
.setView(view)
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(android.R.string.ok) { _, _ ->
val name = nameInput.text.toString()
val rankIdx = rankSpinner.selectedItemPosition
val hunterTypeIdx = hunterTypeSpinner.selectedItemPosition
sendResult(Activity.RESULT_OK, name, ranks[rankIdx], hunterTypeIdx)
}
.create()
// Allow the auto-focused name input to pop up the onscreen keyboard
val window = d.window
window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE)
return d
}
}
|
mit
|
8693a0cc8bbb86c0d41bf78ac7729d43
| 37.695652 | 135 | 0.66427 | 4.202077 | false | false | false | false |
christophpickl/gadsu
|
src/main/kotlin/at/cpickl/gadsu/view/swing/JTextField.kt
|
1
|
1307
|
package at.cpickl.gadsu.view.swing
import at.cpickl.gadsu.view.logic.beep
import java.util.regex.Pattern
import javax.swing.JTextField
import javax.swing.text.AbstractDocument
import javax.swing.text.AttributeSet
import javax.swing.text.DocumentFilter
import javax.swing.text.PlainDocument
fun JTextField.enforceMaxCharacters(enforcedLength: Int) {
// instead of replace, maybe delegate to original document?!?
document = object : PlainDocument() {
override fun insertString(offset: Int, string: String?, attributes: AttributeSet?) {
if (string == null) return
if ((length + string.length) <= enforcedLength) {
super.insertString(offset, string, attributes)
} else {
beep()
}
}
}
}
fun JTextField.enforceCharactersByRegexp(regexp: Pattern) {
(document as AbstractDocument).documentFilter = object : DocumentFilter() {
override fun replace(fb: FilterBypass?, offset: Int, length: Int, text: String?, attrs: AttributeSet?) {
if (!regexp.matcher(text).matches()) {
return
}
super.replace(fb, offset, length, text, attrs)
}
}
}
fun JTextField.enableSearchVariant() {
putClientProperty("JTextField.variant", "search")
}
|
apache-2.0
|
d68e63eaf72e9d059e921b22a23a6f59
| 33.394737 | 112 | 0.661056 | 4.385906 | false | false | false | false |
cliffano/swaggy-jenkins
|
clients/kotlin-spring/generated/src/main/kotlin/org/openapitools/model/HudsonMasterComputerexecutors.kt
|
1
|
1534
|
package org.openapitools.model
import java.util.Objects
import com.fasterxml.jackson.annotation.JsonProperty
import org.openapitools.model.FreeStyleBuild
import javax.validation.constraints.DecimalMax
import javax.validation.constraints.DecimalMin
import javax.validation.constraints.Email
import javax.validation.constraints.Max
import javax.validation.constraints.Min
import javax.validation.constraints.NotNull
import javax.validation.constraints.Pattern
import javax.validation.constraints.Size
import javax.validation.Valid
import io.swagger.v3.oas.annotations.media.Schema
/**
*
* @param currentExecutable
* @param idle
* @param likelyStuck
* @param number
* @param progress
* @param propertyClass
*/
data class HudsonMasterComputerexecutors(
@field:Valid
@Schema(example = "null", description = "")
@field:JsonProperty("currentExecutable") val currentExecutable: FreeStyleBuild? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("idle") val idle: kotlin.Boolean? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("likelyStuck") val likelyStuck: kotlin.Boolean? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("number") val number: kotlin.Int? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("progress") val progress: kotlin.Int? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("_class") val propertyClass: kotlin.String? = null
) {
}
|
mit
|
f2e40c0bb6e286b2e9f06ac4799316e9
| 30.306122 | 91 | 0.741199 | 4.090667 | false | false | false | false |
facebook/litho
|
sample/src/main/java/com/facebook/samples/litho/kotlin/collection/Interactions.kt
|
1
|
2084
|
/*
* 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.
*/
package com.facebook.samples.litho.kotlin.collection
import com.facebook.litho.Component
import com.facebook.litho.ComponentScope
import com.facebook.litho.KComponent
import com.facebook.litho.kotlin.widget.Text
import com.facebook.litho.useState
import com.facebook.litho.widget.collection.LazyCollectionController
import com.facebook.litho.widget.collection.LazyList
// start_scrolling_example
class ScrollingExample() : KComponent() {
override fun ComponentScope.render(): Component {
val controller = useState { LazyCollectionController() }.value
// Use one of these lambdas to scroll, e.g. in an onClick callback
val scrollToTenth = controller.scrollToIndex(10)
val smoothScrollToEnd = controller.smoothScrollToId("End")
return LazyList(
lazyCollectionController = controller,
) {
children(items = (0..20), id = { it }) { Text("$it") }
child(id = "End", component = Text("End"))
}
}
}
// end_scrolling_example
// start_pull_to_refresh_example
class PullToRefreshExample(
val data: List<String>,
val refresh: () -> Unit,
) : KComponent() {
override fun ComponentScope.render(): Component {
val controller = useState { LazyCollectionController() }.value
return LazyList(
lazyCollectionController = controller,
onPullToRefresh = {
refresh()
controller.setRefreshing(false)
},
) { /* Add children */}
}
}
// end_pull_to_refresh_example
|
apache-2.0
|
29f75dddf2ed8f8946cbaa1395eefd6a
| 31.5625 | 75 | 0.714491 | 4.168 | false | false | false | false |
meh/watch_doge
|
src/main/java/meh/watchdoge/backend/Pinger.kt
|
1
|
6944
|
package meh.watchdoge.backend;
import java.util.HashMap;
import java.util.HashSet;
import android.os.Bundle;
import android.os.Message;
import android.os.Messenger;
import org.jetbrains.anko.*;
import nl.komponents.kovenant.*;
import meh.watchdoge.Request;
import meh.watchdoge.response.build as buildResponse;
import meh.watchdoge.response.Event.Pinger as EventBuilder;
import meh.watchdoge.util.*;
import android.os.RemoteException;
class Pinger {
class Conn(conn: Connection): Module.Connection(conn) {
private val _subscriber = Module.Connection.SubscriberWithId<Event>();
inner class Subscription(id: Int, body: (Event) -> Unit): Module.Connection.SubscriptionWithId<Event>(id, body) {
override fun unsubscribe() {
unsubscribe(_subscriber);
if (_subscriber.empty(_id)) {
request { pinger(_id) { unsubscribe() } }
}
}
}
fun subscribe(id: Int, body: (Event) -> Unit): Promise<Module.Connection.ISubscription, Exception> {
return if (_subscriber.empty(id)) {
request { pinger(id) { subscribe() } }
}
else {
Promise.of(1);
} then {
_subscriber.subscribe(id, body);
Subscription(id, body)
}
}
override fun handle(msg: Message): Boolean {
if (msg.what != Command.Event.PINGER) {
return false;
}
_subscriber.emit(Pinger.event(msg));
return true;
}
}
class Mod(backend: Backend): Module(backend) {
private val _map: HashMap<Int, HashSet<Messenger>> = HashMap();
override fun request(req: Request): Boolean {
when (req.command()) {
Command.Pinger.CREATE ->
create(req)
Command.Pinger.START ->
start(req)
Command.Pinger.STOP ->
stop(req)
Command.Pinger.DESTROY ->
destroy(req)
Command.Pinger.SUBSCRIBE ->
subscribe(req)
Command.Pinger.UNSUBSCRIBE ->
unsubscribe(req)
else ->
return false;
}
return true;
}
private fun create(req: Request) {
var target = req.bundle()!!.getString("target");
var interval = req.bundle()!!.getDouble("interval");
forward(req) {
it.packString(target);
if (interval == 0.0) {
it.packLong(Math.round(defaultSharedPreferences
.getString("ping_interval", "0").toDuration() * 1000.0));
}
else {
it.packLong(Math.round(interval * 1000.0));
}
}
}
private fun start(req: Request) {
val id = req.arg();
forward(req) {
it.packInt(id);
}
}
private fun stop(req: Request) {
val id = req.arg();
forward(req) {
it.packInt(id);
}
}
private fun destroy(req: Request) {
val id = req.arg();
forward(req) {
it.packInt(id);
}
}
private fun subscribe(req: Request) {
val id = req.arg();
synchronized(_map) {
if (!_map.containsKey(id)) {
response(req, Command.Pinger.Error.NOT_FOUND);
}
else {
_map.get(id)!!.add(req.origin());
response(req, Command.SUCCESS);
}
}
}
private fun unsubscribe(req: Request) {
val id = req.arg();
synchronized(_map) {
if (_map.containsKey(id)) {
_map.get(id)!!.add(req.origin());
response(req, Command.SUCCESS);
}
else {
response(req, Command.Pinger.Error.NOT_FOUND);
}
}
}
override fun response(messenger: Messenger, req: Request, status: Int) {
when (req.command()) {
Command.Pinger.CREATE -> {
val id = _unpacker.unpackInt();
if (status == Command.SUCCESS) {
synchronized(_map) {
_map.put(id, HashSet());
}
}
messenger.response(req, status) {
arg = id;
}
}
else ->
messenger.response(req, status)
}
}
override fun receive() {
val id = _unpacker.unpackInt();
val event = _unpacker.unpackInt();
when (event) {
Command.Event.Pinger.STATS ->
stats(id)
Command.Event.Pinger.PACKET ->
packet(id)
Command.Event.Pinger.ERROR ->
error(id)
}
}
private fun stats(id: Int) {
send(id) {
stats {
it.putParcelable("packet", Bundle().tap {
it.putLong("sent", _unpacker.unpackLong());
it.putLong("received", _unpacker.unpackLong());
it.putFloat("loss", _unpacker.unpackFloat());
});
it.putParcelable("trip", Bundle().tap {
it.putLong("minimum", _unpacker.unpackLong());
it.putLong("maximum", _unpacker.unpackLong());
it.putLong("average", _unpacker.unpackLong());
});
}
}
}
private fun packet(id: Int) {
send(id) {
packet {
it.putString("source", _unpacker.unpackString());
it.putInt("sequence", _unpacker.unpackInt());
it.putInt("ttl", _unpacker.unpackInt());
it.putLong("trip", _unpacker.unpackLong());
}
}
}
private fun error(id: Int) {
send(id) {
error {
it.putString("source", _unpacker.unpackString());
it.putInt("sequence", _unpacker.unpackInt());
it.putInt("ttl", _unpacker.unpackInt());
it.putString("reason", _unpacker.unpackString());
}
}
}
private fun send(id: Int, body: EventBuilder.() -> Unit) {
var msg = buildResponse {
event {
pinger(id) {
this.body();
}
}
}
synchronized(_map) {
if (_map.containsKey(id)) {
_map.get(id)?.retainAll {
try {
it.send(msg);
true
}
catch (e: RemoteException) {
false
}
}
}
}
}
}
companion object {
fun event(msg: Message): Event {
return when (msg.arg1) {
Command.Event.Pinger.STATS ->
Stats(msg.arg2, msg.getData())
Command.Event.Pinger.PACKET ->
Packet(msg.arg2, msg.getData())
Command.Event.Pinger.ERROR ->
Error(msg.arg2, msg.getData())
else ->
throw IllegalArgumentException("unknown event type")
}
}
}
open class Event(id: Int, bundle: Bundle): Module.EventWithId(id, bundle);
class Stats(id: Int, bundle: Bundle): Event(id, bundle) {
data class Packet(val sent: Long, val received: Long, val loss: Float);
data class Trip(val minimum: Long, val maximum: Long, val average: Long);
fun packet(): Packet {
return bundle().getParcelable<Bundle>("packet").let {
Packet(it.getLong("sent"), it.getLong("received"), it.getFloat("loss"))
};
}
fun trip(): Trip {
return bundle().getParcelable<Bundle>("trip").let {
Trip(it.getLong("minimum"), it.getLong("maximum"), it.getLong("average"))
};
}
}
open class Entry(id: Int, bundle: Bundle): Event(id, bundle) {
fun source(): String {
return bundle().getString("source")
}
fun sequence(): Int {
return bundle().getInt("sequence")
}
fun ttl(): Int {
return bundle().getInt("ttl")
}
}
class Packet(id: Int, bundle: Bundle): Entry(id, bundle) {
fun trip(): Long {
return bundle().getLong("trip")
}
}
class Error(id: Int, bundle: Bundle): Entry(id, bundle) {
fun reason(): String {
return Regex("""-(.)""").replace(bundle().getString("reason").capitalize()) {
" ${it.groups.get(1)!!.value.toUpperCase()}"
}
}
}
}
|
agpl-3.0
|
32b1220bbb553edb99c8b1c0cc192d98
| 20.565217 | 115 | 0.605991 | 3.170776 | false | false | false | false |
fython/PackageTracker
|
mobile/src/main/kotlin/info/papdt/express/helper/services/ClipboardDetectService.kt
|
1
|
5969
|
package info.papdt.express.helper.services
import android.animation.Animator
import android.app.Service
import android.content.ClipboardManager
import android.content.Intent
import android.graphics.PixelFormat
import android.os.Handler
import android.os.IBinder
import android.os.Message
import android.text.TextUtils
import android.util.Log
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.view.WindowManager
import android.view.animation.AnticipateInterpolator
import android.view.animation.BounceInterpolator
import android.widget.ImageView
import info.papdt.express.helper.R
import info.papdt.express.helper.support.ScreenUtils
import info.papdt.express.helper.support.Settings
import info.papdt.express.helper.ui.HomeActivity
import moe.feng.kotlinyan.common.*
import java.util.ArrayList
/**
* 剪切板检测服务
*
* 主动监听剪贴板,在获取订单号后显示气泡提供快捷添加入口。
*
* 在 Android 7.0 开始弃用(由于后台服务限制,显示通知不太优雅)
*/
class ClipboardDetectService : Service(), ClipboardManager.OnPrimaryClipChangedListener {
private var mLayoutParams: WindowManager.LayoutParams? = null
private val mLayout: View by lazy { View.inflate(this, R.layout.popupwindow_app_entry, null) }
private lateinit var mIconView: ImageView
private val mHandler: Handler by lazy { UiHandler() }
private var mLastNumber: String? = null
private var mPositionY: Float = 0.toFloat()
override fun onCreate() {
super.onCreate()
if (Settings.getInstance(this).isClipboardDetectServiceEnabled()) {
clipboardManager.addPrimaryClipChangedListener(this)
mPositionY = ScreenUtils.dpToPx(this, 128f)
initPopupView()
} else {
stopSelf()
}
}
override fun onDestroy() {
super.onDestroy()
clipboardManager.removePrimaryClipChangedListener(this)
}
override fun onBind(intent: Intent): IBinder? {
return null
}
override fun onPrimaryClipChanged() {
clipboardManager.primaryClip?.let {
mLastNumber = getPackageNumber(it.toString())
if (TextUtils.isEmpty(mLastNumber)) return
try {
windowManager.addView(mLayout, mLayoutParams)
mIconView.scaleX = 0.5f
mIconView.scaleY = 0.5f
mIconView.animate()
.scaleX(1f)
.scaleY(1f)
.setListener(null)
.setDuration(500).setInterpolator(BounceInterpolator()).start()
mHandler.sendEmptyMessageDelayed(0, 4500)
} catch (e: Exception) {
e.printStackTrace()
}
}
}
private fun initPopupView() {
mIconView = mLayout.findViewById(R.id.icon_view)
mLayout.setOnClickListener { view ->
mLastNumber?.let {
HomeActivity.search(view.context, it)
mHandler.sendEmptyMessage(0)
}
}
mLayout.setOnTouchListener(object : View.OnTouchListener {
private var lastY: Float = 0.toFloat()
private var nowY: Float = 0.toFloat()
private var tranY: Float = 0.toFloat()
private var distance: Float = 0.toFloat()
override fun onTouch(view: View, event: MotionEvent): Boolean {
var ret = false
when (event.action) {
MotionEvent.ACTION_DOWN -> {
distance = 0f
lastY = event.rawY
ret = true
mHandler.removeMessages(0)
}
MotionEvent.ACTION_MOVE -> {
// 获取移动时的X,Y坐标
nowY = event.rawY
// 计算XY坐标偏移量
tranY = nowY - lastY
distance += Math.abs(tranY)
// 移动悬浮窗
mLayoutParams!!.y += tranY.toInt()
mPositionY = mLayoutParams!!.y.toFloat()
//更新悬浮窗位置
windowManager.updateViewLayout(mLayout, mLayoutParams)
//记录当前坐标作为下一次计算的上一次移动的位置坐标
lastY = nowY
}
MotionEvent.ACTION_UP -> if (distance < 5) {
view.performClick()
} else {
mHandler.sendEmptyMessageDelayed(0, 3000)
}
}
return ret
}
})
mLayoutParams = WindowManager.LayoutParams(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT).apply {
x = 0
y = mPositionY.toInt()
width = WindowManager.LayoutParams.WRAP_CONTENT
height = WindowManager.LayoutParams.WRAP_CONTENT
gravity = Gravity.RIGHT or Gravity.TOP
flags = flags or (WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE)
format = PixelFormat.TRANSLUCENT
}
}
internal inner class UiHandler : Handler() {
override fun handleMessage(msg: Message) {
when (msg.what) {
0 -> mIconView.animate()
.scaleX(0f)
.scaleY(0f)
.setListener(object : Animator.AnimatorListener {
override fun onAnimationStart(animator: Animator) {}
override fun onAnimationEnd(animator: Animator) {
try {
windowManager.removeViewImmediate(mLayout)
} catch (e: Exception) {
}
}
override fun onAnimationCancel(animator: Animator) {}
override fun onAnimationRepeat(animator: Animator) {}
})
.setDuration(500).setInterpolator(AnticipateInterpolator()).start()
}
}
}
companion object {
private val TAG = ClipboardDetectService::class.java.simpleName
fun getPackageNumber(source: String): String? {
val results = ArrayList<String>()
var sb = StringBuffer()
for (i in 0 until source.length) {
val next = if (i + 1 > source.length) source.length - 1 else i + 1
val c = source.substring(i, next)
if (TextUtils.isDigitsOnly(c)) {
sb.append(c)
if (i == source.length - 1) {
results.add(sb.toString())
Log.i(TAG, "getPackageNumber, found " + sb.toString())
}
} else if (sb.isNotEmpty()) {
results.add(sb.toString())
Log.i(TAG, "getPackageNumber, found " + sb.toString())
sb = StringBuffer()
}
}
return if (results.isEmpty()) {
null
} else {
var longest = ""
results.asSequence().filter { longest.length < it.length }.forEach { longest = it }
longest
}
}
}
}
|
gpl-3.0
|
31857bde5649678cbb0f9b2f3593c09c
| 27.310345 | 118 | 0.690447 | 3.567349 | false | false | false | false |
Zhuinden/simple-stack
|
samples/legacy-samples/simple-stack-example-multistack-fragment/src/main/java/com/zhuinden/simplestackdemomultistack/application/MainActivity.kt
|
1
|
3795
|
package com.zhuinden.simplestackdemomultistack.application
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.zhuinden.simplestack.SimpleStateChanger
import com.zhuinden.simplestack.StateChange
import com.zhuinden.simplestackdemomultistack.R
import com.zhuinden.simplestackdemomultistack.core.navigation.Multistack
import com.zhuinden.simplestackdemomultistack.core.navigation.MultistackFragmentStateChanger
import com.zhuinden.simplestackdemomultistack.features.main.chromecast.ChromeCastKey
import com.zhuinden.simplestackdemomultistack.features.main.cloudsync.CloudSyncKey
import com.zhuinden.simplestackdemomultistack.features.main.list.ListKey
import com.zhuinden.simplestackdemomultistack.features.main.mail.MailKey
class MainActivity : AppCompatActivity(), SimpleStateChanger.NavigationHandler {
lateinit var multistack: Multistack
private var isAnimating: Boolean = false
enum class StackType {
CLOUDSYNC,
CHROMECAST,
MAIL,
LIST
}
private lateinit var multistackFragmentStateChanger: MultistackFragmentStateChanger
override fun onCreate(savedInstanceState: Bundle?) {
this.multistack = (lastCustomNonConfigurationInstance as Multistack?)
?: Multistack().apply {
add(CloudSyncKey)
add(ChromeCastKey)
add(MailKey)
add(ListKey)
if (savedInstanceState != null) {
fromBundle(savedInstanceState.getParcelable("multistack"))
}
}
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
multistackFragmentStateChanger = MultistackFragmentStateChanger(R.id.root, supportFragmentManager)
findViewById<View>(R.id.bbn_item1).setOnClickListener {
multistack.setSelectedStack(StackType.values()[0].name)
}
findViewById<View>(R.id.bbn_item2).setOnClickListener {
multistack.setSelectedStack(StackType.values()[1].name)
}
findViewById<View>(R.id.bbn_item3).setOnClickListener {
multistack.setSelectedStack(StackType.values()[2].name)
}
findViewById<View>(R.id.action4).setOnClickListener {
multistack.setSelectedStack(StackType.values()[3].name)
}
multistack.setStateChanger(SimpleStateChanger(this))
}
override fun onRetainCustomNonConfigurationInstance(): Any = multistack
override fun onPostResume() {
super.onPostResume()
multistack.unpause()
}
override fun onPause() {
multistack.pause()
super.onPause()
}
override fun onBackPressed() {
val backstack = multistack.getSelectedStack()
if (!backstack.goBack()) {
super.onBackPressed()
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putParcelable("multistack", multistack.toBundle())
}
override fun onDestroy() {
super.onDestroy()
multistack.executePendingStateChange()
if (isFinishing) {
multistack.finalize()
}
}
override fun getSystemService(name: String): Any? {
if (::multistack.isInitialized) {
if (multistack.has(name)) {
return multistack.get(name)
}
}
return super.getSystemService(name)
}
override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
return !isAnimating && super.dispatchTouchEvent(ev)
}
override fun onNavigationEvent(stateChange: StateChange) {
multistackFragmentStateChanger.handleStateChange(stateChange)
}
}
|
apache-2.0
|
61352979df9e34761345c10041bc6884
| 31.169492 | 106 | 0.689065 | 4.803797 | false | false | false | false |
vsch/idea-multimarkdown
|
src/main/java/com/vladsch/md/nav/editor/PreviewFileEditorBase.kt
|
1
|
37189
|
// Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.editor
import com.intellij.codeHighlighting.BackgroundEditorHighlighter
import com.intellij.find.EditorSearchSession
import com.intellij.find.FindModel
import com.intellij.find.SearchReplaceComponent
import com.intellij.ide.structureView.StructureViewBuilder
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.ScrollType
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.editor.event.SelectionEvent
import com.intellij.openapi.editor.event.SelectionListener
import com.intellij.openapi.fileEditor.*
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.UserDataHolderBase
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.util.Alarm
import com.vladsch.flexmark.util.sequence.Range
import com.vladsch.flexmark.util.sequence.TagRange
import com.vladsch.md.nav.*
import com.vladsch.md.nav.editor.api.MdPreviewCustomizationProvider
import com.vladsch.md.nav.editor.javafx.JavaFxHtmlPanelProvider
import com.vladsch.md.nav.editor.resources.JavaFxHtmlCssProvider
import com.vladsch.md.nav.editor.split.SplitFileEditor
import com.vladsch.md.nav.editor.split.SplitPreviewChangeListener
import com.vladsch.md.nav.editor.swing.SwingHtmlPanelProvider
import com.vladsch.md.nav.editor.text.TextHtmlPanelProvider
import com.vladsch.md.nav.editor.util.HtmlGeneratorProvider
import com.vladsch.md.nav.editor.util.HtmlPanel
import com.vladsch.md.nav.editor.util.HtmlPanelProvider
import com.vladsch.md.nav.editor.util.HtmlPanelProvider.AvailabilityInfo
import com.vladsch.md.nav.settings.*
import com.vladsch.md.nav.util.*
import com.vladsch.md.nav.vcs.GitHubLinkResolver
import com.vladsch.plugin.util.TimeIt
import com.vladsch.plugin.util.debug
import java.awt.BorderLayout
import java.awt.event.ComponentEvent
import java.awt.event.ComponentListener
import java.beans.PropertyChangeListener
import java.lang.reflect.Method
import java.util.*
import java.util.regex.Pattern
import java.util.regex.PatternSyntaxException
import javax.swing.JComponent
import javax.swing.JPanel
abstract class PreviewFileEditorBase constructor(protected val myProject: Project, protected val myFile: VirtualFile) : UserDataHolderBase(), FileEditor, HtmlPanelHost {
private val myHtmlPanelWrapper: JPanel = JPanel(BorderLayout())
private var myPanel: HtmlPanel? = null
protected var myLastPanelProviderInfo: HtmlPanelProvider.Info? = null
protected val myDocument: Document? = FileDocumentManager.getInstance().getDocument(myFile)
private val myDocumentAlarm = Alarm(Alarm.ThreadToUse.POOLED_THREAD, this)
private val mySwingAlarm = Alarm(Alarm.ThreadToUse.SWING_THREAD, this)
private var myLastHtmlOrRefreshRequest: Runnable? = null
private var myLastScrollOffset: Int = 0
private var myLastScrollLineOffsets: Range = Range.of(0, 0)
private var myLastOffsetVertical: Float? = null
protected var myLastRenderedHtml: String = ""
private var myLastRenderedUrl = ""
private var myLastUpdatedModificationStamp = 0L
protected var myRenderingProfile: MdRenderingProfile
private var mySplitEditorLayout: SplitFileEditor.SplitEditorLayout
init {
myRenderingProfile = MdRenderingProfileManager.getInstance(myProject).getRenderingProfile(myFile)
mySplitEditorLayout = myRenderingProfile.previewSettings.splitEditorLayout
}
protected var myHtmlTagRanges: List<TagRange> = ArrayList()
private var inSettingsChange: Boolean = false
protected var mySplitEditorPreviewType: SplitFileEditor.SplitEditorPreviewType = myRenderingProfile.previewSettings.splitEditorPreviewType
private var myPreviewEditorState: PreviewEditorState = PreviewEditorState()
protected var myLastHtmlProviderInfo: HtmlGeneratorProvider.Info? = null
protected var myFirstEditorCounterpart: FileEditor? = null
private var gotFirstEditor = false
protected var myDocumentIsModified: Boolean = false
private val panelSetupTimeoutMs: Long = 10L
private var renderingDelayMs: Long = MdApplicationSettings.instance.documentSettings.typingUpdateDelay.toLong()
protected var myEditor: Editor? = null
private val mySearchReplaceListener: SearchReplaceComponent.Listener
private val myFindModelObserver: FindModel.FindModelObserver
private val myComponentListener: ComponentListener
private val mySelectionListener: SelectionListener
private var myShowingSearch = false
protected var myHighlightEnabled: Boolean = true
private var myEditorListenerRemoved = false
init {
renderingLogger.debug { "initialized rendering profile: '${myRenderingProfile.profileName}' panel info: ${myRenderingProfile.previewSettings.htmlPanelProviderInfo.providerId}, css: ${myRenderingProfile.cssSettings.cssProviderInfo.providerId}" }
}
fun print() {
myPanel?.print()
}
fun canPrint(): Boolean = myPanel?.canPrint() ?: false
fun debug(startStop: Boolean) {
myPanel?.debug(startStop)
}
fun canDebug(): Boolean = myPanel?.canDebug() ?: false
fun isDebuggerEnabled(): Boolean = myPanel?.isDebuggerEnabled() ?: false
fun isDebugging(): Boolean = myPanel?.isDebugging() ?: false
fun isDebugBreakOnLoad(): Boolean = myPanel?.isDebugBreakOnLoad() ?: false
fun debugBreakOnLoad(debugBreakOnLoad: Boolean, debugBreakInjectionOnLoad: Boolean) {
myPanel?.debugBreakOnLoad(debugBreakOnLoad, debugBreakInjectionOnLoad)
}
override fun getRenderingProfile(): MdRenderingProfile = myRenderingProfile
override fun isHighlightEnabled(): Boolean {
return myHighlightEnabled /*&& myIsLicensed*/ && myRenderingProfile.previewSettings.highlightPreviewTypeEnum != HighlightPreviewType.NONE
}
open fun canHighlight(): Boolean {
return true
}
override fun toggleTask(pos: String) {
// pos is start-end
val taskOffset = pos.toIntOrNull() ?: return
ApplicationManager.getApplication().invokeLater {
WriteCommandAction.runWriteCommandAction(myProject) {
val textLength = myDocument?.textLength ?: return@runWriteCommandAction
val charSequence = myDocument.charsSequence
if (taskOffset > 0 && taskOffset + 2 < textLength && charSequence[taskOffset - 1] == '[' && charSequence[taskOffset + 1] == ']') {
myDocument.replaceString(taskOffset, taskOffset + 1, if (charSequence[taskOffset] == ' ') "x" else " ")
}
}
}
}
fun monitorDocument() {
if (myDocumentAlarm.isDisposed) return
var alternatePageUrlEnabled = false
for (provider in MdPreviewCustomizationProvider.EXTENSIONS.value) {
if (provider.isAlternateUrlEnabled(myRenderingProfile)) {
alternatePageUrlEnabled = true
break
}
}
if (!alternatePageUrlEnabled) return
myDocumentAlarm.cancelAllRequests()
myDocumentAlarm.addRequest({
ApplicationManager.getApplication().invokeLater {
val editorCounterpart = myFirstEditorCounterpart
if (myDocumentIsModified) {
if (editorCounterpart != null) {
if (!editorCounterpart.isModified) {
detailLogger.debug { "clearing document modified flag" }
myDocumentIsModified = false
updateHtml()
}
}
monitorDocument()
}
}
}, if (myDocumentIsModified) MODIFIED_DOCUMENT_TIMEOUT_MS else UNMODIFIED_DOCUMENT_TIMEOUT_MS)
}
private fun previewSettingsValidation() {
if (myRenderingProfile.previewSettings.htmlPanelProviderInfo == SwingHtmlPanelProvider.INFO) {
if (myRenderingProfile.cssSettings.cssProviderInfo == JavaFxHtmlCssProvider.INFO) {
// need to change the stylesheets
renderingLogger.debug { "previewSettingsValidation: changing JavaFx CSS to swing, '${myRenderingProfile.profileName}' panel info: ${myRenderingProfile.previewSettings.htmlPanelProviderInfo.providerId}, css: ${myRenderingProfile.cssSettings.cssProviderInfo.providerId}" }
myRenderingProfile = myRenderingProfile.changeToProvider(JavaFxHtmlPanelProvider.INFO, SwingHtmlPanelProvider.INFO)
renderingLogger.debug { "previewSettingsValidation: changed JavaFx CSS to swing, '${myRenderingProfile.profileName}' panel info: ${myRenderingProfile.previewSettings.htmlPanelProviderInfo.providerId}, css: ${myRenderingProfile.cssSettings.cssProviderInfo.providerId}" }
}
}
}
private fun layoutSettingValidation() {
if (mySplitEditorPreviewType == SplitFileEditor.SplitEditorPreviewType.NONE) {
if (mySplitEditorLayout != SplitFileEditor.SplitEditorLayout.FIRST) {
mySplitEditorPreviewType = SplitFileEditor.SplitEditorPreviewType.PREVIEW
}
}
}
init {
myDocument?.addDocumentListener(object : DocumentListener {
override fun beforeDocumentChange(e: DocumentEvent) {
if (!gotFirstEditor) {
// time to get our counterpart
val splitEditor = getUserData(SplitFileEditor.PARENT_SPLIT_KEY)
gotFirstEditor = true
myFirstEditorCounterpart = splitEditor?.mainEditor
}
}
override fun documentChanged(e: DocumentEvent) {
myDocumentIsModified = true
monitorDocument()
updateHtml()
}
}, this)
val messageBusConnection = ApplicationManager.getApplication().messageBus.connect(this)
val projectMessageBusConnection = myProject.messageBus.connect(this)
val imageFileChangedListener = object : MdProjectComponent.FileChangedListener {
override fun onFilesChanged() {
updateHtml()
}
}
projectMessageBusConnection.subscribe(MdProjectComponent.FileChangedListener.TOPIC, imageFileChangedListener)
val settingsChangedListener = ProjectSettingsChangedListener { project, _ ->
renderingLogger.debug { "OnProjectSettingsChange updateRenderingProfile: $project, $inSettingsChange, '${myRenderingProfile.profileName}' ${myRenderingProfile.previewSettings.htmlPanelProviderInfo.providerId}" }
updateRenderingProfile(project)
}
messageBusConnection.subscribe(SettingsChangedListener.TOPIC, object : SettingsChangedListener {
override fun onSettingsChange(settings: MdApplicationSettings) {
val documentSettings = settings.documentSettings
renderingDelayMs = documentSettings.typingUpdateDelay.toLong()
updateGutterIcons()
}
})
projectMessageBusConnection.subscribe(ProjectSettingsChangedListener.TOPIC, settingsChangedListener)
val profilesChangedListener = object : ProfileManagerChangeListener {
override fun onSettingsLoaded(manager: RenderingProfileManager) {
// renderingLogger.debug { "ProfileManager onSettingsLoaded updateRenderingProfile: ${manager.project}, $inSettingsChange, ${myRenderingProfile.previewSettings.htmlPanelProviderInfo.providerId}" }
// updateRenderingProfile(manager.project)
}
override fun onSettingsChange(manager: RenderingProfileManager) {
renderingLogger.debug { "ProfileManager onSettingsChanged updateRenderingProfile: '${myRenderingProfile.profileName}' ${manager.project}, $inSettingsChange, ${myRenderingProfile.previewSettings.htmlPanelProviderInfo.providerId}" }
updateRenderingProfile(manager.project)
}
}
projectMessageBusConnection.subscribe(ProfileManagerChangeListener.TOPIC, profilesChangedListener)
val editorBase = this
val previewChangedListener = SplitPreviewChangeListener { editorPreview, editorLayout, forEditor ->
if (editorBase === forEditor) {
// val updateNeeded = getSplitEditorPreview(mySplitEditorPreviewType, mySplitEditorLayout) != getSplitEditorPreview(editorPreview, editorLayout)
mySplitEditorPreviewType = editorPreview
mySplitEditorLayout = editorLayout
layoutSettingValidation()
if (!setUpPanel()) updateHtml()
}
}
messageBusConnection.subscribe(SplitFileEditor.PREVIEW_CHANGE, previewChangedListener)
projectMessageBusConnection.subscribe(MdRepoChangeListener.TOPIC, MdRepoChangeListener {
ApplicationManager.getApplication().invokeLater {
updateHtml()
detailLogger.debug { ("OnRepoChanged()") }
}
})
mySearchReplaceListener = object : SearchReplaceComponent.Listener {
override fun multilineStateChanged() {
if (canHighlight() && myRenderingProfile.previewSettings.showSearchHighlightsInPreview) {
updateHtml()
}
}
override fun searchFieldDocumentChanged() {
if (canHighlight() && myRenderingProfile.previewSettings.showSearchHighlightsInPreview) {
updateHtml()
}
}
override fun replaceFieldDocumentChanged() {
}
}
myFindModelObserver = FindModel.FindModelObserver {
if (canHighlight() && myRenderingProfile.previewSettings.showSearchHighlightsInPreview) {
updateHtml()
}
}
myComponentListener = object : ComponentListener {
override fun componentMoved(e: ComponentEvent?) {
checkEditorSearchComponent()
}
override fun componentResized(e: ComponentEvent?) {
checkEditorSearchComponent()
}
override fun componentHidden(e: ComponentEvent?) {
}
override fun componentShown(e: ComponentEvent?) {
}
}
mySelectionListener = object : SelectionListener {
override fun selectionChanged(e: SelectionEvent) {
if (canHighlight() && myRenderingProfile.previewSettings.showSelectionInPreview) {
updateHtml()
}
}
}
setUpPanel()
}
private fun updateRenderingProfile(project: Project) {
if (project === myProject) {
renderingLogger.debug { "updateRenderingProfile: $project, $inSettingsChange, '${myRenderingProfile.profileName}' ${myRenderingProfile.previewSettings.htmlPanelProviderInfo.providerId}" }
if (!inSettingsChange) {
inSettingsChange = true
val highlightType = myRenderingProfile.previewSettings.highlightPreviewTypeEnum
myRenderingProfile = MdRenderingProfileManager.getInstance(myProject).getRenderingProfile(myFile)
previewSettingsValidation()
renderingLogger.debug { "after update: '${myRenderingProfile.profileName}' ${myRenderingProfile.previewSettings.htmlPanelProviderInfo.providerId}" }
val updateHtml = !setUpPanel() || highlightType != myRenderingProfile.previewSettings.highlightPreviewTypeEnum /*&& myIsLicensed*/
inSettingsChange = false
if (updateHtml) updateHtml()
} else {
renderingLogger.debug { "skipped already in update" }
}
}
}
private fun updateGutterIcons() {
val editor = myEditor ?: return
val documentSettings = MdApplicationSettings.instance.documentSettings
val enableGutters = documentSettings.iconGutters
val settings = editor.settings
if (settings.isLineMarkerAreaShown != enableGutters) {
settings.isLineMarkerAreaShown = enableGutters
}
}
private fun checkEditorSearchComponent() {
val editor = myEditor ?: return
val searchSession = EditorSearchSession.get(editor)
val showingSearch = searchSession != null
if (searchSession != null) {
searchSession.findModel.addObserver(myFindModelObserver)
searchSession.component.addListener(mySearchReplaceListener)
}
if (showingSearch != myShowingSearch) {
if (myShowingSearch || myRenderingProfile.previewSettings.showSearchHighlightsInPreview) {
updateHtml()
}
}
}
fun getSplitEditorPreview(value: SplitFileEditor.SplitEditorPreviewType, layout: SplitFileEditor.SplitEditorLayout): SplitFileEditor.SplitEditorPreviewType {
return if (layout != SplitFileEditor.SplitEditorLayout.FIRST) value
else SplitFileEditor.SplitEditorPreviewType.NONE
}
override fun synchronizeCaretPos(offset: Int) {
if (myRenderingProfile.previewSettings.synchronizeSourcePositionOnClick) {
ApplicationManager.getApplication().invokeLater {
synchronizeCaretPosRaw(offset)
}
}
}
private fun synchronizeCaretPosRaw(offset: Int) {
val textLength = myDocument?.textLength ?: 0
if (textLength > offset) {
val fileEditor = FileEditorManager.getInstance(myProject).getSelectedEditor(myFile)
val textEditor = (fileEditor as? SplitFileEditor<*, *>)?.mainEditor as? TextEditor
if (fileEditor != null && textEditor != null) {
textEditor.editor.caretModel.moveToOffset(offset)
textEditor.editor.scrollingModel.scrollToCaret(ScrollType.MAKE_VISIBLE)
val focusComponent = textEditor.preferredFocusedComponent ?: textEditor.component
IdeFocusManager.findInstanceByComponent(focusComponent).requestFocus(focusComponent, true)
}
}
}
override fun getComponent(): JComponent {
return myHtmlPanelWrapper
}
override fun getPreferredFocusedComponent(): JComponent? {
return myPanel?.component
}
override fun getName(): String {
return "Markdown HTML Preview"
}
override fun getVirtualFile(): VirtualFile {
return myFile
}
override fun getState(level: FileEditorStateLevel): FileEditorState {
val htmlPanel = myPanel
if (htmlPanel != null) {
myPreviewEditorState = htmlPanel.getState()
}
return myPreviewEditorState
}
override fun setState(state: FileEditorState) {
if (state is PreviewEditorState) {
myPreviewEditorState = state
myPanel?.setState(myPreviewEditorState)
}
}
override fun isModified(): Boolean {
return false
}
override fun isValid(): Boolean {
return true
}
override fun selectNotify() {
if (myProject.isDisposed) return
updateHtml()
}
private fun setUpPanel(): Boolean {
val newPanelProvider = retrievePanelProvider() ?: return false
if (!mySwingAlarm.isDisposed) mySwingAlarm.addRequest({
val newPanel = newPanelProvider.createHtmlPanel(myProject, this)
val oldPanel = myPanel
if (oldPanel != null) {
myHtmlPanelWrapper.remove(oldPanel.component)
Disposer.dispose(oldPanel)
}
myPanel = newPanel
myHtmlPanelWrapper.add(newPanel.component, BorderLayout.CENTER)
//newPanel.setHtmlPanelHost(this)
newPanel.setState(myPreviewEditorState)
myHtmlPanelWrapper.repaint()
updateHtml()
}, /*if (myPanel == null) 1L else */panelSetupTimeoutMs, ModalityState.stateForComponent(myHtmlPanelWrapper))
return true
}
private fun retrievePanelProvider(): HtmlPanelProvider? {
var providerInfo = when (getSplitEditorPreview(mySplitEditorPreviewType, mySplitEditorLayout)) {
SplitFileEditor.SplitEditorPreviewType.PREVIEW -> myRenderingProfile.previewSettings.htmlPanelProviderInfo
SplitFileEditor.SplitEditorPreviewType.NONE -> myRenderingProfile.previewSettings.htmlPanelProviderInfo
else -> TextHtmlPanelProvider.INFO
}
if (providerInfo == myLastPanelProviderInfo) {
return null
}
var provider = HtmlPanelProvider.getFromInfoOrDefault(providerInfo)
if (provider.isAvailable !== AvailabilityInfo.AVAILABLE && provider.isAvailable !== AvailabilityInfo.AVAILABLE_NOTUSED) {
val newSettings = myRenderingProfile.changeToProvider(providerInfo, null)
myRenderingProfile = newSettings
provider = newSettings.previewSettings.htmPanelProvider
val unavailableProviderInfo = providerInfo
providerInfo = newSettings.previewSettings.htmlPanelProviderInfo
PluginNotifications.makeNotification(MdBundle.message("editor.preview.file.no-javafx.message", unavailableProviderInfo.name),
MdBundle.message("editor.preview.file.no-javafx.title"), project = myProject)
// change globally so that all update
val renderingSettings = MdProjectSettings.getInstance(myProject).renderingProfile
if (renderingSettings.previewSettings.htmlPanelProviderInfo == unavailableProviderInfo) {
try {
inSettingsChange = true
val renderingProfile = renderingSettings.changeToProvider(unavailableProviderInfo, providerInfo)
//MdApplicationSettings.instance.renderingProfile = renderingProfile
MdProjectSettings.getInstance(myProject).renderingProfile = renderingProfile
} finally {
inSettingsChange = false
}
}
}
myLastPanelProviderInfo = providerInfo
return provider
}
private val panelGuaranteed: HtmlPanel
get() {
return myPanel ?: throw IllegalStateException("Panel is guaranteed to be not null now")
}
abstract fun makeHtmlPage(pattern: Pattern?): String
private fun updateHtml() {
if (getSplitEditorPreview(mySplitEditorPreviewType, mySplitEditorLayout) == SplitFileEditor.SplitEditorPreviewType.NONE) return
if (!myFile.isValid || myDocument == null) {
return
}
myShowingSearch = false
var highlightRanges: Pattern? = null
if (myEditor != null) {
if (myRenderingProfile.previewSettings.showSearchHighlightsInPreview) {
val searchSession = EditorSearchSession.get(myEditor)
if (searchSession != null) {
val findModel = searchSession.findModel
val searchText = searchSession.component.searchTextComponent.text
val isRegex = findModel.isRegularExpressions
val isCaseSensitive = findModel.isCaseSensitive
val isWord = findModel.isWholeWordsOnly
if (searchText.isNotEmpty()) {
try {
val pattern = if (isRegex) {
Pattern.compile(searchText, if (isCaseSensitive) 0 else Pattern.CASE_INSENSITIVE)
} else {
if (isWord) {
val wordStart = searchText[0].isJavaIdentifierPart() && searchText[0] != '$'
val wordEnd = searchText[searchText.length - 1].isJavaIdentifierPart() && searchText[searchText.length - 1] != '$'
Pattern.compile("${if (wordStart) "\\b" else ""}\\Q$searchText\\E${if (wordEnd) "\\b" else ""}", if (isCaseSensitive) 0 else Pattern.CASE_INSENSITIVE)
} else {
Pattern.compile("\\Q$searchText\\E", if (isCaseSensitive) 0 else Pattern.CASE_INSENSITIVE)
}
}
highlightRanges = pattern
} catch (e: PatternSyntaxException) {
}
}
}
myShowingSearch = searchSession != null
}
}
if (!mySwingAlarm.isDisposed) {
val lastHtmlOrRefreshRequest = myLastHtmlOrRefreshRequest
if (lastHtmlOrRefreshRequest != null) {
mySwingAlarm.cancelRequest(lastHtmlOrRefreshRequest)
}
val nextHtmlOrRefreshRequest = Runnable {
updateHtmlRunner(highlightRanges)
}
myLastHtmlOrRefreshRequest = nextHtmlOrRefreshRequest
val stateForComponent = ModalityState.stateForComponent(component)
mySwingAlarm.addRequest(nextHtmlOrRefreshRequest, renderingDelayMs, stateForComponent)
}
}
open fun scrollToSrcOffset(offset: Int, editor: Editor) {
val document = editor.document
if (myEditor == null) {
myEditor = editor
val editorComponent = editor.contentComponent
editorComponent.addComponentListener(myComponentListener)
editor.selectionModel.addSelectionListener(mySelectionListener)
ApplicationManager.getApplication().invokeLater {
if (!editor.isDisposed) updateGutterIcons()
}
}
val offsetVertical: Float?
val lineOffsets: Range?
if (myRenderingProfile.previewSettings.verticallyAlignSourceAndPreviewSyncPosition) {
// get the vertical position as % of editor content height
syncLogger.debug { "getting editor search info" }
val searchHeight: Int
val searchSession = EditorSearchSession.get(editor)
searchHeight = searchSession?.component?.height ?: 0
val scrollingModel = editor.scrollingModel
val scrollOffset = scrollingModel.verticalScrollOffset
val scrollHeight = scrollingModel.visibleArea.height - searchHeight
val pos = editor.offsetToVisualPosition(offset)
val lineNumber = editor.document.getLineNumber(offset)
val lineStart = editor.document.getLineStartOffset(lineNumber)
val lineEnd = editor.document.getLineEndOffset(lineNumber)
lineOffsets = Range.of(lineStart, lineEnd)
val offsetVerticalPos = editor.visualPositionToXY(pos).y - scrollOffset
offsetVertical = if (scrollHeight > 0) offsetVerticalPos * 100f / scrollHeight else 50f
} else {
syncLogger.debug { "no editor search info" }
offsetVertical = null
lineOffsets = Range.of(offset, offset)
}
if (myRenderingProfile.previewSettings.synchronizePreviewPosition) {
if (document.modificationStamp == myLastUpdatedModificationStamp && myPanel != null) {
TimeIt.logTime(syncLogger, "scrollToMarkdownSrcOffset($offset, myHtmlTagRanges, false, false))") {
myLastScrollOffset = offset
myLastScrollLineOffsets = lineOffsets
myLastOffsetVertical = offsetVertical
panelGuaranteed.scrollToMarkdownSrcOffset(offset, lineOffsets, offsetVertical, myHtmlTagRanges, onLoadUpdate = false, onTypingUpdate = false)
}
} else {
// save it for the page load update
syncLogger.debug { "caching till page load: scrollToMarkdownSrcOffset($offset, myHtmlTagRanges, false, false))" }
myLastScrollOffset = offset
myLastScrollLineOffsets = lineOffsets
myLastOffsetVertical = offsetVertical
}
}
}
private fun updateHtmlRunner(highlightRanges: Pattern?) {
// diagnostic/2940
if (myProject.isDisposed) return
myLastHtmlOrRefreshRequest = null
// set time stamp to eliminate scrolling updates for earlier or later caret moves
myLastUpdatedModificationStamp = myDocument?.modificationStamp ?: 0
val lastRenderedUrl = myLastRenderedUrl
myLastRenderedUrl = ""
if (panelGuaranteed.setPageUrl("") != null && !myDocumentIsModified) {
var url: String? = null
for (provider in MdPreviewCustomizationProvider.EXTENSIONS.value) {
val altUrl = provider.getAlternatePageURL(myProject, myFile, myRenderingProfile)
if (altUrl != null) {
url = altUrl
break
}
}
if (url != null) {
detailLogger.debug { "GitHub preview url: $url" }
//val urlBase = "https://github.com"
myLastRenderedUrl = url
myLastRenderedHtml = ""
panelGuaranteed.setPageUrl(url)
detailLogger.debug { "GitHub preview: $url" }
}
}
if (myLastRenderedUrl.isBlank()) {
var currentHtml = ""
TimeIt.logTime(LOG, "makeHtmlPage() ") {
currentHtml = makeHtmlPage(highlightRanges)
}
detailLogger.debug { "JavaFx preview, last URL = $lastRenderedUrl" }
myLastRenderedHtml = currentHtml
if (!lastRenderedUrl.isBlank()) {
// first one needs to be blank to reset the URL, or it won't render
setUpPanel()
detailLogger.debug { "JavaFx recreating preview to clear URL" }
} else {
myPanel ?: return
if (myRenderingProfile.previewSettings.synchronizePreviewPosition) {
val lastActionId: String? = getLastActionId()
panelGuaranteed.scrollToMarkdownSrcOffset(myLastScrollOffset, myLastScrollLineOffsets, myLastOffsetVertical, myHtmlTagRanges, true, lastActionId == null || lastActionId in arrayOf("EditorBackSpace"))
}
TimeIt.logTime(LOG, "Update") {
if (panelGuaranteed.setHtml(currentHtml)) {
detailLogger.debug { "JavaFx preview, updated" }
} else {
detailLogger.debug { "JavaFx preview, rescheduled" }
}
}
}
}
}
// return true if handled
override fun launchExternalLink(href: String): Boolean {
@Suppress("NAME_SHADOWING")
var href = href
var hrefInfo = PathInfo(href)
if (!myLastRenderedUrl.isBlank() || !hrefInfo.isURI) {
// here we translate to files so that the file is opened, then it will be viewed on GitHub
ApplicationManager.getApplication().runReadAction {
val resolver = GitHubLinkResolver(myFile, myProject)
if (myLastRenderedUrl.isBlank()) {
// regular link resolve
var options = arrayOf(Local.URI, Remote.URI, Links.URL)
for (provider in MdPreviewCustomizationProvider.EXTENSIONS.value) {
val useLinkOptions = provider.getLinkOptions(myRenderingProfile)
if (useLinkOptions != null) {
options = useLinkOptions
break
}
}
val pathInfo = resolver.resolve(LinkRef.parseLinkRef(resolver.containingFile, href, null), Want(*options))
if (pathInfo != null) {
val pos = href.indexOf('#')
val anchorRef = if (pos == -1) "" else href.substring(pos)
hrefInfo = pathInfo
href = pathInfo.filePath + anchorRef
}
detailLogger.debug { "link click resolved: $href, resolved: ${pathInfo?.filePath}" }
} else {
// external page url resolve
val url = if (href.startsWith("/")) "https://github.com$href" else href
val pathInfo = resolver.resolve(LinkRef.parseLinkRef(resolver.containingFile, url, null), Want(Local.URI, Remote.URI, Links.URL))
if (pathInfo != null) {
val pos = href.indexOf('#')
val anchorRef = if (pos == -1) "" else href.substring(pos)
hrefInfo = pathInfo
href = pathInfo.filePath + anchorRef
}
detailLogger.debug { "GitHub preview link: $href, url: $url, resolved: ${pathInfo?.filePath}" }
}
}
}
for (provider in MdPreviewCustomizationProvider.EXTENSIONS.value) {
if (!provider.canLaunchExternalLink(myLastRenderedUrl, href, myRenderingProfile)) return false
}
MdPathResolver.launchExternalLink(myProject, href)
return true
}
override fun deselectNotify() {
}
override fun addPropertyChangeListener(listener: PropertyChangeListener) {
}
override fun removePropertyChangeListener(listener: PropertyChangeListener) {
}
override fun getBackgroundHighlighter(): BackgroundEditorHighlighter? {
return null
}
override fun getCurrentLocation(): FileEditorLocation? {
return null
}
override fun getStructureViewBuilder(): StructureViewBuilder? {
return null
}
override fun dispose() {
val panel = myPanel
if (panel != null) {
Disposer.dispose(panel)
}
val editor = myEditor
if (editor != null && !myEditorListenerRemoved) {
myEditorListenerRemoved = true
val editorComponent = editor.contentComponent
editorComponent.removeComponentListener(myComponentListener)
editor.selectionModel.removeSelectionListener(mySelectionListener)
}
}
companion object {
val LOG = Logger.getInstance("com.vladsch.md.nav.editor.htmlPrep")
val syncLogger = Logger.getInstance("com.vladsch.md.nav.editor.sync-details")
private val detailLogger = Logger.getInstance("com.vladsch.md.nav.editor.htmlPrep-details")
val renderingLogger = Logger.getInstance("com.vladsch.md.nav.editor.htmlPrep-rendering")
private var lastActionInitialized = false
private var lastActionIdMethod: Method? = null
private var editorLastActionTrackerInstance: Any? = null
val MODIFIED_DOCUMENT_TIMEOUT_MS = 1500L
val UNMODIFIED_DOCUMENT_TIMEOUT_MS = 5000L
fun getLastActionId(): String? {
if (!lastActionInitialized) {
lastActionInitialized = true
var editorLastActionTrackerClass: Class<*>? = null
try {
editorLastActionTrackerClass = Class.forName("com.intellij.openapi.editor.impl.EditorLastActionTrackerImpl")
} catch (e: ClassNotFoundException) {
}
if (editorLastActionTrackerClass == null) {
try {
editorLastActionTrackerClass = Class.forName("com.intellij.openapi.editor.impl.EditorLastActionTracker")
} catch (e: ClassNotFoundException) {
}
}
if (editorLastActionTrackerClass != null) {
try {
val instanceMethod: Method = editorLastActionTrackerClass.getMethod("getInstance")
lastActionIdMethod = editorLastActionTrackerClass.getMethod("getLastActionId")
editorLastActionTrackerInstance = instanceMethod.invoke(null)
} catch (e: Throwable) {
}
}
}
if (lastActionIdMethod == null || editorLastActionTrackerInstance == null) {
return null
} else {
return lastActionIdMethod!!.invoke(editorLastActionTrackerInstance) as? String
}
}
private val TEST_HTML: String by lazy {
MdResourceResolverImpl.instance.getResourceFileContent("/com/vladsch/md/nav/test_rendering.html")
}
}
}
|
apache-2.0
|
f841effff69954027f4b173517e4a21e
| 43.272619 | 286 | 0.647181 | 5.544804 | false | false | false | false |
toastkidjp/Yobidashi_kt
|
todo/src/main/java/jp/toastkid/todo/view/appbar/AppBarUi.kt
|
1
|
1081
|
/*
* Copyright (c) 2022 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.todo.view.appbar
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import jp.toastkid.todo.R
@Composable
internal fun AppBarUi(onClickAdd: () -> Unit) {
Button(
onClick = onClickAdd,
colors = ButtonDefaults.textButtonColors(
backgroundColor = MaterialTheme.colors.surface,
contentColor = MaterialTheme.colors.onSurface,
disabledContentColor = Color.LightGray
)
) {
Text(text = stringResource(id = R.string.add))
}
}
|
epl-1.0
|
e2abeafaf221045a39994a058628ed02
| 32.8125 | 88 | 0.743756 | 4.358871 | false | false | false | false |
android/privacy-sandbox-samples
|
AttributionReporting/MeasurementSampleApp/app/src/main/java/com/example/measurement/sampleapp/di/module/AppModule.kt
|
1
|
1392
|
/*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.measurement.sampleapp.di.module
import android.adservices.measurement.MeasurementManager
import android.app.Application
import android.content.Context
import dagger.Module
import dagger.Provides
/*
* Default values
* */
var DEFAULT_SERVER_URL = "https://measurement.sample.server.url.com"
var DEFAULT_SOURCE_REGISTRATION_ID = "1"
var DEFAULT_CONVERSION_REGISTRATION_ID = "1"
/*
* AppModule
* This class provides app modules. Modules that are used in the app.
* */
@Module
internal class AppModule() {
@Provides
fun provideContext(application: Application): Context = application.applicationContext
@Provides
fun provideMeasurementManager(context: Context): MeasurementManager =
context.getSystemService(MeasurementManager::class.java)
}
|
apache-2.0
|
d30cefec0b0caffa1ecb309baa7db443
| 31.395349 | 88 | 0.76796 | 4.18018 | false | false | false | false |
johnnywey/kotlin-koans
|
src/v_builders/_39_HtmlBuilders.kt
|
8
|
1096
|
package v_builders
import util.TODO
import util.doc39
import v_builders.data.getProducts
import v_builders.htmlLibrary.*
fun getTitleColor() = "#b9c9fe"
fun getCellColor(row: Int, column: Int) = if ((row + column) %2 == 0) "#dce4ff" else "#eff2ff"
fun todoTask39(): Nothing = TODO(
"""
Task 39.
1) Fill the table with the proper values from products.
2) Color the table like a chess board (using getTitleColor() and getCellColor() functions above).
Pass a color as an argument to functions 'tr', 'td'.
You can run the 'Html Demo' configuration in IntelliJ IDEA to see the rendered table.
""",
documentation = doc39()
)
fun renderProductTable(): String {
return html {
table {
tr {
td {
text("Product")
}
td {
text("Price")
}
td {
text("Popularity")
}
}
val products = getProducts()
todoTask39()
}
}.toString()
}
|
mit
|
b4621e2b8e4fe150cdfff278683a328f
| 26.4 | 105 | 0.528285 | 4.384 | false | false | false | false |
square/duktape-android
|
zipline-gradle-plugin/src/main/kotlin/app/cash/zipline/gradle/ZiplineServeTask.kt
|
1
|
2556
|
/*
* Copyright (C) 2021 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.cash.zipline.gradle
import javax.inject.Inject
import org.gradle.api.DefaultTask
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.provider.Property
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.Optional
import org.gradle.api.tasks.TaskAction
import org.gradle.deployment.internal.Deployment
import org.gradle.deployment.internal.DeploymentHandle
import org.gradle.deployment.internal.DeploymentRegistry
import org.http4k.core.ContentType
import org.http4k.routing.ResourceLoader.Companion.Directory
import org.http4k.routing.bind
import org.http4k.routing.routes
import org.http4k.routing.static
import org.http4k.server.Http4kServer
import org.http4k.server.SunHttp
import org.http4k.server.asServer
abstract class ZiplineServeTask : DefaultTask() {
@get:Input
abstract val inputDir: DirectoryProperty
@get:Optional
@get:Input
abstract val port: Property<Int>
@TaskAction
fun task() {
val deploymentId = "serveZipline"
val deploymentRegistry = services.get(DeploymentRegistry::class.java)
val deploymentHandle = deploymentRegistry.get(deploymentId, ZiplineServerDeploymentHandle::class.java)
if (deploymentHandle == null) {
val server = routes(
"/" bind static(Directory(inputDir.get().asFile.absolutePath), Pair("zipline", ContentType.TEXT_PLAIN))
).asServer(SunHttp(port.orElse(8080).get()))
deploymentRegistry.start(
deploymentId,
DeploymentRegistry.ChangeBehavior.BLOCK,
ZiplineServerDeploymentHandle::class.java,
server
)
}
}
}
internal open class ZiplineServerDeploymentHandle @Inject constructor(
private val server: Http4kServer
) : DeploymentHandle {
var running: Boolean = false
override fun isRunning(): Boolean = running
override fun start(deployment: Deployment) {
running = true
server.start()
}
override fun stop() {
running = false
server.stop()
}
}
|
apache-2.0
|
2161fd95ca96278010227ee1bc4f3794
| 29.428571 | 111 | 0.753521 | 4.070064 | false | false | false | false |
Yubyf/QuoteLock
|
app/src/main/java/com/crossbowffs/quotelock/components/BaseQuoteListFragment.kt
|
1
|
8182
|
package com.crossbowffs.quotelock.components
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.commit
import androidx.recyclerview.widget.*
import androidx.transition.TransitionInflater
import androidx.transition.TransitionSet
import com.crossbowffs.quotelock.R
import com.crossbowffs.quotelock.app.QuoteDetailFragment
import com.crossbowffs.quotelock.consts.PREF_QUOTE_SOURCE_PREFIX
import com.crossbowffs.quotelock.database.QuoteEntity
import java.util.concurrent.atomic.AtomicBoolean
/**
* @author Yubyf
*/
abstract class BaseQuoteListFragment<T : QuoteEntity> : Fragment() {
protected lateinit var recyclerView: RecyclerView
private var lastSelectPosition = -1
private var lastScrollPosition = 0
private var lastScrollOffset = 0
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?,
): View? {
return inflater.inflate(R.layout.layout_recycler_list, container, false).apply {
recyclerView = findViewById<RecyclerView>(R.id.recycler_view).apply {
layoutManager = LinearLayoutManager(requireContext())
addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL))
adapter = if (showDetailPage()) {
QuoteListAdapter<T> { holder, quote ->
// Exclude the clicked card from the exit transition (e.g. the card will disappear immediately
// instead of fading out with the rest to prevent an overlapping animation of fade and move).
(exitTransition as TransitionSet).excludeTarget(holder.view, true)
lastSelectPosition = holder.adapterPosition
lastScrollPosition =
(layoutManager as? LinearLayoutManager)?.findLastVisibleItemPosition()
?: 0
lastScrollOffset = getChildAt(childCount - 1)?.top ?: 0
parentFragmentManager.commit {
setReorderingAllowed(true)
addSharedElement(holder.quoteTextView,
holder.quoteTextView.transitionName)
addSharedElement(holder.quoteSourceView,
holder.quoteSourceView.transitionName)
replace(R.id.content_frame,
QuoteDetailFragment.newInstance(
quote.text,
quote.run {
if (!author.isNullOrBlank()) {
"$PREF_QUOTE_SOURCE_PREFIX$author" +
if (source.isBlank()) "" else " $source"
} else {
"$PREF_QUOTE_SOURCE_PREFIX$source"
}
},
holder.quoteTextView.transitionName,
holder.quoteSourceView.transitionName))
addToBackStack(null)
goToDetailPage()
}
}.apply {
lastSelectPosition = [email protected]
onSelectedItemLoaded = ::startPostponedEnterTransition
}
} else {
QuoteListAdapter<T>()
}
registerForContextMenu(this)
}
exitTransition = TransitionInflater.from(context)
.inflateTransition(R.transition.quote_list_exit_transition)
if (lastSelectPosition >= 0) {
postponeEnterTransition()
}
}
}
override fun onDestroyView() {
unregisterForContextMenu(recyclerView)
super.onDestroyView()
}
protected abstract fun showDetailPage(): Boolean
protected abstract fun goToDetailPage()
/**
* Scrolls the recycler view to show the last viewed item in the list.
*/
protected fun scrollToPosition() {
if (lastSelectPosition < 0) {
return
}
recyclerView.addOnLayoutChangeListener(object : View.OnLayoutChangeListener {
override fun onLayoutChange(
v: View?,
left: Int,
top: Int,
right: Int,
bottom: Int,
oldLeft: Int,
oldTop: Int,
oldRight: Int,
oldBottom: Int,
) {
recyclerView.removeOnLayoutChangeListener(this)
(recyclerView.layoutManager as? LinearLayoutManager)?.apply {
// Scroll to position if the view for the current position is null (not currently part of
// layout manager children), or it's not completely visible.
recyclerView.post {
scrollToPositionWithOffset(lastScrollPosition, lastScrollOffset)
lastSelectPosition = -1
lastScrollPosition = 0
lastScrollOffset = 0
}
}
}
})
}
}
class QuoteListAdapter<T : QuoteEntity>(
private var viewHolderListener: ((QuoteItemViewHolder, T: QuoteEntity) -> Unit)? = null,
) : ListAdapter<T, QuoteItemViewHolder>(QuoteItemDiffCallback()) {
private val enterTransitionStarted = AtomicBoolean()
var lastSelectPosition = -1
var onSelectedItemLoaded: (() -> Unit)? = null
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int,
): QuoteItemViewHolder {
return QuoteItemViewHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.listitem_custom_quote,
parent,
false
)
)
}
override fun onBindViewHolder(holder: QuoteItemViewHolder, pos: Int) {
val position = holder.adapterPosition
val quote = currentList[position]
holder.apply {
quoteTextView.apply {
text = quote.text
transitionName = "quote_#$position"
}
quoteSourceView.apply {
text = quote.run {
if (!author.isNullOrBlank()) {
"$author${if (source.isBlank()) "" else " $source"}"
} else {
source
}
}
transitionName = "source_#$position"
}
view.setOnClickListener { viewHolderListener?.invoke(holder, quote) }
}
// Call startPostponedEnterTransition only when the 'selected' image loading is completed.
if (lastSelectPosition == position) {
if (!enterTransitionStarted.getAndSet(true)) {
onSelectedItemLoaded?.invoke()
}
}
}
override fun getItemId(position: Int): Long {
return currentList[position].id?.toLong() ?: -1
}
private class QuoteItemDiffCallback<T : QuoteEntity> : DiffUtil.ItemCallback<T>() {
override fun areItemsTheSame(
oldItem: T,
newItem: T,
): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(
oldItem: T,
newItem: T,
): Boolean {
return oldItem == newItem
}
}
}
class QuoteItemViewHolder(val view: View) : RecyclerView.ViewHolder(view) {
val quoteTextView: TextView = view.findViewById(R.id.listitem_custom_quote_text)
val quoteSourceView: TextView = view.findViewById(R.id.listitem_custom_quote_source)
init {
view.isLongClickable = true
}
}
|
mit
|
e3c044f0ae4998fa8f81c5db37bc5857
| 38.336538 | 118 | 0.550966 | 5.933285 | false | false | false | false |
Aidanvii7/Toolbox
|
paging/src/main/java/com/aidanvii/toolbox/paging/Elements.kt
|
1
|
4913
|
package com.aidanvii.toolbox.paging
import com.aidanvii.toolbox.Action
import com.aidanvii.toolbox.Consumer
import io.reactivex.rxkotlin.subscribeBy
import io.reactivex.subjects.BehaviorSubject
internal class Elements<T>(
publishChangesOnInit: Boolean,
private val synchroniseAccess: Boolean,
onError: Consumer<Throwable>,
private val dataSource: PagedList.DataSource<T>,
private val changeSubject: BehaviorSubject<List<T?>>
) {
private val elementList: MutableList<T?>
private val stateList: MutableList<PagedList.ElementState>
private var changed = false
init {
elementList = mutableListOf()
stateList = mutableListOf()
dataSource.dataCount.subscribeBy(onError = onError, onNext = this::resizeIfNecessary)
if (publishChangesOnInit) {
changed = true
publishIfChanged()
}
}
val size: Int get() = elementList.size
/**
* Returns the index of the last item in the list or -1 if the list is empty.
*/
val lastIndex: Int get() = elementList.lastIndex
fun get(index: Int): T? = elementList.get(index)
fun isEmpty(index: Int): Boolean = stateList[index] == PagedList.ElementState.EMPTY
fun isEmptyOrDirty(index: Int): Boolean = when (stateList[index]) {
PagedList.ElementState.EMPTY -> true
PagedList.ElementState.DIRTY -> true
else -> false
}
fun setEmpty(index: Int) {
setElementAndState(index, PagedList.ElementState.EMPTY) {
setElementEmpty(index)
}
}
fun setLoading(index: Int) {
setElementAndState(index, PagedList.ElementState.LOADING) {
setElementEmpty(index)
}
}
fun setDirtyIfLoaded(index: Int) {
if (elementStateFor(index) == PagedList.ElementState.LOADED) {
setElementAndState(index, PagedList.ElementState.DIRTY) { }
}
}
fun setRefreshingIfDirty(index: Int) {
if (elementStateFor(index) == PagedList.ElementState.DIRTY) {
setElementAndState(index, PagedList.ElementState.REFRESHING) { }
}
}
fun setLoaded(index: Int, element: T) {
setElementAndState(index, PagedList.ElementState.LOADED) {
setElement(index, element)
}
}
fun invalidateAsEmpty(startIndex: Int, endIndex: Int) {
for (index in startIndex..endIndex) {
setEmpty(index)
}
}
fun invalidateLoadedAsDirty(startIndex: Int, endIndex: Int) {
for (index in startIndex..endIndex) {
setDirtyIfLoaded(index)
}
}
fun resizeIfNecessary(size: Int) {
if (size != PagedList.UNDEFINED) {
if (shouldGrow(size)) grow(size) else if (shouldShrink(size)) shrink(size)
}
}
fun growIfNecessary(size: Int) {
if (shouldGrow(size)) grow(size)
}
fun publishIfChanged() {
syncWhen(synchroniseAccess, this) {
if (changed) {
changed = false
elementList.toList()
} else null
}?.let {
changeSubject.onNext(it)
}
}
fun asList(): List<T?> = elementList.toList()
fun indexInBounds(index: Int): Boolean = (index < size)
fun elementStateFor(index: Int): PagedList.ElementState = stateList[index]
inline fun <R> runSynchronised(block: Elements<T>.() -> R): R {
return syncWhen(synchroniseAccess, this, { block() }).also {
publishIfChanged()
}
}
private inline fun setElementAndState(index: Int, elementState: PagedList.ElementState, setElement: Action) {
if (stateList[index] != elementState) {
changed = true
stateList[index] = elementState
setElement()
}
}
private fun setElementEmpty(index: Int) {
dataSource.emptyAt(index).let { empty ->
setElement(index, empty)
}
}
private fun setElement(index: Int, element: T?) {
if (elementList[index] != element) {
elementList[index] = element
changed = true
}
}
private fun shouldGrow(size: Int) = this.size < size
private fun shouldShrink(size: Int) = this.size > size
private fun grow(newSize: Int) {
(elementList.size).let { startingIndex ->
(startingIndex until newSize).forEach {
elementList.add(dataSource.emptyAt(it))
stateList.add(PagedList.ElementState.EMPTY)
}
}
changed = true
}
private fun shrink(newSize: Int) {
(newSize until size).forEach {
elementList.removeAt(newSize)
stateList.removeAt(newSize)
}
changed = true
}
private inline fun <R> syncWhen(predicate: Boolean, lock: Any, block: () -> R): R = if (predicate) synchronized(lock, block) else block()
}
|
apache-2.0
|
cc243a4fc1841ef746dec5d3e7fdc138
| 28.781818 | 141 | 0.611235 | 4.32102 | false | false | false | false |
akvo/akvo-flow-mobile
|
domain/src/test/java/org/akvo/flow/domain/interactor/ExportSurveyInstancesTest.kt
|
1
|
5219
|
/*
* Copyright (C) 2019 Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Flow.
*
* Akvo Flow 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.
*
* Akvo Flow 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 Akvo Flow. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.flow.domain.interactor
import io.reactivex.Completable
import io.reactivex.Observable
import io.reactivex.Single
import io.reactivex.observers.TestObserver
import org.akvo.flow.domain.entity.FormInstanceMetadata
import org.akvo.flow.domain.repository.FileRepository
import org.akvo.flow.domain.repository.SurveyRepository
import org.akvo.flow.domain.repository.UserRepository
import org.akvo.flow.domain.util.TextValueCleaner
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.ArgumentMatchers.any
import org.mockito.ArgumentMatchers.anyLong
import org.mockito.ArgumentMatchers.anySet
import org.mockito.ArgumentMatchers.anyString
import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.mockito.Mockito.times
import org.mockito.Mockito.verify
import org.mockito.junit.MockitoJUnitRunner
@RunWith(MockitoJUnitRunner::class)
class ExportSurveyInstancesTest {
@Mock
internal var mockUserRepository: UserRepository? = null
@Mock
internal var mockValueCleaner: TextValueCleaner? = null
@Mock
internal var mockSurveyRepository: SurveyRepository? = null
@Mock
internal var mockFileRepository: FileRepository? = null
@Mock
internal var mockFormInstanceMetadata: FormInstanceMetadata? = null
@Before
fun setUp() {
`when`(mockUserRepository!!.deviceId).thenReturn(Observable.just("123"))
`when`(mockValueCleaner!!.cleanVal("123")).thenReturn("123")
`when`(mockSurveyRepository!!.setInstanceStatusToRequested(anyLong())).thenReturn(
Completable.complete()
)
`when`(mockSurveyRepository!!.getFormInstanceData(anyLong(), anyString())).thenReturn(
Single.just(
mockFormInstanceMetadata
)
)
`when`(
mockFileRepository!!.createDataZip(
any(),
any()
)
).thenReturn(Completable.complete())
`when`(
mockSurveyRepository!!.createTransmissions(
anyLong(),
anyString(),
anySet<String>()
)
).thenReturn(Completable.complete())
`when`(mockFormInstanceMetadata!!.zipFileName).thenReturn("")
`when`(mockFormInstanceMetadata!!.formInstanceData).thenReturn("")
`when`(mockFormInstanceMetadata!!.formId).thenReturn("")
}
@Test
fun buildUseCaseObservableShouldCompleteCorrectlyFor7Instances() {
`when`(mockSurveyRepository!!.pendingSurveyInstances).thenReturn(
Single.just(listOf(1L, 2L, 3L, 4L, 5L, 6L, 7L))
)
val observer = TestObserver<Void>()
val exportSurveyInstances =
ExportSurveyInstances(
mockUserRepository,
mockValueCleaner,
mockSurveyRepository,
mockFileRepository
)
exportSurveyInstances.buildUseCaseObservable().subscribe(observer)
verify(mockSurveyRepository, times(7))!!.setInstanceStatusToRequested(anyLong())
verify(mockSurveyRepository, times(7))!!.getFormInstanceData(anyLong(), anyString())
verify(mockFileRepository, times(7))!!.createDataZip(anyString(), anyString())
verify(mockSurveyRepository, times(7))!!.createTransmissions(
anyLong(),
anyString(),
anySet<String>()
)
observer.assertNoErrors()
}
@Test
fun buildUseCaseObservableShouldCompleteCorrectlyFor0Instances() {
`when`(mockSurveyRepository!!.pendingSurveyInstances).thenReturn(
Single.just(emptyList())
)
val observer = TestObserver<Void>()
val exportSurveyInstances =
ExportSurveyInstances(
mockUserRepository,
mockValueCleaner,
mockSurveyRepository,
mockFileRepository
)
exportSurveyInstances.buildUseCaseObservable().subscribe(observer)
verify(mockSurveyRepository, times(0))!!.setInstanceStatusToRequested(anyLong())
verify(mockSurveyRepository, times(0))!!.getFormInstanceData(anyLong(), anyString())
verify(mockFileRepository, times(0))!!.createDataZip(anyString(), anyString())
verify(mockSurveyRepository, times(0))!!.createTransmissions(
anyLong(),
anyString(),
anySet<String>()
)
observer.assertNoErrors()
}
}
|
gpl-3.0
|
5290abd7eef1cfa488b3eab1fd1d5604
| 33.793333 | 94 | 0.67695 | 4.845868 | false | false | false | false |
brandonpas/Set-list
|
app/src/main/java/com/gmail/pasquarelli/brandon/setlist/MainFragment.kt
|
1
|
3716
|
package com.gmail.pasquarelli.brandon.setlist
import android.app.Fragment
import android.os.Bundle
import android.support.design.widget.BottomNavigationView
import android.support.v4.view.ViewPager
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import com.gmail.pasquarelli.brandon.setlist.tab_bandinfo.view.BandInfoFragmentFragment
import com.gmail.pasquarelli.brandon.setlist.tab_setlists.view.SetListFragment
import com.gmail.pasquarelli.brandon.setlist.tab_setlists.view.SongsFragment
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.viewpager_layout.*
class MainFragment : Fragment() {
// Activity variables
lateinit var prevMenuItem: MenuItem
// Fragments
lateinit var setListsFragment: SetListFragment
lateinit var songsFragment: SongsFragment
lateinit var bandFragment: BandInfoFragmentFragment
// Views, adapters, and listeners
lateinit var viewPager: ViewPager
lateinit var bottomNavigationView: BottomNavigationView
val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
when (item.itemId) {
R.id.navigation_set_lists -> {
viewPager.currentItem = 0
return@OnNavigationItemSelectedListener true
}
R.id.navigation_songs -> {
viewPager.currentItem = 1
return@OnNavigationItemSelectedListener true
}
R.id.navigation_band_info -> {
viewPager.currentItem = 2
return@OnNavigationItemSelectedListener true
}
}
false
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater?.inflate(R.layout.viewpager_layout, container, false)
}
override fun onResume() {
super.onResume()
initViews()
initViewPager(viewPager)
}
/**
* Setup the view pager and view pager adapter for the fragments. This provides a smooth sliding animation when
* switching between the menu items.
*/
fun initViewPager(viewPager: ViewPager) {
val supportFragManager = (activity as MainActivity).supportFragmentManager
val pagerAdapter: ViewPagerAdapter = ViewPagerAdapter(supportFragManager)
pagerAdapter.addFragment(setListsFragment)
pagerAdapter.addFragment(songsFragment)
pagerAdapter.addFragment(bandFragment)
viewPager.adapter = pagerAdapter
viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}
override fun onPageSelected(position: Int) {
prevMenuItem.isChecked = false
bottomNavigationView.menu.getItem(position)?.isChecked = true
prevMenuItem = bottomNavigationView.menu.getItem(position)
}
override fun onPageScrollStateChanged(state: Int) {}
})
}
/**
* Initialize views, attach listeners, etc. here.
*/
fun initViews() {
// View objects
viewPager = content_viewpager
bottomNavigationView = activity.navigation
prevMenuItem = bottomNavigationView.menu.getItem(0)
// Fragments
setListsFragment = SetListFragment()
songsFragment = SongsFragment()
bandFragment = BandInfoFragmentFragment()
// Listeners
activity.navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)
}
}
|
gpl-3.0
|
4373a27ae2817250999c7afdbc0bc99f
| 35.80198 | 117 | 0.700484 | 5.513353 | false | false | false | false |
Cypher121/CSCodeExamples
|
src/coffee/cypher/kotlinexamples/KtNullity.kt
|
1
|
409
|
package coffee.cypher.kotlinexamples
fun main(args: Array<String>) {
var str: String? = "not null"
//str = null;
println(str?.toUpperCase())
var a: Array<Int>? = Array(5, { it * 10 });
//a = null;
println(a?.toList()?.get(3))
var foo: Double? = 0.0;
//foo = null;
println(foo ?: "default")
var bar: String? = "123"
//bar = null;
println(bar!!.length)
}
|
mit
|
3c596466661a5be5c5a3147e6b7d814c
| 16.782609 | 47 | 0.545232 | 3.170543 | false | false | false | false |
mediathekview/MediathekView
|
src/main/java/mediathek/update/UpdateNotificationDialog.kt
|
1
|
2219
|
package mediathek.update
import mediathek.config.Konstanten
import mediathek.gui.actions.DisposeDialogAction
import mediathek.gui.actions.UrlHyperlinkAction
import mediathek.gui.dialog.ButtonFlowPanel
import mediathek.gui.dialog.ButtonPanel
import mediathek.mainwindow.MediathekGui
import mediathek.tool.EscapeKeyHandler
import mediathek.tool.GuiFunktionen
import mediathek.tool.Version
import org.apache.logging.log4j.LogManager
import java.awt.BorderLayout
import java.awt.Frame
import java.net.URI
import java.net.URISyntaxException
import javax.swing.JButton
import javax.swing.JDialog
class UpdateNotificationDialog(owner: Frame?, title: String?, private val version: Version) :
JDialog(owner, title, true) {
private val panel = UpdateNotificationPanel()
private fun createButtonPanel(): ButtonFlowPanel {
val pnl = ButtonFlowPanel()
val dlBtn = JButton("Zur Download-Seite")
dlBtn.addActionListener {
try {
UrlHyperlinkAction.openURI(MediathekGui.ui(), URI(Konstanten.ADRESSE_DOWNLOAD))
dispose()
} catch (e: URISyntaxException) {
logger.error(e)
}
}
val btn = JButton(DisposeDialogAction(this, "Schließen", "Dialog schließen"))
getRootPane().defaultButton = btn
pnl.add(dlBtn)
pnl.add(btn)
return pnl
}
private fun setupDialogInformation() {
val label = ("MediathekView " + version + " ist verfügbar - "
+ "Sie haben Version " + Konstanten.MVVERSION)
panel.releaseInfoLabel.text = label
}
companion object {
private val logger = LogManager.getLogger()
}
init {
defaultCloseOperation = DISPOSE_ON_CLOSE
EscapeKeyHandler.installHandler(this) { dispose() }
setupDialogInformation()
val contentPane = contentPane
contentPane.layout = BorderLayout()
contentPane.add(panel, BorderLayout.CENTER)
val buttonPanel = ButtonPanel()
buttonPanel.add(createButtonPanel(), BorderLayout.EAST)
contentPane.add(buttonPanel, BorderLayout.SOUTH)
pack()
GuiFunktionen.centerOnScreen(this, false)
}
}
|
gpl-3.0
|
06eebedbc6331fcf603e60b734c0391e
| 32.590909 | 95 | 0.689531 | 4.405567 | false | false | false | false |
androidDaniel/treasure
|
gankotlin/src/main/java/com/ad/gan/net/GanApiNetHelper.kt
|
1
|
1560
|
package com.ad.gan.net
import android.util.Log
import com.ad.gan.bean.ArticleItem
import com.ad.gan.define.ReadDefine
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
/**
* Created by yumodev on 17/6/13.
*/
object GanApiNetHelper {
private val LOG_TAG = "GanApiHelper"
fun getTypeDataByPage(type:String, num:Int, page:Int) : GanApiResult? {
val url = "http://gank.io/api/data/$type/$num/$page"
Log.i(LOG_TAG, "Url:"+url)
val response = NetUtils.getBodyResponse(url)
if (response !!.isSuccessful){
val resultStr = response!!.body().string()
return paresDataResult(resultStr) as GanApiResult
Log.i(LOG_TAG, "result:"+resultStr)
}
return null
}
fun paresDataResult(jsonStr:String) :GanApiResult? {
val result = GanApiResult()
val json = JSON.parseObject(jsonStr)
if (json.containsKey(ReadDefine.JSON_KEY_ERROR)){
result.error = json.getBoolean(ReadDefine.JSON_KEY_ERROR)
}
if (json.containsKey(ReadDefine.JSON_KEY_RESULTS)){
val jsonArray = json.getJSONArray(ReadDefine.JSON_KEY_RESULTS)
val dataList = jsonArray.indices.map { convertJsonToReadItem(jsonArray.getJSONObject(it)) }
result.results = dataList as ArrayList<ArticleItem>
}
return result
}
private fun convertJsonToReadItem(json: JSONObject): ArticleItem {
val data = JSONObject.toJavaObject(json, ArticleItem::class.java)
return data
}
}
|
gpl-2.0
|
b1f40a6b86fcd320db08afd6e4413163
| 31.520833 | 103 | 0.657051 | 3.786408 | false | false | false | false |
chandilsachin/DietTracker
|
app/src/main/java/com/chandilsachin/diettracker/ui/FoodListFragment.kt
|
1
|
3259
|
package com.chandilsachin.diettracker.ui
import android.arch.lifecycle.Observer
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentActivity
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.SearchView
import android.view.*
import com.chandilsachin.diettracker.R
import com.chandilsachin.diettracker.adapters.FoodListAdapter
import com.chandilsachin.diettracker.util.*
import com.chandilsachin.diettracker.util.annotation.RequiresTagName
import com.chandilsachin.diettracker.view_model.AddFoodViewModel
import kotlinx.android.synthetic.main.fragment_add_food.*
import kotlinx.android.synthetic.main.toolbar_layout.*
@RequiresTagName("FoodListFragment")
class FoodListFragment : BaseFragment() {
val model: AddFoodViewModel by lazy {
initViewModel(AddFoodViewModel::class.java)
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater?.inflate(R.layout.fragment_add_food, container, false)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
init()
prepareFoodItemList()
super.onViewCreated(view, savedInstanceState)
}
fun init(){
setSupportActionBar(my_toolbar)
setDisplayHomeAsUpEnabled(true)
activity.setTitle(R.string.addFood)
recyclerViewFoodList.layoutManager = LinearLayoutManager(context)
}
var adapter:FoodListAdapter? = null
fun prepareFoodItemList() {
adapter = FoodListAdapter(context) { foodId ->
loadFragment(R.id.frameLayoutFragment, FoodDetailsFragment.getInstance(foodId, false, activity as AppCompatActivity?))
}
recyclerViewFoodList.adapter = adapter
model.allFoodList.observe(this, Observer { list ->
list?.let {
if(list.isNotEmpty())
{
adapter?.foodList = list
adapter?.filter?.filter("")
}
}
})
}
override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {
inflater?.inflate(R.menu.food_list_menu, menu)
val searchView = menu?.findItem(R.id.menu_idSearch)?.actionView as SearchView
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener{
override fun onQueryTextSubmit(p0: String?): Boolean {
adapter!!.filter.filter(p0)
return true
}
override fun onQueryTextChange(p0: String?): Boolean {
adapter!!.filter.filter(p0)
return true
}
})
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
return super.onOptionsItemSelected(item)
}
companion object {
val SELECTED_FOOD_ID = "selectedIndex"
val CODE_FOOD_SELECTION = 1
fun getInstance(activity: FragmentActivity? = null): Fragment {
var fragment = findInstance(activity!!)
if (fragment == null) {
fragment = FoodListFragment()
}
return fragment
}
}
}
|
gpl-3.0
|
a13ca23181c114ef7f10bfd3898919f5
| 33.680851 | 130 | 0.669224 | 4.908133 | false | false | false | false |
FHannes/intellij-community
|
plugins/groovy/src/org/jetbrains/plugins/groovy/ext/logback/LogbackDelegateMemberContributor.kt
|
10
|
5866
|
/*
* 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 org.jetbrains.plugins.groovy.ext.logback
import com.intellij.openapi.util.Key
import com.intellij.psi.*
import com.intellij.psi.CommonClassNames.JAVA_LANG_STRING
import com.intellij.psi.scope.BaseScopeProcessor
import com.intellij.psi.scope.ElementClassHint
import com.intellij.psi.scope.NameHint
import com.intellij.psi.scope.PsiScopeProcessor
import com.intellij.psi.util.PsiTreeUtil
import groovy.lang.Closure.DELEGATE_FIRST
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightMethodBuilder
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrMethodWrapper
import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames.GROOVY_LANG_CLOSURE
import org.jetbrains.plugins.groovy.lang.psi.util.GroovyPropertyUtils
import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil
import org.jetbrains.plugins.groovy.lang.resolve.NonCodeMembersContributor
import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil
import org.jetbrains.plugins.groovy.lang.resolve.delegatesTo.DELEGATES_TO_KEY
import org.jetbrains.plugins.groovy.lang.resolve.delegatesTo.DELEGATES_TO_STRATEGY_KEY
import org.jetbrains.plugins.groovy.lang.resolve.delegatesTo.getContainingCall
import org.jetbrains.plugins.groovy.lang.resolve.wrapClassType
class LogbackDelegateMemberContributor : NonCodeMembersContributor() {
override fun getParentClassName() = componentDelegateFqn
override fun processDynamicElements(qualifierType: PsiType, processor: PsiScopeProcessor, place: PsiElement, state: ResolveState) {
val name = processor.getHint(NameHint.KEY)?.getName(state)
val componentClass = getComponentClass(place) ?: return
val componentProcessor = ComponentProcessor(processor, place, name)
if (name == null) {
componentClass.processDeclarations(componentProcessor, state, null, place)
}
else {
for (prefix in arrayOf("add", "set")) {
for (method in componentClass.findMethodsByName(prefix + name.capitalize(), true)) {
if (!componentProcessor.execute(method, state)) return
}
}
}
}
fun getComponentClass(place: PsiElement): PsiClass? {
val reference = place as? GrReferenceExpression ?: return null
if (reference.isQualified) return null
val closure = PsiTreeUtil.getParentOfType(reference, GrClosableBlock::class.java) ?: return null
val call = getContainingCall(closure) ?: return null
val arguments = PsiUtil.getAllArguments(call)
if (arguments.isEmpty()) return null
val lastIsClosure = (arguments.last().type as? PsiClassType)?.resolve()?.qualifiedName == GROOVY_LANG_CLOSURE
val componentArgumentIndex = (if (lastIsClosure) arguments.size - 1 else arguments.size) - 1
val componentArgument = arguments.getOrNull(componentArgumentIndex)
val componentType = ResolveUtil.unwrapClassType(componentArgument?.type) as? PsiClassType
return componentType?.resolve()
}
class ComponentProcessor(val delegate: PsiScopeProcessor, val place: PsiElement, val name: String?) : BaseScopeProcessor() {
override fun execute(method: PsiElement, state: ResolveState): Boolean {
method as? PsiMethod ?: return true
val prefix = if (GroovyPropertyUtils.isSetterLike(method, "set")) {
if (!delegate.execute(method, state)) return false
"set"
}
else if (GroovyPropertyUtils.isSetterLike(method, "add")) {
val newName = method.name.replaceFirst("add", "set")
val wrapper = GrMethodWrapper.wrap(method, newName)
if (!delegate.execute(wrapper, state)) return false
"add"
}
else {
return true
}
val propertyName = method.name.removePrefix(prefix).decapitalize()
if (name != null && name != propertyName) return true
val parameter = method.parameterList.parameters.singleOrNull() ?: return true
val classType = wrapClassType(parameter.type, place) ?: return true
val wrappedBase = GrLightMethodBuilder(place.manager, propertyName).apply {
returnType = PsiType.VOID
navigationElement = method
}
// (name, clazz)
// (name, clazz, configuration)
wrappedBase.copy().apply {
addParameter("name", JAVA_LANG_STRING)
addParameter("clazz", classType)
addParameter("configuration", GROOVY_LANG_CLOSURE, true)
}.let {
if (!delegate.execute(it, state)) return false
}
// (clazz)
// (clazz, configuration)
wrappedBase.copy().apply {
addParameter("clazz", classType)
addAndGetParameter("configuration", GROOVY_LANG_CLOSURE, true).apply {
putUserData(DELEGATES_TO_KEY, componentDelegateFqn)
putUserData(DELEGATES_TO_STRATEGY_KEY, DELEGATE_FIRST)
}
}.let {
if (!delegate.execute(it, state)) return false
}
return true
}
override fun <T : Any?> getHint(hintKey: Key<T>) = if (hintKey == ElementClassHint.KEY) {
@Suppress("UNCHECKED_CAST")
ElementClassHint { it == ElementClassHint.DeclarationKind.METHOD } as T
}
else {
null
}
}
}
|
apache-2.0
|
4560d0ef2bbb9cea19377f815507f8fd
| 41.208633 | 133 | 0.729628 | 4.430514 | false | false | false | false |
renard314/textfairy
|
app/src/main/java/com/renard/ocr/documents/creation/ocr/OcrWorker.kt
|
1
|
14112
|
package com.renard.ocr.documents.creation.ocr
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.res.Resources
import android.graphics.Rect
import android.net.Uri
import android.os.Build
import android.os.RemoteException
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import androidx.core.app.TaskStackBuilder
import androidx.core.net.toFile
import androidx.core.net.toUri
import androidx.work.*
import com.googlecode.leptonica.android.Pix
import com.googlecode.leptonica.android.ReadFile
import com.googlecode.leptonica.android.WriteFile
import com.googlecode.tesseract.android.NativeBinding
import com.googlecode.tesseract.android.TessBaseAPI
import com.googlecode.tesseract.android.initTessApi
import com.renard.ocr.R
import com.renard.ocr.applicationInstance
import com.renard.ocr.documents.creation.DocumentStore
import com.renard.ocr.documents.creation.PdfDocumentWrapper
import com.renard.ocr.documents.creation.crop.CropImageScaler
import com.renard.ocr.util.Util
import kotlinx.coroutines.coroutineScope
import java.io.Closeable
import java.io.File
import java.io.IOException
class OcrWorker(context: Context, parameters: WorkerParameters) :
CoroutineWorker(context, parameters) {
override suspend fun doWork(): Result {
val inputUrls = inputData.getStringArray(KEY_INPUT_URLS)?.map(Uri::parse)
?: return Result.failure()
val inputLang = inputData.getString(KEY_INPUT_LANG) ?: return Result.failure()
val parentId = inputData.getInt(KEY_INPUT_PARENT_ID, -1)
setForeground(createForegroundInfo(inputUrls.first(), parentId))
takeUriPermission(inputUrls)
return coroutineScope {
when (val result = scanUris(inputUrls, inputLang, parentId)) {
is ScanPdfResult.Success -> Result.success(workDataOf(
KEY_OUTPUT_ACCURACY to result.accuracy,
KEY_OUTPUT_DOCUMENT_ID to result.documentId
))
is ScanPdfResult.Failure -> Result.failure()
}
}.also {
releaseUriPermission(inputUrls)
}
}
private fun releaseUriPermission(inputUrls: List<Uri>) {
if (Build.VERSION.SDK_INT >= 19) {
inputUrls.forEach {
applicationContext.contentResolver.releasePersistableUriPermission(it, Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
}
}
private fun takeUriPermission(inputUrls: List<Uri>) {
if (Build.VERSION.SDK_INT >= 19) {
inputUrls.forEach {
applicationContext.contentResolver.takePersistableUriPermission(it, Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
}
}
private fun sendProgressImage(nativePix: Long, progress: ProgressData): ProgressData {
val pix = Pix(nativePix)
val file = File(applicationContext.cacheDir, "progress/")
val widthPixels = Resources.getSystem().displayMetrics.widthPixels
val heightPixels = Resources.getSystem().displayMetrics.heightPixels
val uri = CropImageScaler().scale(pix, widthPixels, heightPixels).pix.use {
try {
val image = File(file, "progress_${id}_${progress.progressCount}.png")
if (WriteFile.writeImpliedFormat(pix, image)) {
image.toUri()
} else {
null
}
} catch (e: java.lang.Exception) {
null
}
}
progress.previewImage?.toFile()?.delete()
return progress.copy(
previewImage = uri,
progressCount = progress.progressCount + 1
)
}
private suspend fun scanUris(uris: List<Uri>, inputLang: String, parentIdParam: Int): ScanPdfResult {
var parentId = parentIdParam
var progress = ProgressData(pageCount = getPageCount(applicationContext, uris))
val accuracy = mutableListOf<Int>()
NativeBinding().use { binding ->
binding.setProgressCallBack(object : NativeBinding.ProgressCallBack {
override fun onProgressImage(nativePix: Long) {
progress = sendProgressImage(nativePix, progress)
setProgressAsync(progress.asWorkData())
}
override fun onProgressText(message: Int) {}
override fun onLayoutAnalysed(nativePixaText: Long, nativePixaImages: Long) {}
})
initTessApi(applicationContext, inputLang, applicationInstance.crashLogger) {
progress = progress.copy(percent = it.percent, pageBounds = it.currentRect, lineBounds = it.currentWordRect)
setProgressAsync(progress.asWorkData())
}?.use { tess ->
for (uri in uris) {
pages(uri).forEach {
progress = ProgressData(currentPage = progress.currentPage + 1, pageCount = progress.pageCount)
setForeground(createForegroundInfo(uri, parentId, progress.currentPage, progress.pageCount))
Pix(binding.convertBookPage(it))
.use { pixText ->
it.recycle()
progress = sendProgressImage(pixText.nativePix, progress)
setProgress(progress.asWorkData())
val scan = ocr(tess, pixText)
accuracy.add(scan.accuracy)
val documentUri = saveDocument(scan, inputLang, pixText, parentId)
if (parentId == -1 && documentUri != null) {
parentId = DocumentStore.getDocumentId(documentUri)
}
}
}
}
return if (accuracy.isEmpty()) {
ScanPdfResult.Failure
} else {
ScanPdfResult.Success(accuracy.average().toInt(), parentId)
}
}
}
return ScanPdfResult.Failure
}
private fun pages(uri: Uri): Sequence<Pix> = sequence {
if (uri.isPdf(applicationContext.contentResolver)) {
getPdfDocument(uri, applicationContext)?.use {
for(i in 0 until it.getPageCount()){
yield(it.getPage(i))
}
}
} else {
ReadFile.load(applicationContext, uri)?.let { yield(it) }
}
}
private fun saveDocument(scan: ScanPageResult, lang: String, pixText: Pix, parentId: Int): Uri? {
val imageFile = try {
DocumentStore.saveImage(applicationContext, pixText)
} catch (ignored: IOException) {
null
}
val documentUri = try {
DocumentStore.saveDocumentToDB(
parentId,
lang,
applicationContext,
imageFile,
scan.hocrText,
scan.htmlText
)
} catch (ignored: RemoteException) {
null
}
if (documentUri != null && imageFile != null) {
val documentId = DocumentStore.getDocumentId(documentUri)
Util.createThumbnail(applicationContext, imageFile, documentId)
}
return documentUri
}
private fun ocr(tess: TessBaseAPI, pixText: Pix): ScanPageResult {
tess.pageSegMode = TessBaseAPI.PageSegMode.PSM_AUTO
tess.setImage(pixText)
var hocrText = tess.getHOCRText(0)
var accuracy = tess.meanConfidence()
val utf8Text = tess.utF8Text
if (utf8Text.isEmpty()) {
applicationInstance.crashLogger.logMessage("No words found. Looking for sparse text.")
tess.pageSegMode = TessBaseAPI.PageSegMode.PSM_SPARSE_TEXT
tess.setImage(pixText)
hocrText = tess.getHOCRText(0)
accuracy = tess.meanConfidence()
}
val htmlText = tess.htmlText
if (accuracy == 95) {
accuracy = 0
}
return ScanPageResult(htmlText, hocrText, accuracy)
}
private fun createForegroundInfo(pdfFileUri: Uri, parentId: Int, currentPage: Int, pageCount: Int): ForegroundInfo {
return createForegroundInfo(pdfFileUri, parentId) {
it.setProgress(pageCount, currentPage, false)
it.setContentText(applicationContext.getString(R.string.scanning_pdf_progress, currentPage, pageCount))
}
}
private fun createForegroundInfo(fileUri: Uri, parentId: Int, applyToNotif: (NotificationCompat.Builder) -> Unit = {}): ForegroundInfo {
val id = applicationContext.packageName
val title = applicationContext.getString(R.string.notification_scanning_title, fileUri.lastPathSegment?.substringAfterLast("/"))
val cancel = applicationContext.getString(R.string.cancel)
// This PendingIntent can be used to cancel the worker
val intent = WorkManager.getInstance(applicationContext)
.createCancelPendingIntent(getId())
// Create a Notification channel if necessary
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createChannel(id)
}
val ocrPdfActivityIntent = Intent(applicationContext, OcrPdfActivity::class.java)
ocrPdfActivityIntent.data = fileUri
ocrPdfActivityIntent.putExtra(OCRActivity.EXTRA_PARENT_DOCUMENT_ID, parentId)
ocrPdfActivityIntent.putExtra(OcrPdfActivity.KEY_WORK_ID, getId().toString())
val contentIntent = TaskStackBuilder.create(applicationContext)
.addNextIntentWithParentStack(ocrPdfActivityIntent)
.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)
val notification = NotificationCompat.Builder(applicationContext, id)
.setContentTitle(title)
.setTicker(title)
.setSmallIcon(R.drawable.ic_fairy_happy)
.setOngoing(true)
.setContentIntent(contentIntent)
.addAction(android.R.drawable.ic_menu_close_clear_cancel, cancel, intent)
applyToNotif(notification)
return ForegroundInfo(inputData.getInt(KEY_INPUT_NOTIFICATION_ID, 314), notification.build())
}
@RequiresApi(Build.VERSION_CODES.O)
private fun createChannel(id: String) {
val name: CharSequence = applicationContext.getString(R.string.notification_channel_title)
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel(id, name, importance)
channel.setSound(null, null);
val notificationManager = applicationContext.getSystemService(NotificationManager::class.java)
notificationManager.createNotificationChannel(channel)
}
private sealed class ScanPdfResult {
data class Success(val accuracy: Int, val documentId: Int) : ScanPdfResult()
object Failure : ScanPdfResult()
}
private data class ScanPageResult(val htmlText: String, val hocrText: String, val accuracy: Int)
data class ProgressData(
val currentPage: Int = 0,
val pageCount: Int = 0,
val percent: Int = 0,
val previewImage: Uri? = null,
val pageBounds: Rect = Rect(),
val lineBounds: Rect = Rect(),
val progressCount: Int = 0
) {
fun asWorkData() = workDataOf(
CurrentPage to currentPage,
PageCount to pageCount,
Progress to percent,
PreviewImage to previewImage?.toString(),
PageBounds to pageBounds.flattenToString(),
LineBounds to lineBounds.flattenToString(),
"count" to progressCount
)
companion object {
fun fromWorkData(data: Data) = if (data.keyValueMap.isEmpty()) {
null
} else
ProgressData(
currentPage = data.getInt(CurrentPage, 0),
pageCount = data.getInt(PageCount, 0),
percent = data.getInt(Progress, 0),
previewImage = getUri(data),
pageBounds = Rect.unflattenFromString(data.getString(PageBounds))!!,
lineBounds = Rect.unflattenFromString(data.getString(LineBounds))!!,
progressCount = data.getInt("count", 0)
)
private fun getUri(data: Data): Uri? {
val uriString = data.getString(PreviewImage)
return if (uriString != null) {
Uri.parse(uriString)
} else {
null
}
}
}
}
companion object {
const val CurrentPage = "CurrentPage"
const val PageCount = "PageCount"
const val Progress = "Progress"
const val PreviewImage = "Preview"
const val PageBounds = "PageBounds"
const val LineBounds = "LineBounds"
const val KEY_INPUT_NOTIFICATION_ID = "KEY_INPUT_NOTIFICATION_ID"
const val KEY_INPUT_URLS = "KEY_INPUT_URLS"
const val KEY_INPUT_LANG = "KEY_INPUT_LANG"
const val KEY_INPUT_PARENT_ID = "KEY_INPUT_PARENT_ID"
const val KEY_OUTPUT_ACCURACY = "KEY_OUTPUT_ACCURACY"
const val KEY_OUTPUT_DOCUMENT_ID = "KEY_OUTPUT_DOCUMENT_ID"
}
}
fun getPdfDocument(inputUrl: Uri, context: Context): PdfDocumentWrapper? {
val fixedUri = Uri.parse(inputUrl.toString().replace("/file/file", "/file"))
val fd = try {
context.contentResolver.openFileDescriptor(fixedUri, "r") ?: return null
} catch (e: Exception) {
return null
}
return PdfDocumentWrapper(context, fd)
}
|
apache-2.0
|
3f230a4d058d3d5310fde6af2f025e39
| 40.145773 | 140 | 0.61019 | 4.886427 | false | false | false | false |
nemerosa/ontrack
|
ontrack-model/src/main/java/net/nemerosa/ontrack/model/structure/ValidationRunStatusID.kt
|
1
|
2451
|
package net.nemerosa.ontrack.model.structure
import com.fasterxml.jackson.annotation.JsonProperty
class ValidationRunStatusID(
val id: String,
val name: String,
@JsonProperty("root")
val isRoot: Boolean,
@JsonProperty("passed")
val isPassed: Boolean,
val followingStatuses: Collection<String> = emptyList()
) {
companion object {
const val DEFECTIVE = "DEFECTIVE"
@JvmField
val STATUS_DEFECTIVE = ValidationRunStatusID(DEFECTIVE, "Defective", isRoot = false, isPassed = false)
const val EXPLAINED = "EXPLAINED"
@JvmField
val STATUS_EXPLAINED = ValidationRunStatusID(EXPLAINED, "Explained", false, isPassed = false)
const val FAILED = "FAILED"
@JvmField
val STATUS_FAILED = ValidationRunStatusID(FAILED, "Failed", true, isPassed = false)
const val FIXED = "FIXED"
@JvmField
val STATUS_FIXED = ValidationRunStatusID(FIXED, "Fixed", false, isPassed = true)
const val INTERRUPTED = "INTERRUPTED"
@JvmField
val STATUS_INTERRUPTED = ValidationRunStatusID(INTERRUPTED, "Interrupted", isRoot = true, isPassed = false)
const val INVESTIGATING = "INVESTIGATING"
@JvmField
val STATUS_INVESTIGATING = ValidationRunStatusID(INVESTIGATING, "Investigating", isRoot = true, isPassed = false)
const val PASSED = "PASSED"
@JvmField
val STATUS_PASSED = ValidationRunStatusID(PASSED, "Passed", isRoot = true, isPassed = true)
const val WARNING = "WARNING"
@JvmField
val STATUS_WARNING = ValidationRunStatusID(id = WARNING, name = "Warning", isRoot = true, isPassed = false)
@JvmStatic
fun of(id: String, name: String, root: Boolean, passed: Boolean): ValidationRunStatusID {
return ValidationRunStatusID(id, name, root, passed, emptyList());
}
}
fun addDependencies(vararg followingStatuses: String): ValidationRunStatusID {
val dependencies = this.followingStatuses + followingStatuses
return ValidationRunStatusID(id, name, isRoot, isPassed, dependencies)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is ValidationRunStatusID) return false
if (id != other.id) return false
return true
}
override fun hashCode(): Int {
return id.hashCode()
}
}
|
mit
|
baa9294de5373de3625fa58db0122913
| 36.707692 | 121 | 0.656059 | 4.73166 | false | false | false | false |
bailuk/AAT
|
aat-gtk/src/main/kotlin/ch/bailu/aat_gtk/lib/rest/RestClient.kt
|
1
|
1795
|
package ch.bailu.aat_gtk.lib.rest
import ch.bailu.aat_gtk.lib.json.Json
import ch.bailu.gtk.GTK
import ch.bailu.gtk.glib.Glib
import okhttp3.*
import java.io.File
import java.io.IOException
class RestClient(val file: File,
private val userAgent: String,
private val start: String = "",
private val end : String = "") {
private val client = OkHttpClient()
private var call = getCall("http://localhost")
var json = Json.parse(file)
private set
var ok = true
private set
companion object {
var downloads = 0
private set
}
@Throws(IOException::class)
fun download(url: String, observer: (RestClient)->Unit) {
call.cancel()
downloads ++
call = getCall(url)
call.enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
downloads--
ok = false
callBack(observer)
}
override fun onResponse(call: Call, response: Response) {
downloads--
ok = true
val jsonText = start + response.body?.string() + end
file.writeText(jsonText)
json = Json.parse(jsonText)
callBack(observer)
}
})
}
private fun callBack(observer: (RestClient)->Unit) {
Glib.idleAdd({
observer(this@RestClient)
GTK.FALSE
}, null)
}
private fun getCall(url: String) : Call {
return client.newCall(getRequest(url))
}
private fun getRequest(url: String) : Request {
return Request.Builder()
.url(url).header("User-Agent", userAgent)
.build()
}
}
|
gpl-3.0
|
2b216a0533a395a42051017ea7585ed9
| 23.589041 | 69 | 0.545404 | 4.4875 | false | false | false | false |
goodwinnk/intellij-community
|
platform/testGuiFramework/src/com/intellij/testGuiFramework/impl/GuiTestCaseExt.kt
|
1
|
11298
|
// 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.testGuiFramework.impl
import com.intellij.testGuiFramework.cellReader.ExtendedJTreeCellReader
import com.intellij.testGuiFramework.driver.ExtendedJTreePathFinder
import com.intellij.testGuiFramework.fixtures.ActionButtonFixture
import com.intellij.testGuiFramework.fixtures.GutterFixture
import com.intellij.testGuiFramework.fixtures.extended.ExtendedJTreePathFixture
import com.intellij.testGuiFramework.framework.Timeouts
import com.intellij.testGuiFramework.util.*
import org.fest.swing.timing.Condition
import org.fest.swing.timing.Pause
import org.hamcrest.Matcher
import org.junit.After
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Rule
import org.junit.rules.ErrorCollector
import org.junit.rules.TemporaryFolder
import org.junit.rules.TestName
open class GuiTestCaseExt : GuiTestCase() {
@Rule
@JvmField
val testMethod = TestName()
@Rule
@JvmField
val screenshotsDuringTest = ScreenshotsDuringTest(1000) // = 1 sec
@Rule
@JvmField
val logActionsDuringTest = LogActionsDuringTest()
@get:Rule
val testRootPath: TemporaryFolder by lazy {
TemporaryFolder()
}
val projectFolder: String by lazy {
testRootPath.newFolder(testMethod.methodName).canonicalPath
}
// @Rule
// @JvmField
// val collector = object : ErrorCollector() {
// override fun addError(error: Throwable?) {
// val screenshotName = testName + "." + testMethod.methodName
// takeScreenshotOnFailure(error, screenshotName)
// super.addError(error)
// }
// }
@Before
open fun setUp() {
guiTestRule.IdeHandling().setUp()
logStartTest(testMethod.methodName)
}
@After
fun tearDown() {
logEndTest(testMethod.methodName)
guiTestRule.IdeHandling().tearDown()
}
open fun isIdeFrameRun(): Boolean = true
}
fun <T> ErrorCollector.checkThat(value: T, matcher: Matcher<T>, reason: () -> String) {
checkThat(reason(), value, matcher)
}
/**
* Closes the current project
* */
fun GuiTestCase.closeProject() {
ideFrame {
logUIStep("Close the project")
waitAMoment()
closeProject()
}
}
/**
* Wrapper for [waitForBackgroundTasksToFinish]
* adds an extra pause
* This function should be used instead of [waitForBackgroundTasksToFinish]
* because sometimes it doesn't wait enough time
* After [waitForBackgroundTasksToFinish] fixing this function should be removed
* @param extraTimeOut time of additional waiting
* */
fun GuiTestCase.waitAMoment(extraTimeOut: Long = 2000L) {
ideFrame {
this.waitForBackgroundTasksToFinish()
}
robot().waitForIdle()
Pause.pause(extraTimeOut)
}
/**
* Performs test whether the specified item exists in a tree
* Note: the dialog with the investigated tree must be open
* before using this test
* @param expectedItem - expected exact item
* @param name - name of item kind, such as "Library" or "Facet". Used for understandable error message
* */
fun GuiTestCase.testTreeItemExist(name: String, vararg expectedItem: String) {
ideFrame {
logInfo("Check that $name -> ${expectedItem.joinToString(" -> ")} exists in a tree element")
kotlin.assert(exists { jTree(*expectedItem) }) { "$name '${expectedItem.joinToString(", ")}' not found" }
}
}
/**
* Performs test whether the specified item exists in a list
* Note: the dialog with the investigated list must be open
* before using this test
* @param expectedItem - expected exact item
* @param name - name of item kind, such as "Library" or "Facet". Used for understandable error message
* */
fun GuiTestCase.testListItemExist(name: String, expectedItem: String) {
ideFrame {
logInfo("Check that $name -> $expectedItem exists in a list element")
kotlin.assert(exists { jList(expectedItem, timeout = Timeouts.noTimeout) }) { "$name '$expectedItem' not found" }
}
}
/**
* Selects specified [path] in the tree by keyboard searching
* @param path in string form
* @param testCase - test case is required only because of keyboard related functions
*
* TODO: remove [testCase] parameter (so move [shortcut] and [typeText] functions
* out of GuiTestCase)
* */
fun ExtendedJTreePathFixture.selectWithKeyboard(testCase: GuiTestCase, vararg path: String) {
fun currentValue(): String {
val selectedRow = target().selectionRows.first()
return valueAt(selectedRow) ?: throw IllegalStateException("Nothing is selected in the tree")
}
click()
testCase.shortcut(Key.HOME) // select the top row
for((index, step) in path.withIndex()){
if(currentValue() != step) {
testCase.typeText(step)
while (currentValue() != step)
testCase.shortcut(Key.DOWN)
}
if(index < path.size -1) testCase.shortcut(Key.RIGHT)
}
}
/**
* Wait for Gradle reimport finishing
* I detect end of reimport by following signs:
* - action button "Refresh all external projects" becomes enable. But sometimes it becomes
* enable only for a couple of moments and becomes disable again.
* - the gradle tool window contains the project tree. But if reimporting fails the tree is empty.
*
* @param waitForProject true if we expect reimporting successful
* @param waitForProject false if we expect reimporting failing and the tree window is expected empty
* @param rootPath root name expected to be shown in the tree. Checked only if [waitForProject] is true
* */
fun GuiTestCase.waitForGradleReimport(rootPath: String, waitForProject: Boolean){
GuiTestUtilKt.waitUntil("for gradle reimport finishing", timeout = Timeouts.minutes05){
var result = false
try {
ideFrame {
toolwindow(id = "Gradle") {
content(tabName = "") {
// first, check whether the action button "Refresh all external projects" is enabled
val text = "Refresh all external projects"
val isReimportButtonEnabled = try {
val fixtureByTextAnyState = ActionButtonFixture.fixtureByTextAnyState(this.target(), robot(), text)
assertTrue("Gradle refresh button should be visible and showing", this.target().isShowing && this.target().isVisible)
fixtureByTextAnyState.isEnabled
}
catch (e: Exception) {
logInfo("$currentTimeInHumanString: waitForGradleReimport.actionButton: ${e::class.simpleName} - ${e.message}")
false
}
// second, check that Gradle tool window contains a tree with the specified [rootPath]
val gradleWindowHasPath = if(waitForProject){
try {
jTree(rootPath, timeout = Timeouts.noTimeout).hasPath()
}
catch (e: Exception) {
logInfo("$currentTimeInHumanString: waitForGradleReimport.jTree: ${e::class.simpleName} - ${e.message}")
false
}
}
else true
// calculate result whether to continue waiting
logInfo("$currentTimeInHumanString: waitForGradleReimport: jtree = $gradleWindowHasPath, button enabled = $isReimportButtonEnabled")
result = gradleWindowHasPath && isReimportButtonEnabled
}
}
// check status in the Build tool window
var syncState = !waitForProject
if(waitForProject) {
toolwindow(id = "Build") {
content(tabName = "Sync") {
val tree = treeTable().target.tree
val treePath = ExtendedJTreePathFinder(tree).findMatchingPath(listOf([email protected] + ":"))
val state = ExtendedJTreeCellReader().valueAtExtended(tree, treePath) ?: ""
logInfo("$currentTimeInHumanString: state of Build toolwindow: $state")
syncState = state.contains("sync finished")
}
}
}
// final calculating of result
result = result && syncState
}
}
catch (ignore: Exception) {}
result
}
}
fun GuiTestCase.gradleReimport() {
logTestStep("Reimport gradle project")
ideFrame {
toolwindow(id = "Gradle") {
content(tabName = "") {
waitAMoment()
actionButton("Refresh all external projects", timeout = Timeouts.minutes05).click()
}
}
}
}
fun GuiTestCase.mavenReimport() {
logTestStep("Reimport maven project")
ideFrame {
toolwindow(id = "Maven") {
content(tabName = "") {
val button = actionButton("Reimport All Maven Projects")
Pause.pause(object : Condition("Wait for button Reimport All Maven Projects to be enabled.") {
override fun test(): Boolean {
return button.isEnabled
}
}, Timeouts.minutes02)
robot().waitForIdle()
button.click()
robot().waitForIdle()
}
}
}
}
fun GuiTestCase.checkProjectIsCompiled(expectedStatus: String) {
val textEventLog = "Event Log"
ideFrame {
logTestStep("Going to check how the project compiles")
invokeMainMenu("CompileProject")
waitAMoment()
toolwindow(id = textEventLog) {
content(tabName = "") {
editor{
GuiTestUtilKt.waitUntil("Wait for '$expectedStatus' appears") {
val output = this.getCurrentFileContents(false)?.lines() ?: emptyList()
val lastLine = output.lastOrNull { it.trim().isNotEmpty() } ?: ""
lastLine.contains(expectedStatus)
}
}
}
}
}
}
fun GuiTestCase.checkProjectIsRun(configuration: String, message: String) {
val buttonRun = "Run"
logTestStep("Going to run configuration `$configuration`")
ideFrame {
navigationBar {
actionButton(buttonRun).click()
}
waitAMoment()
toolwindow(id = buttonRun) {
content(tabName = configuration) {
editor {
GuiTestUtilKt.waitUntil("Wait for '$message' appears") {
val output = this.getCurrentFileContents(false)?.lines()?.filter { it.trim().isNotEmpty() } ?: listOf()
logInfo("output: ${output.map { "\n\t$it" }}")
logInfo("expected message = '$message'")
output.firstOrNull { it.contains(message) } != null
}
}
}
}
}
}
fun GuiTestCase.checkGutterIcons(gutterIcon: GutterFixture.GutterIcon,
expectedNumberOfIcons: Int,
expectedLines: List<String>) {
ideFrame {
logTestStep("Going to check whether $expectedNumberOfIcons $gutterIcon gutter icons are present")
editor {
waitUntilFileIsLoaded()
waitUntilErrorAnalysisFinishes()
gutter.waitUntilIconsShown(mapOf(gutterIcon to expectedNumberOfIcons))
val gutterLinesWithIcon = gutter.linesWithGutterIcon(gutterIcon)
val contents = [email protected](false)?.lines() ?: listOf()
for ((index, line) in gutterLinesWithIcon.withIndex()) {
// line numbers start with 1, but index in the contents list starts with 0
val currentLine = contents[line - 1]
val expectedLine = expectedLines[index]
assert(currentLine.contains(expectedLine)) {
"At line #$line the actual text is `$currentLine`, but it was expected `$expectedLine`"
}
}
}
}
}
|
apache-2.0
|
978d2c50fc1fb88af0b26379030be83f
| 34.753165 | 144 | 0.674279 | 4.577796 | false | true | false | false |
FFlorien/AmpachePlayer
|
app/src/main/java/be/florien/anyflow/feature/alarms/add/AddAlarmViewModel.kt
|
1
|
1739
|
package be.florien.anyflow.feature.alarms.add
import androidx.lifecycle.MutableLiveData
import be.florien.anyflow.feature.BaseViewModel
import be.florien.anyflow.feature.alarms.AlarmsSynchronizer
import javax.inject.Inject
class AddAlarmViewModel : BaseViewModel() {
val isRepeating: MutableLiveData<Boolean> = MutableLiveData(false)
val time: MutableLiveData<Int> = MutableLiveData()
val monday: MutableLiveData<Boolean> = MutableLiveData()
val tuesday: MutableLiveData<Boolean> = MutableLiveData()
val wednesday: MutableLiveData<Boolean> = MutableLiveData()
val thursday: MutableLiveData<Boolean> = MutableLiveData()
val friday: MutableLiveData<Boolean> = MutableLiveData()
val saturday: MutableLiveData<Boolean> = MutableLiveData()
val sunday: MutableLiveData<Boolean> = MutableLiveData()
@Inject
lateinit var alarmsSynchronizer: AlarmsSynchronizer
suspend fun addAlarm() {
when {
isRepeating.value != true -> alarmsSynchronizer.addSingleAlarm((time.value ?: 0) / 60, (time.value ?: 0) % 60)
isEveryday() -> alarmsSynchronizer.addRepeatingAlarm((time.value ?: 0) / 60, (time.value ?: 0) % 60)
else -> alarmsSynchronizer.addRepeatingAlarmForWeekDays((time.value ?: 0) / 60, (time.value ?: 0) % 60, monday.value ?: false, tuesday.value ?: false, wednesday.value ?: false, thursday.value ?: false, friday.value
?: false, saturday.value ?: false, sunday.value ?: false)
}
}
private fun isEveryday() = monday.value == tuesday.value && tuesday.value == wednesday.value && wednesday.value == thursday.value && thursday.value == friday.value && friday.value == saturday.value && saturday.value == sunday.value
}
|
gpl-3.0
|
f6ee2e4374c5873c58ac17886ef47f31
| 53.375 | 235 | 0.711903 | 4.49354 | false | false | false | false |
groupdocs-comparison/GroupDocs.Comparison-for-Java
|
Demos/Javalin/src/main/kotlin/com/groupdocs/ui/config/ApplicationConfig.kt
|
1
|
2510
|
package com.groupdocs.ui.config
import com.groupdocs.ui.Defaults
import java.nio.file.Path
@kotlinx.serialization.Serializable
data class ApplicationConfig(
val server: Server = Server(),
val common: Common = Common(),
val comparison: Comparison = Comparison(),
val local: Local = Local(),
private val licensePath: String = ""
) {
val licensePathOrDefault: String
get() = licensePath.ifBlank { Defaults.DEFAULT_LICENSE_PATH }
}
@kotlinx.serialization.Serializable
data class Server(
val host: String = "0.0.0.0",
val port: Int = 8080
)
@kotlinx.serialization.Serializable
data class Common(
val pageSelector: Boolean = false,
val download: Boolean = false,
val upload: Boolean = false,
val print: Boolean = false,
val browse: Boolean = false,
val rewrite: Boolean = false,
val enableRightClick: Boolean = false
)
@kotlinx.serialization.Serializable
data class Comparison(
private val filesProviderType: String = "",
val preloadResultPageCount: Int = 0,
private val previewPageWidth: Int = 0,
private val previewPageRatio: Float = 0f,
private val tempDirectory: String = "",
) {
val filesProviderTypeOrDefault: Defaults.Comparison.FilesProviderType
get() =
when (filesProviderType.uppercase()) {
in Defaults.Comparison.FilesProviderType.values()
.map { it.name.uppercase() } -> Defaults.Comparison.FilesProviderType.valueOf(filesProviderType.uppercase())
else -> Defaults.Comparison.DEFAULT_FILES_PROVIDER_TYPE
}
val tempDirectoryOrDefault: String
get() = tempDirectory.ifBlank { Defaults.Comparison.DEFAULT_TEMP_DIRECTORY }
?: throw IllegalStateException("Can't get temp directory!")
val previewPageWidthOrDefault: Int
get() = if (previewPageWidth == 0) Defaults.Comparison.DEFAULT_PREVIEW_PAGE_WIDTH else previewPageWidth
val previewPageRatioOrDefault: Float
get() = if (previewPageRatio == 0f) Defaults.Comparison.DEFAULT_PREVIEW_PAGE_RATIO else previewPageRatio
}
@kotlinx.serialization.Serializable
data class Local(
private val filesDirectory: String = "",
private val resultDirectory: String = "",
) {
val filesDirectoryOrDefault: Path
get() = Path.of(filesDirectory.ifBlank { Defaults.Local.DEFAULT_FILES_DIRECTORY })
val resultDirectoryOrDefault: Path
get() = Path.of(resultDirectory.ifBlank { Defaults.Local.DEFAULT_RESULT_DIRECTORY })
}
|
mit
|
9a3ef610243983bac253f3e0290b7e78
| 34.871429 | 128 | 0.702789 | 4.403509 | false | false | false | false |
soywiz/korge
|
korge/src/commonMain/kotlin/com/soywiz/korge/render/RenderContext.kt
|
1
|
6120
|
package com.soywiz.korge.render
import com.soywiz.kds.*
import com.soywiz.korag.*
import com.soywiz.korag.log.*
import com.soywiz.korge.internal.*
import com.soywiz.korge.stat.*
import com.soywiz.korge.view.*
import com.soywiz.korim.bitmap.*
import com.soywiz.korio.async.*
import com.soywiz.korma.geom.*
import kotlin.coroutines.*
/**
* A context that allows to render objects.
*
* The [RenderContext] contains the [ag] [AG] (Accelerated Graphics),
* that allow to render triangles and other primitives to the current render buffer.
*
* When doing 2D, you should usually use the [batch] to buffer vertices,
* so they can be rendered at once when flushing.
*
* If you plan to do a custom drawing using [ag] directly, you should call [flush],
* so all the pending vertices are rendered.
*
* If you want to perform drawing using a context allowing non-precomputed transformations
* you can use [ctx2d].
*
* If you need to get textures from [Bitmap] that are allocated and deallocated as required
* preventing leaks, you should use [getTex].
*/
class RenderContext constructor(
/** The Accelerated Graphics object that allows direct rendering */
val ag: AG,
val bp: BoundsProvider = BoundsProvider.Dummy,
/** Object storing all the rendering [Stats] like number of batches, number of vertices etc. */
val stats: Stats = Stats(),
val coroutineContext: CoroutineContext = EmptyCoroutineContext,
val batchMaxQuads: Int = BatchBuilder2D.DEFAULT_BATCH_QUADS
) : Extra by Extra.Mixin(), BoundsProvider by bp {
val agBitmapTextureManager = AgBitmapTextureManager(ag)
/** Allows to register handlers when the [flush] method is called */
val flushers = Signal<Unit>()
val views: Views? = bp as? Views?
var debugAnnotateView: View? = null
var stencilIndex: Int = 0
/** Allows to draw quads, sprites and nine patches using a precomputed global matrix or raw vertices */
@Deprecated("Use useBatcher instead")
@KorgeInternal
val batch = BatchBuilder2D(this, batchMaxQuads)
@OptIn(KorgeInternal::class)
inline fun useBatcher(block: (BatchBuilder2D) -> Unit) = batch.use(block)
/** [RenderContext2D] similar to the one from JS, that keeps an matrix (affine transformation) and allows to draw shapes using the current matrix */
@KorgeInternal
@Deprecated("Use useCtx2d instead")
val ctx2d = RenderContext2D(batch, agBitmapTextureManager)
@Suppress("DEPRECATION")
@OptIn(KorgeInternal::class)
inline fun useCtx2d(block: (RenderContext2D) -> Unit) { useBatcher(batch) { block(ctx2d) } }
/** Pool of [Matrix] objects that could be used temporarily by renders */
val matrixPool = Pool(reset = { it.identity() }, preallocate = 8) { Matrix() }
/** Pool of [Matrix3D] objects that could be used temporarily by renders */
val matrix3DPool = Pool(reset = { it.identity() }, preallocate = 8) { Matrix3D() }
/** Pool of [Point] objects that could be used temporarily by renders */
val pointPool = Pool(reset = { it.setTo(0, 0) }, preallocate = 8) { Point() }
/**
* Allows to toggle whether stencil-based masks are enabled or not.
*/
var masksEnabled = true
var currentBatcher: Any? = null
/**
* Flushes all the pending renderings. This is called automatically at the end of the frame.
* You should call this if you plan to render something else not managed via [batch],
* so all the pending vertices are drawn.
*/
fun flush() {
currentBatcher = null
flushers(Unit)
}
/**
* Temporarily sets the render buffer to a temporal texture of the size [width] and [height] that can be used later in the [use] method.
* First the texture is created, then [render] method is called once the render buffer is set to the texture,
* and later the context is restored and the [use] method is called providing as first argument the rendered [Texture].
* This method is useful for per-frame filters. If you plan to keep the texture data, consider using the [renderToBitmap] method.
*/
inline fun renderToTexture(width: Int, height: Int, render: () -> Unit, use: (texture: Texture) -> Unit) {
flush()
ag.renderToTexture(width, height, render = {
val oldScissors = batch.scissor
batch.scissor = null
try {
render()
flush()
} finally {
batch.scissor = oldScissors
}
}, use = {
use(Texture(it, width, height))
flush()
})
}
/**
* Sets the render buffer temporarily to [bmp] [Bitmap32] and calls the [callback] render method that should perform all the renderings inside.
*/
inline fun renderToBitmap(bmp: Bitmap32, callback: () -> Unit): Bitmap32 {
flush()
ag.renderToBitmap(bmp) {
callback()
flush()
}
return bmp
}
inline fun renderToBitmap(width: Int, height: Int, callback: () -> Unit): Bitmap32 =
renderToBitmap(Bitmap32(width, height), callback)
/**
* Finishes the drawing and flips the screen. Called by the KorGe engine at the end of the frame.
*/
fun finish() {
ag.flip()
}
/**
* Temporarily allocates a [Texture] with its coords from a [BmpSlice].
* Textures are managed (allocated and de-allocated) automatically by the engine as required.
* The texture coords matches the region in the [BmpSlice].
*/
fun getTex(bmp: BmpSlice): Texture = agBitmapTextureManager.getTexture(bmp)
/**
* Allocates a [Texture.Base] from a [Bitmap]. A Texture.Base doesn't have region information.
* It is just the whole texture/bitmap.
*/
fun getTex(bmp: Bitmap): Texture.Base = agBitmapTextureManager.getTextureBase(bmp)
inline fun <T> useBatcher(batcher: T, block: (T) -> Unit) {
if (currentBatcher !== batcher) {
flush()
currentBatcher = batcher
}
block(batcher)
}
}
inline fun <T : AG> testRenderContext(ag: T, block: (RenderContext) -> Unit): T {
val ctx = RenderContext(ag)
block(ctx)
ctx.flush()
return ag
}
inline fun testRenderContext(block: (RenderContext) -> Unit): LogAG = testRenderContext(LogAG(), block)
|
apache-2.0
|
fcc8b3d0d8af33817935ecc2cb48d373
| 35.86747 | 152 | 0.686928 | 3.849057 | false | false | false | false |
isuPatches/WiseFy
|
wisefysample/src/main/java/com/isupatches/wisefysample/ui/remove/RemoveNetworkFragment.kt
|
1
|
4995
|
/*
* Copyright 2019 Patches Klinefelter
*
* 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.isupatches.wisefysample.ui.remove
import android.Manifest.permission.ACCESS_FINE_LOCATION
import android.content.pm.PackageManager
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.annotation.VisibleForTesting
import com.isupatches.wisefy.constants.WiseFyCode
import com.isupatches.wisefysample.R
import com.isupatches.wisefysample.internal.base.BaseFragment
import com.isupatches.wisefysample.internal.preferences.RemoveNetworkStore
import com.isupatches.wisefysample.internal.util.getTrimmedInput
import com.isupatches.wisefysample.internal.util.hideKeyboardFrom
import dagger.Binds
import dagger.Module
import javax.inject.Inject
import kotlinx.android.synthetic.main.fragment_remove.networkNameEdt
import kotlinx.android.synthetic.main.fragment_remove.removeNetworkBtn
internal class RemoveNetworkFragment : BaseFragment(), RemoveNetworkMvp.View {
override val layoutRes = R.layout.fragment_remove
@Inject lateinit var presenter: RemoveNetworkMvp.Presenter
@Inject lateinit var removeNetworkStore: RemoveNetworkStore
companion object {
val TAG: String = RemoveNetworkFragment::class.java.simpleName
fun newInstance() = RemoveNetworkFragment()
@VisibleForTesting internal const val WISEFY_REMOVE_NETWORK_REQUEST_CODE = 1
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
if (savedInstanceState == null) {
restoreUI()
}
removeNetworkBtn.setOnClickListener {
hideKeyboardFrom(removeNetworkBtn)
removeNetwork()
}
}
override fun onStart() {
super.onStart()
presenter.attachView(this)
}
override fun onStop() {
presenter.detachView()
super.onStop()
removeNetworkStore.setLastUsedRegex(networkNameEdt.getTrimmedInput())
hideKeyboardFrom(removeNetworkBtn)
}
/*
* View helpers
*/
private fun restoreUI() {
// Restore edit text value
networkNameEdt.setText(removeNetworkStore.getLastUsedRegex())
}
/*
* Presenter callback overrides
*/
override fun displayNetworkRemoved() {
displayInfo(R.string.network_removed, R.string.remover_network_result)
}
override fun displayNetworkNotFoundToRemove() {
displayInfo(R.string.network_not_found_to_remove, R.string.remover_network_result)
}
override fun displayFailureRemovingNetwork() {
displayInfo(R.string.failure_removing_network, R.string.remover_network_result)
}
override fun displayWiseFyFailure(@WiseFyCode wiseFyFailureCode: Int) {
displayWiseFyFailureWithCode(wiseFyFailureCode)
}
/*
* WiseFy helpers
*/
@Throws(SecurityException::class)
private fun removeNetwork() {
if (checkRemoveNetworkPermissions()) {
presenter.removeNetwork(networkNameEdt.getTrimmedInput())
}
}
/*
* Permission helpers
*/
private fun checkRemoveNetworkPermissions(): Boolean {
return isPermissionGranted(ACCESS_FINE_LOCATION, WISEFY_REMOVE_NETWORK_REQUEST_CODE)
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
when (requestCode) {
WISEFY_REMOVE_NETWORK_REQUEST_CODE -> {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
removeNetwork()
} else {
Log.w(TAG, "Permissions for remove saved network are denied")
displayPermissionErrorDialog(R.string.permission_error_remove_network)
}
}
else -> {
Log.wtf(TAG, "Weird permission requested, not handled")
displayPermissionErrorDialog(
getString(R.string.permission_error_unhandled_request_code_args, requestCode)
)
}
}
}
/*
* Dagger
*/
@Suppress("unused")
@Module internal interface RemoveNetworkFragmentModule {
@Binds fun bindRemoveNetworkModel(impl: RemoveNetworkModel): RemoveNetworkMvp.Model
@Binds fun bindRemoveNetworkPresenter(impl: RemoveNetworkPresenter): RemoveNetworkMvp.Presenter
}
}
|
apache-2.0
|
7682b03e31284b6451cccbaa199b5660
| 31.861842 | 119 | 0.697698 | 4.78907 | false | false | false | false |
uchuhimo/kotlin-playground
|
konf/src/main/kotlin/com/uchuhimo/konf/source/json/JsonSource.kt
|
1
|
4555
|
package com.uchuhimo.konf.source.json
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.node.JsonNodeType
import com.uchuhimo.konf.Path
import com.uchuhimo.konf.source.Source
import com.uchuhimo.konf.source.WrongTypeException
import com.uchuhimo.konf.source.toDescription
import java.math.BigDecimal
import java.math.BigInteger
class JsonSource(
val node: JsonNode,
context: Map<String, String> = mapOf()
) : Source {
val _info = mutableMapOf("type" to "JSON")
override val info: Map<String, String> get() = _info
override fun addInfo(name: String, value: String) {
_info.put(name, value)
}
val _context: MutableMap<String, String> = context.toMutableMap()
override val context: Map<String, String> get() = _context
override fun addContext(name: String, value: String) {
_context.put(name, value)
}
override fun contains(path: Path): Boolean {
if (path.isEmpty()) {
return true
} else {
val key = path.first()
val rest = path.drop(1)
val childNode = node[key]
if (childNode != null) {
return JsonSource(childNode, context).contains(rest)
} else {
return false
}
}
}
override fun getOrNull(path: Path): Source? {
if (path.isEmpty()) {
return this
} else {
val key = path.first()
val rest = path.drop(1)
val childNode = node[key]
if (childNode != null) {
return JsonSource(childNode, context).getOrNull(rest)
} else {
return null
}
}
}
override fun toList(): List<Source> {
if (node.isArray) {
return mutableListOf<JsonNode>().apply {
addAll(node.elements().asSequence())
}.map {
JsonSource(it, context).apply {
addInfo("inList", [email protected]())
}
}
} else {
throw WrongTypeException(this, node.nodeType.name, JsonNodeType.ARRAY.name)
}
}
override fun toMap(): Map<String, Source> {
if (node.isObject) {
return mutableMapOf<String, JsonNode>().apply {
for ((key, value) in node.fields()) {
put(key, value)
}
}.mapValues {
(_, value) ->
JsonSource(value, context).apply {
addInfo("inMap", [email protected]())
}
}
} else {
throw WrongTypeException(this, node.nodeType.name, JsonNodeType.OBJECT.name)
}
}
override fun toText(): String {
if (node.isTextual) {
return node.textValue()
} else {
throw WrongTypeException(this, node.nodeType.name, JsonNodeType.STRING.name)
}
}
override fun toBoolean(): Boolean {
if (node.isBoolean) {
return node.booleanValue()
} else {
throw WrongTypeException(this, node.nodeType.name, JsonNodeType.BOOLEAN.name)
}
}
override fun toDouble(): Double {
if (node.isDouble) {
return node.doubleValue()
} else {
throw WrongTypeException(this, node.nodeType.name, "DOUBLE")
}
}
override fun toFloat(): Float {
if (node.isFloat) {
return node.floatValue()
} else {
return super.toFloat()
}
}
override fun toInt(): Int {
if (node.isInt) {
return node.intValue()
} else {
throw WrongTypeException(this, node.nodeType.name, "INT")
}
}
override fun toLong(): Long {
if (node.isLong) {
return node.longValue()
} else {
return super.toLong()
}
}
override fun toShort(): Short {
if (node.isShort) {
return node.shortValue()
} else {
return super.toShort()
}
}
override fun toBigInteger(): BigInteger {
if (node.isBigInteger) {
return node.bigIntegerValue()
} else {
return super.toBigInteger()
}
}
override fun toBigDecimal(): BigDecimal {
if (node.isBigDecimal) {
return node.decimalValue()
} else {
return super.toBigDecimal()
}
}
}
|
apache-2.0
|
24f1f26be155f354c77393293f90bd6b
| 26.77439 | 89 | 0.534138 | 4.568706 | false | false | false | false |
wikimedia/apps-android-wikipedia
|
app/src/main/java/org/wikipedia/feed/FeedCoordinator.kt
|
1
|
1873
|
package org.wikipedia.feed
import android.content.Context
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Completable
import io.reactivex.rxjava3.schedulers.Schedulers
import org.wikipedia.WikipediaApp
import org.wikipedia.feed.aggregated.AggregatedFeedContentClient
import org.wikipedia.feed.announcement.AnnouncementClient
import org.wikipedia.feed.dataclient.FeedClient
import org.wikipedia.feed.model.Card
import org.wikipedia.feed.offline.OfflineCardClient
import org.wikipedia.feed.onboarding.OnboardingClient
import org.wikipedia.feed.searchbar.SearchClient
class FeedCoordinator internal constructor(context: Context) : FeedCoordinatorBase(context) {
private val aggregatedClient = AggregatedFeedContentClient()
init {
FeedContentType.restoreState()
}
override fun reset() {
super.reset()
aggregatedClient.invalidate()
}
override fun buildScript(age: Int) {
val online = WikipediaApp.instance.isOnline
conditionallyAddPendingClient(SearchClient(), age == 0)
conditionallyAddPendingClient(AnnouncementClient(), age == 0 && online)
conditionallyAddPendingClient(OnboardingClient(), age == 0)
conditionallyAddPendingClient(OfflineCardClient(), age == 0 && !online)
for (contentType in FeedContentType.values().sortedBy { it.order }) {
addPendingClient(contentType.newClient(aggregatedClient, age))
}
}
companion object {
fun postCardsToCallback(cb: FeedClient.Callback, cards: List<Card>) {
Completable.fromAction {
val delayMillis = 150L
Thread.sleep(delayMillis)
}.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { cb.success(cards) }
}
}
}
|
apache-2.0
|
04fa346ab98fc0c772f53d1ed97147f9
| 35.72549 | 93 | 0.720235 | 4.6825 | false | false | false | false |
SchibstedSpain/Leku
|
leku/src/main/java/com/schibstedspain/leku/geocoder/GeocoderPresenter.kt
|
1
|
6831
|
package com.schibstedspain.leku.geocoder
import android.annotation.SuppressLint
import android.location.Address
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.LatLngBounds
import com.schibstedspain.leku.geocoder.places.GooglePlacesDataSource
import com.schibstedspain.leku.geocoder.timezone.GoogleTimeZoneDataSource
import com.schibstedspain.leku.utils.ReactiveLocationProvider
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.core.ObservableSource
import io.reactivex.rxjava3.core.Scheduler
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.functions.BiFunction
import io.reactivex.rxjava3.schedulers.Schedulers
import java.util.concurrent.TimeUnit
import java.util.TimeZone
import kotlin.collections.ArrayList
private const val RETRY_COUNT = 3
private const val MAX_PLACES_RESULTS = 3
class GeocoderPresenter @JvmOverloads constructor(
private val locationProvider: ReactiveLocationProvider,
private val geocoderRepository: GeocoderRepository,
private val googlePlacesDataSource: GooglePlacesDataSource? = null,
private val googleTimeZoneDataSource: GoogleTimeZoneDataSource? = null,
private val scheduler: Scheduler = AndroidSchedulers.mainThread()
) {
private var view: GeocoderViewInterface? = null
private val nullView = GeocoderViewInterface.NullView()
private val compositeDisposable = CompositeDisposable()
private var isGooglePlacesEnabled = false
init {
this.view = nullView
}
fun setUI(geocoderViewInterface: GeocoderViewInterface) {
this.view = geocoderViewInterface
}
fun stop() {
this.view = nullView
compositeDisposable.clear()
}
fun getLastKnownLocation() {
@SuppressLint("MissingPermission")
val disposable = locationProvider.getLastKnownLocation()
.retry(RETRY_COUNT.toLong())
.subscribe({ view?.showLastLocation(it) },
{ view?.didGetLastLocation() })
compositeDisposable.add(disposable)
}
fun getFromLocationName(query: String) {
view?.willLoadLocation()
val disposable = geocoderRepository.getFromLocationName(query)
.observeOn(scheduler)
.subscribe({ view?.showLocations(it) },
{ view?.showLoadLocationError() },
{ view?.didLoadLocation() })
compositeDisposable.add(disposable)
}
fun getFromLocationName(query: String, lowerLeft: LatLng, upperRight: LatLng) {
view?.willLoadLocation()
val disposable = Observable.zip<List<Address>, List<Address>, List<Address>>(
geocoderRepository.getFromLocationName(query, lowerLeft, upperRight),
getPlacesFromLocationName(query, lowerLeft, upperRight),
BiFunction<List<Address>, List<Address>, List<Address>> {
geocoderList, placesList -> this.getMergedList(geocoderList, placesList)
})
.subscribeOn(Schedulers.io())
.observeOn(scheduler)
.retry(RETRY_COUNT.toLong())
.subscribe({ view?.showLocations(it) },
{ view?.showLoadLocationError() },
{ view?.didLoadLocation() })
compositeDisposable.add(disposable)
}
fun getDebouncedFromLocationName(query: String, debounceTime: Int) {
view?.willLoadLocation()
val disposable = geocoderRepository.getFromLocationName(query)
.debounce(debounceTime.toLong(), TimeUnit.MILLISECONDS, Schedulers.io())
.observeOn(scheduler)
.subscribe({ view?.showDebouncedLocations(it) },
{ view?.showLoadLocationError() },
{ view?.didLoadLocation() })
compositeDisposable.add(disposable)
}
fun getDebouncedFromLocationName(query: String, lowerLeft: LatLng, upperRight: LatLng, debounceTime: Int) {
view?.willLoadLocation()
val disposable = Observable.zip<List<Address>, List<Address>, List<Address>>(
geocoderRepository.getFromLocationName(query, lowerLeft, upperRight),
getPlacesFromLocationName(query, lowerLeft, upperRight),
BiFunction<List<Address>, List<Address>, List<Address>> {
geocoderList, placesList -> this.getMergedList(geocoderList, placesList) })
.subscribeOn(Schedulers.io())
.debounce(debounceTime.toLong(), TimeUnit.MILLISECONDS, Schedulers.io())
.observeOn(scheduler)
.subscribe({ view?.showDebouncedLocations(it) },
{ view?.showLoadLocationError() },
{ view?.didLoadLocation() })
compositeDisposable.add(disposable)
}
fun getInfoFromLocation(latLng: LatLng) {
view?.willGetLocationInfo(latLng)
val disposable = geocoderRepository.getFromLocation(latLng)
.observeOn(scheduler)
.retry(RETRY_COUNT.toLong())
.filter { addresses -> addresses.isNotEmpty() }
.map { addresses -> addresses[0] }
.flatMap { address -> returnTimeZone(address) }
.subscribe({ pair: Pair<Address, TimeZone?> -> view?.showLocationInfo(pair) },
{ view?.showGetLocationInfoError() },
{ view?.didGetLocationInfo() })
compositeDisposable.add(disposable)
}
private fun returnTimeZone(address: Address): ObservableSource<out Pair<Address, TimeZone?>>? {
return Observable.just(
Pair(address, googleTimeZoneDataSource?.getTimeZone(address.latitude, address.longitude))
).onErrorReturn { Pair(address, null) }
}
fun enableGooglePlaces() {
this.isGooglePlacesEnabled = true
}
private fun getPlacesFromLocationName(
query: String,
lowerLeft: LatLng,
upperRight: LatLng
): Observable<List<Address>> {
return if (isGooglePlacesEnabled)
googlePlacesDataSource!!.getFromLocationName(query, LatLngBounds(lowerLeft, upperRight))
.flatMapIterable { addresses -> addresses }
.take(MAX_PLACES_RESULTS.toLong()).toList().toObservable()
.onErrorReturnItem(ArrayList())
else
Observable.just(ArrayList())
}
private fun getMergedList(geocoderList: List<Address>, placesList: List<Address>): List<Address> {
val mergedList = ArrayList<Address>()
mergedList.addAll(geocoderList)
mergedList.addAll(placesList)
return mergedList
}
}
|
apache-2.0
|
a08cbe4737759fa75e161701c945b827
| 42.509554 | 111 | 0.656419 | 4.982495 | false | false | false | false |
numa08/Gochisou
|
app/src/main/java/net/numa08/gochisou/data/repositories/LoginProfileRepository.kt
|
1
|
636
|
package net.numa08.gochisou.data.repositories
import android.databinding.ObservableList
import net.numa08.gochisou.data.model.LoginProfile
abstract class LoginProfileRepository(val list: ObservableList<LoginProfile>) : ObservableList<LoginProfile> by list {
fun find(token: String): LoginProfile? = list.find { it.token.accessToken == token }
fun updateOrSet(element: LoginProfile) {
val idx = indexOf(find(element.token.accessToken))
val f = when(idx) {
-1 -> {i: Int,e: LoginProfile -> add(e) }
else -> {i: Int, e: LoginProfile -> set(i,e)}
}
f(idx, element)
}
}
|
mit
|
5de4c5fb227dd9bef6f11c7f26c5466e
| 34.388889 | 118 | 0.669811 | 3.975 | false | false | false | false |
wikimedia/apps-android-wikipedia
|
app/src/main/java/org/wikipedia/page/PageFragment.kt
|
1
|
63936
|
package org.wikipedia.page
import android.animation.ObjectAnimator
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.net.Uri
import android.os.Bundle
import android.view.*
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebView
import android.widget.LinearLayout
import androidx.appcompat.app.AlertDialog
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.animation.doOnEnd
import androidx.core.app.ActivityCompat
import androidx.core.app.ActivityOptionsCompat
import androidx.core.graphics.Insets
import androidx.core.view.ActionProvider
import androidx.core.view.MenuItemCompat
import androidx.core.view.forEach
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout.OnRefreshListener
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.google.android.material.textview.MaterialTextView
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Completable
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.schedulers.Schedulers
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.serialization.json.float
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import org.wikipedia.*
import org.wikipedia.Constants.InvokeSource
import org.wikipedia.activity.FragmentUtil.getCallback
import org.wikipedia.analytics.*
import org.wikipedia.analytics.eventplatform.ArticleFindInPageInteractionEvent
import org.wikipedia.analytics.eventplatform.ArticleInteractionEvent
import org.wikipedia.auth.AccountUtil
import org.wikipedia.bridge.CommunicationBridge
import org.wikipedia.bridge.JavaScriptActionHandler
import org.wikipedia.categories.CategoryActivity
import org.wikipedia.categories.CategoryDialog
import org.wikipedia.database.AppDatabase
import org.wikipedia.databinding.FragmentPageBinding
import org.wikipedia.databinding.GroupFindReferencesInPageBinding
import org.wikipedia.dataclient.RestService
import org.wikipedia.dataclient.ServiceFactory
import org.wikipedia.dataclient.WikiSite
import org.wikipedia.dataclient.mwapi.MwQueryPage
import org.wikipedia.dataclient.okhttp.HttpStatusException
import org.wikipedia.dataclient.okhttp.OkHttpWebViewClient
import org.wikipedia.dataclient.watch.Watch
import org.wikipedia.descriptions.DescriptionEditActivity
import org.wikipedia.diff.ArticleEditDetailsActivity
import org.wikipedia.edit.EditHandler
import org.wikipedia.feed.announcement.Announcement
import org.wikipedia.feed.announcement.AnnouncementClient
import org.wikipedia.gallery.GalleryActivity
import org.wikipedia.history.HistoryEntry
import org.wikipedia.json.JsonUtil
import org.wikipedia.login.LoginActivity
import org.wikipedia.main.MainActivity
import org.wikipedia.media.AvPlayer
import org.wikipedia.navtab.NavTab
import org.wikipedia.notifications.PollNotificationWorker
import org.wikipedia.page.PageCacher.loadIntoCache
import org.wikipedia.page.action.PageActionItem
import org.wikipedia.page.edithistory.EditHistoryListActivity
import org.wikipedia.page.leadimages.LeadImagesHandler
import org.wikipedia.page.references.PageReferences
import org.wikipedia.page.references.ReferenceDialog
import org.wikipedia.page.shareafact.ShareHandler
import org.wikipedia.page.tabs.Tab
import org.wikipedia.readinglist.LongPressMenu
import org.wikipedia.readinglist.ReadingListBehaviorsUtil
import org.wikipedia.readinglist.database.ReadingListPage
import org.wikipedia.settings.Prefs
import org.wikipedia.suggestededits.PageSummaryForEdit
import org.wikipedia.talk.TalkTopicsActivity
import org.wikipedia.theme.ThemeChooserDialog
import org.wikipedia.util.*
import org.wikipedia.util.log.L
import org.wikipedia.views.ObservableWebView
import org.wikipedia.views.PageActionOverflowView
import org.wikipedia.views.ViewUtil
import org.wikipedia.watchlist.WatchlistExpiry
import org.wikipedia.watchlist.WatchlistExpiryDialog
import org.wikipedia.wiktionary.WiktionaryDialog
import java.util.*
class PageFragment : Fragment(), BackPressedHandler, CommunicationBridge.CommunicationBridgeListener, ThemeChooserDialog.Callback,
ReferenceDialog.Callback, WiktionaryDialog.Callback, WatchlistExpiryDialog.Callback {
interface Callback {
fun onPageDismissBottomSheet()
fun onPageLoadComplete()
fun onPageLoadPage(title: PageTitle, entry: HistoryEntry)
fun onPageInitWebView(v: ObservableWebView)
fun onPageShowLinkPreview(entry: HistoryEntry)
fun onPageLoadMainPageInForegroundTab()
fun onPageUpdateProgressBar(visible: Boolean)
fun onPageStartSupportActionMode(callback: ActionMode.Callback)
fun onPageHideSoftKeyboard()
fun onPageAddToReadingList(title: PageTitle, source: InvokeSource)
fun onPageMoveToReadingList(sourceReadingListId: Long, title: PageTitle, source: InvokeSource, showDefaultList: Boolean)
fun onPageWatchlistExpirySelect(expiry: WatchlistExpiry)
fun onPageLoadError(title: PageTitle)
fun onPageLoadErrorBackPressed()
fun onPageSetToolbarElevationEnabled(enabled: Boolean)
fun onPageCloseActionMode()
fun onPageRequestEditSection(sectionId: Int, sectionAnchor: String?, title: PageTitle, highlightText: String?)
fun onPageRequestLangLinks(title: PageTitle)
fun onPageRequestGallery(title: PageTitle, fileName: String, wikiSite: WikiSite, revision: Long, source: Int, options: ActivityOptionsCompat?)
fun onPageRequestAddImageTags(mwQueryPage: MwQueryPage, invokeSource: InvokeSource)
fun onPageRequestEditDescriptionTutorial(text: String?, invokeSource: InvokeSource)
fun onPageRequestEditDescription(text: String?, title: PageTitle, sourceSummary: PageSummaryForEdit?,
targetSummary: PageSummaryForEdit?, action: DescriptionEditActivity.Action, invokeSource: InvokeSource)
}
private var _binding: FragmentPageBinding? = null
val binding get() = _binding!!
private val activeTimer = ActiveTimer()
private val bottomSheetPresenter = ExclusiveBottomSheetPresenter()
private val disposables = CompositeDisposable()
private val scrollTriggerListener = WebViewScrollTriggerListener()
private val tabFunnel = TabFunnel()
private val watchlistFunnel = WatchlistFunnel()
private val pageRefreshListener = OnRefreshListener { refreshPage() }
private val pageActionItemCallback = PageActionItemCallback()
private lateinit var bridge: CommunicationBridge
private lateinit var leadImagesHandler: LeadImagesHandler
private lateinit var pageFragmentLoadState: PageFragmentLoadState
private lateinit var bottomBarHideHandler: ViewHideHandler
internal var articleInteractionEvent: ArticleInteractionEvent? = null
private var pageScrollFunnel: PageScrollFunnel? = null
private var pageRefreshed = false
private var errorState = false
private var watchlistExpiryChanged = false
private var scrolledUpForThemeChange = false
private var references: PageReferences? = null
private var avPlayer: AvPlayer? = null
private var avCallback: AvCallback? = null
private var sections: MutableList<Section>? = null
private var app = WikipediaApp.instance
override lateinit var linkHandler: LinkHandler
override lateinit var webView: ObservableWebView
override var model = PageViewModel()
override val toolbarMargin get() = (requireActivity() as PageActivity).getToolbarMargin()
override val isPreview get() = false
override val referencesGroup get() = references?.referencesGroup
override val selectedReferenceIndex get() = references?.selectedIndex ?: 0
lateinit var sidePanelHandler: SidePanelHandler
lateinit var shareHandler: ShareHandler
lateinit var editHandler: EditHandler
var revision = 0L
private val shouldCreateNewTab get() = currentTab.backStack.isNotEmpty()
private val backgroundTabPosition get() = 0.coerceAtLeast(foregroundTabPosition - 1)
private val foregroundTabPosition get() = app.tabList.size
private val tabLayoutOffsetParams get() = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, binding.pageActionsTabLayout.height)
val currentTab get() = app.tabList.last()
val title get() = model.title
val page get() = model.page
val historyEntry get() = model.curEntry
val containerView get() = binding.pageContentsContainer
val headerView get() = binding.pageHeaderView
val isLoading get() = bridge.isLoading
val leadImageEditLang get() = leadImagesHandler.callToActionEditLang
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
_binding = FragmentPageBinding.inflate(inflater, container, false)
webView = binding.pageWebView
initWebViewListeners()
binding.pageRefreshContainer.setColorSchemeResources(ResourceUtil.getThemedAttributeId(requireContext(), R.attr.colorAccent))
binding.pageRefreshContainer.scrollableChild = webView
binding.pageRefreshContainer.setOnRefreshListener(pageRefreshListener)
val swipeOffset = DimenUtil.getContentTopOffsetPx(requireActivity()) + REFRESH_SPINNER_ADDITIONAL_OFFSET
binding.pageRefreshContainer.setProgressViewOffset(false, -swipeOffset, swipeOffset)
binding.pageActionsTabLayout.callback = pageActionItemCallback
savedInstanceState?.let {
scrolledUpForThemeChange = it.getBoolean(ARG_THEME_CHANGE_SCROLLED, false)
}
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
callback()?.onPageInitWebView(webView)
updateFontSize()
// Explicitly set background color of the WebView (independently of CSS, because
// the background may be shown momentarily while the WebView loads content,
// creating a seizure-inducing effect, or at the very least, a migraine with aura).
val activity = requireActivity()
webView.setBackgroundColor(ResourceUtil.getThemedColor(activity, R.attr.paper_color))
bridge = CommunicationBridge(this)
setupMessageHandlers()
binding.pageError.retryClickListener = View.OnClickListener { refreshPage() }
binding.pageError.backClickListener = View.OnClickListener {
if (!onBackPressed()) {
callback()?.onPageLoadErrorBackPressed()
}
}
bottomBarHideHandler = ViewHideHandler(binding.pageActionsTabLayout, null, Gravity.BOTTOM, updateElevation = false) { false }
bottomBarHideHandler.setScrollView(webView)
bottomBarHideHandler.enabled = Prefs.readingFocusModeEnabled
editHandler = EditHandler(this, bridge)
sidePanelHandler = SidePanelHandler(this, bridge)
leadImagesHandler = LeadImagesHandler(this, webView, binding.pageHeaderView, callback())
shareHandler = ShareHandler(this, bridge)
pageFragmentLoadState = PageFragmentLoadState(model, this, webView, bridge, leadImagesHandler, currentTab)
if (callback() != null) {
LongPressHandler(webView, HistoryEntry.SOURCE_INTERNAL_LINK, PageContainerLongPressHandler(this))
}
if (shouldLoadFromBackstack(activity) || savedInstanceState != null) {
reloadFromBackstack()
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putBoolean(ARG_THEME_CHANGE_SCROLLED, scrolledUpForThemeChange)
}
override fun onDestroyView() {
avPlayer?.let {
it.deinit()
avPlayer = null
}
// uninitialize the bridge, so that no further JS events can have any effect.
bridge.cleanup()
sidePanelHandler.log()
leadImagesHandler.dispose()
disposables.clear()
webView.clearAllListeners()
(webView.parent as ViewGroup).removeView(webView)
Prefs.isSuggestedEditsHighestPriorityEnabled = false
_binding = null
super.onDestroyView()
}
override fun onPause() {
super.onPause()
bridge.execute(JavaScriptActionHandler.pauseAllMedia())
if (avPlayer?.isPlaying == true) {
avPlayer?.stop()
updateProgressBar(false)
}
activeTimer.pause()
addTimeSpentReading(activeTimer.elapsedSec)
pageFragmentLoadState.updateCurrentBackStackItem()
app.commitTabState()
closePageScrollFunnel()
val time = if (app.tabList.size >= 1 && !pageFragmentLoadState.backStackEmpty()) System.currentTimeMillis() else 0
Prefs.pageLastShown = time
articleInteractionEvent?.pause()
}
override fun onResume() {
super.onResume()
initPageScrollFunnel()
activeTimer.resume()
val params = CoordinatorLayout.LayoutParams(1, 1)
binding.pageImageTransitionHolder.layoutParams = params
binding.pageImageTransitionHolder.visibility = View.GONE
binding.pageActionsTabLayout.update()
updateQuickActionsAndMenuOptions()
articleInteractionEvent?.resume()
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
// if the screen orientation changes, then re-layout the lead image container,
// but only if we've finished fetching the page.
if (!bridge.isLoading && !errorState) {
pageFragmentLoadState.onConfigurationChanged()
}
}
override fun onBackPressed(): Boolean {
articleInteractionEvent?.logBackClick()
if (sidePanelHandler.isVisible) {
sidePanelHandler.hide()
return true
}
if (pageFragmentLoadState.goBack()) {
return true
}
// if the current tab can no longer go back, then close the tab before exiting
if (app.tabList.isNotEmpty()) {
app.tabList.removeAt(app.tabList.size - 1)
app.commitTabState()
}
return false
}
override fun onToggleDimImages() {
ActivityCompat.recreate(requireActivity())
}
override fun onToggleReadingFocusMode() {
webView.scrollEventsEnabled = false
bottomBarHideHandler.enabled = Prefs.readingFocusModeEnabled
leadImagesHandler.refreshCallToActionVisibility()
page?.let {
bridge.execute(JavaScriptActionHandler.setUpEditButtons(!Prefs.readingFocusModeEnabled, !it.pageProperties.canEdit))
}
// We disable and then re-enable scroll events coming from the WebView, because toggling
// reading focus mode within the article could actually change the dimensions of the page,
// which will cause extraneous scroll events to be sent.
binding.root.postDelayed({
if (isAdded) {
webView.scrollEventsEnabled = true
}
}, 250)
}
override fun onCancelThemeChooser() {
if (scrolledUpForThemeChange) {
val animDuration = 250L
ObjectAnimator.ofInt(webView, "scrollY", webView.scrollY, 0)
.setDuration(animDuration)
.start()
}
}
override fun onEditingPrefsChanged() { }
override fun wiktionaryShowDialogForTerm(term: String) {
shareHandler.showWiktionaryDefinition(term)
}
override fun onExpirySelect(expiry: WatchlistExpiry) {
callback()?.onPageWatchlistExpirySelect(expiry)
dismissBottomSheet()
}
private fun shouldLoadFromBackstack(activity: Activity): Boolean {
return (activity.intent != null && (PageActivity.ACTION_RESUME_READING == activity.intent.action ||
activity.intent.hasExtra(Constants.INTENT_APP_SHORTCUT_CONTINUE_READING)))
}
private fun initWebViewListeners() {
webView.addOnUpOrCancelMotionEventListener {
// update our session, since it's possible for the user to remain on the page for
// a long time, and we wouldn't want the session to time out.
app.sessionFunnel.touchSession()
}
webView.addOnScrollChangeListener { oldScrollY, scrollY, isHumanScroll ->
pageScrollFunnel?.onPageScrolled(oldScrollY, scrollY, isHumanScroll)
}
webView.addOnContentHeightChangedListener(scrollTriggerListener)
webView.webViewClient = object : OkHttpWebViewClient() {
override val model get() = [email protected]
override val linkHandler get() = [email protected]
override fun onPageFinished(view: WebView, url: String) {
bridge.evaluateImmediate("(function() { return (typeof pcs !== 'undefined'); })();") { pcsExists ->
if (!isAdded) {
return@evaluateImmediate
}
// TODO: This is a bit of a hack: If PCS does not exist in the current page, then
// it's implied that this page was loaded via Mobile Web (e.g. the Main Page) and
// doesn't support PCS, meaning that we will never receive the `setup` event that
// tells us the page is finished loading. In such a case, we must infer that the
// page has now loaded and trigger the remaining logic ourselves.
if ("true" != pcsExists) {
onPageSetupEvent()
bridge.onMetadataReady()
bridge.onPcsReady()
bridge.execute(JavaScriptActionHandler.mobileWebChromeShim())
}
}
}
override fun onReceivedError(view: WebView, errorCode: Int, description: String, failingUrl: String) {
onPageLoadError(RuntimeException(description))
}
override fun onReceivedHttpError(view: WebView, request: WebResourceRequest, errorResponse: WebResourceResponse) {
if (!request.url.toString().contains(RestService.PAGE_HTML_ENDPOINT)) {
// If the request is anything except the main mobile-html content request, then
// don't worry about any errors and let the WebView deal with it.
return
}
onPageLoadError(HttpStatusException(errorResponse.statusCode, request.url.toString(), UriUtil.decodeURL(errorResponse.reasonPhrase)))
}
}
}
private fun onPageSetupEvent() {
if (!isAdded) {
return
}
updateProgressBar(false)
webView.visibility = View.VISIBLE
bridge.evaluate(JavaScriptActionHandler.getRevision()) { value ->
if (!isAdded || value == null || value == "null") {
return@evaluate
}
try {
revision = value.replace("\"", "").toLong()
} catch (e: Exception) {
L.e(e)
}
}
bridge.evaluate(JavaScriptActionHandler.getSections()) { value ->
if (!isAdded) {
return@evaluate
}
model.page?.let { page ->
sections = JsonUtil.decodeFromString(value)
sections?.let { sections ->
sections.add(0, Section(0, 0, model.title?.displayText.orEmpty(), model.title?.displayText.orEmpty(), ""))
page.sections = sections
}
sidePanelHandler.setupForNewPage(page)
sidePanelHandler.setEnabled(true)
}
}
bridge.evaluate(JavaScriptActionHandler.getProtection()) { value ->
if (!isAdded) {
return@evaluate
}
model.page?.let { page ->
page.pageProperties.protection = JsonUtil.decodeFromString(value)
}
}
}
private fun handleInternalLink(title: PageTitle) {
if (!isResumed) {
return
}
if (title.namespace() === Namespace.USER_TALK || title.namespace() === Namespace.TALK) {
startTalkTopicsActivity(title)
return
} else if (title.namespace() == Namespace.CATEGORY) {
startActivity(CategoryActivity.newIntent(requireActivity(), title))
return
}
dismissBottomSheet()
val historyEntry = HistoryEntry(title, HistoryEntry.SOURCE_INTERNAL_LINK)
if (title == model.title && !title.fragment.isNullOrEmpty()) {
scrollToSection(title.fragment!!)
return
}
model.title?.run {
historyEntry.referrer = uri
}
if (title.namespace() !== Namespace.MAIN || !Prefs.isLinkPreviewEnabled) {
loadPage(title, historyEntry)
} else {
callback()?.onPageShowLinkPreview(historyEntry)
}
}
private fun setCurrentTabAndReset(position: Int) {
// move the selected tab to the bottom of the list, and navigate to it!
// (but only if it's a different tab than the one currently in view!
if (position < app.tabList.size - 1) {
val tab = app.tabList.removeAt(position)
app.tabList.add(tab)
pageFragmentLoadState.setTab(tab)
}
if (app.tabCount > 0) {
app.tabList.last().squashBackstack()
pageFragmentLoadState.loadFromBackStack()
}
}
private fun selectedTabPosition(title: PageTitle): Int {
return app.tabList.firstOrNull { it.backStackPositionTitle != null &&
title == it.backStackPositionTitle }?.let { app.tabList.indexOf(it) } ?: -1
}
private fun openInNewTab(title: PageTitle, entry: HistoryEntry, position: Int, openFromExistingTab: Boolean = false) {
val selectedTabPosition = selectedTabPosition(title)
if (selectedTabPosition >= 0) {
if (openFromExistingTab) {
setCurrentTabAndReset(selectedTabPosition)
}
return
}
tabFunnel.logOpenInNew(app.tabList.size)
if (shouldCreateNewTab) {
// create a new tab
val tab = Tab()
val isForeground = position == foregroundTabPosition
// if the requested position is at the top, then make its backstack current
if (isForeground) {
pageFragmentLoadState.setTab(tab)
}
// put this tab in the requested position
app.tabList.add(position, tab)
trimTabCount()
// add the requested page to its backstack
tab.backStack.add(PageBackStackItem(title, entry))
if (!isForeground) {
loadIntoCache(title)
}
requireActivity().invalidateOptionsMenu()
} else {
pageFragmentLoadState.setTab(currentTab)
currentTab.backStack.add(PageBackStackItem(title, entry))
}
}
private fun closePageScrollFunnel() {
if (webView.contentHeight > 0) {
pageScrollFunnel?.setViewportHeight(webView.height)
pageScrollFunnel?.setPageHeight(webView.contentHeight)
pageScrollFunnel?.logDone()
}
pageScrollFunnel = null
}
private fun dismissBottomSheet() {
bottomSheetPresenter.dismiss(childFragmentManager)
callback()?.onPageDismissBottomSheet()
}
private fun updateProgressBar(visible: Boolean) {
callback()?.onPageUpdateProgressBar(visible)
}
private fun startLangLinksActivity() {
model.title?.let {
callback()?.onPageRequestLangLinks(it)
}
}
private fun trimTabCount() {
while (app.tabList.size > Constants.MAX_TABS) {
app.tabList.removeAt(0)
}
}
private fun addTimeSpentReading(timeSpentSec: Int) {
model.curEntry?.let {
lifecycleScope.launch(CoroutineExceptionHandler { _, throwable -> L.e(throwable) }) {
withContext(Dispatchers.IO) {
AppDatabase.instance.historyEntryDao().upsertWithTimeSpent(it, timeSpentSec)
}
}
}
}
private fun getContentTopOffsetParams(context: Context): LinearLayout.LayoutParams {
return LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, DimenUtil.getContentTopOffsetPx(context))
}
private fun disableActionTabs(caught: Throwable?) {
val offline = ThrowableUtil.isOffline(caught)
for (i in 0 until binding.pageActionsTabLayout.childCount) {
if (!offline) {
binding.pageActionsTabLayout.disableTab(i)
}
}
}
private fun startTalkTopicsActivity(title: PageTitle, stripUrlFragment: Boolean = false) {
val talkTitle = title.copy()
if (stripUrlFragment) {
talkTitle.fragment = null
}
startActivity(TalkTopicsActivity.newIntent(requireActivity(), talkTitle, InvokeSource.PAGE_ACTIVITY))
}
private fun startGalleryActivity(fileName: String) {
if (app.isOnline) {
bridge.evaluate(JavaScriptActionHandler.getElementAtPosition(DimenUtil.roundedPxToDp(webView.lastTouchX),
DimenUtil.roundedPxToDp(webView.lastTouchY))) { s ->
if (!isAdded) {
return@evaluate
}
var options: ActivityOptionsCompat? = null
val hitInfo: JavaScriptActionHandler.ImageHitInfo? = JsonUtil.decodeFromString(s)
hitInfo?.let {
val params = CoordinatorLayout.LayoutParams(
DimenUtil.roundedDpToPx(it.width),
DimenUtil.roundedDpToPx(it.height)
)
params.topMargin = DimenUtil.roundedDpToPx(it.top)
params.leftMargin = DimenUtil.roundedDpToPx(it.left)
binding.pageImageTransitionHolder.layoutParams = params
binding.pageImageTransitionHolder.visibility = View.VISIBLE
ViewUtil.loadImage(binding.pageImageTransitionHolder, it.src)
GalleryActivity.setTransitionInfo(it)
options = ActivityOptionsCompat.makeSceneTransitionAnimation(requireActivity(),
binding.pageImageTransitionHolder, getString(R.string.transition_page_gallery))
}
webView.post {
if (!isAdded) {
return@post
}
model.title?.let {
callback()?.onPageRequestGallery(it, fileName, it.wikiSite, revision, GalleryFunnel.SOURCE_NON_LEAD_IMAGE, options)
}
}
}
} else {
val snackbar = FeedbackUtil.makeSnackbar(requireActivity(), getString(R.string.gallery_not_available_offline_snackbar))
snackbar.setAction(R.string.gallery_not_available_offline_snackbar_dismiss) { snackbar.dismiss() }
snackbar.show()
}
}
private fun hidePageContent() {
leadImagesHandler.hide()
bridge.loadBlankPage()
webView.visibility = View.INVISIBLE
}
private fun showWatchlistSnackbar(expiry: WatchlistExpiry, watch: Watch) {
title?.let {
model.isWatched = watch.watched
model.hasWatchlistExpiry = expiry !== WatchlistExpiry.NEVER
if (watch.unwatched) {
FeedbackUtil.showMessage(this, getString(R.string.watchlist_page_removed_from_watchlist_snackbar, it.displayText))
} else if (watch.watched) {
val snackbar = FeedbackUtil.makeSnackbar(requireActivity(), getString(R.string.watchlist_page_add_to_watchlist_snackbar,
it.displayText, getString(expiry.stringId)))
if (!watchlistExpiryChanged) {
snackbar.setAction(R.string.watchlist_page_add_to_watchlist_snackbar_action) {
watchlistExpiryChanged = true
bottomSheetPresenter.show(childFragmentManager, WatchlistExpiryDialog.newInstance(expiry))
}
}
snackbar.show()
}
}
}
private fun maybeShowAnnouncement() {
title?.let {
if (Prefs.hasVisitedArticlePage) {
disposables.add(ServiceFactory.getRest(it.wikiSite).announcements
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ list ->
val country = GeoUtil.geoIPCountry
val now = Date()
for (announcement in list.items) {
if (AnnouncementClient.shouldShow(announcement, country, now) &&
announcement.placement == Announcement.PLACEMENT_ARTICLE &&
!Prefs.announcementShownDialogs.contains(announcement.id)) {
val dialog = AnnouncementDialog(requireActivity(), announcement)
dialog.setCancelable(false)
dialog.show()
break
}
}
}) { caught -> L.d(caught) })
}
}
}
private fun showFindReferenceInPage(referenceAnchor: String,
backLinksList: List<String?>,
referenceText: String) {
model.page?.run {
startSupportActionMode(object : ActionMode.Callback {
override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean {
val menuItem = menu.add(R.string.menu_page_find_in_page)
MenuItemCompat.setActionProvider(menuItem, FindReferenceInPageActionProvider(requireContext(), referenceAnchor, referenceText, backLinksList))
menuItem.expandActionView()
return true
}
override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean {
mode.tag = "actionModeFindReferenceInPage"
return false
}
override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
return false
}
override fun onDestroyActionMode(mode: ActionMode) {}
})
}
}
private fun initPageScrollFunnel() {
model.page?.run {
pageScrollFunnel = PageScrollFunnel(app, pageProperties.pageId)
}
}
private fun setupMessageHandlers() {
linkHandler = object : LinkHandler(requireActivity()) {
override fun onPageLinkClicked(anchor: String, linkText: String) {
dismissBottomSheet()
bridge.execute(JavaScriptActionHandler.prepareToScrollTo(anchor, true))
}
override fun onInternalLinkClicked(title: PageTitle) {
handleInternalLink(title)
}
override fun onMediaLinkClicked(title: PageTitle) {
startGalleryActivity(title.prefixedText)
}
override fun onDiffLinkClicked(title: PageTitle, revisionId: Long) {
startActivity(ArticleEditDetailsActivity.newIntent(requireContext(), title, revisionId))
}
// ignore
override var wikiSite: WikiSite
get() = model.title?.run { wikiSite } ?: WikiSite.forLanguageCode("en")
set(wikiSite) {
// ignore
}
}
bridge.addListener("link", linkHandler)
bridge.addListener("setup") { _, _ -> onPageSetupEvent() }
bridge.addListener("final_setup") { _, _ ->
if (!isAdded) {
return@addListener
}
bridge.onPcsReady()
articleInteractionEvent?.logLoaded()
callback()?.onPageLoadComplete()
// do we have a URL fragment to scroll to?
model.title?.let { prevTitle ->
if (!prevTitle.fragment.isNullOrEmpty() && scrollTriggerListener.stagedScrollY == 0) {
val scrollDelay = 100
webView.postDelayed({
if (!isAdded) {
return@postDelayed
}
model.title?.let {
if (!it.fragment.isNullOrEmpty()) {
scrollToSection(it.fragment!!)
}
}
}, scrollDelay.toLong())
}
}
}
bridge.addListener("reference") { _, messagePayload ->
if (!isAdded) {
return@addListener
}
references = JsonUtil.decodeFromString(messagePayload.toString())
references?.let {
if (it.referencesGroup.isNotEmpty()) {
showBottomSheet(ReferenceDialog())
}
}
}
bridge.addListener("back_link") { _, messagePayload ->
messagePayload?.let { payload ->
val backLinks = payload["backLinks"]?.jsonArray
if (backLinks != null && !backLinks.isEmpty()) {
val backLinksList = backLinks.map { it.jsonObject["id"]?.jsonPrimitive?.content }
showFindReferenceInPage(payload["referenceId"]?.jsonPrimitive?.content.orEmpty(), backLinksList, payload["referenceText"]?.jsonPrimitive?.content.orEmpty())
}
}
}
bridge.addListener("scroll_to_anchor") { _, messagePayload ->
messagePayload?.let { payload ->
payload["rect"]?.jsonObject?.let {
val diffY = if (it.containsKey("y")) DimenUtil.roundedDpToPx(it["y"]!!.jsonPrimitive.float) else DimenUtil.roundedDpToPx(it["top"]!!.jsonPrimitive.float)
val offsetFraction = 3
webView.scrollY = webView.scrollY + diffY - webView.height / offsetFraction
}
}
}
bridge.addListener("image") { _, messagePayload ->
messagePayload?.let { payload ->
linkHandler.onUrlClick(UriUtil.decodeURL(payload["href"]?.jsonPrimitive?.content.orEmpty()), payload["title"]?.jsonPrimitive?.content, "")
}
}
bridge.addListener("media") { _, messagePayload ->
messagePayload?.let { payload ->
linkHandler.onUrlClick(UriUtil.decodeURL(payload["href"]?.jsonPrimitive?.content.orEmpty()), payload["title"]?.jsonPrimitive?.content, "")
}
}
bridge.addListener("pronunciation") { _, messagePayload ->
messagePayload?.let { payload ->
if (avPlayer == null) {
avPlayer = AvPlayer()
}
if (avCallback == null) {
avCallback = AvCallback()
}
if (!avPlayer!!.isPlaying && payload.containsKey("url")) {
updateProgressBar(true)
avPlayer!!.play(UriUtil.resolveProtocolRelativeUrl(payload["url"]?.jsonPrimitive?.content.orEmpty()), avCallback!!)
} else {
updateProgressBar(false)
avPlayer!!.stop()
}
}
}
bridge.addListener("footer_item") { _, messagePayload ->
messagePayload?.let { payload ->
when (payload["itemType"]?.jsonPrimitive?.content) {
"talkPage" -> model.title?.run {
articleInteractionEvent?.logTalkPageArticleClick()
startTalkTopicsActivity(this, true)
}
"languages" -> startLangLinksActivity()
"lastEdited" -> {
model.title?.run {
articleInteractionEvent?.logEditHistoryArticleClick()
startActivity(EditHistoryListActivity.newIntent(requireContext(), this))
}
}
"coordinate" -> {
model.page?.let { page ->
page.pageProperties.geo?.let { geo ->
GeoUtil.sendGeoIntent(requireActivity(), geo, page.displayTitle)
}
}
}
"disambiguation" -> {
// TODO
// messagePayload contains an array of URLs called "payload".
}
}
}
}
bridge.addListener("read_more_titles_retrieved") { _, _ -> }
bridge.addListener("view_license") { _, _ ->
UriUtil.visitInExternalBrowser(requireContext(), Uri.parse(getString(R.string.cc_by_sa_3_url)))
}
bridge.addListener("view_in_browser") { _, _ ->
model.title?.let {
UriUtil.visitInExternalBrowser(requireContext(), Uri.parse(it.uri))
}
}
}
fun reloadFromBackstack() {
pageFragmentLoadState.setTab(currentTab)
if (!pageFragmentLoadState.backStackEmpty()) {
pageFragmentLoadState.loadFromBackStack()
} else {
callback()?.onPageLoadMainPageInForegroundTab()
}
}
fun updateInsets(insets: Insets) {
val swipeOffset = DimenUtil.getContentTopOffsetPx(requireActivity()) + insets.top + REFRESH_SPINNER_ADDITIONAL_OFFSET
binding.pageRefreshContainer.setProgressViewOffset(false, -swipeOffset, swipeOffset)
}
fun onPageMetadataLoaded() {
updateQuickActionsAndMenuOptions()
if (model.page == null) {
return
}
model.page?.run {
articleInteractionEvent = ArticleInteractionEvent(model.title?.wikiSite?.dbName()!!, pageProperties.pageId)
}
editHandler.setPage(model.page)
binding.pageRefreshContainer.isEnabled = true
binding.pageRefreshContainer.isRefreshing = false
requireActivity().invalidateOptionsMenu()
initPageScrollFunnel()
model.readingListPage?.let { page ->
model.title?.let { title ->
disposables.add(Completable.fromAction {
page.thumbUrl.equals(title.thumbUrl, true)
if (!page.thumbUrl.equals(title.thumbUrl, true) || !page.description.equals(title.description, true)) {
AppDatabase.instance.readingListPageDao().updateMetadataByTitle(page, title.description, title.thumbUrl)
}
}.subscribeOn(Schedulers.io()).subscribe())
}
}
if (!errorState) {
editHandler.setPage(model.page)
webView.visibility = View.VISIBLE
}
maybeShowAnnouncement()
bridge.onMetadataReady()
// Explicitly set the top margin (even though it might have already been set in the setup
// handler), since the page metadata might have altered the lead image display state.
bridge.execute(JavaScriptActionHandler.setTopMargin(leadImagesHandler.topMargin))
bridge.execute(JavaScriptActionHandler.setFooter(model))
}
fun openInNewBackgroundTab(title: PageTitle, entry: HistoryEntry, openFromExistingTab: Boolean = false) {
if (app.tabCount == 0) {
openInNewTab(title, entry, foregroundTabPosition)
pageFragmentLoadState.loadFromBackStack()
} else {
openInNewTab(title, entry, backgroundTabPosition, openFromExistingTab)
(requireActivity() as PageActivity).animateTabsButton()
}
}
fun openInNewForegroundTab(title: PageTitle, entry: HistoryEntry) {
openInNewTab(title, entry, foregroundTabPosition)
pageFragmentLoadState.loadFromBackStack()
}
fun openFromExistingTab(title: PageTitle, entry: HistoryEntry) {
val selectedTabPosition = selectedTabPosition(title)
if (selectedTabPosition == -1) {
loadPage(title, entry, pushBackStack = true, squashBackstack = false)
return
}
setCurrentTabAndReset(selectedTabPosition)
}
fun loadPage(title: PageTitle, entry: HistoryEntry, pushBackStack: Boolean, squashBackstack: Boolean, isRefresh: Boolean = false) {
// is the new title the same as what's already being displayed?
if (currentTab.backStack.isNotEmpty() &&
title == currentTab.backStack[currentTab.backStackPosition].title) {
if (model.page == null || isRefresh) {
pageFragmentLoadState.loadFromBackStack(isRefresh)
} else if (!title.fragment.isNullOrEmpty()) {
scrollToSection(title.fragment!!)
}
return
}
if (squashBackstack) {
if (app.tabCount > 0) {
app.tabList.last().clearBackstack()
}
}
loadPage(title, entry, pushBackStack, 0, isRefresh)
}
fun loadPage(title: PageTitle, entry: HistoryEntry, pushBackStack: Boolean, stagedScrollY: Int, isRefresh: Boolean = false) {
// clear the title in case the previous page load had failed.
clearActivityActionBarTitle()
if (bottomSheetPresenter.getCurrentBottomSheet(childFragmentManager) !is ThemeChooserDialog) {
dismissBottomSheet()
}
if (AccountUtil.isLoggedIn) {
// explicitly check notifications for the current user
PollNotificationWorker.schedulePollNotificationJob(requireContext())
}
// update the time spent reading of the current page, before loading the new one
addTimeSpentReading(activeTimer.elapsedSec)
activeTimer.reset()
callback()?.onPageSetToolbarElevationEnabled(false)
sidePanelHandler.setEnabled(false)
errorState = false
binding.pageError.visibility = View.GONE
watchlistExpiryChanged = false
model.title = title
model.curEntry = entry
model.page = null
model.readingListPage = null
model.forceNetwork = isRefresh
webView.visibility = View.VISIBLE
binding.pageActionsTabLayout.visibility = View.VISIBLE
binding.pageActionsTabLayout.enableAllTabs()
updateProgressBar(true)
pageRefreshed = isRefresh
references = null
revision = 0
closePageScrollFunnel()
pageFragmentLoadState.load(pushBackStack)
scrollTriggerListener.stagedScrollY = stagedScrollY
}
fun updateFontSize() {
webView.settings.defaultFontSize = app.getFontSize(requireActivity().window).toInt()
}
fun updateQuickActionsAndMenuOptions() {
if (!isAdded) {
return
}
binding.pageActionsTabLayout.forEach { it as MaterialTextView
val pageActionItem = PageActionItem.find(it.id)
val enabled = model.page != null && (!model.shouldLoadAsMobileWeb || (model.shouldLoadAsMobileWeb && pageActionItem.isAvailableOnMobileWeb))
it.isEnabled = enabled
it.alpha = if (enabled) 1f else 0.5f
if (pageActionItem == PageActionItem.SAVE) {
it.setCompoundDrawablesWithIntrinsicBounds(0, PageActionItem.readingListIcon(model.isInReadingList), 0, 0)
} else if (pageActionItem == PageActionItem.ADD_TO_WATCHLIST) {
it.setText(if (model.isWatched) R.string.menu_page_unwatch else R.string.menu_page_watch)
it.setCompoundDrawablesWithIntrinsicBounds(0, PageActionItem.watchlistIcon(model.isWatched, model.hasWatchlistExpiry), 0, 0)
it.isEnabled = enabled && AccountUtil.isLoggedIn
it.alpha = if (it.isEnabled) 1f else 0.5f
}
}
sidePanelHandler.setEnabled(false)
requireActivity().invalidateOptionsMenu()
}
fun updateBookmarkAndMenuOptionsFromDao() {
title?.let {
disposables.add(
Completable.fromAction { model.readingListPage = AppDatabase.instance.readingListPageDao().findPageInAnyList(it) }
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doAfterTerminate {
updateQuickActionsAndMenuOptions()
requireActivity().invalidateOptionsMenu()
}
.subscribe())
}
}
fun onActionModeShown(mode: ActionMode) {
// make sure we have a page loaded, since shareHandler makes references to it.
model.page?.run {
shareHandler.onTextSelected(mode)
}
}
fun onRequestEditSection(sectionId: Int, sectionAnchor: String?, title: PageTitle, highlightText: String?) {
callback()?.onPageRequestEditSection(sectionId, sectionAnchor, title, highlightText)
}
fun sharePageLink() {
model.title?.let {
ShareUtil.shareText(requireActivity(), it)
}
}
fun showFindInPage() {
model.title?.let { title ->
bridge.evaluate(JavaScriptActionHandler.expandCollapsedTables(true)) {
if (!isAdded) {
return@evaluate
}
val funnel = FindInPageFunnel(app, title.wikiSite, model.page?.pageProperties?.pageId ?: -1)
val articleFindInPageInteractionEvent = ArticleFindInPageInteractionEvent(title.wikiSite.dbName(), model.page?.pageProperties?.pageId ?: -1)
val findInPageActionProvider = FindInWebPageActionProvider(this, funnel, articleFindInPageInteractionEvent)
startSupportActionMode(object : ActionMode.Callback {
override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean {
val menuItem = menu.add(R.string.menu_page_find_in_page)
menuItem.actionProvider = findInPageActionProvider
menuItem.expandActionView()
callback()?.onPageSetToolbarElevationEnabled(false)
return true
}
override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean {
mode.tag = "actionModeFindInPage"
return false
}
override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
return false
}
override fun onDestroyActionMode(mode: ActionMode) {
if (!isAdded) {
return
}
funnel.pageHeight = webView.contentHeight
articleFindInPageInteractionEvent.pageHeight = webView.contentHeight
funnel.logDone()
articleFindInPageInteractionEvent.logDone()
webView.clearMatches()
callback()?.onPageHideSoftKeyboard()
callback()?.onPageSetToolbarElevationEnabled(true)
}
})
}
}
}
private fun scrollToSection(sectionAnchor: String) {
if (!isAdded) {
return
}
bridge.execute(JavaScriptActionHandler.prepareToScrollTo(sectionAnchor, false))
}
fun onPageLoadError(caught: Throwable) {
if (!isAdded) {
return
}
title?.let {
updateProgressBar(false)
binding.pageRefreshContainer.isRefreshing = false
if (pageRefreshed) {
pageRefreshed = false
}
hidePageContent()
bridge.onMetadataReady()
if (binding.pageError.visibility != View.VISIBLE) {
binding.pageError.setError(caught, it)
}
binding.pageError.visibility = View.VISIBLE
binding.pageError.contentTopOffset.layoutParams = getContentTopOffsetParams(requireContext())
binding.pageError.contentTopOffset.visibility = View.VISIBLE
binding.pageError.tabLayoutOffset.layoutParams = tabLayoutOffsetParams
binding.pageError.tabLayoutOffset.visibility = View.VISIBLE
disableActionTabs(caught)
binding.pageRefreshContainer.isEnabled = !ThrowableUtil.is404(caught)
errorState = true
callback()?.onPageLoadError(it)
}
}
fun refreshPage(stagedScrollY: Int = 0) {
if (bridge.isLoading) {
binding.pageRefreshContainer.isRefreshing = false
return
}
model.title?.let { title ->
model.curEntry?.let { entry ->
binding.pageError.visibility = View.GONE
binding.pageActionsTabLayout.enableAllTabs()
errorState = false
model.curEntry = HistoryEntry(title, HistoryEntry.SOURCE_HISTORY)
loadPage(title, entry, false, stagedScrollY, app.isOnline)
}
}
}
private fun clearActivityActionBarTitle() {
val currentActivity = requireActivity()
if (currentActivity is PageActivity) {
currentActivity.clearActionBarTitle()
}
}
fun verifyBeforeEditingDescription(text: String?, invokeSource: InvokeSource) {
page?.let {
if (!AccountUtil.isLoggedIn && Prefs.totalAnonDescriptionsEdited >= resources.getInteger(R.integer.description_max_anon_edits)) {
AlertDialog.Builder(requireActivity())
.setMessage(R.string.description_edit_anon_limit)
.setPositiveButton(R.string.page_editing_login) { _, _ ->
startActivity(LoginActivity.newIntent(requireContext(), LoginFunnel.SOURCE_EDIT))
}
.setNegativeButton(R.string.description_edit_login_cancel_button_text, null)
.show()
} else {
startDescriptionEditActivity(text, invokeSource)
}
}
}
fun startDescriptionEditActivity(text: String?, invokeSource: InvokeSource) {
if (Prefs.isDescriptionEditTutorialEnabled) {
callback()?.onPageRequestEditDescriptionTutorial(text, invokeSource)
} else {
title?.run {
val sourceSummary = PageSummaryForEdit(prefixedText, wikiSite.languageCode, this, displayText, description, thumbUrl)
callback()?.onPageRequestEditDescription(text, this, sourceSummary, null,
DescriptionEditActivity.Action.ADD_DESCRIPTION, invokeSource)
}
}
}
fun goForward() {
pageFragmentLoadState.goForward()
}
fun showBottomSheet(dialog: BottomSheetDialogFragment) {
bottomSheetPresenter.show(childFragmentManager, dialog)
}
fun loadPage(title: PageTitle, entry: HistoryEntry) {
callback()?.onPageLoadPage(title, entry)
}
fun startSupportActionMode(actionModeCallback: ActionMode.Callback) {
callback()?.onPageStartSupportActionMode(actionModeCallback)
}
fun addToReadingList(title: PageTitle, source: InvokeSource, addToDefault: Boolean) {
if (addToDefault) {
var finalPageTitle = title
// Make sure handle redirected title before saving into database
disposables.add(ServiceFactory.getRest(title.wikiSite).getSummary(null, title.prefixedText)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doAfterTerminate {
ReadingListBehaviorsUtil.addToDefaultList(requireActivity(), finalPageTitle, source) { readingListId ->
moveToReadingList(readingListId, finalPageTitle, source, false) }
}
.subscribe({
finalPageTitle = it.getPageTitle(title.wikiSite)
}, {
L.e(it)
}))
} else {
callback()?.onPageAddToReadingList(title, source)
}
}
fun moveToReadingList(sourceReadingListId: Long, title: PageTitle, source: InvokeSource, showDefaultList: Boolean) {
callback()?.onPageMoveToReadingList(sourceReadingListId, title, source, showDefaultList)
}
fun callback(): Callback? {
return getCallback(this, Callback::class.java)
}
fun updateWatchlist(expiry: WatchlistExpiry, unwatch: Boolean) {
title?.let {
disposables.add(ServiceFactory.get(it.wikiSite).watchToken
.subscribeOn(Schedulers.io())
.flatMap { response ->
val watchToken = response.query?.watchToken()
if (watchToken.isNullOrEmpty()) {
throw RuntimeException("Received empty watch token.")
}
ServiceFactory.get(it.wikiSite).postWatch(if (unwatch) 1 else null, null, it.prefixedText, expiry.expiry, watchToken)
}
.observeOn(AndroidSchedulers.mainThread())
.doAfterTerminate { updateQuickActionsAndMenuOptions() }
.subscribe({ watchPostResponse ->
watchPostResponse.getFirst()?.let { watch ->
// Reset to make the "Change" button visible.
if (watchlistExpiryChanged && unwatch) {
watchlistExpiryChanged = false
}
if (unwatch) {
watchlistFunnel.logRemoveSuccess()
} else {
watchlistFunnel.logAddSuccess()
}
showWatchlistSnackbar(expiry, watch)
}
}) { caught -> L.d(caught) })
}
}
fun showAnonNotification() {
(requireActivity() as PageActivity).onAnonNotification()
}
fun showOverflowMenu(anchor: View) {
PageActionOverflowView(requireContext()).show(anchor, pageActionItemCallback, currentTab, model)
}
fun goToMainTab() {
startActivity(MainActivity.newIntent(requireContext())
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
.putExtra(Constants.INTENT_RETURN_TO_MAIN, true)
.putExtra(Constants.INTENT_EXTRA_GO_TO_MAIN_TAB, NavTab.EXPLORE.code()))
requireActivity().finish()
}
private inner class AvCallback : AvPlayer.Callback {
override fun onSuccess() {
avPlayer?.stop()
updateProgressBar(false)
}
override fun onError(code: Int, extra: Int) {
if (avPlayer?.isPlaying == true) {
avPlayer?.stop()
}
FeedbackUtil.showMessage(this@PageFragment, R.string.media_playback_error)
updateProgressBar(false)
}
}
private inner class WebViewScrollTriggerListener : ObservableWebView.OnContentHeightChangedListener {
var stagedScrollY = 0
override fun onContentHeightChanged(contentHeight: Int) {
if (stagedScrollY > 0 && contentHeight * DimenUtil.densityScalar - webView.height > stagedScrollY) {
webView.scrollY = stagedScrollY
stagedScrollY = 0
}
}
}
private inner class FindReferenceInPageActionProvider constructor(context: Context,
private val referenceAnchor: String,
private val referenceText: String,
private val backLinksList: List<String?>) : ActionProvider(context), View.OnClickListener {
private val binding = GroupFindReferencesInPageBinding.inflate(LayoutInflater.from(context), null, false)
private var currentPos = 0
override fun onCreateActionView(): View {
binding.findInPagePrev.setOnClickListener(this)
binding.findInPageNext.setOnClickListener(this)
binding.referenceLabel.setOnClickListener(this)
binding.closeButton.setOnClickListener(this)
binding.referenceLabel.text = getString(R.string.reference_list_title).plus(" $referenceText")
if (backLinksList.isNotEmpty()) {
scrollTo(0)
}
return binding.root
}
override fun overridesItemVisibility(): Boolean {
return true
}
override fun onClick(v: View) {
when (v) {
binding.findInPagePrev -> {
if (backLinksList.isNotEmpty()) {
currentPos = if (--currentPos < 0) backLinksList.size - 1 else currentPos
scrollTo(currentPos)
}
}
binding.findInPageNext -> {
if (backLinksList.isNotEmpty()) {
currentPos = if (++currentPos >= backLinksList.size) 0 else currentPos
scrollTo(currentPos)
}
}
binding.referenceLabel -> {
bridge.execute(JavaScriptActionHandler.scrollToAnchor(referenceAnchor))
callback()?.onPageCloseActionMode()
}
binding.closeButton -> callback()?.onPageCloseActionMode()
}
}
private fun scrollTo(position: Int) {
backLinksList[position]?.let {
binding.referenceCount.text = getString(R.string.find_in_page_result, position + 1,
if (backLinksList.isEmpty()) 0 else backLinksList.size)
bridge.execute(JavaScriptActionHandler.prepareToScrollTo(it, true))
}
}
}
inner class PageActionItemCallback : PageActionItem.Callback {
override fun onSaveSelected() {
if (model.isInReadingList) {
val anchor = if (Prefs.customizeToolbarOrder.contains(PageActionItem.SAVE.id))
binding.pageActionsTabLayout else (requireActivity() as PageActivity).getOverflowMenu()
LongPressMenu(anchor, object : LongPressMenu.Callback {
override fun onOpenLink(entry: HistoryEntry) { }
override fun onOpenInNewTab(entry: HistoryEntry) { }
override fun onAddRequest(entry: HistoryEntry, addToDefault: Boolean) {
title?.run {
addToReadingList(this, InvokeSource.BOOKMARK_BUTTON, addToDefault)
}
}
override fun onMoveRequest(page: ReadingListPage?, entry: HistoryEntry) {
page?.let { readingListPage ->
title?.run {
moveToReadingList(readingListPage.listId, this, InvokeSource.BOOKMARK_BUTTON, true)
}
}
}
}).show(historyEntry)
} else {
title?.run {
addToReadingList(this, InvokeSource.BOOKMARK_BUTTON, true)
}
}
articleInteractionEvent?.logSaveClick()
}
override fun onLanguageSelected() {
startLangLinksActivity()
articleInteractionEvent?.logLanguageClick()
}
override fun onFindInArticleSelected() {
showFindInPage()
articleInteractionEvent?.logFindInArticleClick()
}
override fun onThemeSelected() {
articleInteractionEvent?.logThemeClick()
// If we're looking at the top of the article, then scroll down a bit so that at least
// some of the text is shown.
if (webView.scrollY < DimenUtil.leadImageHeightForDevice(requireActivity())) {
scrolledUpForThemeChange = true
val animDuration = 250
val anim = ObjectAnimator.ofInt(webView, "scrollY", webView.scrollY, DimenUtil.leadImageHeightForDevice(requireActivity()))
anim.setDuration(animDuration.toLong()).doOnEnd {
showBottomSheet(ThemeChooserDialog.newInstance(InvokeSource.PAGE_ACTION_TAB))
}
anim.start()
} else {
scrolledUpForThemeChange = false
showBottomSheet(ThemeChooserDialog.newInstance(InvokeSource.PAGE_ACTION_TAB))
}
}
override fun onContentsSelected() {
sidePanelHandler.showToC()
articleInteractionEvent?.logContentsClick()
}
override fun onShareSelected() {
sharePageLink()
articleInteractionEvent?.logShareClick()
}
override fun onAddToWatchlistSelected() {
if (model.isWatched) {
watchlistFunnel.logRemoveArticle()
articleInteractionEvent?.logUnWatchClick()
} else {
watchlistFunnel.logAddArticle()
articleInteractionEvent?.logWatchClick()
}
updateWatchlist(WatchlistExpiry.NEVER, model.isWatched)
}
override fun onViewTalkPageSelected() {
title?.let {
startTalkTopicsActivity(it, true)
}
articleInteractionEvent?.logTalkPageClick()
}
override fun onViewEditHistorySelected() {
title?.run {
startActivity(EditHistoryListActivity.newIntent(requireContext(), this))
}
articleInteractionEvent?.logEditHistoryClick()
}
override fun onNewTabSelected() {
startActivity(PageActivity.newIntentForNewTab(requireContext()))
articleInteractionEvent?.logNewTabClick()
}
override fun onExploreSelected() {
goToMainTab()
articleInteractionEvent?.logExploreClick()
}
override fun onCategoriesSelected() {
title?.let {
bottomSheetPresenter.show(childFragmentManager, CategoryDialog.newInstance(it))
}
articleInteractionEvent?.logCategoriesClick()
}
override fun onEditArticleSelected() {
editHandler.startEditingArticle()
articleInteractionEvent?.logEditArticleClick()
}
override fun forwardClick() {
goForward()
articleInteractionEvent?.logForwardClick()
}
}
companion object {
private const val ARG_THEME_CHANGE_SCROLLED = "themeChangeScrolled"
private val REFRESH_SPINNER_ADDITIONAL_OFFSET = (16 * DimenUtil.densityScalar).toInt()
}
}
|
apache-2.0
|
f17d7143d2e98fea6afaee25afb64c8a
| 42.2 | 176 | 0.619244 | 5.36061 | false | false | false | false |
bl-lia/kktAPK
|
app/src/main/kotlin/com/bl_lia/kirakiratter/presentation/adapter/notification/NotificationItemViewHolder.kt
|
1
|
5475
|
package com.bl_lia.kirakiratter.presentation.adapter.notification
import android.content.Context
import android.support.annotation.LayoutRes
import android.support.v4.content.ContextCompat
import android.support.v7.widget.RecyclerView
import android.text.method.LinkMovementMethod
import android.view.View
import android.widget.ImageView
import com.bl_lia.kirakiratter.R
import com.bl_lia.kirakiratter.domain.entity.Account
import com.bl_lia.kirakiratter.domain.entity.Notification
import com.bl_lia.kirakiratter.domain.entity.Status
import com.bl_lia.kirakiratter.domain.extension.asHtml
import com.bl_lia.kirakiratter.presentation.transform.AvatarTransformation
import com.squareup.picasso.Picasso
import io.reactivex.Observable
import kotlinx.android.synthetic.main.list_item_notification.view.*
class NotificationItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
companion object {
@LayoutRes
val LAYOUT = R.layout.list_item_notification
fun newInstance(parent: View): NotificationItemViewHolder = NotificationItemViewHolder(parent)
}
val onClickAccount = Observable.create<Pair<Account, ImageView>> { subscriber ->
itemView.image_avatar.setOnClickListener {
subscriber.onNext(Pair<Account, ImageView>(notification.status?.account!!, itemView.image_avatar))
}
}
val onClickReply = Observable.create<Status> { subscriber ->
itemView.button_reply.setOnClickListener {
subscriber.onNext(notification.status!!)
}
}
val onClickReblog = Observable.create<Notification> { subscriber ->
itemView.button_reblog.setOnClickListener {
subscriber.onNext(notification)
}
}
val onClickFavourite = Observable.create<Notification> { subscriber ->
itemView.button_favourite.setOnClickListener {
subscriber.onNext(notification)
}
}
val onClickTranslate = Observable.create<Notification> { subscriber ->
itemView.button_translate.setOnClickListener {
subscriber.onNext(notification)
}
}
private lateinit var notification: Notification
fun bind(notification: Notification) {
this.notification = notification
when (notification.type) {
"reblog" -> {
itemView.image_type.setBackgroundResource(R.drawable.ic_reblog_reblog)
itemView.layout_action.visibility = View.GONE
}
"favourite" -> {
itemView.image_type.setBackgroundResource(R.drawable.ic_star_favourite)
itemView.layout_action.visibility = View.GONE
}
"follow" -> {
itemView.image_type.setBackgroundResource(R.drawable.ic_reblog_reblog)
itemView.layout_action.visibility = View.GONE
}
"mention" -> {
itemView.image_type.setBackgroundResource(R.drawable.ic_reply_unreply)
itemView.layout_action.visibility = View.VISIBLE
val target = notification.status?.reblog ?: notification.status
itemView.button_reblog.background =
if (target?.reblogged ?: false) {
ContextCompat.getDrawable(itemView.context, R.drawable.ic_reblog_reblog)
} else {
ContextCompat.getDrawable(itemView.context, R.drawable.ic_reblog_unreblog)
}
itemView.button_favourite.background =
if (target?.favourited ?: false) {
ContextCompat.getDrawable(itemView.context, R.drawable.ic_star_favourite)
} else {
ContextCompat.getDrawable(itemView.context, R.drawable.ic_star_unfavourite)
}
}
}
when (notification.type) {
"reblog",
"favourite",
"follow" -> {
itemView.text_body.text = if (notification.status?.content?.header.isNullOrEmpty()) {
notification.status?.content?.body?.asHtml()?.trim()
} else {
notification.status?.content?.header?.asHtml()?.trim().toString() + "\n" + notification.status?.content?.body?.asHtml()?.trim().toString()
}
notification.status?.account?.loadAvater(itemView.context, itemView.image_avatar)
}
"mention" -> {
val target = notification.status?.reblog ?: notification.status
itemView.text_body.text = if (target?.content?.translatedText.isNullOrEmpty()) {
target?.content?.body?.asHtml()?.trim()
} else {
target?.content?.translatedText
}
notification.account?.loadAvater(itemView.context, itemView.image_avatar)
}
}
itemView.text_body.movementMethod = LinkMovementMethod.getInstance()
itemView.text_notify.text = notification.notifiedMessage(itemView.context)
itemView.text_notify.movementMethod = LinkMovementMethod.getInstance()
}
private fun Account.loadAvater(context: Context, imageView: ImageView) {
Picasso.with(context)
.load(avatar)
.transform(AvatarTransformation(context, R.color.content_border))
.into(imageView)
}
}
|
mit
|
c7c935f29977fd33ecf092875163fe86
| 39.555556 | 158 | 0.628676 | 5.018332 | false | false | false | false |
stripe/stripe-android
|
payments-core/src/main/java/com/stripe/android/cards/DefaultCardAccountRangeRepositoryFactory.kt
|
1
|
3542
|
package com.stripe.android.cards
import android.content.Context
import androidx.annotation.RestrictTo
import com.stripe.android.PaymentConfiguration
import com.stripe.android.core.networking.AnalyticsRequestExecutor
import com.stripe.android.core.networking.ApiRequest
import com.stripe.android.core.networking.DefaultAnalyticsRequestExecutor
import com.stripe.android.model.AccountRange
import com.stripe.android.networking.PaymentAnalyticsEvent
import com.stripe.android.networking.PaymentAnalyticsRequestFactory
import com.stripe.android.networking.StripeApiRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOf
/**
* A [CardAccountRangeRepository.Factory] that returns a [DefaultCardAccountRangeRepositoryFactory].
*
* Will throw an exception if [PaymentConfiguration] has not been instantiated.
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
class DefaultCardAccountRangeRepositoryFactory(
context: Context,
private val analyticsRequestExecutor: AnalyticsRequestExecutor
) : CardAccountRangeRepository.Factory {
private val appContext = context.applicationContext
constructor(context: Context) : this(
context,
DefaultAnalyticsRequestExecutor()
)
@Throws(IllegalStateException::class)
override fun create(): CardAccountRangeRepository {
val store = DefaultCardAccountRangeStore(appContext)
return DefaultCardAccountRangeRepository(
inMemorySource = InMemoryCardAccountRangeSource(store),
remoteSource = createRemoteCardAccountRangeSource(),
staticSource = StaticCardAccountRangeSource(),
store = store
)
}
private fun createRemoteCardAccountRangeSource(): CardAccountRangeSource {
return runCatching {
PaymentConfiguration.getInstance(
appContext
).publishableKey
}.onSuccess { publishableKey ->
fireAnalyticsEvent(
publishableKey,
PaymentAnalyticsEvent.CardMetadataPublishableKeyAvailable
)
}.onFailure {
fireAnalyticsEvent(
ApiRequest.Options.UNDEFINED_PUBLISHABLE_KEY,
PaymentAnalyticsEvent.CardMetadataPublishableKeyUnavailable
)
}.fold(
onSuccess = { publishableKey ->
RemoteCardAccountRangeSource(
StripeApiRepository(
appContext,
{ publishableKey }
),
ApiRequest.Options(
publishableKey
),
DefaultCardAccountRangeStore(appContext),
DefaultAnalyticsRequestExecutor(),
PaymentAnalyticsRequestFactory(appContext, publishableKey)
)
},
onFailure = {
NullCardAccountRangeSource()
}
)
}
private fun fireAnalyticsEvent(
publishableKey: String,
event: PaymentAnalyticsEvent
) {
analyticsRequestExecutor.executeAsync(
PaymentAnalyticsRequestFactory(
appContext,
publishableKey
).createRequest(event)
)
}
private class NullCardAccountRangeSource : CardAccountRangeSource {
override suspend fun getAccountRange(
cardNumber: CardNumber.Unvalidated
): AccountRange? = null
override val loading: Flow<Boolean> = flowOf(false)
}
}
|
mit
|
64e0a776f7ac07181967ec1da00f58a0
| 34.777778 | 100 | 0.663467 | 6.280142 | false | false | false | false |
hannesa2/owncloud-android
|
owncloudData/src/main/java/com/owncloud/android/data/sharing/shares/datasources/implementation/OCLocalShareDataSource.kt
|
2
|
4268
|
/**
* ownCloud Android client application
*
* @author David González Verdugo
* Copyright (C) 2020 ownCloud GmbH.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* 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.owncloud.android.data.sharing.shares.datasources.implementation
import androidx.annotation.VisibleForTesting
import androidx.lifecycle.LiveData
import androidx.lifecycle.Transformations
import com.owncloud.android.data.sharing.shares.datasources.LocalShareDataSource
import com.owncloud.android.data.sharing.shares.db.OCShareDao
import com.owncloud.android.data.sharing.shares.db.OCShareEntity
import com.owncloud.android.domain.sharing.shares.model.OCShare
import com.owncloud.android.domain.sharing.shares.model.ShareType
class OCLocalShareDataSource(
private val ocShareDao: OCShareDao,
) : LocalShareDataSource {
override fun getSharesAsLiveData(
filePath: String,
accountName: String,
shareTypes: List<ShareType>
): LiveData<List<OCShare>> =
Transformations.map(
ocShareDao.getSharesAsLiveData(
filePath,
accountName,
shareTypes.map { it.value })
) { ocShareEntities ->
ocShareEntities.map { ocShareEntity -> ocShareEntity.toModel() }
}
override fun getShareAsLiveData(remoteId: String): LiveData<OCShare> =
Transformations.map(ocShareDao.getShareAsLiveData(remoteId)) { ocShareEntity ->
ocShareEntity.toModel()
}
override fun insert(ocShare: OCShare): Long =
ocShareDao.insert(
ocShare.toEntity()
)
override fun insert(ocShares: List<OCShare>): List<Long> =
ocShareDao.insert(
ocShares.map { ocShare -> ocShare.toEntity() }
)
override fun update(ocShare: OCShare): Long = ocShareDao.update(ocShare.toEntity())
override fun replaceShares(ocShares: List<OCShare>): List<Long> =
ocShareDao.replaceShares(
ocShares.map { ocShare -> ocShare.toEntity() }
)
override fun deleteShare(remoteId: String): Int = ocShareDao.deleteShare(remoteId)
override fun deleteSharesForFile(filePath: String, accountName: String) =
ocShareDao.deleteSharesForFile(filePath, accountName)
companion object {
@VisibleForTesting
fun OCShareEntity.toModel(): OCShare =
OCShare(
id = id,
shareType = ShareType.fromValue(shareType)!!,
shareWith = shareWith,
path = path,
permissions = permissions,
sharedDate = sharedDate,
expirationDate = expirationDate,
token = token,
sharedWithDisplayName = sharedWithDisplayName,
sharedWithAdditionalInfo = sharedWithAdditionalInfo,
isFolder = isFolder,
remoteId = remoteId,
accountOwner = accountOwner,
name = name,
shareLink = shareLink
)
@VisibleForTesting
fun OCShare.toEntity(): OCShareEntity =
OCShareEntity(
shareType = shareType.value,
shareWith = shareWith,
path = path,
permissions = permissions,
sharedDate = sharedDate,
expirationDate = expirationDate,
token = token,
sharedWithDisplayName = sharedWithDisplayName,
sharedWithAdditionalInfo = sharedWithAdditionalInfo,
isFolder = isFolder,
remoteId = remoteId,
accountOwner = accountOwner,
name = name,
shareLink = shareLink
)
}
}
|
gpl-2.0
|
bad59f57819e53bd992b142260b6cce9
| 35.784483 | 87 | 0.639325 | 5.172121 | false | false | false | false |
AndroidX/androidx
|
window/window-samples/src/main/java/androidx/window/sample/DisplayFeaturesConfigChangeActivity.kt
|
3
|
5046
|
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.window.sample
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.FrameLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.RecyclerView
import androidx.window.layout.WindowInfoTracker
import androidx.window.layout.WindowLayoutInfo
import androidx.window.sample.infolog.InfoLogAdapter
import androidx.window.sample.util.PictureInPictureUtil.appendPictureInPictureMenu
import androidx.window.sample.util.PictureInPictureUtil.handlePictureInPictureMenuItem
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
/** Demo activity that shows all display features and current device state on the screen. */
class DisplayFeaturesConfigChangeActivity : AppCompatActivity() {
private val infoLogAdapter = InfoLogAdapter()
private val displayFeatureViews = ArrayList<View>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_display_features_config_change)
val recyclerView = findViewById<RecyclerView>(R.id.infoLogRecyclerView)
recyclerView.adapter = infoLogAdapter
lifecycleScope.launch(Dispatchers.Main) {
// The block passed to repeatOnLifecycle is executed when the lifecycle
// is at least STARTED and is cancelled when the lifecycle is STOPPED.
// It automatically restarts the block when the lifecycle is STARTED again.
lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
// Safely collect from windowInfoRepo when the lifecycle is STARTED
// and stops collection when the lifecycle is STOPPED
WindowInfoTracker.getOrCreate(this@DisplayFeaturesConfigChangeActivity)
.windowLayoutInfo(this@DisplayFeaturesConfigChangeActivity)
.collect { newLayoutInfo ->
// New posture information
updateStateLog(newLayoutInfo)
updateCurrentState(newLayoutInfo)
}
}
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
appendPictureInPictureMenu(menuInflater, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when {
handlePictureInPictureMenuItem(this, item) -> true
else -> super.onOptionsItemSelected(item)
}
}
/** Updates the device state and display feature positions. */
private fun updateCurrentState(windowLayoutInfo: WindowLayoutInfo) {
// Cleanup previously added feature views
val rootLayout = findViewById<FrameLayout>(R.id.featureContainerLayout)
for (featureView in displayFeatureViews) {
rootLayout.removeView(featureView)
}
displayFeatureViews.clear()
// Add views that represent display features
for (displayFeature in windowLayoutInfo.displayFeatures) {
val lp = getLayoutParamsForFeatureInFrameLayout(displayFeature, rootLayout)
// Make sure that zero-wide and zero-high features are still shown
if (lp.width == 0) {
lp.width = 1
}
if (lp.height == 0) {
lp.height = 1
}
val featureView = View(this)
val color = getColor(R.color.colorFeatureFold)
featureView.foreground = ColorDrawable(color)
rootLayout.addView(featureView, lp)
featureView.id = View.generateViewId()
displayFeatureViews.add(featureView)
}
}
/** Adds the current state to the text log of changes on screen. */
private fun updateStateLog(info: Any) {
infoLogAdapter.append(getCurrentTimeString(), info.toString())
infoLogAdapter.notifyDataSetChanged()
}
private fun getCurrentTimeString(): String {
val sdf = SimpleDateFormat("HH:mm:ss.SSS", Locale.getDefault())
val currentDate = sdf.format(Date())
return currentDate.toString()
}
}
|
apache-2.0
|
3725cf2f339669bae677828fb1e478ea
| 39.047619 | 92 | 0.699366 | 5.16479 | false | false | false | false |
vimeo/vimeo-networking-java
|
models/src/main/java/com/vimeo/networking2/PurchaseOnDemandInteraction.kt
|
1
|
594
|
package com.vimeo.networking2
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import com.vimeo.networking2.annotations.Internal
/**
* Purchase season interaction.
*
* @param buy Whether the On Demand video for purchase has DRM.
* @param subscriptionInteraction Subscribe to on demand video.
*/
@Internal
@JsonClass(generateAdapter = true)
data class PurchaseOnDemandInteraction(
@Internal
@Json(name = "buy")
val buy: BuyInteraction? = null,
@Internal
@Json(name = "subscribe")
val subscriptionInteraction: SubscriptionInteraction? = null
)
|
mit
|
4c06521c1c883a187e84501e33da8cd4
| 22.76 | 64 | 0.749158 | 4.068493 | false | false | false | false |
AndroidX/androidx
|
health/health-services-client/src/main/java/androidx/health/services/client/data/HealthEvent.kt
|
3
|
5374
|
/*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.health.services.client.data
import androidx.health.services.client.proto.DataProto
import androidx.health.services.client.proto.DataProto.HealthEvent.MetricsEntry
import java.time.Instant
/** Represents a user's health event. */
public class HealthEvent(
/** Gets the type of event. */
public val type: Type,
/** Returns the time of the health event. */
public val eventTime: Instant,
/** Gets metrics associated to the event. */
public val metrics: DataPointContainer,
) {
/** Health event types. */
public class Type private constructor(public val id: Int, public val name: String) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Type) return false
if (id != other.id) return false
return true
}
override fun hashCode(): Int = id
override fun toString(): String = name
internal fun toProto(): DataProto.HealthEvent.HealthEventType =
DataProto.HealthEvent.HealthEventType.forNumber(id)
?: DataProto.HealthEvent.HealthEventType.HEALTH_EVENT_TYPE_UNKNOWN
public companion object {
/**
* The Health Event is unknown, or is represented by a value too new for this library
* version to parse.
*/
@JvmField
public val UNKNOWN: Type = Type(0, "UNKNOWN")
/** Health Event signifying the device detected that the user fell. */
@JvmField
public val FALL_DETECTED: Type = Type(3, "FALL_DETECTED")
@JvmField
internal val VALUES: List<Type> = listOf(UNKNOWN, FALL_DETECTED)
internal fun fromProto(proto: DataProto.HealthEvent.HealthEventType): Type =
VALUES.firstOrNull { it.id == proto.number } ?: UNKNOWN
}
}
internal constructor(
proto: DataProto.HealthEvent
) : this(
Type.fromProto(proto.type),
Instant.ofEpochMilli(proto.eventTimeEpochMs),
fromHealthEventProto(proto)
)
internal val proto: DataProto.HealthEvent =
DataProto.HealthEvent.newBuilder()
.setType(type.toProto())
.setEventTimeEpochMs(eventTime.toEpochMilli())
.addAllMetrics(toEventProtoList(metrics))
.build()
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is HealthEvent) return false
if (type != other.type) return false
if (eventTime != other.eventTime) return false
if (metrics != other.metrics) return false
return true
}
override fun hashCode(): Int {
var result = type.hashCode()
result = 31 * result + eventTime.hashCode()
result = 31 * result + metrics.hashCode()
return result
}
internal companion object {
internal fun toEventProtoList(container: DataPointContainer): List<MetricsEntry> {
val list = mutableListOf<MetricsEntry>()
for (entry in container.dataPoints) {
if (entry.value.isEmpty()) {
continue
}
when (entry.key.timeType) {
DataType.TimeType.SAMPLE -> {
list.add(
MetricsEntry.newBuilder()
.setDataType(entry.key.proto)
.addAllDataPoints(entry.value.map { (it as SampleDataPoint).proto })
.build()
)
}
DataType.TimeType.INTERVAL -> {
list.add(
MetricsEntry.newBuilder()
.setDataType(entry.key.proto)
.addAllDataPoints(entry.value.map {
(it as IntervalDataPoint).proto
})
.build()
)
}
}
}
return list.sortedBy { it.dataType.name } // Required to ensure equals() works
}
internal fun fromHealthEventProto(
proto: DataProto.HealthEvent
): DataPointContainer {
val dataTypeToDataPoints: Map<DataType<*, *>, List<DataPoint<*>>> =
proto.metricsList.associate { entry ->
DataType.deltaFromProto(entry.dataType) to entry.dataPointsList.map {
DataPoint.fromProto(it)
}
}
return DataPointContainer(dataTypeToDataPoints)
}
}
}
|
apache-2.0
|
445b9b2fd85c0f40a7d198be4f10c141
| 34.596026 | 100 | 0.56792 | 5.137667 | false | false | false | false |
deeplearning4j/deeplearning4j
|
nd4j/samediff-import/samediff-import-api/src/main/kotlin/org/nd4j/samediff/frameworkimport/rule/attribute/AttributeNDArrayToScalarAttribute.kt
|
1
|
5821
|
/*
* ******************************************************************************
* *
* *
* * This program and the accompanying materials are made available under the
* * terms of the Apache License, Version 2.0 which is available at
* * https://www.apache.org/licenses/LICENSE-2.0.
* *
* * See the NOTICE file distributed with this work for additional
* * information regarding copyright ownership.
* * 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.
* *
* * SPDX-License-Identifier: Apache-2.0
* *****************************************************************************
*/
package org.nd4j.samediff.frameworkimport.rule.attribute
import org.nd4j.ir.OpNamespace
import org.nd4j.samediff.frameworkimport.ArgDescriptor
import org.nd4j.samediff.frameworkimport.argDescriptorType
import org.nd4j.samediff.frameworkimport.context.MappingContext
import org.nd4j.samediff.frameworkimport.findOp
import org.nd4j.samediff.frameworkimport.lookupIndexForArgDescriptor
import org.nd4j.samediff.frameworkimport.opdefs.OpDescriptorLoaderHolder
import org.nd4j.shade.protobuf.GeneratedMessageV3
import org.nd4j.shade.protobuf.ProtocolMessageEnum
import java.lang.IllegalArgumentException
abstract class AttributeNDArrayToScalarAttribute<
GRAPH_DEF : GeneratedMessageV3,
OP_DEF_TYPE : GeneratedMessageV3,
NODE_TYPE : GeneratedMessageV3,
ATTR_DEF : GeneratedMessageV3,
ATTR_VALUE_TYPE : GeneratedMessageV3,
TENSOR_TYPE : GeneratedMessageV3, DATA_TYPE : ProtocolMessageEnum>(
mappingNamesToPerform: Map<String, String>,
transformerArgs: Map<String, List<OpNamespace.ArgDescriptor>>) :
BaseAttributeExtractionRule<GRAPH_DEF, OP_DEF_TYPE, NODE_TYPE, ATTR_DEF, ATTR_VALUE_TYPE, TENSOR_TYPE, DATA_TYPE>
(
name = "attributendarraytoscalarattribute",
mappingNamesToPerform = mappingNamesToPerform,
transformerArgs = transformerArgs
) {
override fun acceptsInputType(argDescriptorType: AttributeValueType): Boolean {
return argDescriptorType == AttributeValueType.TENSOR
}
override fun outputsType(argDescriptorType: List<OpNamespace.ArgDescriptor.ArgType>): Boolean {
return argDescriptorType.contains(OpNamespace.ArgDescriptor.ArgType.INT64) ||
argDescriptorType.contains(OpNamespace.ArgDescriptor.ArgType.DOUBLE) ||
argDescriptorType.contains(OpNamespace.ArgDescriptor.ArgType.INT32)
}
override fun convertAttributes(mappingCtx: MappingContext<GRAPH_DEF, NODE_TYPE, OP_DEF_TYPE, TENSOR_TYPE, ATTR_DEF, ATTR_VALUE_TYPE, DATA_TYPE>): List<OpNamespace.ArgDescriptor> {
val ret = ArrayList<OpNamespace.ArgDescriptor>()
for ((k, v) in mappingNamesToPerform()) {
val irAttribute = mappingCtx.tensorAttributeFor(v).toNd4jNDArray()
val nd4jOpDescriptor = OpDescriptorLoaderHolder.nd4jOpDescriptor.findOp(mappingCtx.opName())
val realDataType = argDescriptorType(k, nd4jOpDescriptor)
when(realDataType) {
OpNamespace.ArgDescriptor.ArgType.DOUBLE -> {
ret.add(ArgDescriptor {
argType = OpNamespace.ArgDescriptor.ArgType.DOUBLE
name = k
doubleValue = irAttribute.getDouble(0)
argIndex = lookupIndexForArgDescriptor(
argDescriptorName = k,
opDescriptorName = mappingCtx.nd4jOpName(),
argDescriptorType = OpNamespace.ArgDescriptor.ArgType.DOUBLE
)
})
}
OpNamespace.ArgDescriptor.ArgType.INT64 -> {
ret.add(ArgDescriptor {
argType = OpNamespace.ArgDescriptor.ArgType.INT64
name = k
int64Value = irAttribute.getInt(0).toLong()
argIndex = lookupIndexForArgDescriptor(
argDescriptorName = k,
opDescriptorName = mappingCtx.nd4jOpName(),
argDescriptorType = OpNamespace.ArgDescriptor.ArgType.INT64
)
})
}
OpNamespace.ArgDescriptor.ArgType.FLOAT -> ret.add(ArgDescriptor {
argType = OpNamespace.ArgDescriptor.ArgType.FLOAT
name = k
floatValue = irAttribute.getFloat(0)
argIndex = lookupIndexForArgDescriptor(
argDescriptorName = k,
opDescriptorName = mappingCtx.nd4jOpName(),
argDescriptorType = OpNamespace.ArgDescriptor.ArgType.INT64
)
})
OpNamespace.ArgDescriptor.ArgType.INT32 -> ret.add(ArgDescriptor {
argType = OpNamespace.ArgDescriptor.ArgType.INT32
name = k
int32Value = irAttribute.getInt(0)
argIndex = lookupIndexForArgDescriptor(
argDescriptorName = k,
opDescriptorName = mappingCtx.nd4jOpName(),
argDescriptorType = OpNamespace.ArgDescriptor.ArgType.INT64
)
})
else -> {
throw IllegalArgumentException("Illegal data type ${realDataType}")
}
}
}
return ret
}
}
|
apache-2.0
|
8b7a083c579d1f7219c0e121b1ba962c
| 47.115702 | 183 | 0.609517 | 5.384829 | false | false | false | false |
Undin/intellij-rust
|
src/test/kotlin/org/rust/lang/core/type/RsStdlibExpressionTypeInferenceTest.kt
|
2
|
28122
|
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.type
import org.rust.*
import org.rust.lang.core.macros.MacroExpansionScope
import org.rust.lang.core.psi.ext.*
import org.rust.lang.core.types.ty.TyFloat
import org.rust.lang.core.types.ty.TyInteger
@ProjectDescriptor(WithStdlibRustProjectDescriptor::class)
class RsStdlibExpressionTypeInferenceTest : RsTypificationTestBase() {
fun `test RangeFull`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let x = ..;
x;
//^ RangeFull
}
""")
fun `test RangeFull no_std`() = stubOnlyTypeInfer("""
//- main.rs
#![no_std]
fn main() {
let x = ..;
x;
//^ RangeFull
}
""")
fun `test RangeFrom`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let x = 0u16..;
x;
//^ RangeFrom<u16>
}
""")
fun `test RangeTo`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let x = ..42u16;
x;
//^ RangeTo<u16>
}
""")
fun `test Range 2`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let x = 0u16..42;
x;
//^ Range<u16>
}
""")
fun `test Range 1`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let x = 0..42u16;
x;
//^ Range<u16>
}
""")
fun `test RangeToInclusive`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let x = ...42u16;
x;
//^ RangeToInclusive<u16>
}
""")
fun `test RangeToInclusive new syntax`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let x = ..=42u16;
x;
//^ RangeToInclusive<u16>
}
""")
fun `test RangeInclusive 1`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let x = 0u16...42;
x;
//^ RangeInclusive<u16>
}
""")
fun `test RangeInclusive 2`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let x = 0...42u16;
x;
//^ RangeInclusive<u16>
}
""")
fun `test RangeInclusive new syntax`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let x = 0..=42u16;
x;
//^ RangeInclusive<u16>
}
""")
fun `test vec!`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let x = vec!(1, 2u16, 4, 8);
x;
//^ Vec<u16> | Vec<u16, Global>
}
""")
@ProjectDescriptor(WithStdlibAndStdlibLikeDependencyRustProjectDescriptor::class)
fun `test vec! with stdlib-like dependencies`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let x = vec!(1, 2u16, 4, 8);
x;
//^ Vec<u16> | Vec<u16, Global>
}
""")
fun `test vec! no_std`() = stubOnlyTypeInfer("""
//- main.rs
#![no_std]
fn main() {
let x = vec!(1, 2u16, 4, 8);
x;
//^ Vec<u16> | Vec<u16, Global>
}
""")
fun `test empty vec!`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let mut x = vec![];
x.push(0u16);
x;
//^ Vec<u16> | Vec<u16, Global>
}
""")
fun `test repeat vec!`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let x = vec!(1u8; 2usize);
x;
//^ Vec<u8> | Vec<u8, Global>
}
""")
fun `test custom vec!`() = stubOnlyTypeInfer("""
//- main.rs
macro_rules! vec {
($ name:ident [ $($ field:ident = $ index:expr),* ] = $ fixed:ty) => { };
}
fn main() {
let x = vec!(Vector2 [x=0, y=1] = [T; 2]);
x;
//^ <unknown>
}
""")
fun `test format!`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let x = format!("{} {}", "Hello", "world!");
x;
//^ String
}
""")
fun `test format! no_std`() = stubOnlyTypeInfer("""
//- main.rs
#![no_std]
fn main() {
let x = format!("{} {}", "Hello", "world!");
x;
//^ String
}
""")
fun `test custom format!`() = stubOnlyTypeInfer("""
//- main.rs
macro_rules! format {
($ name:ident [ $($ field:ident = $ index:expr),* ] = $ fixed:ty) => { };
}
fn main() {
let x = format!(Vector2 [x=0, y=1] = [T; 2]);
x;
//^ <unknown>
}
""")
fun `test format_args!`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let x = format_args!("{} {}", "Hello", "world!");
x;
//^ Arguments
}
""")
fun `test format_args! no_std`() = stubOnlyTypeInfer("""
//- main.rs
#![no_std]
fn main() {
let x = format_args!("{} {}", "Hello", "world!");
x;
//^ Arguments
}
""")
fun `test env`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let a = env!("PATH");
a;
//^ &str
}
""")
fun `test env 2 args`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let a = env!("PATH", "PATH env variable not found");
a;
//^ &str
}
""")
fun `test option_env`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let a = option_env!("PATH");
a;
//^ Option<&str>
}
""")
fun `test concat`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let a = concat!("hello", 10);
a;
//^ &str
}
""")
fun `test line`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let a = line!();
a;
//^ u32
}
""")
fun `test column`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let a = column!();
a;
//^ u32
}
""")
fun `test file`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let a = file!();
a;
//^ &str
}
""")
fun `test stringify`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let a = stringify!(1 + 1);
a;
//^ &str
}
""")
fun `test include_str`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let a = include_str!("file.txt");
a;
//^ &str
}
""")
fun `test include_bytes`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let a = include_bytes!("file.txt");
a;
//^ &[u8; <unknown>]
}
""")
fun `test module_path`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let a = module_path!();
a;
//^ &str
}
""")
fun `test cfg`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let a = cfg!(windows);
a;
//^ bool
}
""")
fun `test assert!`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let x = assert!(1 != 2);
x;
//^ ()
}
""")
fun `test debug_assert!`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let x = debug_assert!(1 != 2);
x;
//^ ()
}
""")
fun `test assert_eq!`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let x = assert_eq!(1 + 1, 2);
x;
//^ ()
}
""")
fun `test assert_ne!`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let x = assert_ne!(1, 2);
x;
//^ ()
}
""")
fun `test debug_assert_eq!`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let x = debug_assert_eq!(1 + 1, 2);
x;
//^ ()
}
""")
fun `test debug_assert_ne!`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let x = debug_assert_ne!(1, 2);
x;
//^ ()
}
""")
fun `test custom assert!`() = stubOnlyTypeInfer("""
//- main.rs
macro_rules! assert {
($ name:ident [ $($ field:ident = $ index:expr),* ] = $ fixed:ty) => { };
}
fn main() {
let x = assert!(Vector2 [x=0, y=1] = [T; 2]);
x;
//^ <unknown>
}
""")
fun `test print!`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let x = print!("Something went wrong");
x;
//^ ()
}
""")
fun `test println!`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let x = println!("Something went wrong");
x;
//^ ()
}
""")
fun `test eprint!`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let x = eprint!("Something went wrong");
x;
//^ ()
}
""")
fun `test eprintln!`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let x = eprintln!("Something went wrong");
x;
//^ ()
}
""")
//From the log crate
fun `test warn!`() = stubOnlyTypeInfer("""
//- main.rs
#[derive(PartialOrd, Ord, PartialEq, Eq)]
enum Level {
Warn
}
const STATIC_MAX_LEVEL: Level = Level::Warn;
fn max_level() -> Level { unimplemented!() }
fn __private_api_log(
args: std::fmt::Arguments,
level: Level,
&(target, module_path, file, line): &(&str, &'static str, &'static str, u32),
) {}
#[macro_export]
macro_rules! __log_format_args {
(${'$'}($ args:tt)*) => {
format_args!(${'$'}($ args)*)
};
}
#[macro_export(local_inner_macros)]
macro_rules! log {
(target: $ target:expr, $ lvl:expr, ${'$'}($ arg:tt)+) => ({
let lvl = $ lvl;
if lvl <= STATIC_MAX_LEVEL && lvl <= max_level() {
__private_api_log(
__log_format_args!(${'$'}($ arg)+),
lvl,
&($ target, std::module_path!(), std::file!(), std::line!()),
);
}
});
($ lvl:expr, ${'$'}($ arg:tt)+) => (log!(target: std::module_path!(), $ lvl, ${'$'}($ arg)+))
}
#[macro_export(local_inner_macros)]
macro_rules! warn {
(target: ${'$'} target:expr, ${'$'}(${'$'} arg:tt)+) => (
log!(target: ${'$'} target, Level::Warn, ${'$'}(${'$'} arg)+)
);
(${'$'}(${'$'} arg:tt)+) => (
log!(Level::Warn, ${'$'}(${'$'} arg)+)
)
}
fn main() {
let x = warn!("Something went wrong");
x;
//^ ()
}
""")
fun `test infer lambda expr`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let test: Vec<String> = Vec::new();
test.into_iter().map(|a| a.to_string());
//^ String
}
""")
fun `test infer type of derivable trait method call`() = stubOnlyTypeInfer("""
//- main.rs
#[derive(Clone)]
struct Foo;
fn bar(foo: Foo) {
let foo2 = foo.clone();
foo2;
//^ Foo
}
""")
fun `test infer iterator map chain`() = stubOnlyTypeInfer("""
//- main.rs
struct S<T>(T);
fn main() {
let test: Vec<String> = Vec::new();
let a = test.into_iter()
.map(|x| x.to_string())
.map(|x| S(x))
.map(|x| x.0)
.next().unwrap();
a;
//^ String
}
""")
fun `test infer iterator filter chain`() = stubOnlyTypeInfer("""
//- main.rs
struct S<T>(T);
fn main() {
let test: Vec<i32> = Vec::new();
let a = test.into_iter()
.filter(|x| *x < 30)
.filter(|x| *x > 10)
.filter(|x| x % 2 == 0)
.next().unwrap();
a;
//^ i32
}
""")
@ExpandMacros(MacroExpansionScope.ALL, "std")
fun `test slice iter`() = stubOnlyTypeInfer("""
//- main.rs
struct S<T>(T);
fn main() {
let test: Vec<i32> = Vec::new();
let a = test.iter()
.next().unwrap();
a;
//^ &i32
}
""")
@ExpandMacros(MacroExpansionScope.ALL, "std")
fun `test slice iter_mut`() = stubOnlyTypeInfer("""
//- main.rs
struct S<T>(T);
fn main() {
let mut test: Vec<i32> = Vec::new();
let a = test.iter_mut()
.next().unwrap();
a;
//^ &mut i32
}
""")
@ExpandMacros(MacroExpansionScope.ALL, "std")
fun `test iter take`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let mut names = vec![0i32, 1]
.iter()
.take(3)
.next();
names;
//^ Option<&i32>
}
""")
fun `test iterator collect`() = stubOnlyTypeInfer("""
//- main.rs
use std::vec::Vec;
fn main() {
let vec = vec![1, 2, 3];
let b: Vec<_> = vec.into_iter().collect();
b;
//^ Vec<i32> | Vec<i32, Global>
}
""")
fun `test iterator collect with path parameter`() = stubOnlyTypeInfer("""
//- main.rs
use std::vec::Vec;
fn main() {
let vec = vec![1, 2, 3];
let b = vec.into_iter().collect::<Vec<_>>();
b;
//^ Vec<i32> | Vec<i32, Global>
}
""")
@ExpandMacros(MacroExpansionScope.ALL, "std")
fun `test iterator cloned`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let a = vec![1, 2].iter()
.cloned()
.next();
a;
} //^ Option<i32>
""")
fun `test vec push`() = stubOnlyTypeInfer("""
//- main.rs
use std::vec::Vec;
fn main() {
let mut vec = Vec::new();
vec.push(1);
vec;
//^ Vec<i32> | Vec<i32, Global>
}
""")
fun `test vec push 2`() = stubOnlyTypeInfer("""
//- main.rs
use std::vec::Vec;
fn main() {
let a = 0;
//^ u8
let mut vec = Vec::new();
vec.push(a);
vec.push(1u8);
}
""")
fun `test array indexing`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let xs = ["foo", "bar"];
let x = xs[0];
x;
//^ &str
}
""")
@ExpandMacros(MacroExpansionScope.ALL, "std")
fun `test arithmetic op with unconstrained integer`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let a = 2+2+2;
a;
//^ i32
}
""")
@ExpandMacros(MacroExpansionScope.ALL, "std")
fun `test all arithmetic ops with all numeric types`() {
TyInteger.NAMES.permutations(ArithmeticOp.values())
.forEach { (numeric, op) -> doTestBinOp(numeric, op, "0", numeric) }
val floatOps = listOf(ArithmeticOp.ADD, ArithmeticOp.SUB, ArithmeticOp.MUL, ArithmeticOp.DIV)
TyFloat.NAMES.permutations(floatOps)
.forEach { (numeric, op) -> doTestBinOp(numeric, op, "0.0", numeric) }
}
@ExpandMacros(MacroExpansionScope.ALL, "std")
fun `test all arithmetic assignment ops with all numeric types`() {
TyInteger.NAMES.permutations(ArithmeticAssignmentOp.values())
.forEach { (numeric, op) -> doTestBinOp(numeric, op, "0", "()") }
val floatOps = listOf(ArithmeticAssignmentOp.PLUSEQ, ArithmeticAssignmentOp.MINUSEQ,
ArithmeticAssignmentOp.MULEQ, ArithmeticAssignmentOp.DIVEQ)
TyFloat.NAMES.permutations(floatOps)
.forEach { (numeric, op) -> doTestBinOp(numeric, op, "0.0", "()") }
}
@ExpandMacros(MacroExpansionScope.ALL, "std")
fun `test all cmp ops with all numeric types`() {
val ops: List<OverloadableBinaryOperator> = EqualityOp.values() + ComparisonOp.values()
TyInteger.NAMES.permutations(ops)
.forEach { (numeric, op) -> doTestBinOp(numeric, op, "0", "bool") }
TyFloat.NAMES.permutations(ops)
.forEach { (numeric, op) -> doTestBinOp(numeric, op, "0.0", "bool") }
}
private fun <A, B> Collection<A>.permutations(other: Collection<B>): List<Pair<A, B>> {
val result = ArrayList<Pair<A, B>>(size*other.size)
for (a in this) {
for (b in other) {
result += Pair(a, b)
}
}
return result
}
private fun doTestBinOp(
lhsType: String,
op: OverloadableBinaryOperator,
rhsLiteral: String,
expectedOutputType: String
) {
val sign = op.sign
val expectedRhsType = if ((op as BinaryOperator).category == BinOpCategory.Shift) {
"i32"
} else {
lhsType
}
stubOnlyTypeInfer("""
//- main.rs
fn foo(lhs: $lhsType) {
let rhs = $rhsLiteral;
let x = lhs $sign rhs;
(x, rhs);
//^ ($expectedOutputType, $expectedRhsType)
}
""")
}
@ExpandMacros
fun `test write macro`() = stubOnlyTypeInfer("""
//- main.rs
use std::fmt::Write;
fn main() {
let mut s = String::new();
let a = write!(s, "text");
a;
//^ Result<(), Error>
}
""")
@ExpandMacros
fun `test write macro &mut`() = stubOnlyTypeInfer("""
//- main.rs
use std::fmt::Write;
fn main() {
let mut s = String::new();
let a = write!(&mut s, "text");
a;
//^ Result<(), Error>
}
""")
/** Issue [#2514](https://github.com/intellij-rust/intellij-rust/issues/2514) */
@ExpandMacros(MacroExpansionScope.ALL, "std")
fun `test issue 2514`() = stubOnlyTypeInfer("""
//- main.rs
struct Foo {
bar: Box<i32>
}
impl Foo {
fn test(&self) {
let b = self.bar.as_ref().clone();
b;
} //^ i32
}
""")
/** Issue [#2791](https://github.com/intellij-rust/intellij-rust/issues/2791)*/
fun `test issue 2791`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let mut vec: Vec<i32> = Vec::new();
for x in &mut vec { x; }
} //^ &mut i32
""")
fun `test iterate for impl Iterator type`() = stubOnlyTypeInfer("""
//- main.rs
fn foo() -> impl Iterator<Item=u8> { unimplemented!() }
fn main() {
for x in foo() { x; }
} //^ u8
""")
fun `test box expr`() = stubOnlyTypeInfer("""
//- main.rs
struct S;
fn main() {
let a = box S;
a;
} //^ Box<S> | Box<S, Global>
""")
@ExpandMacros(MacroExpansionScope.ALL, "std")
fun `test iterate 'for' complex pattern in complex type (correct type vars resolve)`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
for (a, _) in [(Some(42), false)].iter().map(|(n, f)| (n, f)) {
a;
} //^ &Option<i32>
}
""")
@ExpandMacros(MacroExpansionScope.ALL, "std")
fun `test iterate 'while let' complex pattern = complex type (correct type vars resolve)`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
while let Some((a, _)) = [(Some(42), false)].iter().map(|(n, f)| (n, f)).next() {
a;
} //^ &Option<i32>
}
""")
@ExpandMacros(MacroExpansionScope.ALL, "std")
fun `test 'if let' complex pattern = complex type (correct type vars resolve)`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
if let Some((a, _)) = [(Some(42), false)].iter().map(|(n, f)| (n, f)).next() {
a;
} //^ &Option<i32>
}
""")
@ExpandMacros(MacroExpansionScope.ALL, "std")
fun `test 'try expr' on a complex type = complex type (correct type vars resolve)`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let a = vec![Some(42)].into_iter().next()??;
a;
} //^ i32
""")
fun `test macro impls`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let a = 0.to_string();
a;
//^ String
}
""")
fun `test overloaded add String + &String`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let a = String::new();
let b = String::new();
let c = a + &b;
c;
} //^ String
""")
fun `test 'Clone' is not derived for generic type`() = stubOnlyTypeInfer("""
//- main.rs
struct X; // Not `Clone`
#[derive(Clone)]
struct S<T>(T);
fn main() {
let a = &S(X);
let b = a.clone(); // `S<X>` is not `Clone`, so resolved to std `impl for &T`
b;
} //^ &S<X>
""")
fun `test await pin future`() = stubOnlyTypeInfer("""
//- main.rs
use std::future::Future;
use std::pin::Pin;
async fn foo<T: Future<Output=i32>>(p: Pin<&mut T>) {
let a = p.await;
a;
} //^ i32
""")
// There is `impl<T: ?Sized> !Clone for &mut T {}`
fun `test clone through mut ref`() = stubOnlyTypeInfer("""
//- main.rs
#[derive(Clone)]
pub struct S;
fn main() {
let a = &mut S;
let b = a.clone();
b;
} //^ S
""")
// Issue https://github.com/intellij-rust/intellij-rust/issues/6749
fun `test diverging and non-diverging match arm`() = stubOnlyTypeInfer("""
//- main.rs
fn foo(x: i32) {}
fn main() {
let num2 = match "42".parse() {
Ok(v) => v,
Err(e) => panic!(),
}; // type of `num2` should be `i32`, not `!`
foo(num2);
num2;
} //^ i32
""")
// https://github.com/intellij-rust/intellij-rust/issues/8405
@MinRustcVersion("1.51.0")
fun `test addr_of_mut!`() = stubOnlyTypeInfer("""
//- main.rs
use std::ptr::addr_of_mut;
fn main() {
let mut a = 123;
let b = addr_of_mut!(a);
b;
//^ *mut i32
}
""")
fun `test iter map using std identity`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let a = vec![1, 2]
.into_iter()
.map(std::convert::identity)
.next()
.unwrap();
a;
} //^ i32
""")
fun `test call an fn pointer reference`() = stubOnlyTypeInfer("""
//- main.rs
fn foo(f: &fn() -> i32) {
let a = f();
a;
} //^ i32
""")
fun `test call an fn pointer 2-reference`() = stubOnlyTypeInfer("""
//- main.rs
fn foo(f: &&fn() -> i32) {
let a = f();
a;
} //^ i32
""")
fun `test call an fn pointer under Rc`() = stubOnlyTypeInfer("""
//- main.rs
use std::rc::Rc;
fn foo(f: Rc<fn() -> i32>) {
let a = f();
a;
} //^ i32
""")
fun `test call type parameter with FnOnce with implicit return type`() = stubOnlyTypeInfer("""
//- main.rs
pub fn foo<F: FnOnce(i32)>(f: F) -> Self {
let a = f(1);
a;
} //^ ()
""")
fun `test box unsizing`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
foo(Box::new([1, 2, 3]));
} //^ Box<[u8; 3], Global>|Box<[u8; 3]>
fn foo(a: Box<[u8]>) {}
""")
fun `test infer lambda parameter type 1`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let a = |b| {
b;
};//^ i32
foo(a);
}
fn foo(_: fn(i32)) {}
""")
fun `test infer lambda parameter type 2`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let a = |b| {
b;
};//^ i32
foo(a);
}
fn foo<T: FnOnce(i32)>(_: T) {}
""")
fun `test try-poll`() = stubOnlyTypeInfer("""
//- main.rs
use std::task::Poll;
fn foo(p: Poll<Result<i32, ()>>) -> Result<(), ()> {
let a = p?;
a;
//^ Poll<i32>
Ok(())
}
""")
fun `test for loop over type parameter implementing Iterator`() = stubOnlyTypeInfer("""
//- main.rs
fn foo<I: Iterator<Item = i32>>(a: I) {
for b in a {
b;
} //^ i32
}
""")
fun `test Option clone method`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let a = Some(String::new());
let b = a.clone();
b;
} //^ Option<String>
""")
fun `test todo macro`() = stubOnlyTypeInfer("""
//- main.rs
fn main() {
let a = todo!();
a;
} //^ !
""")
fun `test custom macros with stdlib names`() {
// name -> argument count
val macros = mapOf(
"dbg" to 1,
"format" to 1,
"format_args" to 1,
"format_args_nl" to 1,
"write" to 1,
"writeln" to 1,
"print" to 1,
"println" to 1,
"eprint" to 1,
"eprintln" to 1,
"panic" to 1,
"unimplemented" to 1,
"unreachable" to 1,
"todo" to 1,
"assert" to 1,
"debug_assert" to 1,
"assert_eq" to 2,
"assert_ne" to 2,
"debug_assert_eq" to 2,
"debug_assert_ne" to 2,
"vec" to 1,
"include_str" to 1,
"include_bytes" to 1,
// `MacroExpansionManagerImpl.getExpansionFor` always processes `include!` call as if `include!` is from stdlib.
// As a result, the expansion is null in this test and the plugin can't infer the proper type.
//
//"include" to 1,
"concat" to 1,
"env" to 1,
"option_env" to 1,
"line" to 0,
"column" to 0,
"file" to 0,
"stringify" to 1,
"cfg" to 1,
"module_path" to 0
)
for ((name, argsCount) in macros) {
val argsDefinition = (0..argsCount).joinToString(", ") { "$ x$it:expr" }
val args = (0..argsCount).joinToString(", ") { "\"it\"" }
// We try to construct custom macro definition in a way to trigger the same parser rules
// as if it would be a macro from stdlib
stubOnlyTypeInfer("""
//- main.rs
struct S;
macro_rules! $name {
($argsDefinition) => { S };
}
fn main() {
let a = $name!($args);
a;
//^ S
}
""", description = "Macro `$name`")
}
}
}
|
mit
|
9d2994a7161e860c8035c4614777e375
| 24.823691 | 124 | 0.421236 | 3.893396 | false | true | false | false |
Undin/intellij-rust
|
src/main/kotlin/org/rust/lang/core/resolve2/util/PathUtil.kt
|
3
|
3244
|
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.resolve2.util
import org.rust.lang.core.stubs.RsPathStub
import org.rust.lang.core.stubs.RsUseItemStub
import org.rust.lang.core.stubs.RsUseSpeckStub
import org.rust.lang.core.stubs.RsVisStub
fun interface RsLeafUseSpeckConsumer {
fun consume(usePath: Array<String>, alias: String?, isStarImport: Boolean, offsetInExpansion: Int)
}
fun RsUseItemStub.forEachLeafSpeck(consumer: RsLeafUseSpeckConsumer) {
val rootUseSpeck = findChildStubByType(RsUseSpeckStub.Type) ?: return
val segments = arrayListOf<String>()
rootUseSpeck.forEachLeafSpeck(consumer, segments, isRootSpeck = true, basePath = null)
}
private fun RsUseSpeckStub.forEachLeafSpeck(
consumer: RsLeafUseSpeckConsumer,
segments: ArrayList<String>,
isRootSpeck: Boolean,
basePath: RsPathStub?
) {
val path = path
val useGroup = useGroup
val isStarImport = isStarImport
if (path == null && isRootSpeck) {
// e.g. `use ::*;` and `use ::{aaa, bbb};`
if (hasColonColon) segments += "crate"
// We ignore `use *;` - https://github.com/sfackler/rust-openssl/blob/0a0da84f939090f72980c77f40199fc76245d289/openssl-sys/src/asn1.rs#L3
// Note that `use ::*;` is correct in 2015 edition
if (!hasColonColon && useGroup == null) return
}
val numberSegments = segments.size
if (path != null) {
if (!addPathSegments(path, segments)) return
}
val newBasePath = basePath ?: path
if (useGroup == null) {
if (!isStarImport && segments.size > 1 && segments.last() == "self") segments.removeAt(segments.lastIndex)
val alias = if (isStarImport) "_" else alias?.name
consumer.consume(segments.toTypedArray(), alias, isStarImport, newBasePath?.startOffset ?: -1)
} else {
for (childSpeck in useGroup.childrenStubs) {
(childSpeck as RsUseSpeckStub).forEachLeafSpeck(consumer, segments, isRootSpeck = false, newBasePath)
}
}
while (segments.size > numberSegments) {
segments.removeAt(segments.lastIndex)
}
}
/** return false if path is incomplete (has empty segments), e.g. `use std::;` */
private fun addPathSegments(path: RsPathStub, segments: ArrayList<String>): Boolean {
val subpath = path.path
if (subpath != null) {
if (!addPathSegments(subpath, segments)) return false
} else if (path.hasColonColon) {
// absolute path: `::foo::bar`
// ~~~~~ this
segments += ""
}
val segment = path.referenceName ?: return false
segments += segment
return true
}
fun RsPathStub.getPathWithAdjustedDollarCrate(): Array<String>? {
val segments = arrayListOf<String>()
if (!addPathSegments(this, segments)) return null
return segments.toTypedArray()
}
fun RsVisStub.getRestrictedPath(): Array<String>? {
val path = visRestrictionPath ?: error("no visibility restriction")
val segments = arrayListOf<String>()
if (!addPathSegments(path, segments)) return null
if (segments.first().let { it.isEmpty() || it == "crate" }) segments.removeAt(0)
return segments.toTypedArray()
}
|
mit
|
961b93b1009691965beee01e2f52f5ff
| 35.044444 | 145 | 0.678483 | 3.936893 | false | false | false | false |
Senspark/ee-x
|
src/android/store/src/main/java/com/ee/internal/IabHelper.kt
|
1
|
6255
|
package com.ee.internal
import com.android.billingclient.api.BillingClient
import com.android.billingclient.api.BillingClient.FeatureType
import com.android.billingclient.api.BillingClient.SkuType
import com.ee.IStoreBridge
class IabHelper(private val _bridge: IStoreBridge) {
private var _setupDone = false
private val _inventory = Inventory()
private var _subscriptionsSupported = false
private var _subscriptionPurchaseHistorySupported = false
val setupDone: Boolean
get() = _setupDone
suspend fun startSetup(): IabResult {
if (_setupDone) {
throw IllegalStateException("IAB helper is already setup")
}
return finishSetup()
}
private suspend fun isFeatureSupported(@FeatureType type: String): Boolean {
var result = false
try {
result = _bridge.isFeatureSupported(type)
} catch (ex: StoreException) {
ex.printStackTrace()
}
return result
}
private suspend fun finishSetup(): IabResult {
// Always support inapp feature.
_subscriptionsSupported = false
_subscriptionPurchaseHistorySupported = false
if (isFeatureSupported(FeatureType.SUBSCRIPTIONS)) {
_subscriptionsSupported = true
_subscriptionPurchaseHistorySupported = true
}
_setupDone = true
return IabResult(BillingClient.BillingResponseCode.OK, "Setup successful")
}
val subscriptionsSupported: Boolean
get() = _subscriptionsSupported
val subscriptionPurchaseHistorySupported: Boolean
get() = _subscriptionPurchaseHistorySupported
suspend fun queryInventory(querySkuDetails: Boolean,
moreSkus: List<String>): Inventory {
var response = queryPurchases(_inventory, SkuType.INAPP)
if (response != BillingClient.BillingResponseCode.OK) {
throw IabException(response, "Error refreshing inventory (querying owned items)")
}
if (querySkuDetails) {
response = querySkuDetails(SkuType.INAPP, _inventory, moreSkus)
if (response != BillingClient.BillingResponseCode.OK) {
throw IabException(response, "Error refreshing inventory (querying prices of items)")
}
}
if (_subscriptionsSupported) {
response = queryPurchases(_inventory, SkuType.SUBS)
if (response != BillingClient.BillingResponseCode.OK) {
throw IabException(response, "Error refreshing inventory (querying owned subscriptions)")
}
if (querySkuDetails) {
response = querySkuDetails(SkuType.SUBS, _inventory, moreSkus)
if (response != BillingClient.BillingResponseCode.OK) {
throw IabException(response, "Error refreshing inventory (querying prices of subscriptions)")
}
}
}
if (_subscriptionPurchaseHistorySupported) {
queryPurchaseHistory(_inventory, SkuType.SUBS)
response = queryPurchaseHistory(_inventory, SkuType.INAPP)
if (response != BillingClient.BillingResponseCode.OK) {
throw IabException(response, "Error query Purchase History")
}
}
return _inventory
}
suspend fun consume(@SkuType itemType: String, token: String, sku: String) {
if (itemType != SkuType.INAPP) {
throw IabException(-1010, "Items of type '$itemType' can't be consumed")
}
if (token.isNotEmpty()) {
try {
_bridge.consume(token)
} catch (ex: StoreException) {
throw IabException(ex.responseCode, "Error consuming sku $sku")
}
} else {
throw IabException(-1007, "PurchaseInfo is missing token for sku $sku")
}
}
suspend fun acknowledge(token: String, sku: String) {
if (token.isNotEmpty()) {
try {
_bridge.acknowledge(token)
} catch (ex: StoreException) {
throw IabException(ex.responseCode, "Error acknowledging sku $sku")
}
} else {
throw IabException(-1007, "PurchaseInfo is missing token for sku $sku")
}
}
private suspend fun queryPurchaseHistory(inv: Inventory, @SkuType itemType: String): Int {
var responseCode = BillingClient.BillingResponseCode.OK
try {
val recordList = _bridge.getPurchaseHistory(itemType)
if (itemType == SkuType.INAPP) {
recordList.forEach {
inv.addPurchaseToConsumablePurchaseHistory(it.sku, it)
}
} else {
recordList.forEach {
inv.addPurchaseToSubscriptionPurchaseHistory(it.sku)
}
}
} catch (ex: StoreException) {
responseCode = ex.responseCode
}
return responseCode
}
@BillingClient.BillingResponseCode
suspend fun queryPurchases(inv: Inventory, @SkuType itemType: String): Int {
var responseCode = BillingClient.BillingResponseCode.OK
try {
val purchaseList = _bridge.getPurchases(itemType)
purchaseList.forEach {
inv.addPurchase(itemType, it)
}
} catch (ex: StoreException) {
responseCode = ex.responseCode
}
return responseCode
}
@BillingClient.BillingResponseCode
private suspend fun querySkuDetails(@SkuType itemType: String,
inv: Inventory,
moreSkus: List<String>): Int {
val skuList = inv.getAllOwnedSkus(itemType).plus(moreSkus)
if (skuList.isEmpty()) {
return BillingClient.BillingResponseCode.OK
}
var responseCode = BillingClient.BillingResponseCode.OK
try {
val detailsList = _bridge.getSkuDetails(itemType, skuList)
detailsList.forEach {
inv.addSkuDetails(it)
}
} catch (ex: StoreException) {
responseCode = ex.responseCode
}
return responseCode
}
}
|
mit
|
5fe4bb93bbca8c146b44a9e253eda7a5
| 36.915152 | 113 | 0.606235 | 5.260723 | false | false | false | false |
androidx/androidx
|
compose/ui/ui/src/androidMain/kotlin/androidx/compose/ui/platform/ViewLayer.android.kt
|
3
|
16442
|
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.platform
import android.annotation.SuppressLint
import android.os.Build
import android.view.View
import android.view.ViewOutlineProvider
import androidx.annotation.RequiresApi
import androidx.compose.ui.geometry.MutableRect
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Canvas
import androidx.compose.ui.graphics.CanvasHolder
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.CompositingStrategy
import androidx.compose.ui.graphics.Matrix
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.graphics.RenderEffect
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.TransformOrigin
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.layout.GraphicLayerInfo
import androidx.compose.ui.node.OwnedLayer
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.LayoutDirection
import java.lang.reflect.Field
import java.lang.reflect.Method
/**
* View implementation of OwnedLayer.
*/
internal class ViewLayer(
val ownerView: AndroidComposeView,
val container: DrawChildContainer,
drawBlock: (Canvas) -> Unit,
invalidateParentLayer: () -> Unit
) : View(ownerView.context), OwnedLayer, GraphicLayerInfo {
private var drawBlock: ((Canvas) -> Unit)? = drawBlock
private var invalidateParentLayer: (() -> Unit)? = invalidateParentLayer
private val outlineResolver = OutlineResolver(ownerView.density)
// Value of the layerModifier's clipToBounds property
private var clipToBounds = false
private var clipBoundsCache: android.graphics.Rect? = null
private val manualClipPath: Path? get() =
if (!clipToOutline || outlineResolver.outlineClipSupported) {
null
} else {
outlineResolver.clipPath
}
var isInvalidated = false
private set(value) {
if (value != field) {
field = value
ownerView.notifyLayerIsDirty(this, value)
}
}
private var drawnWithZ = false
private val canvasHolder = CanvasHolder()
private val matrixCache = LayerMatrixCache(getMatrix)
/**
* Local copy of the transform origin as GraphicsLayerModifier can be implemented
* as a model object. Update this field within [updateLayerProperties] and use it
* in [resize] or other methods
*/
private var mTransformOrigin: TransformOrigin = TransformOrigin.Center
private var mHasOverlappingRendering = true
init {
setWillNotDraw(false) // we WILL draw
id = generateViewId()
container.addView(this)
}
override val layerId: Long
get() = id.toLong()
override val ownerViewId: Long
get() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
UniqueDrawingIdApi29.getUniqueDrawingId(ownerView)
} else {
-1
}
@RequiresApi(29)
private object UniqueDrawingIdApi29 {
@JvmStatic
@androidx.annotation.DoNotInline
fun getUniqueDrawingId(view: View) = view.uniqueDrawingId
}
/**
* Configure the camera distance on the View in pixels. View already has a get/setCameraDistance
* API however, that operates in Dp values.
*/
var cameraDistancePx: Float
get() {
// View internally converts distance to dp so divide by density here to have
// consistent usage of pixels with RenderNode that is backing the View
return cameraDistance / resources.displayMetrics.densityDpi
}
set(value) {
// View internally converts distance to dp so multiply by density here to have
// consistent usage of pixels with RenderNode that is backing the View
cameraDistance = value * resources.displayMetrics.densityDpi
}
override fun updateLayerProperties(
scaleX: Float,
scaleY: Float,
alpha: Float,
translationX: Float,
translationY: Float,
shadowElevation: Float,
rotationX: Float,
rotationY: Float,
rotationZ: Float,
cameraDistance: Float,
transformOrigin: TransformOrigin,
shape: Shape,
clip: Boolean,
renderEffect: RenderEffect?,
ambientShadowColor: Color,
spotShadowColor: Color,
compositingStrategy: CompositingStrategy,
layoutDirection: LayoutDirection,
density: Density
) {
this.mTransformOrigin = transformOrigin
this.scaleX = scaleX
this.scaleY = scaleY
this.alpha = alpha
this.translationX = translationX
this.translationY = translationY
this.elevation = shadowElevation
this.rotation = rotationZ
this.rotationX = rotationX
this.rotationY = rotationY
this.pivotX = mTransformOrigin.pivotFractionX * width
this.pivotY = mTransformOrigin.pivotFractionY * height
this.cameraDistancePx = cameraDistance
this.clipToBounds = clip && shape === RectangleShape
resetClipBounds()
val wasClippingManually = manualClipPath != null
this.clipToOutline = clip && shape !== RectangleShape
val shapeChanged = outlineResolver.update(
shape,
this.alpha,
this.clipToOutline,
this.elevation,
layoutDirection,
density
)
updateOutlineResolver()
val isClippingManually = manualClipPath != null
if (wasClippingManually != isClippingManually || (isClippingManually && shapeChanged)) {
invalidate() // have to redraw the content
}
if (!drawnWithZ && elevation > 0) {
invalidateParentLayer?.invoke()
}
matrixCache.invalidate()
if (Build.VERSION.SDK_INT >= 28) {
ViewLayerVerificationHelper28.setOutlineAmbientShadowColor(
this,
ambientShadowColor.toArgb()
)
ViewLayerVerificationHelper28.setOutlineSpotShadowColor(this, spotShadowColor.toArgb())
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
ViewLayerVerificationHelper31.setRenderEffect(this, renderEffect)
}
mHasOverlappingRendering = when (compositingStrategy) {
CompositingStrategy.Offscreen -> {
setLayerType(LAYER_TYPE_HARDWARE, null)
true
}
CompositingStrategy.ModulateAlpha -> {
setLayerType(LAYER_TYPE_NONE, null)
false
}
else -> { // CompositingStrategy.Auto
setLayerType(LAYER_TYPE_NONE, null)
true
}
}
}
override fun hasOverlappingRendering(): Boolean {
return mHasOverlappingRendering
}
override fun isInLayer(position: Offset): Boolean {
val x = position.x
val y = position.y
if (clipToBounds) {
return 0f <= x && x < width && 0f <= y && y < height
}
if (clipToOutline) {
return outlineResolver.isInOutline(position)
}
return true
}
private fun updateOutlineResolver() {
this.outlineProvider = if (outlineResolver.outline != null) {
OutlineProvider
} else {
null
}
}
private fun resetClipBounds() {
this.clipBounds = if (clipToBounds) {
if (clipBoundsCache == null) {
clipBoundsCache = android.graphics.Rect(0, 0, width, height)
} else {
clipBoundsCache!!.set(0, 0, width, height)
}
clipBoundsCache
} else {
null
}
}
override fun resize(size: IntSize) {
val width = size.width
val height = size.height
if (width != this.width || height != this.height) {
pivotX = mTransformOrigin.pivotFractionX * width
pivotY = mTransformOrigin.pivotFractionY * height
outlineResolver.update(Size(width.toFloat(), height.toFloat()))
updateOutlineResolver()
layout(left, top, left + width, top + height)
resetClipBounds()
matrixCache.invalidate()
}
}
override fun move(position: IntOffset) {
val left = position.x
if (left != this.left) {
offsetLeftAndRight(left - this.left)
matrixCache.invalidate()
}
val top = position.y
if (top != this.top) {
offsetTopAndBottom(top - this.top)
matrixCache.invalidate()
}
}
override fun drawLayer(canvas: Canvas) {
drawnWithZ = elevation > 0f
if (drawnWithZ) {
canvas.enableZ()
}
container.drawChild(canvas, this, drawingTime)
if (drawnWithZ) {
canvas.disableZ()
}
}
override fun dispatchDraw(canvas: android.graphics.Canvas) {
isInvalidated = false
canvasHolder.drawInto(canvas) {
var didClip = false
val clipPath = manualClipPath
if (clipPath != null || !canvas.isHardwareAccelerated) {
didClip = true
save()
outlineResolver.clipToOutline(this)
}
drawBlock?.invoke(this)
if (didClip) {
restore()
}
}
}
override fun invalidate() {
if (!isInvalidated) {
isInvalidated = true
super.invalidate()
ownerView.invalidate()
}
}
override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
}
override fun destroy() {
isInvalidated = false
ownerView.requestClearInvalidObservations()
drawBlock = null
invalidateParentLayer = null
// L throws during RenderThread when reusing the Views. The stack trace
// wasn't easy to decode, so this work-around keeps up to 10 Views active
// only for L. On other versions, it uses the WeakHashMap to retain as many
// as are convenient.
val recycle = ownerView.recycle(this@ViewLayer)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M || shouldUseDispatchDraw || !recycle) {
container.removeViewInLayout(this)
} else {
visibility = GONE
}
}
override fun updateDisplayList() {
if (isInvalidated && !shouldUseDispatchDraw) {
isInvalidated = false
updateDisplayList(this)
}
}
override fun forceLayout() {
// Don't do anything. These Views are treated as RenderNodes, so a forced layout
// should not do anything. If we keep this, we get more redrawing than is necessary.
}
override fun mapOffset(point: Offset, inverse: Boolean): Offset {
return if (inverse) {
matrixCache.calculateInverseMatrix(this)?.map(point) ?: Offset.Infinite
} else {
matrixCache.calculateMatrix(this).map(point)
}
}
override fun mapBounds(rect: MutableRect, inverse: Boolean) {
if (inverse) {
val matrix = matrixCache.calculateInverseMatrix(this)
if (matrix != null) {
matrix.map(rect)
} else {
rect.set(0f, 0f, 0f, 0f)
}
} else {
matrixCache.calculateMatrix(this).map(rect)
}
}
override fun reuseLayer(drawBlock: (Canvas) -> Unit, invalidateParentLayer: () -> Unit) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M || shouldUseDispatchDraw) {
container.addView(this)
} else {
visibility = VISIBLE
}
clipToBounds = false
drawnWithZ = false
mTransformOrigin = TransformOrigin.Center
this.drawBlock = drawBlock
this.invalidateParentLayer = invalidateParentLayer
}
override fun transform(matrix: Matrix) {
matrix.timesAssign(matrixCache.calculateMatrix(this))
}
override fun inverseTransform(matrix: Matrix) {
val inverse = matrixCache.calculateInverseMatrix(this)
if (inverse != null) {
matrix.timesAssign(inverse)
}
}
companion object {
private val getMatrix: (View, android.graphics.Matrix) -> Unit = { view, matrix ->
val newMatrix = view.matrix
matrix.set(newMatrix)
}
val OutlineProvider = object : ViewOutlineProvider() {
override fun getOutline(view: View, outline: android.graphics.Outline) {
view as ViewLayer
outline.set(view.outlineResolver.outline!!)
}
}
private var updateDisplayListIfDirtyMethod: Method? = null
private var recreateDisplayList: Field? = null
var hasRetrievedMethod = false
private set
var shouldUseDispatchDraw = false
internal set // internal so that tests can use it.
@SuppressLint("BanUncheckedReflection")
fun updateDisplayList(view: View) {
try {
if (!hasRetrievedMethod) {
hasRetrievedMethod = true
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
updateDisplayListIfDirtyMethod =
View::class.java.getDeclaredMethod("updateDisplayListIfDirty")
recreateDisplayList =
View::class.java.getDeclaredField("mRecreateDisplayList")
} else {
val getDeclaredMethod = Class::class.java.getDeclaredMethod(
"getDeclaredMethod",
String::class.java,
arrayOf<Class<*>>()::class.java
)
updateDisplayListIfDirtyMethod = getDeclaredMethod.invoke(
View::class.java,
"updateDisplayListIfDirty", emptyArray<Class<*>>()
) as Method?
val getDeclaredField = Class::class.java.getDeclaredMethod(
"getDeclaredField",
String::class.java
)
recreateDisplayList = getDeclaredField.invoke(
View::class.java,
"mRecreateDisplayList"
) as Field?
}
updateDisplayListIfDirtyMethod?.isAccessible = true
recreateDisplayList?.isAccessible = true
}
recreateDisplayList?.setBoolean(view, true)
updateDisplayListIfDirtyMethod?.invoke(view)
} catch (_: Throwable) {
shouldUseDispatchDraw = true
}
}
}
}
@RequiresApi(Build.VERSION_CODES.S)
private object ViewLayerVerificationHelper31 {
@androidx.annotation.DoNotInline
fun setRenderEffect(view: View, target: RenderEffect?) {
view.setRenderEffect(target?.asAndroidRenderEffect())
}
}
@RequiresApi(Build.VERSION_CODES.P)
private object ViewLayerVerificationHelper28 {
@androidx.annotation.DoNotInline
fun setOutlineAmbientShadowColor(view: View, target: Int) {
view.outlineAmbientShadowColor = target
}
@androidx.annotation.DoNotInline
fun setOutlineSpotShadowColor(view: View, target: Int) {
view.outlineSpotShadowColor = target
}
}
|
apache-2.0
|
d85a038642d233567226a676c7495d52
| 33.469602 | 100 | 0.60905 | 4.961376 | false | false | false | false |
OpenConference/DroidconBerlin2017
|
app/src/main/java/de/droidcon/berlin2018/ui/sessiondetails/SessionDetailsViewBinding.kt
|
1
|
7904
|
package de.droidcon.berlin2018.ui.sessiondetails
import android.content.Context
import android.graphics.drawable.AnimatedVectorDrawable
import android.support.design.widget.FloatingActionButton
import android.support.v7.widget.Toolbar
import android.transition.TransitionManager
import android.view.View
import android.view.ViewGroup
import android.view.animation.OvershootInterpolator
import android.widget.ImageView
import android.widget.TextView
import com.bluelinelabs.conductor.Controller
import com.jakewharton.rxbinding2.view.RxView
import de.droidcon.berlin2018.R
import de.droidcon.berlin2018.model.Session
import de.droidcon.berlin2018.ui.applicationComponent
import de.droidcon.berlin2018.ui.gone
import de.droidcon.berlin2018.ui.lce.LceViewState
import de.droidcon.berlin2018.ui.lce.LceViewState.Content
import de.droidcon.berlin2018.ui.lce.LceViewState.Loading
import de.droidcon.berlin2018.ui.sessiondetails.SessionDetailsView.SessionState
import de.droidcon.berlin2018.ui.sessions.shortTime
import de.droidcon.berlin2018.ui.sessions.speakerNames
import de.droidcon.berlin2018.ui.viewbinding.LifecycleAwareRef
import de.droidcon.berlin2018.ui.viewbinding.ViewBinding
import de.droidcon.berlin2018.ui.visible
import io.reactivex.Observable
import io.reactivex.subjects.PublishSubject
import jp.wasabeef.picasso.transformations.CropCircleTransformation
import org.threeten.bp.ZoneId
import timber.log.Timber
/**
*
*
* @author Hannes Dorfmann
*/
class SessionDetailsViewBinding : ViewBinding(), SessionDetailsView {
private lateinit var sessionId: String
private lateinit var session: Session
private lateinit var zoneConferenceTakesPlace: ZoneId
private val loadSubject = PublishSubject.create<String>()
private var fab by LifecycleAwareRef<FloatingActionButton>(this)
private var rootView by LifecycleAwareRef<ViewGroup>(this)
private var loadingView by LifecycleAwareRef<View>(this)
private var errorView by LifecycleAwareRef<View>(this)
private var contentView by LifecycleAwareRef<View>(this)
private var speakerPic1 by LifecycleAwareRef<ImageView>(this)
private var speakerPic2 by LifecycleAwareRef<ImageView>(this)
private var speakerPic3 by LifecycleAwareRef<ImageView>(this)
private var speakerPic4 by LifecycleAwareRef<ImageView>(this)
private var spekersName by LifecycleAwareRef<TextView>(this)
private var title by LifecycleAwareRef<TextView>(this)
private var toolbar by LifecycleAwareRef<Toolbar>(this)
private var time by LifecycleAwareRef<TextView>(this)
private var location by LifecycleAwareRef<TextView>(this)
private var description by LifecycleAwareRef<TextView>(this)
override fun postContextAvailable(controller: Controller, context: Context) {
sessionId = controller.args.getString(SessionDetailsController.KEY_SESSION_ID)
zoneConferenceTakesPlace = controller.applicationComponent().clock().getZoneConferenceTakesPlace()
}
override fun bindView(rootView: ViewGroup) {
this.rootView = rootView
fab = rootView.findViewById(R.id.fab)
errorView = rootView.findViewById(R.id.error)
loadingView = rootView.findViewById(R.id.loading)
contentView = rootView.findViewById(R.id.contentView)
speakerPic1 = rootView.findViewById(R.id.speakerPic1)
speakerPic2 = rootView.findViewById(R.id.speakerPic2)
speakerPic3 = rootView.findViewById(R.id.speakerPic3)
speakerPic4 = rootView.findViewById(R.id.speakerPic4)
spekersName = rootView.findViewById(R.id.speakers)
toolbar = rootView.findViewById(R.id.toolbar)
title = rootView.findViewById(R.id.title)
time = rootView.findViewById(R.id.time)
location = rootView.findViewById(R.id.where)
description = rootView.findViewById(R.id.description)
errorView.setOnClickListener { loadSubject.onNext(sessionId) }
toolbar.setNavigationOnClickListener { navigator.popSelfFromBackstack() }
}
override fun loadIntent(): Observable<String> = loadSubject.startWith(sessionId)
override fun clickOnFabIntent(): Observable<Session> = RxView.clicks(fab).doOnNext {
Timber.d("Click on fab")
}.map { session }
override fun render(state: LceViewState<SessionState>) {
Timber.d("render $state")
if (!restoringViewState)
TransitionManager.beginDelayedTransition(rootView)
when (state) {
is Loading -> {
fab.gone()
contentView.gone()
errorView.gone()
loadingView.visible()
}
is Error -> {
fab.gone()
contentView.gone()
errorView.visible()
loadingView.gone()
}
is Content -> {
session = state.data.session
if (fab.visibility != View.VISIBLE && !restoringViewState) {
// TODO use spring animation
fab.scaleX = 0f
fab.scaleY = 0f
fab.visible()
fab.animate()
.scaleX(1f)
.scaleY(1f)
.setStartDelay(600)
.setInterpolator(OvershootInterpolator())
.start()
} else {
fab.scaleX = 1f
fab.scaleY = 1f
fab.visible()
}
if (state.data.favoriteChanged && !restoringViewState) {
Timber.d("not resoring Session ${session.favorite()}")
setFabDrawable(!session.favorite())
fab.startVectorDrawableAnimation()
} else {
Timber.d("not changed or restoring Session ${session.favorite()}")
setFabDrawable(session.favorite())
}
errorView.gone()
loadingView.gone()
contentView.visible()
title.text = session.title()
time.text = session.shortTime(zoneConferenceTakesPlace, true)
location.text = session.locationName()
description.text = session.description()
val speakers = session.speakers()
spekersName.text = speakers.speakerNames()
if (speakers.isNotEmpty()) {
picasso.load(speakers[0].profilePic())
.transform(CropCircleTransformation())
.placeholder(R.drawable.speaker_circle_placeholder)
.into(speakerPic1)
speakerPic1.setOnClickListener { navigator.showSpeakerDetails(speakers[0]) }
}
if (speakers.size >= 2) {
picasso.load(speakers[1].profilePic())
.transform(CropCircleTransformation())
.placeholder(R.drawable.speaker_circle_placeholder)
.into(speakerPic2)
speakerPic2.setOnClickListener { navigator.showSpeakerDetails(speakers[1]) }
}
if (speakers.size >= 3) {
picasso.load(speakers[2].profilePic())
.transform(CropCircleTransformation())
.placeholder(R.drawable.speaker_circle_placeholder)
.into(speakerPic3)
speakerPic3.setOnClickListener { navigator.showSpeakerDetails(speakers[2]) }
}
if (speakers.size >= 4) {
picasso.load(speakers[3].profilePic())
.transform(CropCircleTransformation())
.placeholder(R.drawable.speaker_circle_placeholder)
.into(speakerPic4)
speakerPic4.setOnClickListener { navigator.showSpeakerDetails(speakers[3]) }
}
}
}
}
private fun setFabDrawable(favorite: Boolean) {
val drawable = fab.drawable as AnimatedVectorDrawable
drawable.stop()
if (favorite) {
fab.setImageDrawable(
fab.context.resources.getDrawable(
R.drawable.avd_remove_from_schedule,
fab.context.theme)!!.mutate().constantState.newDrawable())
} else {
fab.setImageDrawable(
fab.context.resources.getDrawable(
R.drawable.avd_add_to_schedule,
fab.context.theme)!!.mutate().constantState.newDrawable())
}
}
}
fun FloatingActionButton.startVectorDrawableAnimation() {
val drawable = drawable as AnimatedVectorDrawable
drawable.start()
}
|
apache-2.0
|
22023bf197d1ac0ade70d7e02a9685a9
| 34.764706 | 102 | 0.708376 | 4.526919 | false | false | false | false |
cqjjjzr/Laplacian
|
Laplacian.Framework/src/main/kotlin/charlie/laplacian/track/property/Property.kt
|
1
|
2359
|
package charlie.laplacian.track.property
import java.io.Serializable
import java.util.*
abstract class Property<out T>: Serializable {
abstract fun getDisplayName(): String
abstract fun getValue(): T
abstract fun getApplicableFor(): Set<PropertyApplicableType>
abstract fun isStringConvertible(): Boolean
override fun equals(other: Any?): Boolean =
other != null && this.javaClass.isAssignableFrom(other.javaClass)
&& this.getValue() == (other as Property<*>).getValue()
private val hashCode by lazy {
var result = super.hashCode()
result = result * 31 + getDisplayName().hashCode()
result = result * 31 + getValue()!!.hashCode()
result = result * 31 + getApplicableFor().hashCode()
result
}
override fun hashCode(): Int = hashCode
override fun toString(): String {
val value: T = getValue()
if (value is Array<*>) {
return if (value.size == 0) ""
else if (value.size == 1) value[0].toString()
else Arrays.toString(value)
}
return value.toString()
}
}
abstract class PropertyImpl<out T>(private val propValue: T,
private val propDisplayName: String,
private val applicableTypes: Set<PropertyApplicableType>,
private val isPropStringConvertible: Boolean = true): Property<T>() {
override fun getDisplayName(): String = propDisplayName
override fun getValue(): T = propValue
override fun getApplicableFor(): Set<PropertyApplicableType> = applicableTypes
override fun isStringConvertible(): Boolean = isPropStringConvertible
}
enum class PropertyApplicableType {
TRACK, GROUPING_METHOD
}
// FOR OPTIMIZE
class PropertyApplicableTypeSets {
companion object {
@JvmStatic
val TRACK_ONLY: Set<PropertyApplicableType> = Collections.unmodifiableSet(EnumSet.of(PropertyApplicableType.TRACK))
@JvmStatic
val GROUPING_ONLY: Set<PropertyApplicableType> = Collections.unmodifiableSet(EnumSet.of(PropertyApplicableType.TRACK))
@JvmStatic
val TRACK_AND_GROUPING: Set<PropertyApplicableType> = Collections.unmodifiableSet(EnumSet.of(PropertyApplicableType.TRACK, PropertyApplicableType.GROUPING_METHOD))
}
}
|
apache-2.0
|
6a8cd5c7bbb27c95eefd41aedcca609f
| 38.983051 | 171 | 0.662993 | 4.997881 | false | false | false | false |
vdewillem/dynamic-extensions-for-alfresco
|
alfresco-integration/src/main/kotlin/com/github/dynamicextensionsalfresco/osgi/FrameworkManager.kt
|
1
|
8573
|
package com.github.dynamicextensionsalfresco.osgi
import com.github.dynamicextensionsalfresco.debug
import com.github.dynamicextensionsalfresco.warn
import org.alfresco.model.ContentModel
import org.alfresco.service.cmr.repository.ContentService
import org.osgi.framework.Bundle
import org.osgi.framework.BundleException
import org.osgi.framework.Constants
import org.osgi.framework.ServiceRegistration
import org.osgi.framework.launch.Framework
import org.osgi.framework.wiring.FrameworkWiring
import org.slf4j.LoggerFactory
import org.springframework.context.ResourceLoaderAware
import org.springframework.core.io.ResourceLoader
import org.springframework.core.io.support.ResourcePatternResolver
import org.springframework.stereotype.Service
import org.springframework.util.Assert
import org.springframework.util.StringUtils
import java.io.FileNotFoundException
import java.io.IOException
import java.util.ArrayList
/**
* Manages a [Framework]'s lifecycle. It taken care of initializing and destroying the Framework and
* (un)registering services and [BundleListener]s.
* @author Laurens Fridael
*/
interface FrameworkManager {
val framework: Framework
}
Service
public class DefaultFrameworkManager(
override val framework: Framework,
private val bundleContextRegistrars: List<BundleContextRegistrar>,
private val repositoryStoreService: RepositoryStoreService,
private val contentService: ContentService,
private val configuration: Configuration,
private val blueprintBundlesLocation: String,
private val standardBundlesLocation: String,
private val customBundlesLocation: String
) : ResourceLoaderAware, FrameworkManager {
private val logger = LoggerFactory.getLogger(javaClass)
private var resourcePatternResolver: ResourcePatternResolver? = null
val serviceRegistrations = ArrayList<ServiceRegistration<*>>()
/**
* Starts the [Framework] and registers services and [BundleListener]s.
* @throws BundleException
*/
public fun initialize() {
startFramework()
registerServices()
val bundles = ArrayList<Bundle>()
bundles.addAll(installCoreBundles())
if (repositoryInstallEnabled) {
bundles.addAll(installRepositoryBundles())
}
startBundles(bundles)
}
protected fun startFramework() {
try {
logger.debug("Starting Framework.")
framework.start()
} catch (e: BundleException) {
logger.error("Could not start Framework.", e)
}
}
/**
* Installs the Bundles that make up the core of the framework. These bundles are started before any extension
* bundles.
*
*
* The core bundles consist of:
*
* * Gemini Blueprint
* * File Install (optional, can be disabled)
* * Any additional standard bundles configured through [.setStandardBundlesLocation].
*
* @return installed bundles
*/
protected fun installCoreBundles(): List<Bundle> {
val bundles = ArrayList<Bundle>()
try {
val locationPatterns = ArrayList<String>()
locationPatterns.add(blueprintBundlesLocation)
if (StringUtils.hasText(standardBundlesLocation)) {
locationPatterns.add(standardBundlesLocation)
}
if (StringUtils.hasText(customBundlesLocation)) {
locationPatterns.add(customBundlesLocation)
}
for (locationPattern in locationPatterns) {
try {
for (bundleResource in resourcePatternResolver!!.getResources(locationPattern)) {
val location = bundleResource.getURI().toString()
logger.debug ("Installing Bundle: {}", location)
try {
val bundle = framework.getBundleContext().installBundle(location, bundleResource.getInputStream())
bundles.add(bundle)
} catch (e: BundleException) {
logger.error("Error installing Bundle: $location", e)
}
}
} catch (e: FileNotFoundException) {
logger.debug("Could not find Bundles at location '{}'.", locationPattern)
}
}
} catch (e: IOException) {
throw RuntimeException("Error installing core Bundles: ${e.getMessage()}", e)
}
return bundles
}
/**
* Installs the Bundles in the repository.
*
*
* This implementation uses RepositoryStoreService.
*/
protected fun installRepositoryBundles(): List<Bundle> {
val bundles = ArrayList<Bundle>()
for (jarFile in repositoryStoreService.getBundleJarFiles()) {
try {
val location = "%s/%s".format(repositoryStoreService.getBundleRepositoryLocation(), jarFile.getName())
logger.debug("Installing Bundle: {}", location)
val reader = contentService.getReader(jarFile.getNodeRef(), ContentModel.PROP_CONTENT)
if (reader != null) {
val bundle = framework.getBundleContext().installBundle(location, reader.getContentInputStream())
bundles.add(bundle)
} else {
logger.warn("unable to read extension content for ${jarFile?.getNodeRef()}")
}
} catch (e: Exception) {
logger.warn("Error installing Bundle: ${jarFile?.getNodeRef()}", e)
}
}
return bundles
}
protected fun registerServices() {
logger.debug("Registering services.")
for (bundleContextRegistrar in bundleContextRegistrars) {
val servicesRegistered = bundleContextRegistrar.registerInBundleContext(framework.getBundleContext())
serviceRegistrations.addAll(servicesRegistered)
}
}
protected fun startBundles(bundles: List<Bundle>) {
val frameworkWiring = framework.adapt(javaClass<FrameworkWiring>())
if (frameworkWiring.resolveBundles(bundles) == false) {
logger.warn { "Could not resolve all ${bundles.size()} bundles." }
}
for (bundle in bundles) {
if (isFragmentBundle(bundle) == false) {
if (bundle.getState() == Bundle.RESOLVED) {
startBundle(bundle)
} else {
logger.warn {
"Bundle '${bundle.getSymbolicName()}' (${bundle.getBundleId()}) is not resolved. Cannot start bundle."
}
}
}
}
}
protected fun startBundle(bundle: Bundle) {
try {
logger.debug("Starting Bundle {}.", bundle.getBundleId())
bundle.start()
} catch (e: BundleException) {
logger.error("Error starting Bundle ${bundle.getBundleId()}.", e)
}
}
protected fun isFragmentBundle(bundle: Bundle): Boolean {
return bundle.getHeaders().get(Constants.FRAGMENT_HOST) != null
}
/**
* Unregisters services and [BundleListener]s and stops the [Framework].
*/
public fun destroy() {
unregisterServices()
stopFramework()
}
protected fun unregisterServices() {
val it = serviceRegistrations.iterator()
while (it.hasNext()) {
val serviceRegistration = it.next()
try {
logger.debug { "Unregistering service ${serviceRegistration.getReference()}" }
serviceRegistration.unregister()
} catch (e: RuntimeException) {
logger.warn("Error unregistering service $serviceRegistration.", e)
} finally {
it.remove()
}
}
}
protected fun stopFramework() {
try {
logger.debug("Stopping Framework.")
framework.stop()
framework.waitForStop(0)
} catch (e: BundleException) {
logger.error("Could not stop Framework.", e)
} catch (ignore: InterruptedException) {}
}
override fun setResourceLoader(resourceLoader: ResourceLoader) {
Assert.isInstanceOf(javaClass<ResourcePatternResolver>(), resourceLoader)
this.resourcePatternResolver = resourceLoader as ResourcePatternResolver
}
val repositoryInstallEnabled: Boolean
get() = configuration.repositoryBundlesEnabled
}
|
apache-2.0
|
400da8307e9d07974bdb3da66bd1e484
| 35.326271 | 126 | 0.627085 | 5.233822 | false | false | false | false |
bsmr-java/lwjgl3
|
modules/templates/src/main/kotlin/org/lwjgl/system/macosx/MacOSXTypes.kt
|
1
|
1740
|
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.system.macosx
import org.lwjgl.generator.*
val MACOSX_PACKAGE = "org.lwjgl.system.macosx"
fun config() {
packageInfo(
MACOSX_PACKAGE,
"Contains bindings to native APIs specific to the Mac OS X operating system."
)
}
val id = "id".opaque_p // Opaque object pointer
val id_p = id.p
val Boolean = IntegerType("Boolean", PrimitiveMapping.BOOLEAN, unsigned = true)
val BOOL = IntegerType("BOOL", PrimitiveMapping.BOOLEAN)
val uint8_tASCII_p = CharSequenceType("uint8_t")
val UInt8 = IntegerType("UInt8", PrimitiveMapping.BYTE, unsigned = true)
val SInt8 = IntegerType("SInt8", PrimitiveMapping.BYTE)
val UInt16 = IntegerType("UInt16", PrimitiveMapping.SHORT, unsigned = true)
val SInt16 = IntegerType("SInt16", PrimitiveMapping.SHORT)
val UInt32 = IntegerType("UInt32", PrimitiveMapping.INT, unsigned = true)
val SInt32 = IntegerType("SInt32", PrimitiveMapping.INT)
val UInt64 = IntegerType("UInt64", PrimitiveMapping.LONG, unsigned = true)
val SInt64 = IntegerType("SInt64", PrimitiveMapping.LONG)
val Float32 = PrimitiveType("Float32", PrimitiveMapping.FLOAT)
val Float64 = PrimitiveType("Float64", PrimitiveMapping.DOUBLE)
val UTF32Char = typedef(UInt32, "UTF32Char")
val UTF16Char = CharType("UTF16Char", CharMapping.UTF16)
val UTF8Char = CharType("UTF8Char", CharMapping.UTF8)
val CFTypeID = IntegerType("CFTypeID", PrimitiveMapping.LONG, unsigned = true)
val CFOptionFlags = IntegerType("CFOptionFlags", PrimitiveMapping.LONG, unsigned = true)
val CFHashCode = IntegerType("CFHashCode", PrimitiveMapping.LONG, unsigned = true)
val CFIndex = IntegerType("CFIndex", PrimitiveMapping.LONG)
val pid_t = "pid_t".p
|
bsd-3-clause
|
67af52b96a5fe9dfd85c30e580e7ef46
| 36.042553 | 88 | 0.764368 | 3.655462 | false | false | false | false |
klazuka/intellij-elm
|
src/main/kotlin/org/elm/ide/inspections/ElmUnresolvedReferenceInspection.kt
|
1
|
6635
|
package org.elm.ide.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemHighlightType.LIKE_UNKNOWN_SYMBOL
import com.intellij.codeInspection.ProblemHighlightType.WEAK_WARNING
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import org.elm.ide.inspections.import.AddImportFix
import org.elm.ide.inspections.import.AddQualifierFix
import org.elm.ide.inspections.import.MakeDeclarationFix
import org.elm.lang.core.psi.ElmFile
import org.elm.lang.core.psi.ElmPsiElement
import org.elm.lang.core.psi.elements.ElmImportClause
import org.elm.lang.core.psi.elements.ElmTypeAnnotation
import org.elm.lang.core.psi.elements.ElmTypeRef
import org.elm.lang.core.psi.elements.ElmValueExpr
import org.elm.lang.core.resolve.reference.*
import org.elm.lang.core.resolve.scope.GlobalScope
import org.elm.lang.core.resolve.scope.ImportScope
import org.elm.lang.core.resolve.scope.ModuleScope
class ElmUnresolvedReferenceInspection : ElmLocalInspection() {
override fun visitElement(element: ElmPsiElement, holder: ProblemsHolder, isOnTheFly: Boolean) {
val refs = element.references.toMutableList()
// Pre-processing: ignore any qualified value/type refs where the module qualifier could not be resolved.
// This is necessary because a single Psi element like ElmValueExpr can return multiple references:
// one for the module name and the other for the value/type name. If the former reference cannot be resolved,
// then the latter is guaranteed not to resolve. And we don't want to double-report the error, so we will
// instead filter them out.
if (refs.any { it is ModuleNameQualifierReference<*> && it.resolve() == null }) {
refs.removeIf { it is QualifiedReference }
}
for (ref in refs.filter { it.resolve() == null }) {
// Give each handler a chance to deal with the unresolved ref before falling back on an error
if (handleTypeAnnotation(ref, element, holder)) continue
if (handleSafeToIgnore(ref, element, holder)) continue
if (handleModuleHiddenByAlias(ref, element, holder)) continue
// Generic unresolved ref error
//
// Most of the time an ElmReferenceElement is not the ancestor of any other ElmReferenceElement.
// And in these cases, it's ok to treat the error as spanning the entire reference element.
// However, in cases like ElmTypeRef, its children can also be reference elements,
// and so it is vital that we correctly mark the error only on the text range that
// contributed the reference.
val errorRange = (element as? ElmTypeRef)?.upperCaseQID?.textRangeInParent
val fixes = mutableListOf<LocalQuickFix>()
val qualifierContext = AddQualifierFix.findApplicableContext(element)
val importContext = AddImportFix.findApplicableContext(element)
if (importContext != null) {
val t = importContext.candidates[0]
fixes += NamedQuickFixHint(
element = element,
delegate = AddImportFix(),
hint = "${t.moduleName}.${t.nameToBeExposed}",
multiple = importContext.candidates.size > 1
)
}
if (qualifierContext != null) {
fixes += AddQualifierFix()
}
val description = "Unresolved reference '${ref.canonicalText}'"
holder.registerProblem(element, description, LIKE_UNKNOWN_SYMBOL, errorRange, *fixes.toTypedArray())
}
}
private fun handleTypeAnnotation(ref: PsiReference, element: PsiElement, holder: ProblemsHolder): Boolean {
if (element !is ElmTypeAnnotation) return false
val description = "'${ref.canonicalText}' does not exist"
val fixes = when {
MakeDeclarationFix(element).isAvailable -> arrayOf(MakeDeclarationFix(element))
else -> emptyArray()
}
holder.registerProblem(element, description, WEAK_WARNING, *fixes)
return true
}
private fun handleSafeToIgnore(ref: PsiReference, element: PsiElement, @Suppress("UNUSED_PARAMETER") holder: ProblemsHolder): Boolean {
// Ignore refs to Kernel (JavaScript) modules
when {
element is ElmValueExpr && element.qid.isKernelModule -> return true
element is ElmImportClause && element.moduleQID.isKernelModule -> return true
}
// Ignore soft refs
if (ref.isSoft) {
return true
}
// Ignore refs to built-in types and values
if (GlobalScope.allBuiltInSymbols.contains(ref.canonicalText)) {
return true
}
return false
}
// When a module is imported using an alias (e.g. `import Json.Decode as D`),
// Elm prohibits the use of the original module name in qualified references.
// So we will try to detect this condition and present a helpful error.
private fun handleModuleHiddenByAlias(ref: PsiReference, element: PsiElement, holder: ProblemsHolder): Boolean {
if (ref !is QualifiedReference) return false
if (element !is ElmValueExpr && element !is ElmTypeRef) return false
val elmFile = element.containingFile as? ElmFile ?: return false
val importDecl = ModuleScope.getImportDecls(elmFile).find { it.moduleQID.text == ref.qualifierPrefix }
?: return false
val aliasName = importDecl.asClause?.upperCaseIdentifier?.text ?: return false
val importScope = ImportScope.fromImportDecl(importDecl) ?: return false
val exposedNames = when (ref) {
is QualifiedValueReference -> importScope.getExposedValues()
is QualifiedConstructorReference -> importScope.getExposedConstructors()
is QualifiedTypeReference -> importScope.getExposedTypes()
else -> error("Unexpected qualified ref type: $ref")
}
if (exposedNames.elements.none { it.name == ref.nameWithoutQualifier })
return false
// Success! The reference would have succeeded were it not for the alias.
val description = "Unresolved reference '${ref.nameWithoutQualifier}'. " +
"Module '${ref.qualifierPrefix}' is imported as '$aliasName' and so you must use the alias here."
holder.registerProblem(element, description, LIKE_UNKNOWN_SYMBOL)
return true
}
}
|
mit
|
7d90fa7be530f8da70bd622dcf0ba8cd
| 47.430657 | 139 | 0.678674 | 4.86437 | false | false | false | false |
kromkrom/csv-dict-parser
|
src/main/kotlin/ru/grushetsky/app.kt
|
1
|
1293
|
package ru.grushetsky
import java.io.File
fun main(args: Array<String>) {
val fileName = parseArgs(args)
val inputFile = getInputFile(fileName)
val outputFile = getOutputFile(fileName)
parse()
saveOutputFile()
}
fun parseArgs(args: Array<String>): String {
when (args.size) {
0 -> throw IllegalArgumentException("No arguments specified")
1 -> return args.first()
else -> throw IllegalArgumentException("Too many arguments")
}
}
fun saveOutputFile() {
// TODO save parsed data to an output file
TODO("not implemented")
}
fun parse() {
// TODO read file and open output file
// TODO parse row
TODO("not implemented")
}
fun getInputFile(fileName: String): File {
val file = File(fileName)
if (!file.canRead()) {
throw IllegalArgumentException("File $fileName doesn't exist or is not accessible")
}
return file
}
fun getOutputFile(fileName: String): File {
val outputFileName = fileName + ".json"
val file = File(outputFileName)
if (file.exists()) {
throw IllegalArgumentException("File $outputFileName already exists, delete it first")
}
if (!file.canWrite()) {
throw IllegalArgumentException("File $outputFileName is not writable")
}
return file
}
|
mit
|
8ee8d8f961da2d535ecaf931c3880e2d
| 24.86 | 94 | 0.665893 | 4.338926 | false | false | false | false |
WonderBeat/vasilich
|
src/main/kotlin/com/vasilich/webhook/components/Extractor.kt
|
1
|
1149
|
package com.vasilich.webhook.processors
import io.netty.handler.codec.http.HttpRequest
import io.netty.handler.codec.http.HttpMethod
import java.nio.charset.Charset
import io.netty.buffer.ByteBufHolder
/**
* Webhook conditionals are applied to HTTP request.
* Conditional statement contains key and value
* Key -> HTTP header / Body / URI
* Value -> matcher
* This fun extracts data from HTTP packet according conditional key
*/
fun httpConditionFieldValueExtractor(conditionKey: String): (HttpRequest) -> String = { request ->
val header = request.headers()?.entries()?.find { it.getKey() == conditionKey }?.getValue()
val charset = Charset.forName("UTF-8")
when {
conditionKey equalsIgnoreCase "uri" -> request.getUri()!!
conditionKey equalsIgnoreCase "body" && request is ByteBufHolder ->
request.content()?.toString(charset)!!
header != null -> header
request.getMethod() == HttpMethod.POST && request is ByteBufHolder ->
request.content()?.toString(charset)!!
else -> throw NoSuchFieldException("Can't apply condition ${conditionKey}. No such header")
}
}
|
gpl-2.0
|
40b23981833c61c18b116d74e2d641b3
| 41.555556 | 99 | 0.70322 | 4.541502 | false | false | false | false |
PublicXiaoWu/XiaoWuMySelf
|
app/src/main/java/com/xiaowu/myself/utils/DialogUtils.kt
|
1
|
1701
|
package com.xiaowu.myself.utils
import android.app.Dialog
import android.content.Context
import android.widget.TextView
import android.widget.Toast
import com.xiaowu.myself.R
import kotlinx.android.synthetic.main.frist_fragment.view.*
/**
* 作者:Administrator on 2017/8/31 14:49
* 邮箱:[email protected]
* dialog工具类
*/
//提示dialog
fun Context.TsDialog(msg: String, flag: Boolean) {
val progressDialog = Dialog(this, R.style.progress_dialog)
progressDialog.setContentView(R.layout.dialog_ts)
progressDialog.setCancelable(true)
progressDialog.setCanceledOnTouchOutside(flag)
progressDialog.window!!.setBackgroundDrawableResource(android.R.color.transparent)
val tv_msg =progressDialog.findViewById<TextView>(R.id.id_tv_loadingmsg)
val save = progressDialog.findViewById<TextView>(R.id.dialog_save)
save.setOnClickListener {
progressDialog.dismiss()
}
tv_msg.text = msg
progressDialog.show()
}
//加载等待dialog
fun Context.loadDialog(msg: String, flag: Boolean): Dialog {
val progressDialog = Dialog(this, R.style.progress_dialog)
progressDialog.setContentView(R.layout.dialog_loading)
progressDialog.setCancelable(true)
progressDialog.setCanceledOnTouchOutside(flag)
progressDialog.window!!.setBackgroundDrawableResource(android.R.color.transparent)
val tv_msg = progressDialog.findViewById<TextView>(R.id.id_tv_loadingmsg)
tv_msg.text = msg
return progressDialog
}
//强大的Toast
fun Context.showToast(message: String): Toast {
var toast: Toast = Toast.makeText(this, message, Toast.LENGTH_SHORT)
// toast.setGravity(Gravity.CENTER,0,0)
toast.show()
return toast
}
|
apache-2.0
|
3b7e244fb616a133730f9835ce703500
| 31.019231 | 86 | 0.758559 | 3.863109 | false | false | false | false |
HabitRPG/habitica-android
|
Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/shops/PurchaseDialogItemContent.kt
|
1
|
887
|
package com.habitrpg.android.habitica.ui.views.shops
import android.content.Context
import android.widget.TextView
import com.habitrpg.android.habitica.databinding.DialogPurchaseContentItemBinding
import com.habitrpg.common.habitica.extensions.layoutInflater
import com.habitrpg.android.habitica.models.shops.ShopItem
import com.habitrpg.common.habitica.views.PixelArtView
class PurchaseDialogItemContent(context: Context) : PurchaseDialogContent(context) {
private val binding = DialogPurchaseContentItemBinding.inflate(context.layoutInflater, this)
override val imageView: PixelArtView
get() = binding.imageView
override val titleTextView: TextView
get() = binding.titleTextView
override fun setItem(item: ShopItem) {
super.setItem(item)
binding.notesTextView.text = item.notes
binding.stepperView.iconDrawable = null
}
}
|
gpl-3.0
|
9672f35de4c515ed05cdd8bc449445c6
| 39.318182 | 96 | 0.789177 | 4.619792 | false | false | false | false |
campos20/tnoodle
|
buildSrc/src/main/kotlin/configurations/ProjectVersions.kt
|
1
|
1177
|
package configurations
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.plugins.ExtraPropertiesExtension
import org.gradle.kotlin.dsl.extra
import org.gradle.kotlin.dsl.invoke
import org.gradle.kotlin.dsl.provideDelegate
object ProjectVersions {
const val TNOODLE_IMPL_KEY = "TNOODLE_IMPL"
const val TNOODLE_VERSION_KEY = "TNOODLE_VERSION"
const val TNOODLE_IMPL_DEFAULT = "TNoodle-LOCAL"
const val TNOODLE_SYMLINK = "TNoodle-Build-latest.jar"
fun Project.gitVersionTag(): String {
val gitVersion: groovy.lang.Closure<String> by extra
return gitVersion()
}
fun Task.setTNoodleRelease(ext: ExtraPropertiesExtension, name: String, version: String? = null) {
ext.set(TNOODLE_IMPL_KEY, name)
ext.set(TNOODLE_VERSION_KEY, version ?: project.version)
}
fun Project.tNoodleImplOrDefault(): String {
return project.findProperty(TNOODLE_IMPL_KEY)?.toString()
?: TNOODLE_IMPL_DEFAULT
}
fun Project.tNoodleVersionOrDefault(): String {
return project.findProperty(TNOODLE_VERSION_KEY)?.toString()
?: "devel-${gitVersionTag()}"
}
}
|
gpl-3.0
|
19f83a54e03f10366eea229a4d0e101a
| 30.810811 | 102 | 0.706032 | 3.513433 | false | false | false | false |
StepicOrg/stepic-android
|
app/src/main/java/org/stepik/android/view/personal_deadlines/ui/dialogs/LearningRateDialog.kt
|
2
|
3113
|
package org.stepik.android.view.personal_deadlines.ui.dialogs
import android.app.Activity
import android.app.Dialog
import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.os.Parcelable
import androidx.core.content.ContextCompat
import androidx.fragment.app.DialogFragment
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import org.stepic.droid.R
import org.stepic.droid.analytic.AmplitudeAnalytic
import org.stepic.droid.analytic.Analytic
import org.stepic.droid.base.App
import org.stepic.droid.util.AppConstants
import org.stepik.android.domain.personal_deadlines.model.LearningRate
import org.stepik.android.view.personal_deadlines.ui.adapters.LearningRateAdapter
import javax.inject.Inject
class LearningRateDialog : DialogFragment() {
companion object {
const val KEY_LEARNING_RATE = "hours_per_week"
const val LEARNING_RATE_REQUEST_CODE = 3994
const val TAG = "learning_rate_dialog"
fun newInstance(): DialogFragment =
LearningRateDialog()
}
@Inject
lateinit var analytic: Analytic
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
App.component().inject(this)
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val context = requireContext()
val recyclerView = RecyclerView(context)
.apply {
layoutManager = LinearLayoutManager(context)
adapter = LearningRateAdapter(LearningRate.values(), ::selectLearningRate)
val divider = DividerItemDecoration(context, DividerItemDecoration.VERTICAL)
divider.setDrawable(ContextCompat.getDrawable(context, R.drawable.bg_divider_vertical)!!)
addItemDecoration(divider)
}
return MaterialAlertDialogBuilder(context)
.setTitle(R.string.deadlines_create_title)
.setView(recyclerView)
.create()
}
private fun selectLearningRate(learningRate: LearningRate) {
targetFragment
?.onActivityResult(
LEARNING_RATE_REQUEST_CODE,
Activity.RESULT_OK,
Intent().putExtra(KEY_LEARNING_RATE, learningRate as Parcelable)
)
val hoursValue = learningRate.millisPerWeek / AppConstants.MILLIS_IN_1HOUR
analytic.reportEvent(Analytic.Deadlines.PERSONAL_DEADLINE_MODE_CHOSEN, Bundle().apply {
putLong(Analytic.Deadlines.Params.HOURS, hoursValue)
})
analytic.reportAmplitudeEvent(AmplitudeAnalytic.Deadlines.PERSONAL_DEADLINE_CREATED,
mapOf(AmplitudeAnalytic.Deadlines.Params.HOURS to hoursValue))
dismiss()
}
override fun onDismiss(dialog: DialogInterface) {
super.onDismiss(dialog)
analytic.reportEvent(Analytic.Deadlines.PERSONAL_DEADLINE_MODE_CLOSED)
}
}
|
apache-2.0
|
db7af4c504667952d5991e84781da607
| 36.518072 | 105 | 0.719884 | 4.972843 | false | false | false | false |
StepicOrg/stepic-android
|
app/src/main/java/org/stepik/android/domain/course_reviews/repository/CourseReviewsRepository.kt
|
1
|
1092
|
package org.stepik.android.domain.course_reviews.repository
import io.reactivex.Completable
import io.reactivex.Maybe
import io.reactivex.Single
import ru.nobird.android.core.model.PagedList
import org.stepik.android.domain.base.DataSourceType
import org.stepik.android.domain.course_reviews.model.CourseReview
interface CourseReviewsRepository {
/**
* Returns [page] of items if exists from [sourceType]
*/
fun getCourseReviewsByCourseId(courseId: Long, page: Int = 1, sourceType: DataSourceType = DataSourceType.CACHE): Single<PagedList<CourseReview>>
fun getCourseReviewByCourseIdAndUserId(courseId: Long, userId: Long, primarySourceType: DataSourceType = DataSourceType.CACHE): Maybe<CourseReview>
fun getCourseReviewsByUserId(userId: Long, page: Int = 1, sourceType: DataSourceType = DataSourceType.CACHE): Single<PagedList<CourseReview>>
fun createCourseReview(courseReview: CourseReview): Single<CourseReview>
fun saveCourseReview(courseReview: CourseReview): Single<CourseReview>
fun removeCourseReview(courseReviewId: Long): Completable
}
|
apache-2.0
|
5b3df0a03223b284b5f0365332cbe91d
| 42.72 | 151 | 0.800366 | 4.706897 | false | false | false | false |
alangibson27/plus-f
|
plus-f/src/main/kotlin/com/socialthingy/plusf/ui/RedefineKeysPanel.kt
|
1
|
3626
|
package com.socialthingy.plusf.ui
import com.socialthingy.plusf.spectrum.UserPreferences
import com.socialthingy.plusf.spectrum.UserPreferences.*
import java.awt.GridLayout
import java.awt.event.*
import java.awt.event.KeyEvent.*
import javax.swing.*
import javax.swing.JComponent.WHEN_FOCUSED
data class JoystickKeys(val up: Int, val down: Int, val left: Int, val right: Int, val fire: Int) {
constructor(prefs: UserPreferences) : this(
prefs.getOrElse(JOYSTICK_UP, VK_Q),
prefs.getOrElse(JOYSTICK_DOWN, VK_A),
prefs.getOrElse(JOYSTICK_LEFT, VK_O),
prefs.getOrElse(JOYSTICK_RIGHT, VK_P),
prefs.getOrElse(JOYSTICK_FIRE, VK_M)
)
fun save(prefs: UserPreferences) {
prefs.set(JOYSTICK_UP, up.toString())
prefs.set(JOYSTICK_DOWN, down.toString())
prefs.set(JOYSTICK_LEFT, left.toString())
prefs.set(JOYSTICK_RIGHT, right.toString())
prefs.set(JOYSTICK_FIRE, fire.toString())
}
}
class RedefineKeysPanel(initialJoystickKeys: JoystickKeys) : JPanel(), KeyListener {
private val up = RedefinableKey("Up", initialJoystickKeys.up)
private val down = RedefinableKey("Down", initialJoystickKeys.down)
private val left = RedefinableKey("Left", initialJoystickKeys.left)
private val right = RedefinableKey("Right", initialJoystickKeys.right)
private val fire = RedefinableKey("Fire", initialJoystickKeys.fire)
private val allKeys = listOf(up, down, left, right, fire)
private var currentKey: RedefinableKey? = null
init {
layout = GridLayout(5, 2, 2, 2)
allKeys.forEach { key ->
add(key.label)
add(key.button)
key.button.addActionListener {
if (key != currentKey) {
currentKey?.hidePrompt()
currentKey = key
key.showPrompt()
}
}
key.button.addKeyListener(this)
}
}
fun getKeys(): JoystickKeys = JoystickKeys(up.value, down.value, left.value, right.value, fire.value)
override fun keyTyped(e: KeyEvent?) {
}
override fun keyPressed(e: KeyEvent?) {
}
override fun keyReleased(e: KeyEvent?) {
if (e != null) {
if (currentKey != null) {
currentKey?.hidePrompt()
currentKey?.value = e.keyCode
}
currentKey = null
}
}
}
private class RedefinableKey(labelText: String, initialValue: Int) {
private val spacePressedKeyStroke = KeyStroke.getKeyStroke("SPACE")
private val spaceReleasedKeyStroke = KeyStroke.getKeyStroke("released SPACE")
val label = JLabel(labelText)
val button = JButton(KeyEvent.getKeyText(initialValue))
var value = initialValue
set(value) {
field = value
button.text = KeyEvent.getKeyText(value)
}
fun showPrompt() {
button.getInputMap(WHEN_FOCUSED).put(spacePressedKeyStroke, "")
button.getInputMap(WHEN_FOCUSED).put(spaceReleasedKeyStroke, "")
button.text = "?"
}
fun hidePrompt() {
button.text = KeyEvent.getKeyText(value)
button.getInputMap(WHEN_FOCUSED).put(spacePressedKeyStroke, "pressed")
button.getInputMap(WHEN_FOCUSED).put(spaceReleasedKeyStroke, "released")
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as RedefinableKey
return label == other.label
}
override fun hashCode(): Int {
return label.hashCode()
}
}
|
mit
|
a35717b56f4668a5dd9ae1580d5feecd
| 31.675676 | 105 | 0.637893 | 4.187067 | false | false | false | false |
exponentjs/exponent
|
packages/expo-calendar/android/src/main/java/expo/modules/calendar/CalendarModule.kt
|
2
|
36192
|
package expo.modules.calendar
import android.Manifest
import android.content.ContentUris
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.database.Cursor
import android.os.Bundle
import android.provider.CalendarContract
import android.util.Log
import expo.modules.interfaces.permissions.Permissions
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import expo.modules.core.ExportedModule
import expo.modules.core.ModuleRegistry
import expo.modules.core.ModuleRegistryDelegate
import expo.modules.core.Promise
import expo.modules.core.arguments.ReadableArguments
import expo.modules.core.errors.InvalidArgumentException
import expo.modules.core.interfaces.ExpoMethod
import expo.modules.core.interfaces.RegistryLifecycleListener
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList
class CalendarModule(
private val mContext: Context,
private val moduleRegistryDelegate: ModuleRegistryDelegate = ModuleRegistryDelegate()
) : ExportedModule(mContext), RegistryLifecycleListener {
private val mPermissions: Permissions by moduleRegistry()
private val moduleCoroutineScope = CoroutineScope(Dispatchers.Default)
private val contentResolver
get() = mContext.contentResolver
private val sdf = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").apply {
timeZone = TimeZone.getTimeZone("GMT")
}
override fun getName() = "ExpoCalendar"
private inline fun <reified T> moduleRegistry() = moduleRegistryDelegate.getFromModuleRegistry<T>()
override fun onCreate(moduleRegistry: ModuleRegistry) {
moduleRegistryDelegate.onCreate(moduleRegistry)
}
override fun onDestroy() {
try {
moduleCoroutineScope.cancel(ModuleDestroyedException())
} catch (e: IllegalStateException) {
Log.e(TAG, "The scope does not have a job in it")
}
}
private inline fun launchAsyncWithModuleScope(promise: Promise, crossinline block: () -> Unit) {
moduleCoroutineScope.launch {
try {
block()
} catch (e: ModuleDestroyedException) {
promise.reject("E_CALENDAR_MODULE_DESTROYED", "Module destroyed, promise canceled")
}
}
}
private inline fun withPermissions(promise: Promise, block: () -> Unit) {
if (!checkPermissions(promise)) {
return
}
block()
}
//region Exported methods
@ExpoMethod
fun getCalendarsAsync(type: String?, promise: Promise) = withPermissions(promise) {
if (type != null && type == "reminder") {
promise.reject("E_CALENDARS_NOT_FOUND", "Calendars of type `reminder` are not supported on Android")
return
}
launchAsyncWithModuleScope(promise) {
try {
val calendars = findCalendars()
promise.resolve(calendars)
} catch (e: Exception) {
promise.reject("E_CALENDARS_NOT_FOUND", "Calendars could not be found", e)
}
}
}
@ExpoMethod
fun saveCalendarAsync(details: ReadableArguments, promise: Promise) = withPermissions(promise) {
launchAsyncWithModuleScope(promise) {
try {
val calendarID = saveCalendar(details)
promise.resolve(calendarID.toString())
} catch (e: Exception) {
promise.reject("E_CALENDAR_NOT_SAVED", "Calendar could not be saved: " + e.message, e)
}
}
}
@ExpoMethod
fun deleteCalendarAsync(calendarID: String, promise: Promise) = withPermissions(promise) {
launchAsyncWithModuleScope(promise) {
val successful = deleteCalendar(calendarID)
if (successful) {
promise.resolve(null)
} else {
promise.reject("E_CALENDAR_NOT_DELETED", "Calendar with id $calendarID could not be deleted")
}
}
}
@ExpoMethod
fun getEventsAsync(startDate: Any, endDate: Any, calendars: List<String>, promise: Promise) = withPermissions(promise) {
launchAsyncWithModuleScope(promise) {
try {
val results = findEvents(startDate, endDate, calendars)
promise.resolve(results)
} catch (e: Exception) {
promise.reject("E_EVENTS_NOT_FOUND", "Events could not be found", e)
}
}
}
@ExpoMethod
fun getEventByIdAsync(eventID: String, promise: Promise) = withPermissions(promise) {
launchAsyncWithModuleScope(promise) {
val results = findEventById(eventID)
if (results != null) {
promise.resolve(results)
} else {
promise.reject("E_EVENT_NOT_FOUND", "Event with id $eventID could not be found")
}
}
}
@ExpoMethod
fun saveEventAsync(details: ReadableArguments, options: ReadableArguments?, promise: Promise) = withPermissions(promise) {
launchAsyncWithModuleScope(promise) {
try {
val eventID = saveEvent(details)
promise.resolve(eventID.toString())
} catch (e: ParseException) {
promise.reject("E_EVENT_NOT_SAVED", "Event could not be saved", e)
} catch (e: EventNotSavedException) {
promise.reject("E_EVENT_NOT_SAVED", "Event could not be saved", e)
} catch (e: InvalidArgumentException) {
promise.reject("E_EVENT_NOT_SAVED", "Event could not be saved", e)
}
}
}
@ExpoMethod
fun deleteEventAsync(details: ReadableArguments, options: ReadableArguments?, promise: Promise) = withPermissions(promise) {
launchAsyncWithModuleScope(promise) {
try {
val successful = removeEvent(details)
if (successful) {
promise.resolve(null)
} else {
promise.reject("E_EVENT_NOT_DELETED", "Event with id ${details.getString("id")} could not be deleted")
}
} catch (e: Exception) {
promise.reject("E_EVENT_NOT_DELETED", "Event with id ${details.getString("id")} could not be deleted", e)
}
}
}
@ExpoMethod
fun getAttendeesForEventAsync(eventID: String, promise: Promise) = withPermissions(promise) {
launchAsyncWithModuleScope(promise) {
val results = findAttendeesByEventId(eventID)
promise.resolve(results)
}
}
@ExpoMethod
fun saveAttendeeForEventAsync(details: ReadableArguments, eventID: String?, promise: Promise) = withPermissions(promise) {
launchAsyncWithModuleScope(promise) {
try {
val attendeeID = saveAttendeeForEvent(details, eventID)
promise.resolve(attendeeID.toString())
} catch (e: Exception) {
promise.reject("E_ATTENDEE_NOT_SAVED", "Attendees for event with id $eventID could not be saved", e)
}
}
}
@ExpoMethod
fun deleteAttendeeAsync(attendeeID: String, promise: Promise) = withPermissions(promise) {
launchAsyncWithModuleScope(promise) {
val successful = deleteAttendee(attendeeID)
if (successful) {
promise.resolve(null)
} else {
promise.reject("E_ATTENDEE_NOT_DELETED", "Attendee with id $attendeeID could not be deleted")
}
}
}
@ExpoMethod
fun openEventInCalendar(eventID: Int, promise: Promise) {
val uri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, eventID.toLong())
val sendIntent = Intent(Intent.ACTION_VIEW).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).setData(uri)
if (sendIntent.resolveActivity(mContext.packageManager) != null) {
mContext.startActivity(sendIntent)
}
promise.resolve(null)
}
@ExpoMethod
fun requestCalendarPermissionsAsync(promise: Promise?) {
mPermissions.askForPermissionsWithPromise(promise, Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR)
}
@ExpoMethod
fun getCalendarPermissionsAsync(promise: Promise) {
mPermissions.getPermissionsWithPromise(promise, Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR)
}
//endregion
@Throws(SecurityException::class)
private fun findCalendars(): List<Bundle> {
val uri = CalendarContract.Calendars.CONTENT_URI
val cursor = contentResolver.query(uri, findCalendarsQueryParameters, null, null, null)
requireNotNull(cursor) { "Cursor shouldn't be null" }
return cursor.use(::serializeEventCalendars)
}
private fun findEvents(startDate: Any, endDate: Any, calendars: List<String>): List<Bundle> {
val eStartDate = Calendar.getInstance()
val eEndDate = Calendar.getInstance()
try {
setDateInCalendar(eStartDate, startDate)
setDateInCalendar(eEndDate, endDate)
} catch (e: ParseException) {
Log.e(TAG, "error parsing", e)
} catch (e: Exception) {
Log.e(TAG, "misc error parsing", e)
}
val uriBuilder = CalendarContract.Instances.CONTENT_URI.buildUpon()
ContentUris.appendId(uriBuilder, eStartDate.timeInMillis)
ContentUris.appendId(uriBuilder, eEndDate.timeInMillis)
val uri = uriBuilder.build()
var selection =
"((${CalendarContract.Instances.BEGIN} >= ${eStartDate.timeInMillis}) " +
"AND (${CalendarContract.Instances.END} <= ${eEndDate.timeInMillis}) " +
"AND (${CalendarContract.Instances.VISIBLE} = 1) "
if (calendars.isNotEmpty()) {
var calendarQuery = "AND ("
for (i in calendars.indices) {
calendarQuery += CalendarContract.Instances.CALENDAR_ID + " = '" + calendars[i] + "'"
if (i != calendars.size - 1) {
calendarQuery += " OR "
}
}
calendarQuery += ")"
selection += calendarQuery
}
selection += ")"
val cursor = contentResolver.query(
uri,
findEventsQueryParameters,
selection,
null,
null
)
requireNotNull(cursor) { "Cursor shouldn't be null" }
return cursor.use(::serializeEvents)
}
private fun findEventById(eventID: String): Bundle? {
val uri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, eventID.toInt().toLong())
val selection = "((${CalendarContract.Events.DELETED} != 1))"
val cursor = contentResolver.query(
uri,
findEventByIdQueryParameters,
selection,
null,
null
)
requireNotNull(cursor) { "Cursor shouldn't be null" }
return cursor.use {
if (cursor.count > 0) {
cursor.moveToFirst()
serializeEvent(cursor)
} else {
null
}
}
}
private fun findCalendarById(calendarID: String): Bundle? {
val uri = ContentUris.withAppendedId(CalendarContract.Calendars.CONTENT_URI, calendarID.toInt().toLong())
val cursor = contentResolver.query(
uri,
findCalendarByIdQueryFields,
null,
null,
null
)
requireNotNull(cursor) { "Cursor shouldn't be null" }
return cursor.use {
if (it.count > 0) {
it.moveToFirst()
serializeEventCalendar(it)
} else {
null
}
}
}
private fun findAttendeesByEventId(eventID: String): List<Bundle> {
val cursor = CalendarContract.Attendees.query(
contentResolver,
eventID.toLong(),
findAttendeesByEventIdQueryParameters
)
return cursor.use(::serializeAttendees)
}
@Throws(Exception::class)
private fun saveCalendar(details: ReadableArguments): Int {
val calendarEventBuilder = CalendarEventBuilder(details)
calendarEventBuilder
.putEventString(CalendarContract.Calendars.NAME, "name")
.putEventString(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME, "title")
.putEventBoolean(CalendarContract.Calendars.VISIBLE, "isVisible")
.putEventBoolean(CalendarContract.Calendars.SYNC_EVENTS, "isSynced")
return if (details.containsKey("id")) {
val calendarID = details.getString("id").toInt()
val updateUri = ContentUris.withAppendedId(CalendarContract.Calendars.CONTENT_URI, calendarID.toLong())
contentResolver.update(updateUri, calendarEventBuilder.build(), null, null)
calendarID
} else {
calendarEventBuilder.checkIfContainsRequiredKeys(
"name",
"title",
"source",
"color",
"accessLevel",
"ownerAccount"
)
val source = details.getArguments("source")
if (!source.containsKey("name")) {
throw Exception("new calendars require a `source` object with a `name`")
}
var isLocalAccount = false
if (source.containsKey("isLocalAccount")) {
isLocalAccount = source.getBoolean("isLocalAccount")
}
if (!source.containsKey("type") && !isLocalAccount) {
throw Exception("new calendars require a `source` object with a `type`, or `isLocalAccount`: true")
}
calendarEventBuilder
.put(CalendarContract.Calendars.ACCOUNT_NAME, source.getString("name"))
.put(CalendarContract.Calendars.ACCOUNT_TYPE, if (isLocalAccount) CalendarContract.ACCOUNT_TYPE_LOCAL else source.getString("type"))
.put(CalendarContract.Calendars.CALENDAR_COLOR, details.getInt("color"))
.put(CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL, calAccessConstantMatchingString(details.getString("accessLevel")))
.put(CalendarContract.Calendars.OWNER_ACCOUNT, details.getString("ownerAccount"))
// end required fields
.putEventTimeZone(CalendarContract.Calendars.CALENDAR_TIME_ZONE, "timeZone")
.putEventDetailsList(CalendarContract.Calendars.ALLOWED_REMINDERS, "allowedReminders") { reminderConstantMatchingString(it as String?) }
.putEventDetailsList(CalendarContract.Calendars.ALLOWED_AVAILABILITY, "allowedAvailabilities") { availabilityConstantMatchingString(it as String) }
.putEventDetailsList(CalendarContract.Calendars.ALLOWED_ATTENDEE_TYPES, "allowedAttendeeTypes") { attendeeTypeConstantMatchingString(it as String) }
val uriBuilder = CalendarContract.Calendars.CONTENT_URI
.buildUpon()
.appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true")
.appendQueryParameter(CalendarContract.Calendars.ACCOUNT_NAME, source.getString("name"))
.appendQueryParameter(CalendarContract.Calendars.ACCOUNT_TYPE, if (isLocalAccount) CalendarContract.ACCOUNT_TYPE_LOCAL else source.getString("type"))
val calendarsUri = uriBuilder.build()
val calendarUri = contentResolver.insert(calendarsUri, calendarEventBuilder.build())
calendarUri!!.lastPathSegment!!.toInt()
}
}
@Throws(SecurityException::class)
private fun deleteCalendar(calendarId: String): Boolean {
val uri = ContentUris.withAppendedId(CalendarContract.Calendars.CONTENT_URI, calendarId.toInt().toLong())
val rows = contentResolver.delete(uri, null, null)
return rows > 0
}
@Throws(EventNotSavedException::class, ParseException::class, SecurityException::class, InvalidArgumentException::class)
private fun saveEvent(details: ReadableArguments): Int {
val calendarEventBuilder = CalendarEventBuilder(details)
if (details.containsKey("startDate")) {
val startCal = Calendar.getInstance()
val startDate = details["startDate"]
try {
when (startDate) {
is String -> {
val parsedDate = sdf.parse(startDate)
if (parsedDate != null) {
startCal.time = parsedDate
calendarEventBuilder.put(CalendarContract.Events.DTSTART, startCal.timeInMillis)
} else {
Log.e(TAG, "Parsed date is null")
}
}
is Number -> {
calendarEventBuilder.put(CalendarContract.Events.DTSTART, startDate.toLong())
}
else -> {
Log.e(TAG, "startDate has unsupported type")
}
}
} catch (e: ParseException) {
Log.e(TAG, "error", e)
throw e
}
}
if (details.containsKey("endDate")) {
val endCal = Calendar.getInstance()
val endDate = details["endDate"]
try {
if (endDate is String) {
val parsedDate = sdf.parse(endDate)
if (parsedDate != null) {
endCal.time = parsedDate
calendarEventBuilder.put(CalendarContract.Events.DTEND, endCal.timeInMillis)
} else {
Log.e(TAG, "Parsed date is null")
}
} else if (endDate is Number) {
calendarEventBuilder.put(CalendarContract.Events.DTEND, endDate.toLong())
}
} catch (e: ParseException) {
Log.e(TAG, "error", e)
throw e
}
}
if (details.containsKey("recurrenceRule")) {
val recurrenceRule = details.getArguments("recurrenceRule")
if (recurrenceRule.containsKey("frequency")) {
val frequency = recurrenceRule.getString("frequency")
var interval: Int? = null
var occurrence: Int? = null
var endDate: String? = null
if (recurrenceRule.containsKey("interval")) {
interval = recurrenceRule.getInt("interval")
}
if (recurrenceRule.containsKey("occurrence")) {
occurrence = recurrenceRule.getInt("occurrence")
}
if (recurrenceRule.containsKey("endDate")) {
val format = SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'")
val endDateObj = recurrenceRule["endDate"]
if (endDateObj is String) {
val parsedDate = sdf.parse(endDateObj)
if (parsedDate != null) {
endDate = format.format(parsedDate)
} else {
Log.e(TAG, "endDate is null")
}
} else if (endDateObj is Number) {
val calendar = Calendar.getInstance()
calendar.timeInMillis = endDateObj.toLong()
endDate = format.format(calendar.time)
}
}
if (endDate == null && occurrence == null) {
val eventStartDate = calendarEventBuilder.getAsLong(CalendarContract.Events.DTSTART)
val eventEndDate = calendarEventBuilder.getAsLong(CalendarContract.Events.DTEND)
val duration = (eventEndDate - eventStartDate) / 1000
calendarEventBuilder
.putNull(CalendarContract.Events.LAST_DATE)
.putNull(CalendarContract.Events.DTEND)
.put(CalendarContract.Events.DURATION, "PT${duration}S")
}
val rule = createRecurrenceRule(frequency, interval, endDate, occurrence)
calendarEventBuilder.put(CalendarContract.Events.RRULE, rule)
}
}
calendarEventBuilder
.putEventBoolean(CalendarContract.Events.HAS_ALARM, "alarms", true)
.putEventString(CalendarContract.Events.AVAILABILITY, "availability", ::availabilityConstantMatchingString)
.putEventString(CalendarContract.Events.TITLE, "title")
.putEventString(CalendarContract.Events.DESCRIPTION, "notes")
.putEventString(CalendarContract.Events.EVENT_LOCATION, "location")
.putEventString(CalendarContract.Events.ORGANIZER, "organizerEmail")
.putEventBoolean(CalendarContract.Events.ALL_DAY, "allDay")
.putEventBoolean(CalendarContract.Events.GUESTS_CAN_MODIFY, "guestsCanModify")
.putEventBoolean(CalendarContract.Events.GUESTS_CAN_INVITE_OTHERS, "guestsCanInviteOthers")
.putEventBoolean(CalendarContract.Events.GUESTS_CAN_SEE_GUESTS, "guestsCanSeeGuests")
.putEventTimeZone(CalendarContract.Events.EVENT_TIMEZONE, "timeZone")
.putEventTimeZone(CalendarContract.Events.EVENT_END_TIMEZONE, "endTimeZone")
.putEventString(CalendarContract.Events.ACCESS_LEVEL, "accessLevel", ::accessConstantMatchingString)
return if (details.containsKey("id")) {
val eventID = details.getString("id").toInt()
val updateUri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, eventID.toLong())
contentResolver.update(updateUri, calendarEventBuilder.build(), null, null)
removeRemindersForEvent(eventID)
if (details.containsKey("alarms")) {
createRemindersForEvent(eventID, details.getList("alarms"))
}
eventID
} else {
if (details.containsKey("calendarId")) {
val calendar = findCalendarById(details.getString("calendarId"))
if (calendar != null) {
calendarEventBuilder.put(CalendarContract.Events.CALENDAR_ID, calendar.getString("id")!!.toInt())
} else {
throw InvalidArgumentException("Couldn't find calendar with given id: " + details.getString("calendarId"))
}
} else {
throw InvalidArgumentException("CalendarId is required.")
}
val eventsUri = CalendarContract.Events.CONTENT_URI
val eventUri = contentResolver.insert(eventsUri, calendarEventBuilder.build())
?: throw EventNotSavedException()
val eventID = eventUri.lastPathSegment!!.toInt()
if (details.containsKey("alarms")) {
createRemindersForEvent(eventID, details.getList("alarms"))
}
eventID
}
}
@Throws(ParseException::class, SecurityException::class)
private fun removeEvent(details: ReadableArguments): Boolean {
val rows: Int
val eventID = details.getString("id").toInt()
if (!details.containsKey("instanceStartDate")) {
val uri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, eventID.toLong())
rows = contentResolver.delete(uri, null, null)
return rows > 0
} else {
val exceptionValues = ContentValues()
val startCal = Calendar.getInstance()
val instanceStartDate = details["instanceStartDate"]
try {
if (instanceStartDate is String) {
val parsedDate = sdf.parse(instanceStartDate)
if (parsedDate != null) {
startCal.time = parsedDate
exceptionValues.put(CalendarContract.Events.ORIGINAL_INSTANCE_TIME, startCal.timeInMillis)
} else {
Log.e(TAG, "Parsed date is null")
}
} else if (instanceStartDate is Number) {
exceptionValues.put(CalendarContract.Events.ORIGINAL_INSTANCE_TIME, instanceStartDate.toLong())
}
} catch (e: ParseException) {
Log.e(TAG, "error", e)
throw e
}
exceptionValues.put(CalendarContract.Events.STATUS, CalendarContract.Events.STATUS_CANCELED)
val exceptionUri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_EXCEPTION_URI, eventID.toLong())
contentResolver.insert(exceptionUri, exceptionValues)
}
return true
}
@Throws(Exception::class, SecurityException::class)
private fun saveAttendeeForEvent(details: ReadableArguments, eventID: String?): Int {
// Key "id" should be called "attendeeId",
// but for now to keep API reverse compatibility it wasn't changed
val isNew = !details.containsKey("id")
val attendeeBuilder = AttendeeBuilder(details)
.putString("name", CalendarContract.Attendees.ATTENDEE_NAME)
.putString("email", CalendarContract.Attendees.ATTENDEE_EMAIL, isNew)
.putString("role", CalendarContract.Attendees.ATTENDEE_RELATIONSHIP, isNew, ::attendeeRelationshipConstantMatchingString)
.putString("type", CalendarContract.Attendees.ATTENDEE_TYPE, isNew, ::attendeeTypeConstantMatchingString)
.putString("status", CalendarContract.Attendees.ATTENDEE_STATUS, isNew, ::attendeeStatusConstantMatchingString)
return if (isNew) {
attendeeBuilder.put(CalendarContract.Attendees.EVENT_ID, eventID?.toInt())
val attendeesUri = CalendarContract.Attendees.CONTENT_URI
val attendeeUri = contentResolver.insert(attendeesUri, attendeeBuilder.build())
attendeeUri!!.lastPathSegment!!.toInt()
} else {
val attendeeID = details.getString("id").toInt()
val updateUri = ContentUris.withAppendedId(CalendarContract.Attendees.CONTENT_URI, attendeeID.toLong())
contentResolver.update(updateUri, attendeeBuilder.build(), null, null)
attendeeID
}
}
@Throws(SecurityException::class)
private fun deleteAttendee(attendeeID: String): Boolean {
val rows: Int
val uri = ContentUris.withAppendedId(CalendarContract.Attendees.CONTENT_URI, attendeeID.toInt().toLong())
rows = contentResolver.delete(uri, null, null)
return rows > 0
}
@Throws(SecurityException::class)
private fun createRemindersForEvent(eventID: Int, reminders: List<*>) {
for (i in reminders.indices) {
val reminder = reminders[i] as Map<*, *>
val relativeOffset = reminder["relativeOffset"]
if (relativeOffset is Number) {
val minutes = -relativeOffset.toInt()
var method = CalendarContract.Reminders.METHOD_DEFAULT
val reminderValues = ContentValues()
if (reminder.containsKey("method")) {
method = reminderConstantMatchingString(reminder["method"] as? String)
}
reminderValues.put(CalendarContract.Reminders.EVENT_ID, eventID)
reminderValues.put(CalendarContract.Reminders.MINUTES, minutes)
reminderValues.put(CalendarContract.Reminders.METHOD, method)
contentResolver.insert(CalendarContract.Reminders.CONTENT_URI, reminderValues)
}
}
}
@Throws(SecurityException::class)
private fun removeRemindersForEvent(eventID: Int) {
val cursor = CalendarContract.Reminders.query(
contentResolver, eventID.toLong(),
arrayOf(
CalendarContract.Reminders._ID
)
)
while (cursor.moveToNext()) {
val reminderUri = ContentUris.withAppendedId(CalendarContract.Reminders.CONTENT_URI, cursor.getLong(0))
contentResolver.delete(reminderUri, null, null)
}
}
private fun createRecurrenceRule(recurrence: String, interval: Int?, endDate: String?, occurrence: Int?): String {
var rrule: String = when (recurrence) {
"daily" -> "FREQ=DAILY"
"weekly" -> "FREQ=WEEKLY"
"monthly" -> "FREQ=MONTHLY"
"yearly" -> "FREQ=YEARLY"
else -> ""
}
if (interval != null) {
rrule += ";INTERVAL=$interval"
}
if (endDate != null) {
rrule += ";UNTIL=$endDate"
} else if (occurrence != null) {
rrule += ";COUNT=$occurrence"
}
return rrule
}
private fun serializeEvents(cursor: Cursor): List<Bundle> {
val results: MutableList<Bundle> = ArrayList()
while (cursor.moveToNext()) {
results.add(serializeEvent(cursor))
}
return results
}
private fun serializeEvent(cursor: Cursor): Bundle {
val foundStartDate = Calendar.getInstance()
val foundEndDate = Calendar.getInstance()
var startDateUTC = ""
var endDateUTC = ""
// may be CalendarContract.Instances.BEGIN or CalendarContract.Events.DTSTART (which have different string values)
val startDate = cursor.getString(3)
if (startDate != null) {
foundStartDate.timeInMillis = startDate.toLong()
startDateUTC = sdf.format(foundStartDate.time)
}
// may be CalendarContract.Instances.END or CalendarContract.Events.DTEND (which have different string values)
val endDate = cursor.getString(4)
if (endDate != null) {
foundEndDate.timeInMillis = endDate.toLong()
endDateUTC = sdf.format(foundEndDate.time)
}
val rrule = optStringFromCursor(cursor, CalendarContract.Events.RRULE)
val rruleBundle = if (rrule != null) {
val recurrenceRule = Bundle()
val recurrenceRules = rrule.split(";").toTypedArray()
recurrenceRule.putString("frequency", recurrenceRules[0].split("=").toTypedArray()[1].toLowerCase(Locale.getDefault()))
if (recurrenceRules.size >= 2 && recurrenceRules[1].split("=").toTypedArray()[0] == "INTERVAL") {
recurrenceRule.putInt("interval", recurrenceRules[1].split("=").toTypedArray()[1].toInt())
}
if (recurrenceRules.size >= 3) {
val terminationRules = recurrenceRules[2].split("=").toTypedArray()
if (terminationRules.size >= 2) {
if (terminationRules[0] == "UNTIL") {
try {
recurrenceRule.putString("endDate", sdf.parse(terminationRules[1])?.toString())
} catch (e: ParseException) {
Log.e(TAG, "Couldn't parse the `endDate` property.", e)
} catch (e: NullPointerException) {
Log.e(TAG, "endDate is null", e)
}
} else if (terminationRules[0] == "COUNT") {
recurrenceRule.putInt("occurrence", recurrenceRules[2].split("=").toTypedArray()[1].toInt())
}
}
Log.e(TAG, "Couldn't parse termination rules: '${recurrenceRules[2]}'.", null)
}
recurrenceRule
} else {
null
}
// may be CalendarContract.Instances.EVENT_ID or CalendarContract.Events._ID (which have different string values)
val event = Bundle().apply {
rruleBundle?.let {
putBundle("recurrenceRule", it)
}
putString("id", cursor.getString(0))
putString("calendarId", optStringFromCursor(cursor, CalendarContract.Events.CALENDAR_ID))
putString("title", optStringFromCursor(cursor, CalendarContract.Events.TITLE))
putString("notes", optStringFromCursor(cursor, CalendarContract.Events.DESCRIPTION))
putString("startDate", startDateUTC)
putString("endDate", endDateUTC)
putBoolean("allDay", optIntFromCursor(cursor, CalendarContract.Events.ALL_DAY) != 0)
putString("location", optStringFromCursor(cursor, CalendarContract.Events.EVENT_LOCATION))
putString("availability", availabilityStringMatchingConstant(optIntFromCursor(cursor, CalendarContract.Events.AVAILABILITY)))
putParcelableArrayList("alarms", serializeAlarms(cursor.getLong(0)))
putString("organizerEmail", optStringFromCursor(cursor, CalendarContract.Events.ORGANIZER))
putString("timeZone", optStringFromCursor(cursor, CalendarContract.Events.EVENT_TIMEZONE))
putString("endTimeZone", optStringFromCursor(cursor, CalendarContract.Events.EVENT_END_TIMEZONE))
putString("accessLevel", accessStringMatchingConstant(optIntFromCursor(cursor, CalendarContract.Events.ACCESS_LEVEL)))
putBoolean("guestsCanModify", optIntFromCursor(cursor, CalendarContract.Events.GUESTS_CAN_MODIFY) != 0)
putBoolean("guestsCanInviteOthers", optIntFromCursor(cursor, CalendarContract.Events.GUESTS_CAN_INVITE_OTHERS) != 0)
putBoolean("guestsCanSeeGuests", optIntFromCursor(cursor, CalendarContract.Events.GUESTS_CAN_SEE_GUESTS) != 0)
putString("originalId", optStringFromCursor(cursor, CalendarContract.Events.ORIGINAL_ID))
}
// unfortunately the string values of CalendarContract.Events._ID and CalendarContract.Instances._ID are equal
// so we'll use the somewhat brittle column number from the query
if (cursor.columnCount > 18) {
event.putString("instanceId", cursor.getString(18))
}
return event
}
private fun serializeAlarms(eventID: Long): ArrayList<Bundle> {
val alarms = ArrayList<Bundle>()
val cursor = CalendarContract.Reminders.query(
contentResolver, eventID,
arrayOf(
CalendarContract.Reminders.MINUTES,
CalendarContract.Reminders.METHOD
)
)
while (cursor.moveToNext()) {
val thisAlarm = Bundle()
thisAlarm.putInt("relativeOffset", -cursor.getInt(0))
val method = cursor.getInt(1)
thisAlarm.putString("method", reminderStringMatchingConstant(method))
alarms.add(thisAlarm)
}
return alarms
}
private fun serializeEventCalendars(cursor: Cursor): List<Bundle> {
val results: MutableList<Bundle> = ArrayList()
while (cursor.moveToNext()) {
results.add(serializeEventCalendar(cursor))
}
return results
}
private fun serializeEventCalendar(cursor: Cursor): Bundle {
val calendar = Bundle().apply {
putString("id", optStringFromCursor(cursor, CalendarContract.Calendars._ID))
putString("title", optStringFromCursor(cursor, CalendarContract.Calendars.CALENDAR_DISPLAY_NAME))
putBoolean("isPrimary", optStringFromCursor(cursor, CalendarContract.Calendars.IS_PRIMARY) === "1")
putStringArrayList("allowedAvailabilities", calendarAllowedAvailabilitiesFromDBString(stringFromCursor(cursor, CalendarContract.Calendars.ALLOWED_AVAILABILITY)))
putString("name", optStringFromCursor(cursor, CalendarContract.Calendars.NAME))
putString("color", String.format("#%06X", 0xFFFFFF and optIntFromCursor(cursor, CalendarContract.Calendars.CALENDAR_COLOR)))
putString("ownerAccount", optStringFromCursor(cursor, CalendarContract.Calendars.OWNER_ACCOUNT))
putString("timeZone", optStringFromCursor(cursor, CalendarContract.Calendars.CALENDAR_TIME_ZONE))
putStringArrayList("allowedReminders", calendarAllowedRemindersFromDBString(stringFromCursor(cursor, CalendarContract.Calendars.ALLOWED_REMINDERS)))
putStringArrayList("allowedAttendeeTypes", calendarAllowedAttendeeTypesFromDBString(stringFromCursor(cursor, CalendarContract.Calendars.ALLOWED_ATTENDEE_TYPES)))
putBoolean("isVisible", optIntFromCursor(cursor, CalendarContract.Calendars.VISIBLE) != 0)
putBoolean("isSynced", optIntFromCursor(cursor, CalendarContract.Calendars.SYNC_EVENTS) != 0)
val accessLevel = optIntFromCursor(cursor, CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL)
putString("accessLevel", calAccessStringMatchingConstant(accessLevel))
putBoolean(
"allowsModifications",
accessLevel == CalendarContract.Calendars.CAL_ACCESS_ROOT ||
accessLevel == CalendarContract.Calendars.CAL_ACCESS_OWNER ||
accessLevel == CalendarContract.Calendars.CAL_ACCESS_EDITOR ||
accessLevel == CalendarContract.Calendars.CAL_ACCESS_CONTRIBUTOR
)
}
val source = Bundle().apply {
putString("name", optStringFromCursor(cursor, CalendarContract.Calendars.ACCOUNT_NAME))
val type = optStringFromCursor(cursor, CalendarContract.Calendars.ACCOUNT_TYPE)
putString("type", type)
putBoolean("isLocalAccount", type == CalendarContract.ACCOUNT_TYPE_LOCAL)
}
calendar.putBundle("source", source)
return calendar
}
private fun serializeAttendees(cursor: Cursor): List<Bundle> {
val results: MutableList<Bundle> = ArrayList()
while (cursor.moveToNext()) {
results.add(serializeAttendee(cursor))
}
return results
}
private fun serializeAttendee(cursor: Cursor): Bundle = Bundle().apply {
putString("id", optStringFromCursor(cursor, CalendarContract.Attendees._ID))
putString("name", optStringFromCursor(cursor, CalendarContract.Attendees.ATTENDEE_NAME))
putString("email", optStringFromCursor(cursor, CalendarContract.Attendees.ATTENDEE_EMAIL))
putString("role", attendeeRelationshipStringMatchingConstant(optIntFromCursor(cursor, CalendarContract.Attendees.ATTENDEE_RELATIONSHIP)))
putString("type", attendeeTypeStringMatchingConstant(optIntFromCursor(cursor, CalendarContract.Attendees.ATTENDEE_TYPE)))
putString("status", attendeeStatusStringMatchingConstant(optIntFromCursor(cursor, CalendarContract.Attendees.ATTENDEE_STATUS)))
}
private fun optStringFromCursor(cursor: Cursor, columnName: String): String? {
val index = cursor.getColumnIndex(columnName)
return if (index == -1) {
null
} else {
cursor.getString(index)
}
}
private fun stringFromCursor(cursor: Cursor, columnName: String): String {
val index = cursor.getColumnIndex(columnName)
if (index == -1) {
throw Exception("String not found")
} else {
return cursor.getString(index)
}
}
private fun optIntFromCursor(cursor: Cursor, columnName: String): Int {
val index = cursor.getColumnIndex(columnName)
return if (index == -1) {
0
} else {
cursor.getInt(index)
}
}
private fun checkPermissions(promise: Promise): Boolean {
if (!mPermissions.hasGrantedPermissions(Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR)) {
promise.reject("E_MISSING_PERMISSIONS", "CALENDAR permission is required to do this operation.")
return false
}
return true
}
private fun setDateInCalendar(calendar: Calendar, date: Any) {
when (date) {
is String -> {
val parsedDate = sdf.parse(date)
if (parsedDate != null) {
calendar.time = parsedDate
} else {
Log.e(TAG, "Parsed date is null")
}
}
is Number -> {
calendar.timeInMillis = date.toLong()
}
else -> {
Log.e(TAG, "date has unsupported type")
}
}
}
companion object {
internal val TAG = CalendarModule::class.java.simpleName
}
}
|
bsd-3-clause
|
00cc996fabb40b7ea414389a9683d395
| 40.220957 | 167 | 0.691396 | 4.513281 | false | false | false | false |
Heiner1/AndroidAPS
|
medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/ui/MedtronicUITask.kt
|
1
|
7329
|
package info.nightscout.androidaps.plugins.pump.medtronic.comm.ui
import dagger.android.HasAndroidInjector
import info.nightscout.shared.logging.AAPSLogger
import info.nightscout.shared.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.pump.common.defs.PumpDeviceState
import info.nightscout.androidaps.plugins.pump.common.events.EventRileyLinkDeviceStatusChange
import info.nightscout.androidaps.plugins.pump.medtronic.comm.MedtronicCommunicationManager
import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.PumpHistoryEntry
import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.BasalProfile
import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.TempBasalPair
import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicCommandType
import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicUIResponseType
import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus
import info.nightscout.androidaps.plugins.pump.medtronic.events.EventMedtronicPumpValuesChanged
import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil
import org.joda.time.LocalDateTime
import java.util.*
import javax.inject.Inject
/**
* Created by andy on 6/14/18.
*/
class MedtronicUITask {
@Inject lateinit var rxBus: RxBus
@Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var medtronicPumpStatus: MedtronicPumpStatus
@Inject lateinit var medtronicUtil: MedtronicUtil
private val injector: HasAndroidInjector
var commandType: MedtronicCommandType
var result: Any? = null
var errorDescription: String? = null
var parameters: List<Any?>? = null
var responseType: MedtronicUIResponseType? = null
constructor(injector: HasAndroidInjector, commandType: MedtronicCommandType) {
this.injector = injector
this.injector.androidInjector().inject(this)
this.commandType = commandType
}
constructor(injector: HasAndroidInjector, commandType: MedtronicCommandType, parameters: List<Any>?) {
this.injector = injector
this.injector.androidInjector().inject(this)
this.commandType = commandType
this.parameters = parameters //as Array<Any>
}
fun execute(communicationManager: MedtronicCommunicationManager) {
aapsLogger.debug(LTag.PUMP, "MedtronicUITask: @@@ In execute. $commandType")
when (commandType) {
MedtronicCommandType.PumpModel -> {
result = communicationManager.getPumpModel()
}
MedtronicCommandType.GetBasalProfileSTD -> {
result = communicationManager.getBasalProfile()
}
MedtronicCommandType.GetRemainingInsulin -> {
result = communicationManager.getRemainingInsulin()
}
MedtronicCommandType.GetRealTimeClock -> {
result = communicationManager.getPumpTime()
//medtronicUtil.pumpTime = null
}
MedtronicCommandType.SetRealTimeClock -> {
result = communicationManager.setPumpTime()
}
MedtronicCommandType.GetBatteryStatus -> {
result = communicationManager.getRemainingBattery()
}
MedtronicCommandType.SetTemporaryBasal -> {
val tbr = getTbrSettings()
if (tbr != null) {
result = communicationManager.setTemporaryBasal(tbr)
}
}
MedtronicCommandType.ReadTemporaryBasal -> {
result = communicationManager.getTemporaryBasal()
}
MedtronicCommandType.Settings, MedtronicCommandType.Settings_512 -> {
result = communicationManager.getPumpSettings()
}
MedtronicCommandType.SetBolus -> {
val amount = getDoubleFromParameters(0)
if (amount != null) result = communicationManager.setBolus(amount)
}
MedtronicCommandType.CancelTBR -> {
result = communicationManager.cancelTBR()
}
MedtronicCommandType.SetBasalProfileSTD,
MedtronicCommandType.SetBasalProfileA -> {
val profile = parameters!![0] as BasalProfile
result = communicationManager.setBasalProfile(profile)
}
MedtronicCommandType.GetHistoryData -> {
result = communicationManager.getPumpHistory(parameters!![0] as PumpHistoryEntry?,
parameters!![1] as LocalDateTime?)
}
else -> {
aapsLogger.warn(LTag.PUMP, String.format(Locale.ENGLISH, "This commandType is not supported (yet) - %s.", commandType))
// invalid = true;
responseType = MedtronicUIResponseType.Invalid
}
}
if (responseType == null) {
if (result == null) {
errorDescription = communicationManager.errorResponse
responseType = MedtronicUIResponseType.Error
} else {
responseType = MedtronicUIResponseType.Data
}
}
}
private fun getTbrSettings(): TempBasalPair? {
return TempBasalPair(getDoubleFromParameters(0)!!, //
false, //
getIntegerFromParameters(1))
}
private fun getFloatFromParameters(index: Int): Float {
return parameters!![index] as Float
}
fun getDoubleFromParameters(index: Int): Double? {
return parameters!![index] as Double?
}
private fun getIntegerFromParameters(index: Int): Int {
return parameters!![index] as Int
}
val isReceived: Boolean
get() = result != null || errorDescription != null
fun postProcess(postprocessor: MedtronicUIPostprocessor) {
aapsLogger.debug(LTag.PUMP, "MedtronicUITask: @@@ In execute. $commandType")
if (responseType === MedtronicUIResponseType.Data) {
postprocessor.postProcessData(this)
}
if (responseType === MedtronicUIResponseType.Invalid) {
rxBus.send(EventRileyLinkDeviceStatusChange(PumpDeviceState.ErrorWhenCommunicating,
"Unsupported command in MedtronicUITask"))
} else if (responseType === MedtronicUIResponseType.Error) {
rxBus.send(EventRileyLinkDeviceStatusChange(PumpDeviceState.ErrorWhenCommunicating,
errorDescription))
} else {
rxBus.send(EventMedtronicPumpValuesChanged())
medtronicPumpStatus.setLastCommunicationToNow()
}
medtronicUtil.setCurrentCommand(null)
}
fun hasData(): Boolean {
return responseType === MedtronicUIResponseType.Data
}
fun getParameter(index: Int): Any? {
return parameters!![index]
}
}
|
agpl-3.0
|
d4b63afad143a266d1df8c6d9e8a466b
| 40.179775 | 135 | 0.630645 | 5.734742 | false | false | false | false |
sirixdb/sirix
|
bundles/sirix-rest-api/src/main/kotlin/org/sirix/rest/crud/json/JsonUpdate.kt
|
1
|
15259
|
package org.sirix.rest.crud.json
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonToken
import io.vertx.core.Promise
import io.vertx.core.http.HttpHeaders
import io.vertx.ext.web.Route
import io.vertx.ext.web.RoutingContext
import io.vertx.kotlin.coroutines.await
import org.sirix.access.Databases
import org.sirix.access.trx.node.HashType
import org.sirix.access.trx.node.json.objectvalue.*
import org.sirix.api.json.JsonNodeTrx
import org.sirix.rest.crud.Revisions
import org.sirix.rest.crud.SirixDBUser
import org.sirix.rest.crud.json.JsonInsertionMode.Companion.getInsertionModeByName
import org.sirix.service.json.JsonNumber
import org.sirix.service.json.serialize.JsonSerializer
import org.sirix.service.json.shredder.JsonShredder
import java.io.IOException
import java.io.StringWriter
import java.math.BigInteger
import java.nio.file.Path
import java.time.Instant
import java.util.*
@Suppress("unused")
enum class JsonInsertionMode {
ASFIRSTCHILD {
override fun insertSubtree(
wtx: JsonNodeTrx,
jsonReader: JsonReader,
commitMessage: String?,
commitTimestamp: Instant?
) {
wtx.insertSubtreeAsFirstChild(jsonReader, JsonNodeTrx.Commit.NO)
wtx.commit(commitMessage, commitTimestamp)
}
override fun insertString(
wtx: JsonNodeTrx,
jsonReader: JsonReader,
commitMessage: String?,
commitTimestamp: Instant?
) {
wtx.insertStringValueAsFirstChild(jsonReader.nextString())
wtx.commit(commitMessage, commitTimestamp)
}
override fun insertNumber(
wtx: JsonNodeTrx,
jsonReader: JsonReader,
commitMessage: String?,
commitTimestamp: Instant?
) {
wtx.insertNumberValueAsFirstChild(JsonNumber.stringToNumber(jsonReader.nextString()))
wtx.commit(commitMessage, commitTimestamp)
}
override fun insertNull(
wtx: JsonNodeTrx,
jsonReader: JsonReader,
commitMessage: String?,
commitTimestamp: Instant?
) {
jsonReader.nextNull()
wtx.insertNullValueAsFirstChild()
wtx.commit(commitMessage, commitTimestamp)
}
override fun insertBoolean(
wtx: JsonNodeTrx,
jsonReader: JsonReader,
commitMessage: String?,
commitTimestamp: Instant?
) {
wtx.insertBooleanValueAsFirstChild(jsonReader.nextBoolean())
wtx.commit(commitMessage, commitTimestamp)
}
override fun insertObjectRecord(
wtx: JsonNodeTrx,
jsonReader: JsonReader,
commitMessage: String?,
commitTimestamp: Instant?
) {
wtx.insertObjectRecordAsFirstChild(jsonReader.nextName(), getObjectRecordValue(jsonReader))
wtx.commit(commitMessage, commitTimestamp)
}
},
ASRIGHTSIBLING {
override fun insertSubtree(
wtx: JsonNodeTrx,
jsonReader: JsonReader,
commitMessage: String?,
commitTimestamp: Instant?
) {
wtx.insertSubtreeAsRightSibling(jsonReader, JsonNodeTrx.Commit.NO)
wtx.commit(commitMessage, commitTimestamp)
}
override fun insertString(
wtx: JsonNodeTrx,
jsonReader: JsonReader,
commitMessage: String?,
commitTimestamp: Instant?
) {
wtx.insertStringValueAsRightSibling(jsonReader.nextString())
wtx.commit(commitMessage, commitTimestamp)
}
override fun insertNumber(
wtx: JsonNodeTrx,
jsonReader: JsonReader,
commitMessage: String?,
commitTimestamp: Instant?
) {
wtx.insertNumberValueAsRightSibling(JsonNumber.stringToNumber(jsonReader.nextString()))
wtx.commit(commitMessage, commitTimestamp)
}
override fun insertNull(
wtx: JsonNodeTrx,
jsonReader: JsonReader,
commitMessage: String?,
commitTimestamp: Instant?
) {
jsonReader.nextNull()
wtx.insertNullValueAsRightSibling()
wtx.commit(commitMessage, commitTimestamp)
}
override fun insertBoolean(
wtx: JsonNodeTrx,
jsonReader: JsonReader,
commitMessage: String?,
commitTimestamp: Instant?
) {
wtx.insertBooleanValueAsRightSibling(jsonReader.nextBoolean())
wtx.commit(commitMessage, commitTimestamp)
}
override fun insertObjectRecord(
wtx: JsonNodeTrx,
jsonReader: JsonReader,
commitMessage: String?,
commitTimestamp: Instant?
) {
wtx.insertObjectRecordAsRightSibling(jsonReader.nextName(), getObjectRecordValue(jsonReader))
wtx.commit(commitMessage, commitTimestamp)
}
},
ASLEFTSIBLING {
override fun insertSubtree(
wtx: JsonNodeTrx,
jsonReader: JsonReader,
commitMessage: String?,
commitTimestamp: Instant?
) {
wtx.insertSubtreeAsLeftSibling(jsonReader, JsonNodeTrx.Commit.NO)
wtx.commit(commitMessage, commitTimestamp)
}
override fun insertString(
wtx: JsonNodeTrx,
jsonReader: JsonReader,
commitMessage: String?,
commitTimestamp: Instant?
) {
wtx.insertStringValueAsLeftSibling(jsonReader.nextString())
wtx.commit(commitMessage, commitTimestamp)
}
override fun insertNumber(
wtx: JsonNodeTrx,
jsonReader: JsonReader,
commitMessage: String?,
commitTimestamp: Instant?
) {
wtx.insertNumberValueAsLeftSibling(JsonNumber.stringToNumber(jsonReader.nextString()))
wtx.commit(commitMessage, commitTimestamp)
}
override fun insertNull(
wtx: JsonNodeTrx,
jsonReader: JsonReader,
commitMessage: String?,
commitTimestamp: Instant?
) {
jsonReader.nextNull()
wtx.insertNullValueAsLeftSibling()
wtx.commit(commitMessage, commitTimestamp)
}
override fun insertBoolean(
wtx: JsonNodeTrx,
jsonReader: JsonReader,
commitMessage: String?,
commitTimestamp: Instant?
) {
wtx.insertBooleanValueAsLeftSibling(jsonReader.nextBoolean())
wtx.commit(commitMessage, commitTimestamp)
}
override fun insertObjectRecord(
wtx: JsonNodeTrx,
jsonReader: JsonReader,
commitMessage: String?,
commitTimestamp: Instant?
) {
wtx.insertObjectRecordAsLeftSibling(jsonReader.nextName(), getObjectRecordValue(jsonReader))
wtx.commit(commitMessage, commitTimestamp)
}
};
@Throws(IOException::class)
fun getObjectRecordValue(jsonReader: JsonReader): ObjectRecordValue<*> {
val value: ObjectRecordValue<*> = when (jsonReader.peek()) {
JsonToken.BEGIN_OBJECT -> {
jsonReader.beginObject()
ObjectValue()
}
JsonToken.BEGIN_ARRAY -> {
jsonReader.beginArray()
ArrayValue()
}
JsonToken.BOOLEAN -> {
val booleanVal: Boolean = jsonReader.nextBoolean()
BooleanValue(booleanVal)
}
JsonToken.STRING -> {
val stringVal: String = jsonReader.nextString()
StringValue(stringVal)
}
JsonToken.NULL -> {
jsonReader.nextNull()
NullValue()
}
JsonToken.NUMBER -> {
val numberVal: Number = JsonNumber.stringToNumber(jsonReader.nextString())
NumberValue(numberVal)
}
JsonToken.END_ARRAY, JsonToken.END_DOCUMENT, JsonToken.END_OBJECT, JsonToken.NAME -> throw AssertionError()
else -> throw AssertionError()
}
return value
}
abstract fun insertSubtree(
wtx: JsonNodeTrx,
jsonReader: JsonReader,
commitMessage: String?,
commitTimestamp: Instant?
)
abstract fun insertString(
wtx: JsonNodeTrx,
jsonReader: JsonReader,
commitMessage: String?,
commitTimestamp: Instant?
)
abstract fun insertNumber(
wtx: JsonNodeTrx,
jsonReader: JsonReader,
commitMessage: String?,
commitTimestamp: Instant?
)
abstract fun insertNull(wtx: JsonNodeTrx, jsonReader: JsonReader, commitMessage: String?, commitTimestamp: Instant?)
abstract fun insertBoolean(
wtx: JsonNodeTrx,
jsonReader: JsonReader,
commitMessage: String?,
commitTimestamp: Instant?
)
abstract fun insertObjectRecord(
wtx: JsonNodeTrx,
jsonReader: JsonReader,
commitMessage: String?,
commitTimestamp: Instant?
)
companion object {
fun getInsertionModeByName(name: String) = valueOf(name.uppercase(Locale.getDefault()))
}
}
class JsonUpdate(private val location: Path) {
suspend fun handle(ctx: RoutingContext): Route {
val databaseName = ctx.pathParam("database")
val resource = ctx.pathParam("resource")
val nodeId: String? = ctx.queryParam("nodeId").getOrNull(0)
val insertionMode: String? = ctx.queryParam("insert").getOrNull(0)
if (databaseName == null || resource == null) {
throw IllegalArgumentException("Database name and resource name not given.")
}
val body = ctx.bodyAsString
update(databaseName, resource, nodeId?.toLongOrNull(), insertionMode, body, ctx)
return ctx.currentRoute()
}
private suspend fun update(
databaseName: String, resPathName: String, nodeId: Long?, insertionModeAsString: String?,
resFileToStore: String, ctx: RoutingContext
) {
val vertxContext = ctx.vertx().orCreateContext
vertxContext.executeBlocking { promise: Promise<Nothing> ->
val sirixDBUser = SirixDBUser.create(ctx)
val dbFile = location.resolve(databaseName)
var body: String? = null
val database = Databases.openJsonDatabase(dbFile, sirixDBUser)
database.use {
val manager = database.beginResourceSession(resPathName)
manager.use {
val commitMessage = ctx.queryParam("commitMessage").getOrNull(0)
val commitTimestampAsString = ctx.queryParam("commitTimestamp").getOrNull(0)
val commitTimestamp = if (commitTimestampAsString == null) {
null
} else {
Revisions.parseRevisionTimestamp(commitTimestampAsString).toInstant()
}
val wtx = manager.beginNodeTrx()
val revision = wtx.revisionNumber
val (maxNodeKey, hash) = wtx.use {
if (nodeId != null) {
wtx.moveTo(nodeId)
}
if (wtx.isDocumentRoot && wtx.hasFirstChild()) {
wtx.moveToFirstChild()
}
if (manager.resourceConfig.hashType != HashType.NONE && !wtx.isDocumentRoot) {
val hashCode = ctx.request().getHeader(HttpHeaders.ETAG)
?: throw IllegalStateException("Hash code is missing in ETag HTTP-Header.")
if (wtx.hash != BigInteger(hashCode)) {
throw IllegalArgumentException("Someone might have changed the resource in the meantime.")
}
}
if (insertionModeAsString == null) {
throw IllegalArgumentException("Insertion mode must be given.")
}
val jsonReader = JsonShredder.createStringReader(resFileToStore)
val insertionModeByName = getInsertionModeByName(insertionModeAsString)
@Suppress("unused")
if (jsonReader.peek() != JsonToken.BEGIN_ARRAY && jsonReader.peek() != JsonToken.BEGIN_OBJECT) {
when (jsonReader.peek()) {
JsonToken.STRING -> insertionModeByName.insertString(wtx, jsonReader, commitMessage, commitTimestamp)
JsonToken.NULL -> insertionModeByName.insertNull(wtx, jsonReader, commitMessage, commitTimestamp)
JsonToken.NUMBER -> insertionModeByName.insertNumber(wtx, jsonReader, commitMessage, commitTimestamp)
JsonToken.BOOLEAN -> insertionModeByName.insertBoolean(wtx, jsonReader, commitMessage, commitTimestamp)
JsonToken.NAME -> insertionModeByName.insertObjectRecord(wtx, jsonReader, commitMessage, commitTimestamp)
else -> throw IllegalStateException()
}
} else {
insertionModeByName.insertSubtree(wtx, jsonReader, commitMessage, commitTimestamp)
}
if (nodeId != null) {
wtx.moveTo(nodeId)
}
if (wtx.isDocumentRoot && wtx.hasFirstChild()) {
wtx.moveToFirstChild()
}
Pair(wtx.maxNodeKey, wtx.hash)
}
if (maxNodeKey > 5000) {
ctx.response().statusCode = 200
if (manager.resourceConfig.hashType == HashType.NONE) {
ctx.response()
} else {
ctx.response().putHeader(HttpHeaders.ETAG, hash.toString())
}
} else {
val out = StringWriter()
val serializerBuilder = JsonSerializer.newBuilder(manager, out)
val serializer = serializerBuilder.build()
body = JsonSerializeHelper().serialize(
serializer,
out,
ctx,
manager,
intArrayOf(revision),
nodeId
)
}
}
}
if (body != null) {
ctx.response().end(body)
} else {
ctx.response().end()
}
promise.complete(null)
}.await()
}
}
|
bsd-3-clause
|
374cc81d711760089450319d8608a17c
| 35.244656 | 137 | 0.564847 | 5.597579 | false | false | false | false |
sirixdb/sirix
|
bundles/sirix-rest-api/src/main/kotlin/org/sirix/rest/crud/DeleteHandler.kt
|
1
|
2065
|
package org.sirix.rest.crud
import io.vertx.core.Promise
import io.vertx.ext.auth.authorization.AuthorizationProvider
import io.vertx.ext.web.Route
import io.vertx.ext.web.RoutingContext
import io.vertx.kotlin.core.executeBlockingAwait
import io.vertx.kotlin.coroutines.await
import org.sirix.access.DatabaseType
import org.sirix.access.Databases
import org.sirix.access.DatabasesInternals
import org.sirix.rest.crud.json.JsonDelete
import org.sirix.rest.crud.xml.XmlDelete
import java.nio.file.Files
import java.nio.file.Path
class DeleteHandler(private val location: Path, private val authz: AuthorizationProvider) {
suspend fun handle(ctx: RoutingContext): Route {
if (ctx.pathParam("database") == null && ctx.pathParam("resource") == null) {
val openDatabases = DatabasesInternals.getOpenDatabases()
if (openDatabases.isNotEmpty()) {
throw IllegalStateException("Open databases found: $openDatabases")
}
ctx.vertx().executeBlocking { _: Promise<Unit> ->
val databases = Files.list(location)
databases.use {
databases.filter { Files.isDirectory(it) }
.forEach {
it.toFile().deleteRecursively()
}
}
ctx.response().setStatusCode(204).end()
}.await()
} else {
val databaseName = ctx.pathParam("database")
if (databaseName == null) {
throw IllegalStateException("No database name given.")
} else {
val databaseType = Databases.getDatabaseType(location.resolve(databaseName).toAbsolutePath())
@Suppress("WHEN_ENUM_CAN_BE_NULL_IN_JAVA")
when (databaseType) {
DatabaseType.JSON -> JsonDelete(location, authz).handle(ctx)
DatabaseType.XML -> XmlDelete(location, authz).handle(ctx)
}
}
}
return ctx.currentRoute()
}
}
|
bsd-3-clause
|
4d18ca2e908adbe1245c8dcef713354e
| 35.245614 | 109 | 0.613075 | 4.693182 | false | false | false | false |
Adventech/sabbath-school-android-2
|
common/runtime-permissions/src/main/kotlin/app/ss/runtime/permissions/RuntimePermissions.kt
|
1
|
2920
|
/*
* Copyright (c) 2022. Adventech <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package app.ss.runtime.permissions
import android.content.Context
import android.content.pm.PackageManager
import androidx.activity.result.ActivityResultCaller
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
interface RuntimePermissions {
fun isGranted(permission: String): Boolean
fun setup(caller: ActivityResultCaller, listener: Listener)
fun request(permission: String)
interface Listener {
fun onPermissionGranted()
fun onPermissionDenied()
}
}
internal class RuntimePermissionsImpl @Inject constructor(
@ApplicationContext private val context: Context
) : RuntimePermissions {
private var requestPermissionLauncher: ActivityResultLauncher<String>? = null
override fun isGranted(permission: String): Boolean = ContextCompat.checkSelfPermission(
context,
permission
) == PackageManager.PERMISSION_GRANTED
override fun setup(caller: ActivityResultCaller, listener: RuntimePermissions.Listener) {
requestPermissionLauncher =
caller.registerForActivityResult(
ActivityResultContracts.RequestPermission()
) { isGranted: Boolean ->
if (isGranted) {
listener.onPermissionGranted()
} else {
listener.onPermissionDenied()
}
}
}
override fun request(permission: String) {
if (requestPermissionLauncher == null) throw IllegalStateException("Call setup before requesting permissions")
requestPermissionLauncher?.launch(permission)
}
}
|
mit
|
0c57df2938ad17d56d99c610e83b4fd5
| 38.459459 | 118 | 0.736301 | 5.251799 | false | false | false | false |
square/wire
|
wire-library/wire-tests/src/jvmKotlinInteropTest/kotlin/com/squareup/wire/TestAllTypesData.kt
|
1
|
8595
|
/*
* Copyright 2019 Square Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.wire
import okio.ByteString.Companion.decodeHex
object TestAllTypesData {
val expectedOutput = (
"" +
// optional
"08" + // tag = 1, type = 0
"6f" + // value = 111
"10" + // tag = 2, type = 0
"70" + // value = 112
"18" + // tag = 3, type = 0
"e201" + // value = 226 (=113 zig-zag)
"25" + // tag = 4, type = 5
"72000000" + // value = 114 (fixed32)
"2d" + // tag = 5, type = 5
"73000000" + // value = 115 (sfixed32)
"30" + // tag = 6, type = 0
"74" + // value = 116
"38" + // tag = 7, type = 0
"75" + // value = 117
"40" + // tag = 8, type = 0
"ec01" + // value = 236 (=118 zigzag)
"49" + // tag = 9, type = 1
"7700000000000000" + // value = 119
"51" + // tag = 10, type = 1
"7800000000000000" + // value = 120
"58" + // tag = 11, type = 0
"01" + // value = 1 (true)
"65" + // tag = 12, type = 5
"0000f442" + // value = 122.0F
"69" + // tag = 13, type = 1
"0000000000c05e40" + // value = 123.0
"72" + // tag = 14, type = 2
"03" + // length = 3
"313234" +
"7a" + // tag = 15, type = 2
"02" + // length = 2
"7de1" + // value = { 125, 225 }
"8001" + // tag = 16, type = 0
"01" + // value = 1
"8a01" + // tag = 17, type = 2
"03" + // length = 3
"08" + // nested tag = 1, type = 0
"e707" + // value = 999
// required
"a806" + // tag = 101, type = 0
"6f" + // value = 111
"b006" + // tag = 102, type = 0
"70" + // value = 112
"b806" + // tag = 103, type = 0
"e201" + // value = 226 (=113 zig-zag)
"c506" + // tag = 104, type = 5
"72000000" + // value = 114 (fixed32)
"cd06" + // tag = 105, type = 5
"73000000" + // value = 115 (sfixed32)
"d006" + // tag = 106, type = 0
"74" + // value = 116
"d806" + // tag = 107, type = 0
"75" + // value = 117
"e006" + // tag = 108, type = 0
"ec01" + // value = 236 (=118 zigzag)
"e906" + // tag = 109, type = 1
"7700000000000000" + // value = 119
"f106" + // tag = 110, type = 1
"7800000000000000" + // value = 120
"f806" + // tag = 111, type = 0
"01" + // value = 1 (true)
"8507" + // tag = 112, type = 5
"0000f442" + // value = 122.0F
"8907" + // tag = 113, type = 1
"0000000000c05e40" + // value = 123.0
"9207" + // tag = 114, type = 2
"03" + // length = 3
"313234" + // value = "124"
"9a07" + // tag = 115, type = 2
"02" + // length = 2
"7de1" + // value = { 125, 225 }
"a007" + // tag = 116, type = 0
"01" + // value = 1
"aa07" + // tag = 117, type = 2
"03" + // length = 3
"08" + // nested tag = 1, type = 0
"e707" + // value = 999
// repeated
"c80c" + // tag = 201, type = 0
"6f" + // value = 111
"c80c" + // tag = 201, type = 0
"6f" + // value = 111
"d00c" + // tag = 202, type = 0
"70" + // value = 112
"d00c" + // tag = 202, type = 0
"70" + // value = 112
"d80c" + // tag = 203, type = 0
"e201" + // value = 226 (=113 zig-zag)
"d80c" + // tag = 203, type = 0
"e201" + // value = 226 (=113 zig-zag)
"e50c" + // tag = 204, type = 5
"72000000" + // value = 114 (fixed32)
"e50c" + // tag = 204, type = 5
"72000000" + // value = 114 (fixed32)
"ed0c" + // tag = 205, type = 5
"73000000" + // value = 115 (sfixed32)
"ed0c" + // tag = 205, type = 5
"73000000" + // value = 115 (sfixed32)
"f00c" + // tag = 206, type = 0
"74" + // value = 116
"f00c" + // tag = 206, type = 0
"74" + // value = 116
"f80c" + // tag = 207, type = 0
"75" + // value = 117
"f80c" + // tag = 207, type = 0
"75" + // value = 117
"800d" + // tag = 208, type = 0
"ec01" + // value = 236 (=118 zigzag)
"800d" + // tag = 208, type = 0
"ec01" + // value = 236 (=118 zigzag)
"890d" + // tag = 209, type = 1
"7700000000000000" + // value = 119
"890d" + // tag = 209, type = 1
"7700000000000000" + // value = 119
"910d" + // tag = 210, type = 1
"7800000000000000" + // value = 120
"910d" + // tag = 210, type = 1
"7800000000000000" + // value = 120
"980d" + // tag = 211, type = 0
"01" + // value = 1 (true)
"980d" + // tag = 211, type = 0
"01" + // value = 1 (true)
"a50d" + // tag = 212, type = 5
"0000f442" + // value = 122.0F
"a50d" + // tag = 212, type = 5
"0000f442" + // value = 122.0F
"a90d" + // tag = 213, type = 1
"0000000000c05e40" + // value = 123.0
"a90d" + // tag = 213, type = 1
"0000000000c05e40" + // value = 123.0
"b20d" + // tag = 214, type = 2
"03" + // length = 3
"313234" + // value = "124"
"b20d" + // tag = 214, type = 2
"03" + // length = 3
"313234" + // value = "124"
"ba0d" + // tag = 215, type = 2
"02" + // length = 2
"7de1" + // value = { 125, 225 }
"ba0d" + // tag = 215, type = 2
"02" + // length = 2
"7de1" + // value = { 125, 225 }
"c00d" + // tag = 216, type = 0
"01" + // value = 1
"c00d" + // tag = 216, type = 0
"01" + // value = 1
"ca0d" + // tag = 217, type = 2
"03" + // length = 3
"08" + // nested tag = 1, type = 0
"e707" + // value = 999
"ca0d" + // tag = 217, type = 2
"03" + // length = 3
"08" + // nested tag = 1, type = 0
"e707" + // value = 999
// packed
"ea12" + // tag = 301, type = 2
"02" + // length = 2
"6f" + // value = 111
"6f" + // value = 111
"f212" + // tag = 302, type = 2
"02" + // length = 2
"70" + // value = 112
"70" + // value = 112
"fa12" + // tag = 303, type = 2
"04" + // length = 4
"e201" + // value = 226 (=113 zig-zag)
"e201" + // value = 226 (=113 zig-zag)
"8213" + // tag = 304, type = 2
"08" + // length = 8
"72000000" + // value = 114 (fixed32)
"72000000" + // value = 114 (fixed32)
"8a13" + // tag = 305, type = 2
"08" + // length = 8
"73000000" + // value = 115 (sfixed32)
"73000000" + // value = 115 (sfixed32)
"9213" + // tag = 306, type = 2
"02" + // length = 2
"74" + // value = 116
"74" + // value = 116
"9a13" + // tag = 307, type = 2
"02" + // length = 2
"75" + // value = 117
"75" + // value = 117
"a213" + // tag = 308, type = 2
"04" + // length = 4
"ec01" + // value = 236 (=118 zigzag)
"ec01" + // value = 236 (=118 zigzag)
"aa13" + // tag = 309, type = 2
"10" + // length = 16
"7700000000000000" + // value = 119
"7700000000000000" + // value = 119
"b213" + // tag = 310, type = 2
"10" + // length = 16
"7800000000000000" + // value = 120
"7800000000000000" + // value = 120
"ba13" + // tag = 311, type = 2
"02" + // length = 2
"01" + // value = 1 (true)
"01" + // value = 1 (true)
"c213" + // tag = 312, type = 2
"08" + // length = 8
"0000f442" + // value = 122.0F
"0000f442" + // value = 122.0F
"ca13" + // tag = 313, type = 2
"10" + // length = 16
"0000000000c05e40" + // value = 123.0
"0000000000c05e40" + // value = 123.0
"e213" + // tag = 316, type = 2
"02" + // length = 2
"01" + // value = 1
"01" + // value = 1
// extensions
"983f" + // tag = 1011, type = 0
"01" + // value = 1 (true)
"b845" + // tag = 1111, type = 0
"01" + // value = 1 (true)
"b845" + // tag = 1111, type = 0
"01" + // value = 1 (true)
"da4b" + // tag = 1211, type = 2
"02" + // length = 2
"01" + // value = 1 (true)
"01" // value = 1 (true)
).decodeHex()
}
|
apache-2.0
|
48bc0a11fb8a55e7ae30db1a795410ee
| 32.574219 | 75 | 0.441419 | 2.987487 | false | false | false | false |
JetBrains/ideavim
|
src/main/java/com/maddyhome/idea/vim/statistic/OptionsState.kt
|
1
|
3510
|
/*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.statistic
import com.intellij.internal.statistic.beans.MetricEvent
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.BooleanEventField
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.eventLog.events.EventPair
import com.intellij.internal.statistic.eventLog.events.StringEventField
import com.intellij.internal.statistic.eventLog.events.VarargEventId
import com.intellij.internal.statistic.service.fus.collectors.ApplicationUsagesCollector
import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.options.OptionConstants
import com.maddyhome.idea.vim.options.OptionScope
import com.maddyhome.idea.vim.vimscript.services.IjVimOptionService
internal class OptionsState : ApplicationUsagesCollector() {
override fun getGroup(): EventLogGroup = GROUP
override fun getMetrics(): Set<MetricEvent> {
val optionService = VimPlugin.getOptionService()
return setOf(
OPTIONS.metric(
IDEAJOIN withOption IjVimOptionService.ideajoinName,
IDEAMARKS withOption IjVimOptionService.ideamarksName,
IDEAREFACTOR withOption IjVimOptionService.idearefactormodeName,
IDEAPUT with optionService.contains(OptionScope.GLOBAL, OptionConstants.clipboardName, OptionConstants.clipboard_ideaput),
IDEASTATUSICON withOption IjVimOptionService.ideastatusiconName,
IDEAWRITE withOption IjVimOptionService.ideawriteName,
IDEASELECTION with optionService.contains(OptionScope.GLOBAL, OptionConstants.selectmodeName, "ideaselection"),
IDEAVIMSUPPORT with optionService.getValues(OptionScope.GLOBAL, IjVimOptionService.ideavimsupportName)!!
)
)
}
private infix fun BooleanEventField.withOption(name: String): EventPair<Boolean> {
return this.with(VimPlugin.getOptionService().isSet(OptionScope.GLOBAL, name))
}
private infix fun StringEventField.withOption(name: String): EventPair<String?> {
return this.with(VimPlugin.getOptionService().getOptionValue(OptionScope.GLOBAL, name).asString())
}
companion object {
private val GROUP = EventLogGroup("vim.options", 1)
private val IDEAJOIN = BooleanEventField(IjVimOptionService.ideajoinName)
private val IDEAMARKS = BooleanEventField(IjVimOptionService.ideamarksName)
private val IDEAREFACTOR = EventFields.String(IjVimOptionService.ideamarksName, IjVimOptionService.ideaRefactorModeValues.toList())
private val IDEAPUT = BooleanEventField("ideaput")
private val IDEASTATUSICON = EventFields.String(IjVimOptionService.ideastatusiconName, IjVimOptionService.ideaStatusIconValues.toList())
private val IDEAWRITE = EventFields.String(IjVimOptionService.ideawriteName, IjVimOptionService.ideaWriteValues.toList())
private val IDEASELECTION = BooleanEventField("ideaselection")
private val IDEAVIMSUPPORT = EventFields.StringList(IjVimOptionService.ideavimsupportName, IjVimOptionService.ideavimsupportValues.toList())
private val OPTIONS: VarargEventId = GROUP.registerVarargEvent(
"vim.options",
IDEAJOIN,
IDEAMARKS,
IDEAREFACTOR,
IDEAPUT,
IDEASTATUSICON,
IDEAWRITE,
IDEASELECTION,
IDEAVIMSUPPORT,
)
}
}
|
mit
|
df05614a729fe963d6b6e6171d3d5d72
| 44.584416 | 144 | 0.795157 | 4.564369 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.