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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Skatteetaten/boober | src/main/kotlin/no/skatteetaten/aurora/boober/service/vault/VaultService.kt | 1 | 10308 | package no.skatteetaten.aurora.boober.service.vault
import org.eclipse.jgit.api.Git
import org.springframework.core.io.ByteArrayResource
import org.springframework.core.io.support.PropertiesLoaderUtils
import org.springframework.stereotype.Service
import mu.KotlinLogging
import no.skatteetaten.aurora.boober.Domain.VAULT
import no.skatteetaten.aurora.boober.TargetDomain
import no.skatteetaten.aurora.boober.controller.security.User
import no.skatteetaten.aurora.boober.service.AuroraVaultServiceException
import no.skatteetaten.aurora.boober.service.EncryptionService
import no.skatteetaten.aurora.boober.service.EncryptionWrapper
import no.skatteetaten.aurora.boober.service.GitService
import no.skatteetaten.aurora.boober.service.UnauthorizedAccessException
import no.skatteetaten.aurora.boober.service.UserDetailsProvider
private val logger = KotlinLogging.logger {}
data class VaultWithAccess(
val vault: EncryptedFileVault?, // Will be null if the user does not have access
val vaultName: String,
val hasAccess: Boolean = true
) {
companion object {
fun create(vault: EncryptedFileVault, user: User): VaultWithAccess {
val hasAccess = user.hasAccess(vault.permissions)
return VaultWithAccess(if (hasAccess) vault else null, vault.name, hasAccess)
}
}
}
@Service
class VaultService(
@TargetDomain(VAULT)
val gitService: GitService,
val encryptionService: EncryptionService,
val userDetailsProvider: UserDetailsProvider
) {
fun findVaultKeys(vaultCollectionName: String, vaultName: String, fileName: String): Set<String> {
val vaultCollection = findVaultCollection(vaultCollectionName)
val vault = vaultCollection.findVaultByName(vaultName) ?: return emptySet()
val content = vault.secrets[fileName] ?: return emptySet()
return PropertiesLoaderUtils.loadProperties(ByteArrayResource(content)).stringPropertyNames()
}
fun findFileInVault(
vaultCollectionName: String,
vaultName: String,
fileName: String
): ByteArray {
val vault = findVault(vaultCollectionName, vaultName)
return vault.getFile(fileName)
}
fun findAllPublicVaults(vaultCollectionName: String): List<String> {
return findAllVaultsInVaultCollection(vaultCollectionName).filter {
it.publicVault
}.map { it.name }
}
fun findAllVaultsWithUserAccessInVaultCollection(vaultCollectionName: String): List<VaultWithAccess> {
val authenticatedUser = userDetailsProvider.getAuthenticatedUser()
return findAllVaultsInVaultCollection(vaultCollectionName)
.map { VaultWithAccess.create(it, authenticatedUser) }
}
fun findVault(vaultCollectionName: String, vaultName: String): EncryptedFileVault {
val vaultCollection = findVaultCollection(vaultCollectionName)
return findVault(vaultCollection, vaultName)
}
fun findVault(vaultCollection: VaultCollection, vaultName: String) =
(
findVaultByNameIfAllowed(vaultCollection, vaultName)
?: throw IllegalArgumentException("Vault not found name=$vaultName")
)
fun vaultExists(vaultCollectionName: String, vaultName: String): Boolean {
return withVaultCollectionAndRepoForUpdate(vaultCollectionName) { vaultCollection, _ ->
vaultCollection.findVaultByName(vaultName) != null
}
}
fun createOrUpdateFileInVault(
vaultCollectionName: String,
vaultName: String,
fileName: String,
fileContents: ByteArray,
previousSignature: String? = null
): EncryptedFileVault {
assertSecretKeysAreValid(mapOf(fileName to fileContents))
return withVaultCollectionAndRepoForUpdate(vaultCollectionName) { vaultCollection, repo ->
val vault = findVaultByNameIfAllowed(vaultCollection, vaultName) ?: vaultCollection.createVault(vaultName)
vault.updateFile(fileName, fileContents, previousSignature)
gitService.commitAndPushChanges(repo)
vault
}
}
fun deleteFileInVault(vaultCollectionName: String, vaultName: String, fileName: String): EncryptedFileVault? {
return withVaultCollectionAndRepoForUpdate(vaultCollectionName) { vaultCollection, repo ->
val vault = findVault(vaultCollection, vaultName)
vault.deleteFile(fileName)
gitService.commitAndPushChanges(repo)
vault
}
}
fun deleteVault(vaultCollectionName: String, vaultName: String) {
if (vaultName.isBlank()) {
throw IllegalArgumentException("vault name can not be empty")
}
return withVaultCollectionAndRepoForUpdate(vaultCollectionName) { vaultCollection, repo ->
val vault =
findVaultByNameIfAllowed(vaultCollection, vaultName) ?: return@withVaultCollectionAndRepoForUpdate
vault.vaultFolder.deleteRecursively()
gitService.commitAndPushChanges(repo = repo, rmFilePattern = vault.vaultFolder.name, addFilePattern = null)
val isClean = gitService.cleanRepo(repo)
if (!isClean) {
logger.warn("could not clean repository")
}
}
}
fun setVaultPermissions(vaultCollectionName: String, vaultName: String, groupPermissions: List<String>) {
assertCurrentUserHasAccess(groupPermissions)
return withVaultCollectionAndRepoForUpdate(vaultCollectionName) { vaultCollection, repo ->
val vault = findVault(vaultCollection, vaultName)
vault.permissions = groupPermissions
gitService.commitAndPushChanges(repo)
}
}
fun import(
vaultCollectionName: String,
vaultName: String,
permissions: List<String>,
secrets: Map<String, ByteArray>
): EncryptedFileVault {
if (permissions.isEmpty()) {
throw IllegalArgumentException("Public vaults are not allowed. Please specify atleast one permisssion group.")
}
assertCurrentUserHasAccess(permissions)
assertSecretKeysAreValid(secrets)
return withVaultCollectionAndRepoForUpdate(vaultCollectionName) { vaultCollection, repo ->
findVaultByNameIfAllowed(vaultCollection, vaultName)
vaultCollection.createVault(vaultName).let { vault ->
vault.clear()
secrets.forEach { (name, contents) -> vault.updateFile(name, contents) }
vault.permissions = permissions
gitService.commitAndPushChanges(repo)
vault
}
}
}
fun reencryptVaultCollection(vaultCollectionName: String, newKey: String) {
val vaults = findAllVaultsInVaultCollection(vaultCollectionName)
vaults.forEach { vault: EncryptedFileVault ->
val newEncryptionService = EncryptionService(
EncryptionWrapper(newKey),
encryptionService.metrics
)
val vaultCopy = EncryptedFileVault.createFromFolder(
vault.vaultFolder,
newEncryptionService::encrypt,
encryptionService::decrypt
)
vaultCopy.secrets.forEach { (t, u) -> vaultCopy.updateFile(t, u) }
}
}
private fun findVaultByNameIfAllowed(vaultCollection: VaultCollection, vaultName: String): EncryptedFileVault? {
val vault = vaultCollection.findVaultByName(vaultName)
return vault?.apply { assertCurrentUserHasAccess(this.permissions) }
}
private fun assertCurrentUserHasAccess(permissions: List<String>) {
val user = userDetailsProvider.getAuthenticatedUser()
if (!user.hasAccess(permissions)) {
val message = "You (${user.username}) do not have required permissions to " +
"operate on this vault. You have ${user.authorities.map { it.authority }}"
throw UnauthorizedAccessException(message)
}
}
private fun <T> withVaultCollectionAndRepoForUpdate(
vaultCollectionName: String,
function: (vaultCollection: VaultCollection, repo: Git) -> T
): T {
return synchronized(vaultCollectionName) {
val repo = gitService.checkoutRepository(vaultCollectionName, refName = "master")
val folder = repo.repository.directory.parentFile
val vaultCollection =
VaultCollection.fromFolder(folder, encryptionService::encrypt, encryptionService::decrypt)
val response = try {
function(vaultCollection, repo)
} catch (e: Exception) {
throw AuroraVaultServiceException(
"Could not update auroraVault underlying message=${e.localizedMessage}",
e
)
}
repo.close()
response
}
}
fun findVaultCollection(vaultCollectionName: String): VaultCollection {
return withVaultCollectionAndRepoForUpdate(vaultCollectionName, { vaultCollection, repo -> vaultCollection })
}
private fun findAllVaultsInVaultCollection(vaultCollectionName: String): List<EncryptedFileVault> {
return findVaultCollection(vaultCollectionName).vaults
}
companion object {
val rePattern = "^[-._a-zA-Z0-9]+$"
val re = Regex(rePattern)
// Note that a properties file can be delimitered by space and =, very few people know this so we check for it
fun assertSecretKeysAreValid(secrets: Map<String, ByteArray>) {
val filesToKeys = secrets.filter { it.key.endsWith(".properties") }
.mapValues {
String(it.value)
.lines()
.filter { !it.isBlank() }
.map { it.substringBefore("=") }
.filter { !it.matches(re) }
}
val invalidKeys = filesToKeys.flatMap { fileToKey ->
fileToKey.value.map { "${fileToKey.key}/$it" }
}
if (invalidKeys.isNotEmpty()) {
throw IllegalArgumentException("Vault key=$invalidKeys is not valid. Regex used for matching $rePattern")
}
}
}
}
| apache-2.0 | b3b3175d38d7fa891e987ead64b7778c | 38.193916 | 122 | 0.670838 | 5.030747 | false | false | false | false |
allotria/intellij-community | platform/platform-impl/src/com/intellij/ide/cds/CDSManager.kt | 3 | 12569 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.cds
import com.intellij.diagnostic.VMOptions
import com.intellij.execution.CommandLineWrapperUtil
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.process.OSProcessUtil
import com.intellij.execution.util.ExecUtil
import com.intellij.ide.IdeBundle
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.PerformInBackgroundOption
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.TimeoutUtil
import com.intellij.util.system.CpuArch
import com.sun.management.OperatingSystemMXBean
import com.sun.tools.attach.VirtualMachine
import java.io.File
import java.lang.management.ManagementFactory
import java.nio.charset.StandardCharsets
import java.util.concurrent.TimeUnit
import kotlin.system.measureTimeMillis
sealed class CDSTaskResult(val statusName: String) {
object Success : CDSTaskResult("success")
abstract class Cancelled(statusName: String) : CDSTaskResult(statusName)
object InterruptedForRetry : Cancelled("cancelled")
object TerminatedByUser : Cancelled("terminated-by-user")
object PluginsChanged : Cancelled("plugins-changed")
data class Failed(val error: String) : CDSTaskResult("failed")
}
object CDSManager {
private val LOG = Logger.getInstance(javaClass)
val isValidEnv: Boolean by lazy {
// AppCDS requires classes packed into JAR files, not from the out folder
if (PluginManagerCore.isRunningFromSources()) return@lazy false
// CDS features are only available on 64-bit JVMs
if (CpuArch.is32Bit()) return@lazy false
// AppCDS does not support Windows and macOS, but specific patches are included into JetBrains runtime
if (!(SystemInfo.isLinux || SystemInfo.isJetBrainsJvm)) return@lazy false
// we do not like to overload a potentially small computer with our process
val osBean = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean::class.java)
if (osBean.totalPhysicalMemorySize < 4L * 1024 * 1024 * 1024) return@lazy false
if (osBean.availableProcessors < 4) return@lazy false
if (!VMOptions.canWriteOptions()) return@lazy false
true
}
val currentCDSArchive: File? by lazy {
val arguments = ManagementFactory.getRuntimeMXBean().inputArguments
val xShare = arguments.any { it == "-Xshare:auto" || it == "-Xshare:on" }
if (!xShare) return@lazy null
val key = "-XX:SharedArchiveFile="
return@lazy arguments.firstOrNull { it.startsWith(key) }?.removePrefix(key)?.let(::File)
}
fun cleanupStaleCDSFiles(isCDSEnabled: Boolean): CDSTaskResult {
val paths = CDSPaths.current
val currentCDSPath = currentCDSArchive
val files = paths.baseDir.listFiles() ?: arrayOf()
if (files.isEmpty()) return CDSTaskResult.Success
for (path in files) {
if (path == currentCDSPath) continue
if (isCDSEnabled && paths.isOurFile(path)) continue
FileUtil.delete(path)
}
return CDSTaskResult.Success
}
fun removeCDS() {
if (currentCDSArchive?.isFile != true ) return
VMOptions.writeDisableCDSArchiveOption()
LOG.warn("Disabled CDS")
}
private interface CDSProgressIndicator {
/// returns non-null value if cancelled
val cancelledStatus: CDSTaskResult.Cancelled?
var text2: String?
}
fun installCDS(canStillWork: () -> Boolean, onResult: (CDSTaskResult) -> Unit) {
CDSFUSCollector.logCDSBuildingStarted()
val startTime = System.nanoTime()
ProgressManager.getInstance().run(object : Task.Backgroundable(
null,
IdeBundle.message("progress.title.cds.optimize.startup"),
true,
PerformInBackgroundOption.ALWAYS_BACKGROUND
) {
override fun run(indicator: ProgressIndicator) {
indicator.isIndeterminate = true
val progress = object : CDSProgressIndicator {
override val cancelledStatus: CDSTaskResult.Cancelled?
get() {
if (!canStillWork()) return CDSTaskResult.InterruptedForRetry
if (indicator.isCanceled) return CDSTaskResult.TerminatedByUser
if (ApplicationManager.getApplication().isDisposed) return CDSTaskResult.InterruptedForRetry
return null
}
override var text2: String?
get() = indicator.text2
set(@NlsContexts.ProgressText value) {
indicator.text2 = value
}
}
val paths = CDSPaths.current
val result = try {
installCDSImpl(progress, paths)
} catch (t: Throwable) {
LOG.warn("Settings up CDS Archive crashed unexpectedly. ${t.message}", t)
val message = "Unexpected crash $t"
paths.markError(message)
CDSTaskResult.Failed(message)
}
val installTime = TimeoutUtil.getDurationMillis(startTime)
CDSFUSCollector.logCDSBuildingCompleted(installTime, result)
onResult(result)
}
})
}
private fun installCDSImpl(indicator: CDSProgressIndicator, paths: CDSPaths): CDSTaskResult {
if (paths.isSame(currentCDSArchive)) {
val message = "CDS archive is already generated and being used. Nothing to do"
LOG.debug(message)
return CDSTaskResult.Success
}
if (paths.classesErrorMarkerFile.isFile) {
return CDSTaskResult.Failed("CDS archive has already failed, skipping")
}
LOG.info("Starting generation of CDS archive to the ${paths.classesArchiveFile} and ${paths.classesArchiveFile} files")
paths.mkdirs()
val listResult = generateFileIfNeeded(indicator, paths, paths.classesListFile, ::generateClassList) { t ->
"Failed to attach CDS Java Agent to the running IDE instance. ${t.message}"
}
if (listResult != CDSTaskResult.Success) return listResult
val archiveResult = generateFileIfNeeded(indicator, paths, paths.classesArchiveFile, ::generateSharedArchive) { t ->
"Failed to generated CDS archive. ${t.message}"
}
if (archiveResult != CDSTaskResult.Success) return archiveResult
VMOptions.writeEnableCDSArchiveOption(paths.classesArchiveFile.absolutePath)
LOG.warn("Enabled CDS archive from ${paths.classesArchiveFile}, VMOptions were updated")
return CDSTaskResult.Success
}
private val agentPath: File
get() {
val libPath = File(PathManager.getLibPath()) / "cds" / "classesLogAgent.jar"
if (libPath.isFile) return libPath
LOG.warn("Failed to find bundled CDS classes agent in $libPath")
//consider local debug IDE case
val probe = File(PathManager.getHomePath()) / "out" / "classes" / "artifacts" / "classesLogAgent_jar" / "classesLogAgent.jar"
if (probe.isFile) return probe
error("Failed to resolve path to the CDS agent")
}
private fun generateClassList(indicator: CDSProgressIndicator, paths: CDSPaths) {
indicator.text2 = IdeBundle.message("progress.text.collecting.classes")
val selfAttachKey = "jdk.attach.allowAttachSelf"
if (!System.getProperties().containsKey(selfAttachKey)) {
throw RuntimeException("Please make sure you have -D$selfAttachKey=true set in the VM options")
}
val duration = measureTimeMillis {
val vm = VirtualMachine.attach(OSProcessUtil.getApplicationPid())
try {
vm.loadAgent(agentPath.path, "${paths.classesListFile}")
}
finally {
vm.detach()
}
}
LOG.info("CDS classes file is generated in ${StringUtil.formatDuration(duration)}")
}
private fun generateSharedArchive(indicator: CDSProgressIndicator, paths: CDSPaths) {
indicator.text2 = IdeBundle.message("progress.text.generate.classes.archive")
val logLevel = if (LOG.isDebugEnabled) "=debug" else ""
val args = listOf(
"-Djava.class.path=${ManagementFactory.getRuntimeMXBean().classPath}",
"-Xlog:cds$logLevel",
"-Xlog:class+path$logLevel",
"-Xshare:dump",
"-XX:+UnlockDiagnosticVMOptions",
"-XX:SharedClassListFile=${paths.classesListFile}",
"-XX:SharedArchiveFile=${paths.classesArchiveFile}"
)
CommandLineWrapperUtil.writeArgumentsFile(paths.classesPathFile, args, StandardCharsets.UTF_8)
val durationLink = measureTimeMillis {
val ext = if (SystemInfo.isWindows) ".exe" else ""
val javaExe = File(System.getProperty("java.home")!!) / "bin" / "java$ext"
val javaArgs = listOf(
javaExe.path,
"@${paths.classesPathFile}"
)
val cwd = File(".").canonicalFile
LOG.info("Running CDS generation process: $javaArgs in $cwd with classpath: ${args}")
//recreate files for sanity
FileUtil.delete(paths.dumpOutputFile)
FileUtil.delete(paths.classesArchiveFile)
val commandLine = object : GeneralCommandLine() {
override fun buildProcess(builder: ProcessBuilder) : ProcessBuilder {
return super.buildProcess(builder)
.redirectErrorStream(true)
.redirectInput(ProcessBuilder.Redirect.PIPE)
.redirectOutput(paths.dumpOutputFile)
}
}
commandLine.workDirectory = cwd
commandLine.exePath = javaExe.absolutePath
commandLine.addParameter("@${paths.classesPathFile}")
if (!SystemInfo.isWindows) {
// the utility does not recover process exit code from the call on Windows
ExecUtil.setupLowPriorityExecution(commandLine)
}
val timeToWaitFor = System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(10)
fun shouldWaitForProcessToComplete() = timeToWaitFor > System.currentTimeMillis()
val process = commandLine.createProcess()
try {
runCatching { process.outputStream.close() }
while (shouldWaitForProcessToComplete()) {
if (indicator.cancelledStatus != null) throw InterruptedException()
if (process.waitFor(200, TimeUnit.MILLISECONDS)) break
}
}
finally {
if (process.isAlive) {
process.destroyForcibly()
}
}
if (!shouldWaitForProcessToComplete()) {
throw RuntimeException("The process took too long and will be killed. See ${paths.dumpOutputFile} for details")
}
val exitValue = process.exitValue()
if (exitValue != 0) {
val outputLines = runCatching {
paths.dumpOutputFile.readLines().takeLast(30).joinToString("\n")
}.getOrElse { "" }
throw RuntimeException("The process existed with code $exitValue. See ${paths.dumpOutputFile} for details:\n$outputLines")
}
}
LOG.info("Generated CDS archive in ${paths.classesArchiveFile}, " +
"size = ${StringUtil.formatFileSize(paths.classesArchiveFile.length())}, " +
"it took ${StringUtil.formatDuration(durationLink)}")
}
private operator fun File.div(s: String) = File(this, s)
private val File.isValidFile get() = isFile && length() > 42
private inline fun generateFileIfNeeded(indicator: CDSProgressIndicator,
paths: CDSPaths,
theOutputFile: File,
generate: (CDSProgressIndicator, CDSPaths) -> Unit,
errorMessage: (Throwable) -> String): CDSTaskResult {
try {
if (theOutputFile.isValidFile) return CDSTaskResult.Success
indicator.cancelledStatus?.let { return it }
if (!paths.hasSameEnvironmentToBuildCDSArchive()) return CDSTaskResult.PluginsChanged
generate(indicator, paths)
LOG.assertTrue(theOutputFile.isValidFile, "Result file must be generated and be valid")
return CDSTaskResult.Success
}
catch (t: Throwable) {
FileUtil.delete(theOutputFile)
indicator.cancelledStatus?.let { return it }
if (t is InterruptedException) {
return CDSTaskResult.InterruptedForRetry
}
val message = errorMessage(t)
LOG.warn(message, t)
paths.markError(message)
return CDSTaskResult.Failed(message)
}
}
}
| apache-2.0 | 58f70d02250b670840787f165b16979f | 37.320122 | 140 | 0.69751 | 4.757381 | false | false | false | false |
allotria/intellij-community | python/python-psi-impl/src/com/jetbrains/python/psi/types/PyLiteralType.kt | 2 | 6154 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.psi.types
import com.intellij.openapi.util.Ref
import com.jetbrains.python.PyNames
import com.jetbrains.python.PyTokenTypes
import com.jetbrains.python.codeInsight.dataflow.scope.ScopeUtil
import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider
import com.jetbrains.python.psi.*
import com.jetbrains.python.psi.impl.PyEvaluator
import com.jetbrains.python.psi.resolve.PyResolveContext
/**
* Represents literal type introduced in PEP 586.
*/
class PyLiteralType private constructor(cls: PyClass, val expression: PyExpression) : PyClassTypeImpl(cls, false) {
override fun getName(): String = "Literal[${expression.text}]"
override fun toString(): String = "PyLiteralType: ${expression.text}"
override fun equals(other: Any?): Boolean {
return this === other || javaClass == other?.javaClass && match(this, other as PyLiteralType)
}
override fun hashCode(): Int = 31 * pyClass.hashCode()
companion object {
/**
* Tries to construct literal type for index passed to `typing.Literal[...]`
*/
fun fromLiteralParameter(expression: PyExpression, context: TypeEvalContext): PyType? = newInstance(expression, context, true)
/**
* Tries to construct literal type for a value that could be considered as literal and downcasted to `typing.Literal[...]` type.
*/
fun fromLiteralValue(expression: PyExpression, context: TypeEvalContext): PyType? = newInstance(expression, context, false)
/**
* [actual] matches [expected] if it has the same type and its expression evaluates to the same value
*/
fun match(expected: PyLiteralType, actual: PyLiteralType): Boolean {
return expected.pyClass == actual.pyClass &&
PyEvaluator.evaluateNoResolve(expected.expression, Any::class.java) ==
PyEvaluator.evaluateNoResolve(actual.expression, Any::class.java)
}
/**
* If [expected] type is `typing.Literal[...]`,
* then tries to infer `typing.Literal[...]` for [expression],
* otherwise returns type inferred by [context].
*/
fun promoteToLiteral(expression: PyExpression, expected: PyType?, context: TypeEvalContext): PyType? {
if (PyTypeUtil.toStream(if (expected is PyGenericType) expected.bound else expected).any { it is PyLiteralType }) {
val value = if (expression is PyKeywordArgument) expression.valueExpression else expression
if (value != null) {
val literalType = fromLiteralValue(value, context)
if (literalType != null) {
return literalType
}
}
}
return context.getType(expression)
}
private fun newInstance(expression: PyExpression, context: TypeEvalContext, index: Boolean): PyType? {
return when (expression) {
is PyTupleExpression -> {
val elements = expression.elements
val classes = elements.mapNotNull { toLiteralType(it, context, index) }
if (elements.size == classes.size) PyUnionType.union(classes) else null
}
else -> toLiteralType(expression, context, index)
}
}
private fun toLiteralType(expression: PyExpression, context: TypeEvalContext, index: Boolean): PyType? {
if (expression is PyNoneLiteralExpression && !expression.isEllipsis ||
expression is PyReferenceExpression &&
expression.name == PyNames.NONE &&
LanguageLevel.forElement(expression).isPython2) return PyNoneType.INSTANCE
if (index && (expression is PyReferenceExpression || expression is PySubscriptionExpression)) {
val subLiteralType = Ref.deref(PyTypingTypeProvider.getType(expression, context))
if (PyTypeUtil.toStream(subLiteralType).all { it is PyLiteralType }) return subLiteralType
}
if (expression is PyReferenceExpression && expression.isQualified) {
PyUtil
.multiResolveTopPriority(expression, PyResolveContext.defaultContext().withTypeEvalContext(context))
.asSequence()
.filterIsInstance<PyTargetExpression>()
.mapNotNull { ScopeUtil.getScopeOwner(it) as? PyClass }
.firstOrNull { owner -> owner.getAncestorTypes(context).any { it?.classQName == "enum.Enum" } }
?.let {
val type = context.getType(it)
return if (type is PyInstantiableType<*>) type.toInstance() else type
}
}
return classOfAcceptableLiteral(expression, context, index)?.let { PyLiteralType(it, expression) }
}
private fun classOfAcceptableLiteral(expression: PyExpression, context: TypeEvalContext, index: Boolean): PyClass? {
return when {
expression is PyNumericLiteralExpression -> if (expression.isIntegerLiteral) getPyClass(expression, context) else null
expression is PyStringLiteralExpression ->
if (isAcceptableStringLiteral(expression, index)) getPyClass(expression, context) else null
expression is PyLiteralExpression -> getPyClass(expression, context)
expression is PyPrefixExpression && expression.operator == PyTokenTypes.MINUS -> {
val operand = expression.operand
if (operand is PyNumericLiteralExpression && operand.isIntegerLiteral) getPyClass(operand, context) else null
}
expression is PyReferenceExpression &&
expression.name.let { it == PyNames.TRUE || it == PyNames.FALSE } &&
LanguageLevel.forElement(expression).isPython2 -> getPyClass(expression, context)
else -> null
}
}
private fun getPyClass(expression: PyExpression, context: TypeEvalContext) = (context.getType(expression) as? PyClassType)?.pyClass
private fun isAcceptableStringLiteral(expression: PyStringLiteralExpression, index: Boolean): Boolean {
val singleElement = expression.stringElements.singleOrNull() ?: return false
return if (!index && singleElement is PyFormattedStringElement) singleElement.fragments.isEmpty()
else singleElement is PyPlainStringElement
}
}
}
| apache-2.0 | ae62cd06bda90ff93d990c9571490e8d | 44.25 | 140 | 0.702957 | 4.891892 | false | false | false | false |
grover-ws-1/http4k | http4k-format-argo/src/main/kotlin/org/http4k/format/Argo.kt | 1 | 2839 | package org.http4k.format
import argo.format.CompactJsonFormatter
import argo.format.PrettyJsonFormatter
import argo.jdom.JdomParser
import argo.jdom.JsonNode
import argo.jdom.JsonNodeFactories
import argo.jdom.JsonNodeFactories.`object`
import argo.jdom.JsonNodeType
import argo.jdom.JsonRootNode
import java.math.BigDecimal
import java.math.BigInteger
object Argo : Json<JsonRootNode, JsonNode> {
override fun typeOf(value: JsonNode): JsonType =
when (value.type) {
JsonNodeType.STRING -> JsonType.String
JsonNodeType.TRUE -> JsonType.Boolean
JsonNodeType.FALSE -> JsonType.Boolean
JsonNodeType.NUMBER -> JsonType.Number
JsonNodeType.ARRAY -> JsonType.Array
JsonNodeType.OBJECT -> JsonType.Object
JsonNodeType.NULL -> JsonType.Null
else -> throw IllegalArgumentException("Don't know now to translate $value")
}
private val pretty = PrettyJsonFormatter()
private val compact = CompactJsonFormatter()
private val jdomParser = JdomParser()
override fun String.asJsonObject(): JsonRootNode = this.let(jdomParser::parse)
override fun String?.asJsonValue(): JsonNode = this?.let { JsonNodeFactories.string(it) } ?: JsonNodeFactories.nullNode()
override fun Int?.asJsonValue(): JsonNode = this?.let { JsonNodeFactories.number(it.toLong()) } ?: JsonNodeFactories.nullNode()
override fun Double?.asJsonValue(): JsonNode = this?.let { JsonNodeFactories.number(BigDecimal(it)) } ?: JsonNodeFactories.nullNode()
override fun Long?.asJsonValue(): JsonNode = this?.let { JsonNodeFactories.number(it) } ?: JsonNodeFactories.nullNode()
override fun BigDecimal?.asJsonValue(): JsonNode = this?.let { JsonNodeFactories.number(it) } ?: JsonNodeFactories.nullNode()
override fun BigInteger?.asJsonValue(): JsonNode = this?.let { JsonNodeFactories.number(it) } ?: JsonNodeFactories.nullNode()
override fun Boolean?.asJsonValue(): JsonNode = this?.let { JsonNodeFactories.booleanNode(it) } ?: JsonNodeFactories.nullNode()
override fun <T : Iterable<JsonNode>> T.asJsonArray(): JsonRootNode = JsonNodeFactories.array(this)
override fun JsonRootNode.asPrettyJsonString(): String = pretty.format(this)
override fun JsonRootNode.asCompactJsonString(): String = compact.format(this)
override fun <LIST : Iterable<Pair<String, JsonNode>>> LIST.asJsonObject(): JsonRootNode = `object`(this.map { field(it.first, it.second) })
override fun fields(node: JsonNode): Iterable<Pair<String, JsonNode>> = node.fieldList.map { it.name.text to it.value }
override fun elements(value: JsonNode): Iterable<JsonNode> = value.elements
override fun text(value: JsonNode): String = value.text
private fun field(name: String, value: JsonNode) = JsonNodeFactories.field(name, value)
}
| apache-2.0 | ced623098203538b222517fa74880137 | 56.938776 | 144 | 0.733005 | 4.275602 | false | false | false | false |
romannurik/muzei | main/src/main/java/com/google/android/apps/muzei/notifications/NotificationSettingsDialogFragment.kt | 2 | 3251 | /*
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.muzei.notifications
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.widget.Toast
import androidx.core.content.edit
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import androidx.preference.PreferenceManager
import com.google.android.apps.muzei.util.toast
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import net.nurik.roman.muzei.R
class NotificationSettingsDialogFragment : DialogFragment() {
companion object {
/**
* Show the notification settings. This may come in the form of this dialog or the
* system notification settings on O+ devices.
*/
fun showSettings(context: Context, fragmentManager: FragmentManager) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Ensure the notification channel exists
NewWallpaperNotificationReceiver.createNotificationChannel(context)
val intent = Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS)
intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName)
if (intent.resolveActivity(context.packageManager) != null) {
context.startActivity(intent)
} else {
context.toast(R.string.notification_settings_failed, Toast.LENGTH_LONG)
}
} else {
NotificationSettingsDialogFragment().show(
fragmentManager, "notifications")
}
}
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val context = context ?: return super.onCreateDialog(savedInstanceState)
val items = arrayOf(context.getText(R.string.notification_new_wallpaper_channel_name))
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
val checkedItems = booleanArrayOf(sharedPreferences
.getBoolean(NewWallpaperNotificationReceiver.PREF_ENABLED, true))
return MaterialAlertDialogBuilder(context)
.setTitle(R.string.notification_settings)
.setMultiChoiceItems(items, checkedItems) { _, _, isChecked ->
sharedPreferences.edit {
putBoolean(NewWallpaperNotificationReceiver.PREF_ENABLED, isChecked)
}
}
.setPositiveButton(R.string.notification_settings_done, null)
.create()
}
} | apache-2.0 | fd47cfcc81d44e058ecd57e3be1d6270 | 42.36 | 94 | 0.684712 | 5.119685 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/when/exhaustiveBreakContinue.kt | 5 | 410 | enum class Color { RED, GREEN, BLUE }
fun foo(arr: Array<Color>): Color {
loop@ for (color in arr) {
when (color) {
Color.RED -> return color
Color.GREEN -> break@loop
Color.BLUE -> if (arr.size == 1) return color else continue@loop
}
}
return Color.GREEN
}
fun box() = if (foo(arrayOf(Color.BLUE, Color.GREEN)) == Color.GREEN) "OK" else "FAIL" | apache-2.0 | 7abb7b389e88d3965973828276ca665a | 28.357143 | 86 | 0.568293 | 3.534483 | false | false | false | false |
smmribeiro/intellij-community | platform/indexing-impl/src/com/intellij/psi/stubs/ShareableStubTreeSerializer.kt | 12 | 1999 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.psi.stubs
import org.jetbrains.annotations.NotNull
import java.io.*
class ShareableStubTreeSerializer : StubTreeSerializer {
private val serializationManager = SerializationManagerEx.getInstanceEx() as SerializationManagerImpl
private val serializer = object : StubTreeSerializerBase<FileLocalStringEnumerator>() {
override fun readSerializationState(stream: StubInputStream): FileLocalStringEnumerator {
val enumerator = FileLocalStringEnumerator(false)
enumerator.read(stream) { it }
return enumerator
}
override fun createSerializationState(): FileLocalStringEnumerator =
FileLocalStringEnumerator(true)
override fun saveSerializationState(state: FileLocalStringEnumerator, stream: DataOutputStream) =
state.write(stream)
override fun writeSerializerId(serializer: @NotNull ObjectStubSerializer<Stub, Stub>,
state: @NotNull FileLocalStringEnumerator): Int =
state.enumerate(serializationManager.getSerializerName(serializer)!!)
override fun getClassByIdLocal(localId: Int, parentStub: Stub?, state: FileLocalStringEnumerator): ObjectStubSerializer<*, Stub> {
val serializerName = state.valueOf(localId)
?: throw SerializerNotFoundException("Can't find serializer for local id $localId")
@Suppress("UNCHECKED_CAST")
return serializationManager.getSerializer(serializerName) as ObjectStubSerializer<*, Stub>
}
}
override fun serialize(rootStub: Stub, stream: OutputStream) {
serializationManager.initSerializers()
serializer.serialize(rootStub, stream)
}
@Throws(SerializerNotFoundException::class)
override fun deserialize(stream: @NotNull InputStream): @NotNull Stub {
serializationManager.initSerializers()
return serializer.deserialize(stream)
}
} | apache-2.0 | d579c03eb2d046be166e4e68379584b9 | 43.444444 | 140 | 0.755378 | 5.060759 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/project-wizard/idea/src/org/jetbrains/kotlin/tools/projectWizard/wizard/ui/springUtils.kt | 5 | 1048 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.tools.projectWizard.wizard.ui
import com.intellij.openapi.util.NlsSafe
import javax.swing.Spring
import javax.swing.SpringLayout
internal operator fun Spring.plus(other: Spring) = Spring.sum(this, other)
internal operator fun Spring.plus(gap: Int) = Spring.sum(this, Spring.constant(gap))
internal operator fun Spring.minus(other: Spring) = this + Spring.minus(other)
internal operator fun Spring.unaryMinus() = Spring.minus(this)
internal operator fun Spring.times(by: Float) = Spring.scale(this, by)
internal fun Int.asSpring() = Spring.constant(this)
internal operator fun SpringLayout.Constraints.get(@NlsSafe edgeName: String) = getConstraint(edgeName)
internal operator fun SpringLayout.Constraints.set(@NlsSafe edgeName: String, spring: Spring) {
setConstraint(edgeName, spring)
}
fun springMin(s1: Spring, s2: Spring) = -Spring.max(-s1, -s2)
| apache-2.0 | 94d560911849db30031e46164531fd45 | 46.636364 | 158 | 0.782443 | 3.651568 | false | false | false | false |
smmribeiro/intellij-community | platform/platform-tests/testSrc/com/intellij/ui/dsl/builder/components/DslLabelTest.kt | 9 | 2517 | // 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.ui.dsl.builder.components
import com.intellij.lang.documentation.DocumentationMarkup
import com.intellij.ui.dsl.UiDslException
import com.intellij.ui.dsl.builder.MAX_LINE_LENGTH_NO_WRAP
import org.junit.Test
import org.junit.jupiter.api.assertThrows
import kotlin.test.assertEquals
class DslLabelTest {
@Test
fun testSetHtmlText() {
val externalLink = DocumentationMarkup.EXTERNAL_LINK_ICON.toString()
.replace("/>", ">") // End of the tag removed by html framework
val testValues = mapOf(
"""Some text""" to """Some text""",
"""Some <a>link</a>""" to """Some <a href="">link</a>""",
"""Some <a href="aaa">link</a>""" to """Some <a href="aaa">link</a>""",
"""Some text<a href="http://url">a link</a>""" to """Some text<a href="http://url">a link$externalLink</a>""",
"""Some text<a href="https://url">a link</a>""" to """Some text<a href="https://url">a link$externalLink</a>""",
"""Some text<a href="nothttps://url">a link</a>""" to """Some text<a href="nothttps://url">a link</a>""",
"""<a href="https://url">https</a>, <a>link</a>, <a href="http://url">http</a>""" to
"""<a href="https://url">https$externalLink</a>, <a href="">link</a>, <a href="http://url">http$externalLink</a>""",
)
val bodyRegex = Regex("<body>(.*)</body>", RegexOption.DOT_MATCHES_ALL)
val newLineRegex = Regex("\\s+", RegexOption.DOT_MATCHES_ALL)
val dslLabel = DslLabel(DslLabelType.LABEL)
fun getDslLabelBody(text: String): String {
dslLabel.maxLineLength = MAX_LINE_LENGTH_NO_WRAP
dslLabel.text = text
return bodyRegex.find(dslLabel.text)!!.groups[1]!!
.value.trim()
.replace(newLineRegex, " ") // Remove new lines with indents
}
for ((text, expectedResult) in testValues) {
assertEquals(expectedResult, getDslLabelBody(text))
assertEquals(expectedResult, getDslLabelBody(text.replace('\"', '\'')))
}
}
@Test
fun testInvalidHtmlText() {
val testValues = listOf(
"<html>text",
"<BODY>text",
"<a href=''>text</a>",
"""<a HREF = "" >""",
)
val dslLabel = DslLabel(DslLabelType.LABEL)
for (text in testValues) {
assertThrows<UiDslException>(text) {
dslLabel.maxLineLength = MAX_LINE_LENGTH_NO_WRAP
dslLabel.text = text
}
}
}
}
| apache-2.0 | 119640da2b7c5b861bddf7df513da44a | 39.596774 | 158 | 0.629718 | 3.663755 | false | true | false | false |
tensorflow/examples | lite/examples/digit_classifier/android/app/src/main/java/org/tensorflow/lite/examples/digitclassification/fragments/ClassificationResultsAdapter.kt | 1 | 2640 | /*
* Copyright 2022 The TensorFlow Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.tensorflow.lite.examples.digitclassification.fragments
import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import org.tensorflow.lite.examples.digitclassification.databinding.ItemClassificationResultBinding
import org.tensorflow.lite.support.label.Category
import org.tensorflow.lite.task.vision.classifier.Classifications
import java.util.Locale
class ClassificationResultsAdapter :
RecyclerView.Adapter<ClassificationResultsAdapter.ViewHolder>() {
private var categories: MutableList<Category?> = mutableListOf()
@SuppressLint("NotifyDataSetChanged")
fun updateResults(listClassifications: List<Classifications>?) {
listClassifications?.get(0)?.categories?.let {
categories = it
notifyDataSetChanged()
}
}
@SuppressLint("NotifyDataSetChanged")
fun reset() {
categories = mutableListOf()
notifyDataSetChanged()
}
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): ViewHolder {
val binding = ItemClassificationResultBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
return ViewHolder(binding)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
categories[position]?.let { category ->
holder.bind(category.label, category.score)
}
}
override fun getItemCount(): Int = categories.size
inner class ViewHolder(private val binding: ItemClassificationResultBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(label: String, score: Float) {
with(binding) {
tvLabel.text = label
tvScore.text = String.format(
Locale.US,
"%.4f",
score
)
}
}
}
}
| apache-2.0 | 3d6c58d6b43aef2056a9347dc959635b | 31.592593 | 99 | 0.676136 | 4.971751 | false | false | false | false |
fabmax/kool | kool-core/src/commonMain/kotlin/de/fabmax/kool/scene/Mesh.kt | 1 | 5684 | package de.fabmax.kool.scene
import de.fabmax.kool.KoolContext
import de.fabmax.kool.math.RayTest
import de.fabmax.kool.math.spatial.BoundingBox
import de.fabmax.kool.pipeline.Attribute
import de.fabmax.kool.pipeline.Pipeline
import de.fabmax.kool.pipeline.RenderPass
import de.fabmax.kool.pipeline.Shader
import de.fabmax.kool.scene.animation.Skin
import de.fabmax.kool.scene.geometry.IndexedVertexList
import de.fabmax.kool.scene.geometry.MeshBuilder
inline fun mesh(attributes: List<Attribute>, name: String? = null, block: Mesh.() -> Unit): Mesh {
val mesh = Mesh(IndexedVertexList(attributes), name)
mesh.block()
return mesh
}
fun colorMesh(name: String? = null, generate: Mesh.() -> Unit): Mesh {
return mesh(listOf(Attribute.POSITIONS, Attribute.NORMALS, Attribute.COLORS), name, generate)
}
fun textureMesh(name: String? = null, isNormalMapped: Boolean = false, generate: Mesh.() -> Unit): Mesh {
val attributes = mutableListOf(Attribute.POSITIONS, Attribute.NORMALS, Attribute.TEXTURE_COORDS)
if (isNormalMapped) {
attributes += Attribute.TANGENTS
}
val mesh = mesh(attributes, name, generate)
if (isNormalMapped) {
mesh.geometry.generateTangents()
}
return mesh
}
/**
* Class for renderable geometry (triangles, lines, points).
*/
open class Mesh(var geometry: IndexedVertexList, name: String? = null) : Node(name) {
val id = instanceId++
var instances: MeshInstanceList? = null
set(value) {
field = value
if (value != null) {
// frustum checking does not play well with instancing -> disable it if instancing is used
isFrustumChecked = false
}
}
var morphWeights: FloatArray? = null
var skin: Skin? = null
var isOpaque = true
var shader: Shader? = null
set(value) {
if (field !== value) {
field = value
// fixme: this is not optimal in cases where the old shader is still used in other places
pipeline?.let { discardedPipelines += it }
pipeline = null
}
}
/**
* Optional shader used by DepthMapPass (mainly used for rendering shadow maps). If null DepthMapPass uses a
* geometry based default shader.
*/
var depthShader: Shader? = null
var normalLinearDepthShader: Shader? = null
/**
* Optional list with lod geometry used by shadow passes. Shadow passes will use the geometry at index
* [de.fabmax.kool.util.SimpleShadowMap.shadowMapLevel] or the last list entry in case the list has fewer entries.
* If list is empty the regular geometry is used.
*/
val shadowGeometry = mutableListOf<IndexedVertexList>()
/**
* Determines whether this node is considered during shadow pass.
*/
var isCastingShadowLevelMask = -1
var isCastingShadow: Boolean
get() = isCastingShadowLevelMask != 0
set(value) {
isCastingShadowLevelMask = if (value) -1 else 0
}
private var pipeline: Pipeline? = null
private val discardedPipelines = mutableListOf<Pipeline>()
var rayTest = MeshRayTest.boundsTest()
override val bounds: BoundingBox
get() = geometry.bounds
open fun generate(generator: MeshBuilder.() -> Unit) {
geometry.batchUpdate {
clear()
MeshBuilder(this).generator()
}
}
open fun getPipeline(ctx: KoolContext): Pipeline? {
if (discardedPipelines.isNotEmpty()) {
discardedPipelines.forEach { ctx.disposePipeline(it) }
discardedPipelines.clear()
}
return pipeline ?: shader?.let { s ->
s.createPipeline(this, ctx).also { pipeline = it }
}
}
fun setIsCastingShadow(shadowMapLevel: Int, enabled: Boolean) {
isCastingShadowLevelMask = if (enabled) {
isCastingShadowLevelMask or (1 shl shadowMapLevel)
} else {
isCastingShadowLevelMask and (1 shl shadowMapLevel).inv()
}
}
fun disableShadowCastingAboveLevel(shadowMapLevel: Int) {
isCastingShadowLevelMask = isCastingShadowLevelMask and ((2 shl shadowMapLevel) - 1)
}
fun isCastingShadow(shadowMapLevel: Int): Boolean {
return (isCastingShadowLevelMask and (1 shl shadowMapLevel)) != 0
}
override fun rayTest(test: RayTest) = rayTest.rayTest(test)
/**
* Deletes all buffers associated with this mesh.
*/
override fun dispose(ctx: KoolContext) {
super.dispose(ctx)
pipeline?.let { ctx.disposePipeline(it) }
pipeline = null
}
override fun collectDrawCommands(updateEvent: RenderPass.UpdateEvent) {
if (!updateEvent.meshFilter(this)) {
return
}
super.collectDrawCommands(updateEvent)
if (!isRendered) {
// mesh is not visible (either hidden or outside frustum)
return
}
val insts = instances
if (insts != null && insts.numInstances == 0) {
// instanced mesh has no instances
return
}
// update bounds and ray test if geometry has changed
if (geometry.hasChanged && !geometry.isBatchUpdate) {
// don't clear the hasChanged flag yet, is done by rendering backend after vertex buffers are updated
if (geometry.isRebuildBoundsOnSync) {
geometry.rebuildBounds()
}
rayTest.onMeshDataChanged(this)
}
updateEvent.renderPass.addMesh(this, updateEvent.ctx)
}
companion object {
private var instanceId = 1L
}
} | apache-2.0 | 90067f781c7ec6a65921bcb1cb200ebd | 31.485714 | 118 | 0.639866 | 4.423346 | false | true | false | false |
mbrlabs/Mundus | editor/src/main/com/mbrlabs/mundus/editor/assets/EditorAssetManager.kt | 1 | 11928 | /*
* Copyright (c) 2016. See AUTHORS file.
*
* 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.mbrlabs.mundus.editor.assets
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.files.FileHandle
import com.badlogic.gdx.graphics.Pixmap
import com.badlogic.gdx.graphics.PixmapIO
import com.badlogic.gdx.utils.ObjectSet
import com.mbrlabs.mundus.commons.assets.*
import com.mbrlabs.mundus.commons.assets.meta.Meta
import com.mbrlabs.mundus.commons.assets.meta.MetaTerrain
import com.mbrlabs.mundus.editor.utils.Log
import org.apache.commons.io.FileUtils
import org.apache.commons.io.FilenameUtils
import java.io.*
import java.util.*
/**
* @author Marcus Brummer
* @version 24-01-2016
*/
class EditorAssetManager(assetsRoot: FileHandle) : AssetManager(assetsRoot) {
companion object {
private val TAG = EditorAssetManager::class.java.simpleName
val STANDARD_ASSET_TEXTURE_CHESSBOARD = "chessboard"
}
/** Modified assets that need to be saved. */
private val dirtyAssets = ObjectSet<Asset>()
private val metaSaver = MetaSaver()
init {
if (rootFolder != null && (!rootFolder.exists() || !rootFolder.isDirectory)) {
Log.fatal(TAG, "Root asset folder is not a directory")
}
}
fun addDirtyAsset(asset: Asset) {
dirtyAssets.add(asset)
}
fun getDirtyAssets(): ObjectSet<Asset> {
return dirtyAssets
}
/**
* Creates a new meta file and saves it at the given location.
*
* @param file
* save location
* @param type
* asset type
* @return saved meta file
*
* @throws IOException
*/
@Throws(IOException::class, AssetAlreadyExistsException::class)
fun createNewMetaFile(file: FileHandle, type: AssetType): Meta {
if (file.exists()) throw AssetAlreadyExistsException()
val meta = Meta(file)
meta.uuid = newUUID()
meta.version = Meta.CURRENT_VERSION
meta.lastModified = System.currentTimeMillis()
meta.type = type
metaSaver.save(meta)
return meta
}
private fun newUUID(): String {
return UUID.randomUUID().toString().replace("-".toRegex(), "")
}
/**
* Creates a couple of standard assets.
*
* Creates a couple of standard assets in the current project, that should
* be included in every project.
*/
fun createStandardAssets() {
try {
// chessboard
val chessboard = createTextureAsset(Gdx.files.internal("standardAssets/chessboard.png"))
assetIndex.remove(chessboard.id)
chessboard.meta.uuid = STANDARD_ASSET_TEXTURE_CHESSBOARD
assetIndex.put(chessboard.id, chessboard)
metaSaver.save(chessboard.meta)
} catch (e: Exception) {
e.printStackTrace()
}
}
/**
* Creates a new model asset.
*
* Creates a new model asset in the current project and adds it to this
* asset manager.
*
* @param model imported model
* @return model asset
*
* @throws IOException
*/
@Throws(IOException::class, AssetAlreadyExistsException::class)
fun createModelAsset(model: ModelImporter.ImportedModel): ModelAsset {
val modelFilename = model.g3dbFile!!.name()
val metaFilename = modelFilename + ".meta"
// create meta file
val metaPath = FilenameUtils.concat(rootFolder.path(), metaFilename)
val meta = createNewMetaFile(FileHandle(metaPath), AssetType.MODEL)
// copy model file
val assetFile = FileHandle(FilenameUtils.concat(rootFolder.path(), modelFilename))
model.g3dbFile!!.copyTo(assetFile)
// load & return asset
val asset = ModelAsset(meta, assetFile)
asset.load()
addAsset(asset)
return asset
}
/**
* Creates a new terrainAsset asset.
*
* This creates a .terra file (height data) and a pixmap texture (splatmap).
* The asset will be added to this asset manager.
*
* @param vertexResolution
* vertex resolution of the terrainAsset
* @param size
* terrainAsset size
* @return new terrainAsset asset
* @throws IOException
*/
@Throws(IOException::class, AssetAlreadyExistsException::class)
fun createTerraAsset(name: String, vertexResolution: Int, size: Int): TerrainAsset {
val terraFilename = name + ".terra"
val metaFilename = terraFilename + ".meta"
// create meta file
val metaPath = FilenameUtils.concat(rootFolder.path(), metaFilename)
val meta = createNewMetaFile(FileHandle(metaPath), AssetType.TERRAIN)
meta.terrain = MetaTerrain()
meta.terrain.size = size
metaSaver.save(meta)
// create terra file
val terraPath = FilenameUtils.concat(rootFolder.path(), terraFilename)
val terraFile = File(terraPath)
FileUtils.touch(terraFile)
// create initial height data
val data = FloatArray(vertexResolution * vertexResolution)
for (i in data.indices) {
data[i] = 0f
}
// write terra file
val outputStream = DataOutputStream(BufferedOutputStream(FileOutputStream(terraFile)))
for (f in data) {
outputStream.writeFloat(f)
}
outputStream.flush()
outputStream.close()
// load & apply standard chessboard texture
val asset = TerrainAsset(meta, FileHandle(terraFile))
asset.load()
// set base texture
val chessboard = findAssetByID(STANDARD_ASSET_TEXTURE_CHESSBOARD)
if (chessboard != null) {
asset.splatBase = chessboard as TextureAsset
asset.applyDependencies()
metaSaver.save(asset.meta)
}
addAsset(asset)
return asset
}
/**
* Creates a new pixmap texture asset.
*
* This creates a new pixmap texture and adds it to this asset manager.
*
* @param size
* size of the pixmap in pixels
* @return new pixmap asset
* @throws IOException
*/
@Throws(IOException::class, AssetAlreadyExistsException::class)
fun createPixmapTextureAsset(size: Int): PixmapTextureAsset {
val pixmapFilename = newUUID().substring(0, 5) + ".png"
val metaFilename = pixmapFilename + ".meta"
// create meta file
val metaPath = FilenameUtils.concat(rootFolder.path(), metaFilename)
val meta = createNewMetaFile(FileHandle(metaPath), AssetType.PIXMAP_TEXTURE)
// create pixmap
val pixmapPath = FilenameUtils.concat(rootFolder.path(), pixmapFilename)
val pixmap = Pixmap(size, size, Pixmap.Format.RGBA8888)
val pixmapAssetFile = FileHandle(pixmapPath)
PixmapIO.writePNG(pixmapAssetFile, pixmap)
pixmap.dispose()
// load & return asset
val asset = PixmapTextureAsset(meta, pixmapAssetFile)
asset.load()
addAsset(asset)
return asset
}
/**
* Creates a new texture asset using the given texture file.
*
* @param texture
* @return
* @throws IOException
*/
@Throws(IOException::class, AssetAlreadyExistsException::class)
fun createTextureAsset(texture: FileHandle): TextureAsset {
val meta = createMetaFileFromAsset(texture, AssetType.TEXTURE)
val importedAssetFile = copyToAssetFolder(texture)
val asset = TextureAsset(meta, importedAssetFile)
// TODO parse special texture instead of always setting them
asset.setTileable(true)
asset.generateMipmaps(true)
asset.load()
addAsset(asset)
return asset
}
/**
* Creates a new & empty material asset.
*
* @return new material asset
* @throws IOException
*/
@Throws(IOException::class, AssetAlreadyExistsException::class)
fun createMaterialAsset(name: String): MaterialAsset {
// create empty material file
val path = FilenameUtils.concat(rootFolder.path(), name) + MaterialAsset.EXTENSION
val matFile = Gdx.files.absolute(path)
FileUtils.touch(matFile.file())
val meta = createMetaFileFromAsset(matFile, AssetType.MATERIAL)
val asset = MaterialAsset(meta, matFile)
asset.load()
addAsset(asset)
return asset
}
/**
* @param asset
* @throws IOException
*/
@Throws(IOException::class)
fun saveAsset(asset: Asset) {
if (asset is MaterialAsset) {
saveMaterialAsset(asset)
} else if (asset is TerrainAsset) {
saveTerrainAsset(asset)
} else if (asset is ModelAsset) {
saveModelAsset(asset)
}
// TODO other assets ?
}
/**
* @param asset
*/
@Throws(IOException::class)
fun saveModelAsset(asset: ModelAsset) {
for (g3dbMatID in asset.defaultMaterials.keys) {
asset.meta.model.defaultMaterials.put(g3dbMatID, asset.defaultMaterials[g3dbMatID]!!.id)
}
metaSaver.save(asset.meta)
}
/**
* Saves an existing terrainAsset asset.
*
* This updates all modifiable assets and the meta file.
*
* @param terrain
* terrainAsset asset
* @throws IOException
*/
@Throws(IOException::class)
fun saveTerrainAsset(terrain: TerrainAsset) {
// save .terra file
val outputStream = DataOutputStream(BufferedOutputStream(FileOutputStream(terrain.file.file())))
for (f in terrain.terrain.heightData) {
outputStream.writeFloat(f)
}
outputStream.flush()
outputStream.close()
// save splatmap
val splatmap = terrain.splatmap
if (splatmap != null) {
PixmapIO.writePNG(splatmap.file, splatmap.pixmap)
}
// save meta file
metaSaver.save(terrain.meta)
}
@Throws(IOException::class)
fun saveMaterialAsset(mat: MaterialAsset) {
// save .mat
val props = Properties()
if (mat.diffuseColor != null) {
props.setProperty(MaterialAsset.PROP_DIFFUSE_COLOR, mat.diffuseColor.toString())
}
if (mat.diffuseTexture != null) {
props.setProperty(MaterialAsset.PROP_DIFFUSE_TEXTURE, mat.diffuseTexture.id)
}
if (mat.normalMap != null) {
props.setProperty(MaterialAsset.PROP_MAP_NORMAL, mat.normalMap.id)
}
props.setProperty(MaterialAsset.PROP_OPACITY, mat.opacity.toString())
props.setProperty(MaterialAsset.PROP_SHININESS, mat.shininess.toString())
props.store(FileOutputStream(mat.file.file()), null)
// save meta file
metaSaver.save(mat.meta)
}
@Throws(IOException::class, AssetAlreadyExistsException::class)
private fun createMetaFileFromAsset(assetFile: FileHandle, type: AssetType): Meta {
val metaName = assetFile.name() + "." + Meta.META_EXTENSION
val metaPath = FilenameUtils.concat(rootFolder.path(), metaName)
return createNewMetaFile(FileHandle(metaPath), type)
}
private fun copyToAssetFolder(file: FileHandle): FileHandle {
val copy = FileHandle(FilenameUtils.concat(rootFolder.path(), file.name()))
file.copyTo(copy)
return copy
}
}
| apache-2.0 | f55aaec20bb48466a3b12cfdc211ba99 | 31.150943 | 104 | 0.63942 | 4.364435 | false | false | false | false |
idea4bsd/idea4bsd | plugins/git4idea/tests/git4idea/test/MockVcsHelper.kt | 9 | 6994 | /*
* 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 git4idea.test
import com.intellij.ide.errorTreeView.HotfixData
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.*
import com.intellij.openapi.vcs.annotate.AnnotationProvider
import com.intellij.openapi.vcs.annotate.FileAnnotation
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vcs.changes.CommitResultHandler
import com.intellij.openapi.vcs.changes.LocalChangeList
import com.intellij.openapi.vcs.history.VcsFileRevision
import com.intellij.openapi.vcs.history.VcsHistoryProvider
import com.intellij.openapi.vcs.history.VcsRevisionNumber
import com.intellij.openapi.vcs.merge.MergeDialogCustomizer
import com.intellij.openapi.vcs.merge.MergeProvider
import com.intellij.openapi.vcs.versionBrowser.ChangeBrowserSettings
import com.intellij.openapi.vcs.versionBrowser.CommittedChangeList
import com.intellij.openapi.vfs.VirtualFile
import java.awt.Component
import java.io.File
class MockVcsHelper(project: Project) : AbstractVcsHelper(project) {
@Volatile private var myCommitDialogShown: Boolean = false
@Volatile private var myMergeDialogShown: Boolean = false
@Volatile private var myMergeDelegate: () -> Unit = { throw IllegalStateException() }
@Volatile private var myCommitDelegate: (String) -> Boolean = { throw IllegalStateException() }
override fun runTransactionRunnable(vcs: AbstractVcs<*>?, runnable: TransactionRunnable?, vcsParameters: Any?): MutableList<VcsException>? {
throw UnsupportedOperationException()
}
override fun showAnnotation(annotation: FileAnnotation?, file: VirtualFile?, vcs: AbstractVcs<*>?) {
throw UnsupportedOperationException()
}
override fun showAnnotation(annotation: FileAnnotation?, file: VirtualFile?, vcs: AbstractVcs<*>?, line: Int) {
throw UnsupportedOperationException()
}
override fun showChangesBrowser(provider: CommittedChangesProvider<*, *>?, location: RepositoryLocation?, title: String?, parent: Component?) {
throw UnsupportedOperationException()
}
override fun openCommittedChangesTab(vcs: AbstractVcs<*>?, root: VirtualFile?, settings: ChangeBrowserSettings?, maxCount: Int, title: String?) {
throw UnsupportedOperationException()
}
override fun openCommittedChangesTab(provider: CommittedChangesProvider<*, *>?, location: RepositoryLocation?, settings: ChangeBrowserSettings?, maxCount: Int, title: String?) {
throw UnsupportedOperationException()
}
override fun showFileHistory(historyProvider: VcsHistoryProvider, path: FilePath, vcs: AbstractVcs<*>, repositoryPath: String?) {
throw UnsupportedOperationException()
}
override fun showFileHistory(historyProvider: VcsHistoryProvider, annotationProvider: AnnotationProvider?, path: FilePath, repositoryPath: String?, vcs: AbstractVcs<*>) {
throw UnsupportedOperationException()
}
override fun showErrors(abstractVcsExceptions: List<VcsException>, tabDisplayName: String) {
throw UnsupportedOperationException()
}
override fun showErrors(exceptionGroups: Map<HotfixData, List<VcsException>>, tabDisplayName: String) {
throw UnsupportedOperationException()
}
override fun showDifferences(cvsVersionOn: VcsFileRevision, cvsVersionOn1: VcsFileRevision, file: File) {
throw UnsupportedOperationException()
}
override fun showChangesListBrowser(changelist: CommittedChangeList, title: String) {
throw UnsupportedOperationException()
}
override fun showChangesBrowser(changelists: List<CommittedChangeList>) {
throw UnsupportedOperationException()
}
override fun showChangesBrowser(changelists: List<CommittedChangeList>, title: String) {
throw UnsupportedOperationException()
}
override fun showWhatDiffersBrowser(parent: Component?, changes: Collection<Change>, title: String) {
throw UnsupportedOperationException()
}
override fun <T : CommittedChangeList, U : ChangeBrowserSettings> chooseCommittedChangeList(provider: CommittedChangesProvider<T, U>, location: RepositoryLocation): T? {
throw UnsupportedOperationException()
}
override fun showRollbackChangesDialog(changes: List<Change>) {
throw UnsupportedOperationException()
}
override fun selectFilesToProcess(files: List<VirtualFile>, title: String, prompt: String?, singleFileTitle: String, singleFilePromptTemplate: String, confirmationOption: VcsShowConfirmationOption): Collection<VirtualFile>? {
throw UnsupportedOperationException()
}
override fun selectFilePathsToProcess(files: List<FilePath>, title: String, prompt: String?, singleFileTitle: String, singleFilePromptTemplate: String, confirmationOption: VcsShowConfirmationOption): Collection<FilePath>? {
throw UnsupportedOperationException()
}
override fun loadAndShowCommittedChangesDetails(project: Project, revision: VcsRevisionNumber, file: VirtualFile, key: VcsKey, location: RepositoryLocation?, local: Boolean) {
throw UnsupportedOperationException()
}
override fun showMergeDialog(files: List<VirtualFile>, provider: MergeProvider, mergeDialogCustomizer: MergeDialogCustomizer): List<VirtualFile> {
myMergeDialogShown = true
myMergeDelegate()
return emptyList()
}
override fun commitChanges(changes: Collection<Change>, initialChangeList: LocalChangeList, commitMessage: String, customResultHandler: CommitResultHandler?): Boolean {
myCommitDialogShown = true
val success = myCommitDelegate(commitMessage)
if (customResultHandler != null) {
if (success) {
customResultHandler.onSuccess(commitMessage)
}
else {
customResultHandler.onFailure()
}
}
return success
}
fun mergeDialogWasShown(): Boolean {
return myMergeDialogShown
}
fun commitDialogWasShown(): Boolean {
return myCommitDialogShown
}
fun onMerge(delegate : () -> Unit) {
myMergeDelegate = delegate
}
fun onCommit(delegate : (String) -> Boolean) {
myCommitDelegate = delegate
}
@Deprecated("use onCommit") fun registerHandler(handler: CommitHandler) {
myCommitDelegate = { handler.commit(it) }
}
@Deprecated("use onMerge") fun registerHandler(handler: MergeHandler) {
myMergeDelegate = { handler.showMergeDialog() }
}
@Deprecated("use onCommit") interface CommitHandler {
fun commit(commitMessage: String): Boolean
}
@Deprecated("use onMerge") interface MergeHandler {
fun showMergeDialog()
}
}
| apache-2.0 | d90db131b412db5f187e70e32c5f6bf6 | 38.738636 | 227 | 0.774092 | 4.914968 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertObjectLiteralToClassIntention.kt | 1 | 7017 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.codeInsight.CodeInsightUtilCore
import com.intellij.codeInsight.template.TemplateBuilderImpl
import com.intellij.codeInsight.template.TemplateManager
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiComment
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.core.KotlinNameSuggester
import org.jetbrains.kotlin.idea.core.replaced
import org.jetbrains.kotlin.idea.refactoring.chooseContainerElementIfNecessary
import org.jetbrains.kotlin.idea.refactoring.getExtractionContainers
import org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine.*
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.idea.util.getResolutionScope
import org.jetbrains.kotlin.idea.util.psi.patternMatching.toRange
import org.jetbrains.kotlin.idea.util.reformatted
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.resolve.scopes.utils.findClassifier
class ConvertObjectLiteralToClassIntention : SelfTargetingRangeIntention<KtObjectLiteralExpression>(
KtObjectLiteralExpression::class.java,
KotlinBundle.lazyMessage("convert.object.literal.to.class")
) {
override fun applicabilityRange(element: KtObjectLiteralExpression) = element.objectDeclaration.getObjectKeyword()?.textRange
override fun startInWriteAction() = false
private fun doApply(editor: Editor, element: KtObjectLiteralExpression, targetParent: KtElement) {
val project = element.project
val scope = element.getResolutionScope()
val validator: (String) -> Boolean = { scope.findClassifier(Name.identifier(it), NoLookupLocation.FROM_IDE) == null }
val classNames = element.objectDeclaration.superTypeListEntries
.mapNotNull { it.typeReference?.typeElement?.let { KotlinNameSuggester.suggestTypeAliasNameByPsi(it, validator) } }
.takeIf { it.isNotEmpty() }
?: listOf(KotlinNameSuggester.suggestNameByName("O", validator))
val className = classNames.first()
val psiFactory = KtPsiFactory(element)
val targetSibling = element.parentsWithSelf.first { it.parent == targetParent }
val objectDeclaration = element.objectDeclaration
val containingClass = element.containingClass()
val hasMemberReference = containingClass?.body?.allChildren?.any {
(it is KtProperty || it is KtNamedFunction) &&
ReferencesSearch.search(it, element.useScope).findFirst() != null
} ?: false
val newClass = psiFactory.createClass("class $className")
objectDeclaration.getSuperTypeList()?.let {
newClass.add(psiFactory.createColon())
newClass.add(it)
}
objectDeclaration.body?.let {
newClass.add(it)
}
ExtractionEngine(
object : ExtractionEngineHelper(text) {
override fun configureAndRun(
project: Project,
editor: Editor,
descriptorWithConflicts: ExtractableCodeDescriptorWithConflicts,
onFinish: (ExtractionResult) -> Unit
) {
project.executeWriteCommand(text) {
val descriptor = descriptorWithConflicts.descriptor.copy(suggestedNames = listOf(className))
doRefactor(
ExtractionGeneratorConfiguration(descriptor, ExtractionGeneratorOptions.DEFAULT),
onFinish
)
}
}
}
).run(editor, ExtractionData(element.containingKtFile, element.toRange(), targetSibling)) { extractionResult ->
val functionDeclaration = extractionResult.declaration as KtFunction
if (functionDeclaration.valueParameters.isNotEmpty()) {
val valKeyword = psiFactory.createValKeyword()
newClass.createPrimaryConstructorParameterListIfAbsent()
.replaced(functionDeclaration.valueParameterList!!)
.parameters
.forEach {
it.addAfter(valKeyword, null)
it.addModifier(KtTokens.PRIVATE_KEYWORD)
}
}
val introducedClass = functionDeclaration.replaced(newClass).apply {
if (hasMemberReference && containingClass == (parent.parent as? KtClass)) addModifier(KtTokens.INNER_KEYWORD)
primaryConstructor?.reformatted()
}.let { CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(it) } ?: return@run
val file = introducedClass.containingFile
val template = TemplateBuilderImpl(file).let { builder ->
builder.replaceElement(introducedClass.nameIdentifier!!, NEW_CLASS_NAME, ChooseStringExpression(classNames), true)
for (psiReference in ReferencesSearch.search(introducedClass, LocalSearchScope(file), false)) {
builder.replaceElement(psiReference.element, USAGE_VARIABLE_NAME, NEW_CLASS_NAME, false)
}
builder.buildInlineTemplate()
}
editor.caretModel.moveToOffset(file.startOffset)
TemplateManager.getInstance(project).startTemplate(editor, template)
}
}
override fun applyTo(element: KtObjectLiteralExpression, editor: Editor?) {
if (editor == null) return
val containers = element.getExtractionContainers(strict = true, includeAll = true)
if (ApplicationManager.getApplication().isUnitTestMode) {
val targetComment = element.containingKtFile.findDescendantOfType<PsiComment>()?.takeIf {
it.text == "// TARGET_BLOCK:"
}
val target = containers.firstOrNull { it == targetComment?.parent } ?: containers.last()
return doApply(editor, element, target)
}
chooseContainerElementIfNecessary(
containers,
editor,
if (containers.first() is KtFile) KotlinBundle.message("select.target.file") else KotlinBundle.message("select.target.code.block.file"),
true
) {
doApply(editor, element, it)
}
}
}
private const val NEW_CLASS_NAME = "NEW_CLASS_NAME"
private const val USAGE_VARIABLE_NAME = "OTHER_VAR"
| apache-2.0 | 09095ef910f71a9493c30f4162c0793c | 45.470199 | 158 | 0.68163 | 5.473479 | false | false | false | false |
BijoySingh/Quick-Note-Android | base/src/main/java/com/maubis/scarlet/base/note/selection/sheet/SelectedNotesOptionsBottomSheet.kt | 1 | 11806 | package com.maubis.scarlet.base.note.selection.sheet
import android.app.Dialog
import androidx.core.content.ContextCompat
import com.facebook.litho.ComponentContext
import com.github.bijoysingh.starter.util.IntentUtils
import com.github.bijoysingh.starter.util.TextUtils
import com.maubis.scarlet.base.R
import com.maubis.scarlet.base.core.format.FormatBuilder
import com.maubis.scarlet.base.core.format.sectionPreservingSort
import com.maubis.scarlet.base.core.note.NoteState
import com.maubis.scarlet.base.core.note.getFormats
import com.maubis.scarlet.base.main.sheets.AlertBottomSheet
import com.maubis.scarlet.base.main.sheets.AlertSheetConfig
import com.maubis.scarlet.base.note.addTag
import com.maubis.scarlet.base.note.delete
import com.maubis.scarlet.base.note.folder.sheet.SelectedFolderChooseOptionsBottomSheet
import com.maubis.scarlet.base.note.mark
import com.maubis.scarlet.base.note.removeTag
import com.maubis.scarlet.base.note.save
import com.maubis.scarlet.base.note.selection.activity.SelectNotesActivity
import com.maubis.scarlet.base.note.tag.sheet.SelectedTagChooserBottomSheet
import com.maubis.scarlet.base.security.sheets.openUnlockSheet
import com.maubis.scarlet.base.support.sheets.GridOptionBottomSheet
import com.maubis.scarlet.base.support.sheets.openSheet
import com.maubis.scarlet.base.support.specs.GridSectionItem
import com.maubis.scarlet.base.support.specs.GridSectionOptionItem
class SelectedNotesOptionsBottomSheet : GridOptionBottomSheet() {
override fun title(): Int = R.string.choose_action
override fun getOptions(componentContext: ComponentContext, dialog: Dialog): List<GridSectionItem> {
val options = ArrayList<GridSectionItem>()
options.add(getQuickActions(componentContext))
options.add(getSecondaryActions(componentContext, dialog))
options.add(getTertiaryActions(componentContext, dialog))
return options
}
private fun getQuickActions(componentContext: ComponentContext): GridSectionItem {
val activity = componentContext.androidContext as SelectNotesActivity
val options = ArrayList<GridSectionOptionItem>()
val allItemsInTrash = !activity.getAllSelectedNotes().any { it.state !== NoteState.TRASH.name }
options.add(
GridSectionOptionItem(
label = R.string.restore_note,
icon = R.drawable.ic_restore,
listener = lockAwareFunctionRunner(activity) {
activity.runNoteFunction {
it.mark(activity, NoteState.DEFAULT)
}
activity.finish()
},
visible = allItemsInTrash
))
val allItemsInFavourite = !activity.getAllSelectedNotes().any { it.state !== NoteState.FAVOURITE.name }
options.add(
GridSectionOptionItem(
label = R.string.not_favourite_note,
icon = R.drawable.ic_favorite_white_48dp,
listener = lockAwareFunctionRunner(activity) {
activity.runNoteFunction {
it.mark(activity, NoteState.DEFAULT)
}
activity.finish()
},
visible = allItemsInFavourite
))
options.add(
GridSectionOptionItem(
label = R.string.favourite_note,
icon = R.drawable.ic_favorite_border_white_48dp,
listener = lockAwareFunctionRunner(activity) {
activity.runNoteFunction {
it.mark(activity, NoteState.FAVOURITE)
}
activity.finish()
},
visible = !allItemsInFavourite
))
val allItemsInArchived = !activity.getAllSelectedNotes().any { it.state !== NoteState.ARCHIVED.name }
options.add(
GridSectionOptionItem(
label = R.string.unarchive_note,
icon = R.drawable.ic_archive_white_48dp,
listener = lockAwareFunctionRunner(activity) {
activity.runNoteFunction {
it.mark(activity, NoteState.DEFAULT)
}
activity.finish()
},
visible = allItemsInArchived
))
options.add(
GridSectionOptionItem(
label = R.string.archive_note,
icon = R.drawable.ic_archive_white_48dp,
listener = lockAwareFunctionRunner(activity) {
activity.runNoteFunction {
it.mark(activity, NoteState.ARCHIVED)
}
activity.finish()
},
visible = !allItemsInArchived
))
options.add(GridSectionOptionItem(
label = R.string.send_note,
icon = R.drawable.ic_share_white_48dp,
listener = lockAwareFunctionRunner(activity) {
activity.runTextFunction {
IntentUtils.ShareBuilder(activity)
.setChooserText(getString(R.string.share_using))
.setText(it)
.share()
}
}
))
options.add(GridSectionOptionItem(
label = R.string.copy_note,
icon = R.drawable.ic_content_copy_white_48dp,
listener = lockAwareFunctionRunner(activity) {
activity.runTextFunction {
TextUtils.copyToClipboard(activity, it)
}
activity.finish()
}
))
options.add(
GridSectionOptionItem(
label = R.string.trash_note,
icon = R.drawable.ic_delete_white_48dp,
listener = lockAwareFunctionRunner(activity) {
activity.runNoteFunction {
it.mark(activity, NoteState.TRASH)
}
activity.finish()
},
visible = !allItemsInTrash
))
return GridSectionItem(
options = options,
sectionColor = ContextCompat.getColor(activity, R.color.material_blue_800))
}
private fun getSecondaryActions(componentContext: ComponentContext, dialog: Dialog): GridSectionItem {
val activity = componentContext.androidContext as SelectNotesActivity
val options = ArrayList<GridSectionOptionItem>()
options.add(GridSectionOptionItem(
label = R.string.change_tags,
icon = R.drawable.ic_action_tags,
listener = lockAwareFunctionRunner(activity) {
openSheet(activity, SelectedTagChooserBottomSheet().apply {
onActionListener = { tag, selectTag ->
activity.runNoteFunction {
when (selectTag) {
true -> it.addTag(tag)
false -> it.removeTag(tag)
}
it.save(activity)
}
activity.finish()
}
})
}
))
options.add(GridSectionOptionItem(
label = R.string.folder_option_change_notebook,
icon = R.drawable.ic_folder,
listener = lockAwareFunctionRunner(activity) {
openSheet(activity, SelectedFolderChooseOptionsBottomSheet().apply {
this.dismissListener = {}
this.onActionListener = { folder, selectFolder ->
activity.runNoteFunction {
when (selectFolder) {
true -> it.folder = folder.uuid
false -> it.folder = ""
}
it.save(activity)
}
activity.finish()
}
})
}
))
val allLocked = !activity.getAllSelectedNotes().any { !it.locked }
options.add(
GridSectionOptionItem(
label = R.string.lock_note,
icon = R.drawable.ic_action_lock,
listener = lockAwareFunctionRunner(activity) {
activity.runNoteFunction {
it.locked = true
it.save(activity)
}
activity.finish()
},
visible = !allLocked
))
options.add(
GridSectionOptionItem(
label = R.string.unlock_note,
icon = R.drawable.ic_action_unlock,
listener = lockAwareFunctionRunner(activity) {
activity.runNoteFunction {
it.locked = false
it.save(activity)
}
activity.finish()
},
visible = allLocked
))
return GridSectionItem(
options = options,
sectionColor = ContextCompat.getColor(activity, R.color.material_red_800))
}
private fun getTertiaryActions(componentContext: ComponentContext, dialog: Dialog): GridSectionItem {
val activity = componentContext.androidContext as SelectNotesActivity
val options = ArrayList<GridSectionOptionItem>()
val allItemsPinned = !activity.getAllSelectedNotes().any { !it.pinned }
options.add(
GridSectionOptionItem(
label = R.string.pin_note,
icon = R.drawable.ic_pin,
listener = lockAwareFunctionRunner(activity) {
activity.runNoteFunction {
it.pinned = true
it.save(activity)
}
activity.finish()
},
visible = !allItemsPinned
))
options.add(
GridSectionOptionItem(
label = R.string.unpin_note,
icon = R.drawable.ic_pin,
listener = lockAwareFunctionRunner(activity) {
activity.runNoteFunction {
it.pinned = false
it.save(activity)
}
activity.finish()
},
visible = allItemsPinned
))
options.add(GridSectionOptionItem(
label = R.string.merge_notes,
icon = R.drawable.ic_merge_note,
listener = lockAwareFunctionRunner(activity) {
val selectedNotes = activity.getOrderedSelectedNotes().toMutableList()
if (selectedNotes.isEmpty()) {
return@lockAwareFunctionRunner
}
val note = selectedNotes.firstOrNull()
if (note === null) {
return@lockAwareFunctionRunner
}
val formats = note.getFormats().toMutableList()
selectedNotes.removeAt(0)
for (noteToAdd in selectedNotes) {
formats.addAll(noteToAdd.getFormats())
noteToAdd.delete(activity)
}
note.description = FormatBuilder().getDescription(sectionPreservingSort(formats))
note.save(activity)
activity.finish()
}
))
options.add(GridSectionOptionItem(
label = R.string.delete_note_permanently,
icon = R.drawable.ic_delete_permanently,
listener = lockAwareFunctionRunner(activity) {
openSheet(activity, AlertBottomSheet().apply {
config = AlertSheetConfig(
description = R.string.delete_sheet_delete_selected_notes_permanently,
onPositiveClick = {
activity.runNoteFunction {
it.delete(activity)
}
activity.finish()
}
)
})
}
))
val allBackupDisabled = !activity.getAllSelectedNotes().any { !it.disableBackup }
options.add(
GridSectionOptionItem(
label = R.string.backup_note_enable,
icon = R.drawable.ic_action_backup,
listener = lockAwareFunctionRunner(activity) {
activity.runNoteFunction {
it.disableBackup = false
it.save(activity)
}
activity.finish()
},
visible = allBackupDisabled
))
options.add(
GridSectionOptionItem(
label = R.string.backup_note_disable,
icon = R.drawable.ic_action_backup_no,
listener = lockAwareFunctionRunner(activity) {
activity.runNoteFunction {
it.disableBackup = true
it.save(activity)
}
activity.finish()
},
visible = !allBackupDisabled
))
return GridSectionItem(
options = options,
sectionColor = ContextCompat.getColor(activity, R.color.material_teal_800))
}
private fun lockAwareFunctionRunner(
activity: SelectNotesActivity,
listener: () -> Unit): () -> Unit = {
val hasLockedNote = activity.getAllSelectedNotes().any { it.locked }
when {
hasLockedNote -> openUnlockSheet(
activity = activity,
onUnlockSuccess = {
listener()
dismiss()
},
onUnlockFailure = {})
else -> {
listener()
dismiss()
}
}
}
} | gpl-3.0 | 21b8d3cd328dbe72580199343c7c629d | 32.542614 | 107 | 0.637303 | 4.395383 | false | false | false | false |
jwren/intellij-community | build/tasks/src/org/jetbrains/intellij/build/tasks/mac.kt | 1 | 2815 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:Suppress("ReplaceGetOrSet", "ReplaceNegatedIsEmptyWithIsNotEmpty")
package org.jetbrains.intellij.build.tasks
import io.opentelemetry.api.common.AttributeKey
import org.jetbrains.intellij.build.io.writeNewFile
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.attribute.PosixFilePermission
fun buildMacZip(targetFile: Path,
zipRoot: String,
productJson: ByteArray,
allDist: Path,
macDist: Path,
extraFiles: Collection<Map.Entry<Path, String>>,
executableFilePatterns: List<String>,
compressionLevel: Int,
errorsConsumer: (String) -> Unit) {
tracer.spanBuilder("build zip archive for macOS")
.setAttribute("file", targetFile.toString())
.setAttribute("zipRoot", zipRoot)
.setAttribute(AttributeKey.stringArrayKey("executableFilePatterns"), executableFilePatterns)
.startSpan()
.use {
val fs = targetFile.fileSystem
val patterns = executableFilePatterns.map { fs.getPathMatcher("glob:$it") }
val entryCustomizer: EntryCustomizer = { entry, file, relativeFile ->
when {
patterns.any { it.matches(relativeFile) } -> entry.unixMode = executableFileUnixMode
PosixFilePermission.OWNER_EXECUTE in Files.getPosixFilePermissions(file) -> {
errorsConsumer("Executable permissions of $relativeFile won't be set in $targetFile. " +
"Please make sure that executable file patterns are updated.")
}
}
}
writeNewFile(targetFile) { targetFileChannel ->
NoDuplicateZipArchiveOutputStream(targetFileChannel).use { zipOutStream ->
zipOutStream.setLevel(compressionLevel)
zipOutStream.entry("$zipRoot/Resources/product-info.json", productJson)
val fileFilter: (Path, Path) -> Boolean = { sourceFile, relativeFile ->
val path = relativeFile.toString()
if (path.endsWith(".txt") && !path.contains('/')) {
zipOutStream.entry("$zipRoot/Resources/$relativeFile", sourceFile)
false
}
else {
true
}
}
zipOutStream.dir(allDist, "$zipRoot/", fileFilter = fileFilter, entryCustomizer = entryCustomizer)
zipOutStream.dir(macDist, "$zipRoot/", fileFilter = fileFilter, entryCustomizer = entryCustomizer)
for ((file, relativePath) in extraFiles) {
zipOutStream.entry("$zipRoot/$relativePath${if (relativePath.isEmpty()) "" else "/"}${file.fileName}", file)
}
}
}
}
} | apache-2.0 | a2564ac5b0e10fae460e6bacadddc7b7 | 41.666667 | 158 | 0.646181 | 5.081227 | false | false | false | false |
SimpleMobileTools/Simple-Calendar | app/src/main/kotlin/com/simplemobiletools/calendar/pro/interfaces/EventsDao.kt | 1 | 7058 | package com.simplemobiletools.calendar.pro.interfaces
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.simplemobiletools.calendar.pro.helpers.*
import com.simplemobiletools.calendar.pro.models.Event
@Dao
interface EventsDao {
@Query("SELECT * FROM events")
fun getAllEvents(): List<Event>
@Query("SELECT * FROM events WHERE event_type IN (:eventTypeIds) AND type = $TYPE_EVENT")
fun getAllEventsWithTypes(eventTypeIds: List<Long>): List<Event>
@Query("SELECT * FROM events WHERE id = :id AND type = $TYPE_EVENT")
fun getEventWithId(id: Long): Event?
@Query("SELECT * FROM events WHERE id = :id AND type = $TYPE_TASK")
fun getTaskWithId(id: Long): Event?
@Query("SELECT * FROM events WHERE id = :id AND (type = $TYPE_EVENT OR type = $TYPE_TASK)")
fun getEventOrTaskWithId(id: Long): Event?
@Query("SELECT * FROM events WHERE import_id = :importId AND type = $TYPE_EVENT")
fun getEventWithImportId(importId: String): Event?
@Query("SELECT * FROM events WHERE start_ts <= :toTS AND end_ts >= :fromTS AND repeat_interval = 0 AND (type = $TYPE_EVENT OR type = $TYPE_TASK)")
fun getOneTimeEventsOrTasksFromTo(toTS: Long, fromTS: Long): List<Event>
@Query("SELECT * FROM events WHERE start_ts <= :toTS AND start_ts >= :fromTS AND event_type IN (:eventTypeIds) AND type = $TYPE_TASK")
fun getTasksFromTo(fromTS: Long, toTS: Long, eventTypeIds: List<Long>): List<Event>
@Query("SELECT * FROM events WHERE id = :id AND start_ts <= :toTS AND end_ts >= :fromTS AND repeat_interval = 0 AND (type = $TYPE_EVENT OR type = $TYPE_TASK)")
fun getOneTimeEventFromToWithId(id: Long, toTS: Long, fromTS: Long): List<Event>
@Query("SELECT * FROM events WHERE start_ts <= :toTS AND end_ts >= :fromTS AND start_ts != 0 AND repeat_interval = 0 AND event_type IN (:eventTypeIds) AND (type = $TYPE_EVENT OR type = $TYPE_TASK)")
fun getOneTimeEventsFromToWithTypes(toTS: Long, fromTS: Long, eventTypeIds: List<Long>): List<Event>
@Query("SELECT * FROM events WHERE end_ts > :toTS AND repeat_interval = 0 AND event_type IN (:eventTypeIds) AND type = $TYPE_EVENT")
fun getOneTimeFutureEventsWithTypes(toTS: Long, eventTypeIds: List<Long>): List<Event>
@Query("SELECT * FROM events WHERE start_ts <= :toTS AND repeat_interval != 0 AND (type = $TYPE_EVENT OR type = $TYPE_TASK)")
fun getRepeatableEventsOrTasksWithTypes(toTS: Long): List<Event>
@Query("SELECT * FROM events WHERE id = :id AND start_ts <= :toTS AND repeat_interval != 0 AND (type = $TYPE_EVENT OR type = $TYPE_TASK)")
fun getRepeatableEventsOrTasksWithId(id: Long, toTS: Long): List<Event>
@Query("SELECT * FROM events WHERE start_ts <= :toTS AND start_ts != 0 AND repeat_interval != 0 AND event_type IN (:eventTypeIds) AND (type = $TYPE_EVENT OR type = $TYPE_TASK)")
fun getRepeatableEventsOrTasksWithTypes(toTS: Long, eventTypeIds: List<Long>): List<Event>
@Query("SELECT * FROM events WHERE repeat_interval != 0 AND (repeat_limit == 0 OR repeat_limit > :currTS) AND event_type IN (:eventTypeIds) AND type = $TYPE_EVENT")
fun getRepeatableFutureEventsWithTypes(currTS: Long, eventTypeIds: List<Long>): List<Event>
@Query("SELECT * FROM events WHERE id IN (:ids) AND import_id != \"\" AND type = $TYPE_EVENT")
fun getEventsByIdsWithImportIds(ids: List<Long>): List<Event>
@Query("SELECT * FROM events WHERE title LIKE :searchQuery OR location LIKE :searchQuery OR description LIKE :searchQuery AND type = $TYPE_EVENT")
fun getEventsForSearch(searchQuery: String): List<Event>
@Query("SELECT * FROM events WHERE source = \'$SOURCE_CONTACT_BIRTHDAY\' AND type = $TYPE_EVENT")
fun getBirthdays(): List<Event>
@Query("SELECT * FROM events WHERE source = \'$SOURCE_CONTACT_ANNIVERSARY\' AND type = $TYPE_EVENT")
fun getAnniversaries(): List<Event>
@Query("SELECT * FROM events WHERE import_id != \"\" AND type = $TYPE_EVENT")
fun getEventsWithImportIds(): List<Event>
@Query("SELECT * FROM events WHERE source = :source AND type = $TYPE_EVENT")
fun getEventsFromCalDAVCalendar(source: String): List<Event>
@Query("SELECT * FROM events WHERE id IN (:ids) AND type = $TYPE_EVENT")
fun getEventsWithIds(ids: List<Long>): List<Event>
//val selection = "$COL_REMINDER_MINUTES != -1 AND ($COL_START_TS > ? OR $COL_REPEAT_INTERVAL != 0) AND $COL_START_TS != 0"
@Query("SELECT * FROM events WHERE reminder_1_minutes != -1 AND (start_ts > :currentTS OR repeat_interval != 0) AND start_ts != 0 AND (type = $TYPE_EVENT OR type = $TYPE_TASK)")
fun getEventsOrTasksAtReboot(currentTS: Long): List<Event>
@Query("SELECT id FROM events")
fun getEventIds(): List<Long>
@Query("SELECT id FROM events WHERE import_id = :importId AND type = $TYPE_EVENT")
fun getEventIdWithImportId(importId: String): Long?
@Query("SELECT id FROM events WHERE import_id LIKE :importId AND type = $TYPE_EVENT")
fun getEventIdWithLastImportId(importId: String): Long?
@Query("SELECT id FROM events WHERE event_type = :eventTypeId AND type = $TYPE_EVENT")
fun getEventIdsByEventType(eventTypeId: Long): List<Long>
@Query("SELECT id FROM events WHERE event_type IN (:eventTypeIds) AND type = $TYPE_EVENT")
fun getEventIdsByEventType(eventTypeIds: List<Long>): List<Long>
@Query("SELECT id FROM events WHERE parent_id IN (:parentIds) AND type = $TYPE_EVENT")
fun getEventIdsWithParentIds(parentIds: List<Long>): List<Long>
@Query("SELECT id FROM events WHERE source = :source AND import_id != \"\" AND type = $TYPE_EVENT")
fun getCalDAVCalendarEvents(source: String): List<Long>
@Query("UPDATE events SET event_type = $REGULAR_EVENT_TYPE_ID WHERE event_type = :eventTypeId AND type = $TYPE_EVENT")
fun resetEventsWithType(eventTypeId: Long)
@Query("UPDATE events SET import_id = :importId, source = :source WHERE id = :id AND type = $TYPE_EVENT")
fun updateEventImportIdAndSource(importId: String, source: String, id: Long)
@Query("UPDATE events SET repeat_limit = :repeatLimit WHERE id = :id AND (type = $TYPE_EVENT OR type = $TYPE_TASK)")
fun updateEventRepetitionLimit(repeatLimit: Long, id: Long)
@Query("UPDATE events SET repetition_exceptions = :repetitionExceptions WHERE id = :id AND (type = $TYPE_EVENT OR type = $TYPE_TASK)")
fun updateEventRepetitionExceptions(repetitionExceptions: String, id: Long)
@Deprecated("Use Context.updateTaskCompletion() instead unless you know what you are doing.")
@Query("UPDATE events SET flags = :newFlags WHERE id = :id")
fun updateTaskCompletion(id: Long, newFlags: Int)
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertOrUpdate(event: Event): Long
@Query("DELETE FROM events WHERE id IN (:ids)")
fun deleteEvents(ids: List<Long>)
@Query("DELETE FROM events WHERE source = :source AND import_id = :importId")
fun deleteBirthdayAnniversary(source: String, importId: String): Int
}
| gpl-3.0 | aaecc8b902ad4250096ad960e03e77bc | 54.574803 | 202 | 0.706007 | 3.695288 | false | false | false | false |
allotria/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ChangesViewDiffPreviewProcessor.kt | 2 | 2002 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.changes
import com.intellij.diff.util.DiffUserDataKeysEx
import com.intellij.diff.util.DiffUtil
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.changes.ChangeViewDiffRequestProcessor.*
import com.intellij.openapi.vcs.changes.actions.diff.lst.LocalChangeListDiffTool.ALLOW_EXCLUDE_FROM_COMMIT
import com.intellij.openapi.vcs.changes.ui.ChangesListView
import com.intellij.util.ui.tree.TreeUtil
import one.util.streamex.StreamEx
import java.util.stream.Stream
private fun wrap(changes: Stream<Change>, unversioned: Stream<FilePath>): Stream<Wrapper> =
Stream.concat(
changes.map { ChangeWrapper(it) },
unversioned.map { UnversionedFileWrapper(it) }
)
private class ChangesViewDiffPreviewProcessor(private val changesView: ChangesListView,
place : String) :
ChangeViewDiffRequestProcessor(changesView.project, place) {
init {
putContextUserData(DiffUserDataKeysEx.LAST_REVISION_WITH_LOCAL, true)
}
override fun getSelectedChanges(): Stream<Wrapper> =
if (changesView.isSelectionEmpty) allChanges
else wrap(StreamEx.of(changesView.selectedChanges.iterator()), StreamEx.of(changesView.selectedUnversionedFiles.iterator()))
override fun getAllChanges(): Stream<Wrapper> = wrap(StreamEx.of(changesView.changes.iterator()), changesView.unversionedFiles)
override fun selectChange(change: Wrapper) {
changesView.findNodePathInTree(change.userObject)?.let { TreeUtil.selectPath(changesView, it, false) }
}
fun setAllowExcludeFromCommit(value: Boolean) {
if (DiffUtil.isUserDataFlagSet(ALLOW_EXCLUDE_FROM_COMMIT, context) == value) return
context.putUserData(ALLOW_EXCLUDE_FROM_COMMIT, value)
fireDiffSettingsChanged()
}
fun fireDiffSettingsChanged() {
dropCaches()
updateRequest(true)
}
} | apache-2.0 | ddd2f5438762b3423c2aac5e4e880ee6 | 40.729167 | 140 | 0.771229 | 4.268657 | false | false | false | false |
androidx/androidx | compose/ui/ui/src/commonMain/kotlin/androidx/compose/ui/node/BackwardsCompatNode.kt | 3 | 17437 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("DEPRECATION")
package androidx.compose.ui.node
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.BuildDrawCacheParams
import androidx.compose.ui.draw.DrawCacheModifier
import androidx.compose.ui.draw.DrawModifier
import androidx.compose.ui.focus.FocusOrderModifier
import androidx.compose.ui.focus.FocusOrderModifierToProperties
import androidx.compose.ui.focus.FocusPropertiesModifier
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.drawscope.ContentDrawScope
import androidx.compose.ui.input.pointer.PointerEvent
import androidx.compose.ui.input.pointer.PointerEventPass
import androidx.compose.ui.input.pointer.PointerInputModifier
import androidx.compose.ui.layout.IntermediateLayoutModifier
import androidx.compose.ui.layout.IntrinsicMeasurable
import androidx.compose.ui.layout.IntrinsicMeasureScope
import androidx.compose.ui.layout.LayoutCoordinates
import androidx.compose.ui.layout.LayoutModifier
import androidx.compose.ui.layout.LookaheadLayoutCoordinates
import androidx.compose.ui.layout.LookaheadOnPlacedModifier
import androidx.compose.ui.layout.Measurable
import androidx.compose.ui.layout.MeasureResult
import androidx.compose.ui.layout.MeasureScope
import androidx.compose.ui.layout.OnGloballyPositionedModifier
import androidx.compose.ui.layout.OnPlacedModifier
import androidx.compose.ui.layout.OnRemeasuredModifier
import androidx.compose.ui.layout.ParentDataModifier
import androidx.compose.ui.layout.RemeasurementModifier
import androidx.compose.ui.modifier.BackwardsCompatLocalMap
import androidx.compose.ui.modifier.ModifierLocal
import androidx.compose.ui.modifier.ModifierLocalConsumer
import androidx.compose.ui.modifier.ModifierLocalMap
import androidx.compose.ui.modifier.ModifierLocalNode
import androidx.compose.ui.modifier.ModifierLocalProvider
import androidx.compose.ui.modifier.ModifierLocalReadScope
import androidx.compose.ui.modifier.modifierLocalMapOf
import androidx.compose.ui.platform.debugInspectorInfo
import androidx.compose.ui.semantics.SemanticsConfiguration
import androidx.compose.ui.semantics.SemanticsModifier
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.toSize
/**
* This entity will end up implementing all of the entity type interfaces, but its [kindSet]
* will only be set to the expected values based on the interface(s) that the modifier element that
* it has implements. This is nice because it will be one class that simply delegates / pipes
* everything to the modifier instance, but those interfaces should only be called in the cases
* where the modifier would have been previously.
*/
@Suppress("NOTHING_TO_INLINE")
@OptIn(ExperimentalComposeUiApi::class)
internal class BackwardsCompatNode(element: Modifier.Element) :
LayoutModifierNode,
IntermediateLayoutModifierNode,
DrawModifierNode,
SemanticsModifierNode,
PointerInputModifierNode,
ModifierLocalNode,
ModifierLocalReadScope,
ParentDataModifierNode,
LayoutAwareModifierNode,
GlobalPositionAwareModifierNode,
OwnerScope,
BuildDrawCacheParams,
Modifier.Node() {
init {
kindSet = calculateNodeKindSetFrom(element)
}
var element: Modifier.Element = element
set(value) {
if (isAttached) uninitializeModifier()
field = value
kindSet = calculateNodeKindSetFrom(value)
if (isAttached) initializeModifier(false)
}
override fun onAttach() {
initializeModifier(true)
}
override fun onDetach() {
uninitializeModifier()
}
private fun uninitializeModifier() {
check(isAttached)
val element = element
if (isKind(Nodes.Locals)) {
if (element is ModifierLocalProvider<*>) {
requireOwner()
.modifierLocalManager
.removedProvider(this, element.key)
}
if (element is ModifierLocalConsumer) {
element.onModifierLocalsUpdated(DetachedModifierLocalReadScope)
}
if (element is FocusOrderModifier) {
val focusOrderElement = focusOrderElement
if (focusOrderElement != null) {
requireOwner()
.modifierLocalManager
.removedProvider(this, focusOrderElement.key)
}
}
}
if (isKind(Nodes.Semantics)) {
requireOwner().onSemanticsChange()
}
}
private fun initializeModifier(duringAttach: Boolean) {
check(isAttached)
val element = element
if (isKind(Nodes.Locals)) {
if (element is ModifierLocalProvider<*>) {
updateModifierLocalProvider(element)
}
if (element is ModifierLocalConsumer) {
if (duringAttach)
updateModifierLocalConsumer()
else
sideEffect { updateModifierLocalConsumer() }
}
// Special handling for FocusOrderModifier -- we have to use modifier local
// consumers and providers for it.
if (element is FocusOrderModifier) {
// Have to create a new consumer/provider
val scope = FocusOrderModifierToProperties(element)
focusOrderElement = FocusPropertiesModifier(
focusPropertiesScope = scope,
inspectorInfo = debugInspectorInfo {
name = "focusProperties"
properties["scope"] = scope
}
)
updateModifierLocalProvider(focusOrderElement!!)
if (duringAttach)
updateFocusOrderModifierLocalConsumer()
else
sideEffect { updateFocusOrderModifierLocalConsumer() }
}
}
if (isKind(Nodes.Draw)) {
if (element is DrawCacheModifier) {
invalidateCache = true
}
invalidateLayer()
}
if (isKind(Nodes.Layout)) {
val isChainUpdate = requireLayoutNode().nodes.tail.isAttached
if (isChainUpdate) {
val coordinator = coordinator!!
coordinator as LayoutModifierNodeCoordinator
coordinator.layoutModifierNode = this
coordinator.onLayoutModifierNodeChanged()
}
invalidateLayer()
requireLayoutNode().invalidateMeasurements()
}
if (element is RemeasurementModifier) {
element.onRemeasurementAvailable(this)
}
if (isKind(Nodes.LayoutAware)) {
if (element is OnRemeasuredModifier) {
// if the modifier was added but layout has already happened and might not change,
// we want to call remeasured in case layout doesn't happen again
val isChainUpdate = requireLayoutNode().nodes.tail.isAttached
if (isChainUpdate) {
requireLayoutNode().invalidateMeasurements()
}
}
if (element is OnPlacedModifier) {
lastOnPlacedCoordinates = null
val isChainUpdate = requireLayoutNode().nodes.tail.isAttached
if (isChainUpdate) {
requireOwner().registerOnLayoutCompletedListener(
object : Owner.OnLayoutCompletedListener {
override fun onLayoutComplete() {
if (lastOnPlacedCoordinates == null) {
onPlaced(requireCoordinator(Nodes.LayoutAware))
}
}
}
)
}
}
}
if (isKind(Nodes.GlobalPositionAware)) {
// if the modifier was added but layout has already happened and might not change,
// we want to call remeasured in case layout doesn't happen again
if (element is OnGloballyPositionedModifier) {
val isChainUpdate = requireLayoutNode().nodes.tail.isAttached
if (isChainUpdate) {
requireLayoutNode().invalidateMeasurements()
}
}
}
if (isKind(Nodes.PointerInput)) {
if (element is PointerInputModifier) {
element.pointerInputFilter.layoutCoordinates = coordinator
}
}
if (isKind(Nodes.Semantics)) {
requireOwner().onSemanticsChange()
}
}
// BuildDrawCacheParams
override val density get() = requireLayoutNode().density
override val layoutDirection: LayoutDirection get() = requireLayoutNode().layoutDirection
override val size: Size
get() {
return requireCoordinator(Nodes.LayoutAware).size.toSize()
}
// Flag to determine if the cache should be re-built
private var invalidateCache = true
override fun onMeasureResultChanged() {
invalidateCache = true
invalidateDraw()
}
private fun updateDrawCache() {
val element = element
if (element is DrawCacheModifier) {
requireOwner()
.snapshotObserver
.observeReads(this, onDrawCacheReadsChanged) {
element.onBuildCache(this)
}
}
invalidateCache = false
}
internal fun onDrawCacheReadsChanged() {
invalidateCache = true
invalidateDraw()
}
private var focusOrderElement: FocusPropertiesModifier? = null
private var _providedValues: BackwardsCompatLocalMap? = null
var readValues = hashSetOf<ModifierLocal<*>>()
override val providedValues: ModifierLocalMap get() = _providedValues ?: modifierLocalMapOf()
override val <T> ModifierLocal<T>.current: T
get() {
val key = this
readValues.add(key)
visitAncestors(Nodes.Locals) {
if (it.providedValues.contains(key)) {
@Suppress("UNCHECKED_CAST")
return it.providedValues[key] as T
}
}
return key.defaultFactory()
}
fun updateModifierLocalConsumer() {
if (isAttached) {
readValues.clear()
requireOwner().snapshotObserver.observeReads(
this,
updateModifierLocalConsumer
) {
(element as ModifierLocalConsumer).onModifierLocalsUpdated(this)
}
}
}
fun updateFocusOrderModifierLocalConsumer() {
if (isAttached) {
requireOwner().snapshotObserver.observeReads(
this,
updateFocusOrderModifierLocalConsumer
) {
(focusOrderElement!! as ModifierLocalConsumer).onModifierLocalsUpdated(this)
}
}
}
fun updateModifierLocalProvider(element: ModifierLocalProvider<*>) {
val providedValues = _providedValues
if (providedValues != null && providedValues.contains(element.key)) {
providedValues.element = element
requireOwner()
.modifierLocalManager
.updatedProvider(this, element.key)
} else {
_providedValues = BackwardsCompatLocalMap(element)
// we only need to notify the modifierLocalManager of an inserted provider
// in the cases where a provider was added to the chain where it was possible
// that consumers below it could need to be invalidated. If this layoutnode
// is just now being created, then that is impossible. In this case, we can just
// do nothing and wait for the child consumers to read us. We infer this by
// checking to see if the tail node is attached or not. If it is not, then the node
// chain is being attached for the first time.
val isChainUpdate = requireLayoutNode().nodes.tail.isAttached
if (isChainUpdate) {
requireOwner()
.modifierLocalManager
.insertedProvider(this, element.key)
}
}
}
override val isValid: Boolean get() = isAttached
override var targetSize: IntSize
get() = (element as IntermediateLayoutModifier).targetSize
set(value) {
(element as IntermediateLayoutModifier).targetSize = value
}
override fun MeasureScope.measure(
measurable: Measurable,
constraints: Constraints
): MeasureResult {
return with(element as LayoutModifier) {
measure(measurable, constraints)
}
}
override fun IntrinsicMeasureScope.minIntrinsicWidth(
measurable: IntrinsicMeasurable,
height: Int
): Int = with(element as LayoutModifier) {
minIntrinsicWidth(measurable, height)
}
override fun IntrinsicMeasureScope.minIntrinsicHeight(
measurable: IntrinsicMeasurable,
width: Int
): Int = with(element as LayoutModifier) {
minIntrinsicHeight(measurable, width)
}
override fun IntrinsicMeasureScope.maxIntrinsicWidth(
measurable: IntrinsicMeasurable,
height: Int
): Int = with(element as LayoutModifier) {
maxIntrinsicWidth(measurable, height)
}
override fun IntrinsicMeasureScope.maxIntrinsicHeight(
measurable: IntrinsicMeasurable,
width: Int
): Int = with(element as LayoutModifier) {
maxIntrinsicHeight(measurable, width)
}
override fun ContentDrawScope.draw() {
val element = element
with(element as DrawModifier) {
if (invalidateCache && element is DrawCacheModifier) {
updateDrawCache()
}
draw()
}
}
override val semanticsConfiguration: SemanticsConfiguration
get() = (element as SemanticsModifier).semanticsConfiguration
override fun onPointerEvent(
pointerEvent: PointerEvent,
pass: PointerEventPass,
bounds: IntSize
) {
with(element as PointerInputModifier) {
pointerInputFilter.onPointerEvent(pointerEvent, pass, bounds)
}
}
override fun onCancelPointerInput() {
with(element as PointerInputModifier) {
pointerInputFilter.onCancel()
}
}
@OptIn(ExperimentalComposeUiApi::class)
override fun sharePointerInputWithSiblings(): Boolean {
return with(element as PointerInputModifier) {
pointerInputFilter.shareWithSiblings
}
}
override fun interceptOutOfBoundsChildEvents(): Boolean {
return with(element as PointerInputModifier) {
pointerInputFilter.interceptOutOfBoundsChildEvents
}
}
override fun Density.modifyParentData(parentData: Any?): Any? {
return with(element as ParentDataModifier) {
modifyParentData(parentData)
}
}
override fun onGloballyPositioned(coordinates: LayoutCoordinates) {
(element as OnGloballyPositionedModifier).onGloballyPositioned(coordinates)
}
@OptIn(ExperimentalComposeUiApi::class)
override fun onLookaheadPlaced(coordinates: LookaheadLayoutCoordinates) {
val element = element
if (element is LookaheadOnPlacedModifier) {
element.onPlaced(coordinates)
}
}
override fun onRemeasured(size: IntSize) {
val element = element
if (element is OnRemeasuredModifier) {
element.onRemeasured(size)
}
}
private var lastOnPlacedCoordinates: LayoutCoordinates? = null
override fun onPlaced(coordinates: LayoutCoordinates) {
lastOnPlacedCoordinates = coordinates
val element = element
if (element is OnPlacedModifier) {
element.onPlaced(coordinates)
}
}
override fun toString(): String = element.toString()
}
private val DetachedModifierLocalReadScope = object : ModifierLocalReadScope {
override val <T> ModifierLocal<T>.current: T
get() = defaultFactory()
}
private val onDrawCacheReadsChanged = { it: BackwardsCompatNode ->
it.onDrawCacheReadsChanged()
}
private val updateModifierLocalConsumer = { it: BackwardsCompatNode ->
it.updateModifierLocalConsumer()
}
private val updateFocusOrderModifierLocalConsumer = { it: BackwardsCompatNode ->
it.updateFocusOrderModifierLocalConsumer()
}
| apache-2.0 | a2f9f7a71d65e4ffce84ac0637297de5 | 36.179104 | 99 | 0.647761 | 5.358636 | false | false | false | false |
androidx/androidx | paging/samples/src/main/java/androidx/paging/samples/PagingSourceSample.kt | 3 | 7413 | /*
* 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.
*/
@file:Suppress("unused")
package androidx.paging.samples
import androidx.annotation.Sampled
import androidx.paging.PagingSource
import androidx.paging.PagingSource.LoadResult
import androidx.paging.PagingState
import retrofit2.HttpException
import java.io.IOException
internal class MyBackendService {
data class RemoteResult(
val items: List<Item>,
val prev: String?,
val next: String?
)
@Suppress("RedundantSuspendModifier", "UNUSED_PARAMETER")
suspend fun searchItems(pageKey: String?): RemoteResult {
throw NotImplementedError()
}
@Suppress("RedundantSuspendModifier", "UNUSED_PARAMETER")
suspend fun searchItems(pageNumber: Int): RemoteResult {
throw NotImplementedError()
}
@Suppress("RedundantSuspendModifier", "UNUSED_PARAMETER")
suspend fun itemsAfter(itemKey: String?): RemoteResult {
throw NotImplementedError()
}
}
@Sampled
fun itemKeyedPagingSourceSample() {
/**
* Sample item-keyed [PagingSource], which uses String tokens to load pages.
*
* Loads Items from network requests via Retrofit to a backend service.
*/
class MyPagingSource(
val myBackend: MyBackendService
) : PagingSource<String, Item>() {
override suspend fun load(params: LoadParams<String>): LoadResult<String, Item> {
// Retrofit calls that return the body type throw either IOException for network
// failures, or HttpException for any non-2xx HTTP status codes. This code reports all
// errors to the UI, but you can inspect/wrap the exceptions to provide more context.
return try {
// Suspending network load via Retrofit. This doesn't need to be wrapped in a
// withContext(Dispatcher.IO) { ... } block since Retrofit's Coroutine
// CallAdapter dispatches on a worker thread.
val response = myBackend.searchItems(params.key)
LoadResult.Page(
data = response.items,
prevKey = response.prev,
nextKey = response.next
)
} catch (e: IOException) {
LoadResult.Error(e)
} catch (e: HttpException) {
LoadResult.Error(e)
}
}
override fun getRefreshKey(state: PagingState<String, Item>): String? {
return state.anchorPosition?.let { state.closestItemToPosition(it)?.id }
}
}
}
@Sampled
fun pageKeyedPagingSourceSample() {
/**
* Sample page-keyed PagingSource, which uses Int page number to load pages.
*
* Loads Items from network requests via Retrofit to a backend service.
*
* Note that the key type is Int, since we're using page number to load a page.
*/
class MyPagingSource(
val myBackend: MyBackendService
) : PagingSource<Int, Item>() {
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Item> {
// Retrofit calls that return the body type throw either IOException for network
// failures, or HttpException for any non-2xx HTTP status codes. This code reports all
// errors to the UI, but you can inspect/wrap the exceptions to provide more context.
return try {
// Key may be null during a refresh, if no explicit key is passed into Pager
// construction. Use 0 as default, because our API is indexed started at index 0
val pageNumber = params.key ?: 0
// Suspending network load via Retrofit. This doesn't need to be wrapped in a
// withContext(Dispatcher.IO) { ... } block since Retrofit's Coroutine
// CallAdapter dispatches on a worker thread.
val response = myBackend.searchItems(pageNumber)
// Since 0 is the lowest page number, return null to signify no more pages should
// be loaded before it.
val prevKey = if (pageNumber > 0) pageNumber - 1 else null
// This API defines that it's out of data when a page returns empty. When out of
// data, we return `null` to signify no more pages should be loaded
val nextKey = if (response.items.isNotEmpty()) pageNumber + 1 else null
LoadResult.Page(
data = response.items,
prevKey = prevKey,
nextKey = nextKey
)
} catch (e: IOException) {
LoadResult.Error(e)
} catch (e: HttpException) {
LoadResult.Error(e)
}
}
override fun getRefreshKey(state: PagingState<Int, Item>): Int? {
return state.anchorPosition?.let {
state.closestPageToPosition(it)?.prevKey?.plus(1)
?: state.closestPageToPosition(it)?.nextKey?.minus(1)
}
}
}
}
@Sampled
fun pageKeyedPage() {
// One common method of pagination is to use next (and optionally previous) tokens.
// The below code shows you how to
data class NetworkResponseObject(
val items: List<Item>,
val next: String,
val approximateItemsRemaining: Int
)
// The following shows how you use convert such a response loaded in PagingSource.load() to
// a Page, which can be returned from that method
fun NetworkResponseObject.toPage() = LoadResult.Page(
data = items,
prevKey = null, // this implementation can only append, can't load a prepend
nextKey = next, // next token will be the params.key of a subsequent append load
itemsAfter = approximateItemsRemaining
)
}
@Sampled
fun pageIndexedPage() {
// If you load by page number, the response may not define how to load the next page.
data class NetworkResponseObject(
val items: List<Item>
)
// The following shows how you use the current page number (e.g., the current key in
// PagingSource.load() to convert a response into a Page, which can be returned from that method
fun NetworkResponseObject.toPage(pageNumber: Int): LoadResult.Page<Int, Item> {
return LoadResult.Page(
data = items,
// Since 0 is the lowest page number, return null to signify no more pages
// should be loaded before it.
prevKey = if (pageNumber > 0) pageNumber - 1 else null,
// This API defines that it's out of data when a page returns empty. When out of
// data, we return `null` to signify no more pages should be loaded
// If the response instead
nextKey = if (items.isNotEmpty()) pageNumber + 1 else null
)
}
} | apache-2.0 | 9eb084a0e5d9f85664d99d3fedd784ca | 39.293478 | 100 | 0.632268 | 4.841933 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/ir/buildsystem/gradle/GradleIR.kt | 4 | 4881 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.gradle
import org.jetbrains.annotations.NonNls
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.BuildSystemIR
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.FreeIR
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.RepositoryIR
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.render
import org.jetbrains.kotlin.tools.projectWizard.plugins.printer.BuildFilePrinter
import org.jetbrains.kotlin.tools.projectWizard.plugins.printer.GradlePrinter
interface GradleIR : BuildSystemIR {
fun GradlePrinter.renderGradle()
override fun BuildFilePrinter.render() {
if (this is GradlePrinter) renderGradle()
}
}
data class RawGradleIR(
val renderer: GradlePrinter.() -> Unit
) : GradleIR, FreeIR {
override fun GradlePrinter.renderGradle() = renderer()
}
class CreateGradleValueIR(@NonNls val name: String, val body: BuildSystemIR) : GradleIR {
override fun GradlePrinter.renderGradle() {
when (dsl) {
GradlePrinter.GradleDsl.KOTLIN -> {
+"val "
+name
+" = "
body.render(this)
}
GradlePrinter.GradleDsl.GROOVY -> {
+"def "
+name
+" = "
body.render(this)
}
}
}
}
data class GradleCallIr(
@NonNls val name: String,
val parameters: List<BuildSystemIR> = emptyList(),
val isConstructorCall: Boolean = false,
) : GradleIR {
constructor(
name: String,
vararg parameters: BuildSystemIR,
isConstructorCall: Boolean = false
) : this(name, parameters.toList(), isConstructorCall)
override fun GradlePrinter.renderGradle() {
if (isConstructorCall && dsl == GradlePrinter.GradleDsl.GROOVY) +"new "
call(name, forceBrackets = true) {
parameters.list { it.render(this) }
}
}
}
data class GradleNewInstanceCall(
@NonNls val name: String,
val parameters: List<BuildSystemIR> = emptyList()
) : GradleIR {
override fun GradlePrinter.renderGradle() {
if (dsl == GradlePrinter.GradleDsl.GROOVY) {
+"new "
}
call(name, forceBrackets = true) {
parameters.list { it.render(this) }
}
}
}
data class GradleSectionIR(
@NonNls val name: String,
val irs: List<BuildSystemIR>
) : GradleIR, FreeIR {
override fun GradlePrinter.renderGradle() {
sectionCall(name) {
if (irs.isNotEmpty()) {
irs.listNl()
}
}
}
}
data class GradleAssignmentIR(
@NonNls val target: String,
val assignee: BuildSystemIR
) : GradleIR, FreeIR {
override fun GradlePrinter.renderGradle() {
+"$target = "
assignee.render(this)
}
}
data class GradleStringConstIR(
@NonNls val text: String
) : GradleIR {
override fun GradlePrinter.renderGradle() {
+text.quotified
}
}
data class CompilationAccessIr(
@NonNls val targetName: String,
@NonNls val compilationName: String,
@NonNls val property: String?
) : GradleIR {
override fun GradlePrinter.renderGradle() {
when (dsl) {
GradlePrinter.GradleDsl.KOTLIN -> +"kotlin.$targetName().compilations[\"$compilationName\"]"
GradlePrinter.GradleDsl.GROOVY -> +"kotlin.$targetName().compilations.$compilationName"
}
property?.let { +".$it" }
}
}
data class GradleDynamicPropertyAccessIR(val qualifier: BuildSystemIR, @NonNls val propertyName: String) : GradleIR {
override fun GradlePrinter.renderGradle() {
qualifier.render(this)
when (dsl) {
GradlePrinter.GradleDsl.KOTLIN -> +"[${propertyName.quotified}]"
GradlePrinter.GradleDsl.GROOVY -> +".$propertyName"
}
}
}
data class GradlePropertyAccessIR(val propertyName: String) : GradleIR {
override fun GradlePrinter.renderGradle() {
+propertyName
}
}
data class GradleImportIR(val import: String) : GradleIR {
override fun GradlePrinter.renderGradle() {
+"import "
+import
}
}
data class GradleBinaryExpressionIR(val left: BuildSystemIR, val op: String, val right: BuildSystemIR) : GradleIR {
override fun GradlePrinter.renderGradle() {
left.render(this)
+" $op "
right.render(this)
}
}
interface BuildScriptIR : BuildSystemIR
data class BuildScriptDependencyIR(val dependencyIR: BuildSystemIR) : BuildScriptIR, BuildSystemIR by dependencyIR
data class BuildScriptRepositoryIR(val repositoryIR: RepositoryIR) : BuildScriptIR, BuildSystemIR by repositoryIR | apache-2.0 | ea7457a07b85dbc755d6f06567ce56e9 | 29.5125 | 158 | 0.659701 | 4.417195 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/highlighting/src/org/jetbrains/kotlin/idea/highlighting/highlighters/VariableReferenceHighlighter.kt | 4 | 4520 | // 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.highlighting.highlighters
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.symbols.*
import org.jetbrains.kotlin.analysis.api.symbols.markers.KtSymbolKind
import org.jetbrains.kotlin.idea.base.highlighting.KotlinBaseHighlightingBundle
import org.jetbrains.kotlin.idea.base.highlighting.isNameHighlightingEnabled
import org.jetbrains.kotlin.idea.highlighter.KotlinHighlightingColors
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.idea.highlighter.KotlinHighlightingColors as Colors
internal class VariableReferenceHighlighter(
holder: AnnotationHolder,
project: Project
) : AfterResolveHighlighter(holder, project) {
context(KtAnalysisSession)
override fun highlight(element: KtElement) {
when (element) {
is KtSimpleNameExpression -> highlightSimpleNameExpression(element)
else -> {}
}
}
context(KtAnalysisSession)
private fun highlightSimpleNameExpression(expression: KtSimpleNameExpression) {
if (!expression.project.isNameHighlightingEnabled) return
if (expression.isAssignmentReference()) return
if (expression.isByNameArgumentReference()) return
if (expression.parent is KtInstanceExpressionWithLabel) return
when (val symbol = expression.mainReference.resolveToSymbol()) {
is KtBackingFieldSymbol -> highlightBackingField(symbol, expression)
is KtKotlinPropertySymbol -> highlightProperty(symbol, expression)
is KtLocalVariableSymbol -> {
if (!symbol.isVal) {
highlightName(expression, Colors.MUTABLE_VARIABLE)
}
highlightName(expression, Colors.LOCAL_VARIABLE)
}
is KtSyntheticJavaPropertySymbol -> highlightName(expression, Colors.SYNTHETIC_EXTENSION_PROPERTY)
is KtValueParameterSymbol -> highlightValueParameter(symbol, expression)
is KtEnumEntrySymbol -> highlightName(expression, Colors.ENUM_ENTRY)
}
}
context(KtAnalysisSession)
private fun highlightValueParameter(symbol: KtValueParameterSymbol, expression: KtSimpleNameExpression) {
when {
symbol.isImplicitLambdaParameter -> {
createInfoAnnotation(
expression,
KotlinBaseHighlightingBundle.message("automatically.declared.based.on.the.expected.type"),
Colors.FUNCTION_LITERAL_DEFAULT_PARAMETER
)
}
else -> highlightName(expression, Colors.PARAMETER)
}
}
context(KtAnalysisSession)
private fun highlightProperty(
symbol: KtKotlinPropertySymbol,
expression: KtSimpleNameExpression
) {
if (!symbol.isVal) {
highlightName(expression, Colors.MUTABLE_VARIABLE)
}
val hasExplicitGetterOrSetter = symbol.getter?.hasBody == true || symbol.setter?.hasBody == true
val color = when {
symbol.isExtension -> Colors.EXTENSION_PROPERTY
symbol.symbolKind == KtSymbolKind.TOP_LEVEL -> when {
hasExplicitGetterOrSetter -> Colors.PACKAGE_PROPERTY_CUSTOM_PROPERTY_DECLARATION
else -> Colors.PACKAGE_PROPERTY
}
else -> when {
hasExplicitGetterOrSetter -> Colors.INSTANCE_PROPERTY_CUSTOM_PROPERTY_DECLARATION
else -> Colors.INSTANCE_PROPERTY
}
}
highlightName(expression, color)
}
context(KtAnalysisSession)
private fun highlightBackingField(symbol: KtBackingFieldSymbol, expression: KtSimpleNameExpression) {
if (!symbol.owningProperty.isVal) {
highlightName(expression, Colors.MUTABLE_VARIABLE)
}
highlightName(expression, Colors.BACKING_FIELD_VARIABLE)
}
private fun KtSimpleNameExpression.isByNameArgumentReference() =
parent is KtValueArgumentName
}
private fun KtSimpleNameExpression.isAssignmentReference(): Boolean {
if (this !is KtOperationReferenceExpression) return false
return operationSignTokenType == KtTokens.EQ
}
| apache-2.0 | 83d2cbc7eb7a97a4496efef207d898a2 | 40.46789 | 120 | 0.700885 | 5.387366 | false | false | false | false |
ReplayMod/ReplayMod | src/main/kotlin/com/replaymod/core/gui/utils/boxSelect.kt | 1 | 5445 | package com.replaymod.core.gui.utils
import com.replaymod.core.gui.utils.Box.Companion.toBox
import gg.essential.elementa.UIComponent
import gg.essential.elementa.components.UIBlock
import gg.essential.elementa.components.Window
import gg.essential.elementa.effects.Effect
import gg.essential.elementa.effects.ScissorEffect
import gg.essential.elementa.utils.withAlpha
import gg.essential.universal.UMatrixStack
import gg.essential.universal.UResolution
import java.awt.Color
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
interface BoxSelectable
/**
* Enables box selections to be draw anywhere within this component (usually the window).
* This is safe to call multiple times on the same component (e.g. for the window by independent code).
*/
fun <T : UIComponent> T.onBoxSelection(onChange: (selected: List<BoxSelectable>, final: Boolean) -> Unit) = apply {
var currentBoxSelect: BoxSelect? = null
onLeftClick { event ->
event.stopPropagation()
currentBoxSelect = BoxSelect(event.absoluteX to event.absoluteY)
}
onMouseDrag { mouseX, mouseY, _ ->
val boxSelect = currentBoxSelect ?: return@onMouseDrag
boxSelect.second = (mouseX + getLeft()) to (mouseY + getTop())
val box = boxSelect.box
if (!boxSelect.passedThreshold) {
if (box.width < 3 && box.height < 3) {
return@onMouseDrag
} else {
boxSelect.passedThreshold = true
if (effects.find { it is BoxSelectionEffect } == null) {
enableEffect(BoxSelectionEffect(boxSelect))
}
}
}
onChange(findAllInBox(box), false)
}
onMouseRelease {
val boxSelect = currentBoxSelect?.also { currentBoxSelect = null } ?: return@onMouseRelease
if (!boxSelect.passedThreshold) {
return@onMouseRelease
}
removeEffect<BoxSelectionEffect>()
onChange(findAllInBox(boxSelect.box), true)
}
}
private data class BoxSelect(
var first: Pair<Float, Float>,
var second: Pair<Float, Float> = first,
var passedThreshold: Boolean = false,
) {
val box: Box
get() {
val (x1, y1) = first
val (x2, y2) = second
return Box.fromBounds(min(x1, x2), min(y1, y2), max(x1, x2), max(y1, y2))
}
}
/** Box around some center point (x, y). Note that (x, y) is **not** the top left point here, it is the center. */
private data class Box(val x: Float, val y: Float, val width: Float, val height: Float) {
val left get() = x - width / 2
val top get() = y - height / 2
val right get() = x + width / 2
val bottom get() = y + height / 2
private fun intersectsX(other: Box) = abs(this.x - other.x) * 2 < this.width + other.width
private fun intersectsY(other: Box) = abs(this.y - other.y) * 2 < this.height + other.height
fun intersects(other: Box) = intersectsX(other) && intersectsY(other)
companion object {
fun fromBounds(left: Float, top: Float, right: Float, bottom: Float): Box {
val width = right - left
val height = bottom - top
return Box(left + width / 2, top + height / 2, width, height)
}
fun UIComponent.toBox() = fromBounds(getLeft(), getTop(), getRight(), getBottom())
}
}
private val dummyMatrixStack = UMatrixStack()
private fun UIComponent.findAllInBox(box: Box): List<BoxSelectable> {
val parentWindow = Window.of(this)
val result = mutableListOf<BoxSelectable>()
fun UIComponent.collect() {
if (!box.intersects(this.toBox())) {
return
}
if (this is BoxSelectable) {
result.add(this)
}
// Window.isAreaVisible uses the scissor effect to determine whether an area is visible
val scissors = effects.filterIsInstance<ScissorEffect>()
scissors.forEach { it.beforeDraw(dummyMatrixStack) }
for (child in children) {
if (alwaysDrawChildren() || parentWindow.isAreaVisible(
child.getLeft().toDouble(),
child.getTop().toDouble(),
child.getRight().toDouble(),
child.getBottom().toDouble()
)
) {
child.collect()
}
}
scissors.forEach { it.afterDraw(dummyMatrixStack) }
}
collect()
return result
}
/**
* Draws a highlight and border for the given box selection on top of a component.
*/
private class BoxSelectionEffect(val boxSelect: BoxSelect) : Effect() {
override fun afterDraw(matrixStack: UMatrixStack) {
val box = boxSelect.box
val l = box.left.toDouble()
val t = box.top.toDouble()
val r = box.right.toDouble()
val b = box.bottom.toDouble()
val w = box.width.toDouble()
val h = box.height.toDouble()
val d = 1.0 / UResolution.scaleFactor // a single (real) pixel
// Background
UIBlock.drawBlock(matrixStack, Color.YELLOW.withAlpha(0.3f), l, t, r, b)
// Outline
UIBlock.drawBlockSized(matrixStack, Color.YELLOW, l, t, d, h) // left
UIBlock.drawBlockSized(matrixStack, Color.YELLOW, l, t, w, d) // top
UIBlock.drawBlockSized(matrixStack, Color.YELLOW, r, t, d, h) // right
UIBlock.drawBlockSized(matrixStack, Color.YELLOW, l, b, w, d) // bottom
}
}
| gpl-3.0 | 53f92230b77a27c51053bb8071f83e0e | 34.129032 | 115 | 0.624426 | 3.951379 | false | false | false | false |
siosio/intellij-community | plugins/gradle/java/src/service/project/wizard/GradleStructureWizardStep.kt | 1 | 4379 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.gradle.service.project.wizard
import com.intellij.ide.highlighter.ModuleFileType
import com.intellij.ide.util.newProjectWizard.AbstractProjectWizard.getNewProjectJdk
import com.intellij.ide.util.projectWizard.WizardContext
import com.intellij.openapi.components.StorageScheme
import com.intellij.openapi.externalSystem.model.project.ProjectData
import com.intellij.openapi.externalSystem.model.project.ProjectId
import com.intellij.openapi.externalSystem.service.project.ProjectDataManager
import com.intellij.openapi.externalSystem.service.project.wizard.MavenizedStructureWizardStep
import com.intellij.openapi.externalSystem.util.ui.DataView
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.ui.layout.*
import icons.GradleIcons
import org.jetbrains.plugins.gradle.util.GradleBundle
import org.jetbrains.plugins.gradle.util.GradleConstants
import javax.swing.Icon
class GradleStructureWizardStep(
private val builder: AbstractGradleModuleBuilder,
context: WizardContext
) : MavenizedStructureWizardStep<ProjectData>(context) {
override fun getHelpId() = "Gradle_Archetype_Dialog"
override fun getBuilderId(): String? = builder.builderId
override fun createView(data: ProjectData) = GradleDataView(data)
override fun findAllParents(): List<ProjectData> {
val project = context.project ?: return emptyList()
return ProjectDataManager.getInstance()
.getExternalProjectsData(project, GradleConstants.SYSTEM_ID)
.mapNotNull { it.externalProjectStructure }
.map { it.data }
}
override fun ValidationInfoBuilder.validateGroupId(): ValidationInfo? = null
override fun ValidationInfoBuilder.validateVersion(): ValidationInfo? = null
override fun ValidationInfoBuilder.validateName(): ValidationInfo? {
return validateNameAndArtifactId() ?: superValidateName()
}
override fun ValidationInfoBuilder.validateArtifactId(): ValidationInfo? {
return validateNameAndArtifactId() ?: superValidateArtifactId()
}
private fun ValidationInfoBuilder.validateNameAndArtifactId(): ValidationInfo? {
if (artifactId == entityName) return null
val presentationName = context.presentationName.capitalize()
return error(GradleBundle.message("gradle.structure.wizard.name.and.artifact.id.is.different.error", presentationName))
}
override fun updateProjectData() {
context.projectBuilder = builder
builder.setParentProject(parentData)
builder.projectId = ProjectId(groupId, artifactId, version)
builder.isInheritGroupId = parentData?.group == groupId
builder.isInheritVersion = parentData?.version == version
builder.name = entityName
builder.contentEntryPath = location
builder.moduleFilePath = getModuleFilePath()
builder.isCreatingNewProject = context.isCreatingNewProject
builder.moduleJdk = builder.moduleJdk ?: getNewProjectJdk(context)
}
private fun getModuleFilePath(): String {
val moduleFileDirectory = getModuleFileDirectory()
val moduleFilePath = FileUtil.join(moduleFileDirectory, artifactId + ModuleFileType.DOT_DEFAULT_EXTENSION)
return FileUtil.toCanonicalPath(moduleFilePath)
}
private fun getModuleFileDirectory(): String {
val projectPath = context.project?.basePath ?: location
return when (context.projectStorageFormat) {
StorageScheme.DEFAULT -> location
StorageScheme.DIRECTORY_BASED -> FileUtil.join(projectPath, Project.DIRECTORY_STORE_FOLDER, "modules")
else -> projectPath
}
}
override fun _init() {
builder.name?.let { entityName = it }
builder.projectId?.let { projectId ->
projectId.groupId?.let { groupId = it }
projectId.artifactId?.let { artifactId = it }
projectId.version?.let { version = it }
}
}
class GradleDataView(override val data: ProjectData) : DataView<ProjectData>() {
override val location: String = data.linkedExternalProjectPath
override val icon: Icon = GradleIcons.GradleFile
override val presentationName: String = data.externalName
override val groupId: String = data.group ?: ""
override val version: String = data.version ?: ""
}
} | apache-2.0 | 321f20e6a6cb5f865f35ff289d56b00f | 41.115385 | 140 | 0.778032 | 4.887277 | false | false | false | false |
jwren/intellij-community | platform/platform-api/src/com/intellij/util/ui/LafIconLookup.kt | 1 | 2392 | // 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.util.ui
import com.intellij.icons.AllIcons
import com.intellij.openapi.util.IconLoader
import javax.swing.Icon
/**
* @author Konstantin Bulenkov
*/
private const val ICONS_DIR_PREFIX = "com/intellij/ide/ui/laf/icons/"
private val defaultDirProver = DirProvider()
open class DirProvider {
open val defaultExtension: String
get() = "png"
open fun dir(): String = ICONS_DIR_PREFIX + if (StartupUiUtil.isUnderDarcula()) "darcula/" else "intellij/"
}
object LafIconLookup {
@JvmStatic
@JvmOverloads
fun getIcon(name: String,
selected: Boolean = false,
focused: Boolean = false,
enabled: Boolean = true,
editable: Boolean = false,
pressed: Boolean = false): Icon {
return findIcon(name,
selected = selected,
focused = focused,
enabled = enabled,
editable = editable,
pressed = pressed,
dirProvider = DirProvider())
?: AllIcons.Actions.Stub
}
fun findIcon(name: String,
selected: Boolean = false,
focused: Boolean = false,
enabled: Boolean = true,
editable: Boolean = false,
pressed: Boolean = false,
dirProvider: DirProvider = defaultDirProver): Icon? {
var key = name
if (editable) {
key += "Editable"
}
if (selected) {
key += "Selected"
}
when {
pressed -> key += "Pressed"
focused -> key += "Focused"
!enabled -> key += "Disabled"
}
// for Mac blue theme and other LAFs use default directory icons
val providerClass = dirProvider.javaClass
val classLoader = providerClass.classLoader
val dir = dirProvider.dir()
val path = if (dir.startsWith(ICONS_DIR_PREFIX)) {
// optimization - all icons are SVG
"$dir$key.svg"
}
else {
"$dir$key.${dirProvider.defaultExtension}"
}
return IconLoader.findIcon(path, classLoader)
}
@JvmStatic
fun getDisabledIcon(name: String): Icon = getIcon(name, enabled = false)
@JvmStatic
fun getSelectedIcon(name: String): Icon = findIcon(name, selected = true) ?: getIcon(name)
} | apache-2.0 | 7548e6232e24b78ebe7fdf00373a41c5 | 27.831325 | 120 | 0.603679 | 4.364964 | false | false | false | false |
JetBrains/kotlin-native | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/llvm/coverage/LLVMCoverageWriter.kt | 1 | 3727 | /*
* Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package org.jetbrains.kotlin.backend.konan.llvm.coverage
import kotlinx.cinterop.*
import llvm.*
import org.jetbrains.kotlin.backend.konan.Context
import org.jetbrains.kotlin.backend.konan.llvm.name
import org.jetbrains.kotlin.ir.declarations.IrFile
import org.jetbrains.kotlin.ir.declarations.path
import org.jetbrains.kotlin.konan.file.File
private fun RegionKind.toLLVMCoverageRegionKind(): LLVMCoverageRegionKind = when (this) {
RegionKind.Code -> LLVMCoverageRegionKind.CODE
RegionKind.Gap -> LLVMCoverageRegionKind.GAP
is RegionKind.Expansion -> LLVMCoverageRegionKind.EXPANSION
}
private fun LLVMCoverageRegion.populateFrom(region: Region, regionId: Int, filesIndex: Map<IrFile, Int>) = apply {
fileId = filesIndex.getValue(region.file)
lineStart = region.startLine
columnStart = region.startColumn
lineEnd = region.endLine
columnEnd = region.endColumn
counterId = regionId
kind = region.kind.toLLVMCoverageRegionKind()
expandedFileId = if (region.kind is RegionKind.Expansion) filesIndex.getValue(region.kind.expandedFile) else 0
}
/**
* Writes all of the coverage information to the [org.jetbrains.kotlin.backend.konan.Context.llvmModule].
* See http://llvm.org/docs/CoverageMappingFormat.html for the format description.
*/
internal class LLVMCoverageWriter(
private val context: Context,
private val filesRegionsInfo: List<FileRegionInfo>
) {
fun write() {
if (filesRegionsInfo.isEmpty()) return
val module = context.llvmModule
?: error("LLVM module should be initialized.")
val filesIndex = filesRegionsInfo.mapIndexed { index, fileRegionInfo -> fileRegionInfo.file to index }.toMap()
val coverageGlobal = memScoped {
val (functionMappingRecords, functionCoverages) = filesRegionsInfo.flatMap { it.functions }.map { functionRegions ->
val regions = (functionRegions.regions.values).map { region ->
alloc<LLVMCoverageRegion>().populateFrom(region, functionRegions.regionEnumeration.getValue(region), filesIndex).ptr
}
val fileIds = functionRegions.regions.map { filesIndex.getValue(it.value.file) }.toSet().toIntArray()
val functionCoverage = LLVMWriteCoverageRegionMapping(
fileIds.toCValues(), fileIds.size.signExtend(),
regions.toCValues(), regions.size.signExtend())
val functionName = context.llvmDeclarations.forFunction(functionRegions.function).llvmFunction.name
val functionMappingRecord = LLVMAddFunctionMappingRecord(LLVMGetModuleContext(context.llvmModule),
functionName, functionRegions.structuralHash, functionCoverage)!!
Pair(functionMappingRecord, functionCoverage)
}.unzip()
val (filenames, fileIds) = filesIndex.entries.toList().map { File(it.key.path).absolutePath to it.value }.unzip()
val retval = LLVMCoverageEmit(module, functionMappingRecords.toCValues(), functionMappingRecords.size.signExtend(),
filenames.toCStringArray(this), fileIds.toIntArray().toCValues(), fileIds.size.signExtend(),
functionCoverages.map { it }.toCValues(), functionCoverages.size.signExtend())!!
// TODO: Is there a better way to cleanup fields of T* type in `memScoped`?
functionCoverages.forEach { LLVMFunctionCoverageDispose(it) }
retval
}
context.llvm.usedGlobals.add(coverageGlobal)
}
}
| apache-2.0 | 8c28c6410e0dfbf20582fcf644700dd1 | 48.693333 | 136 | 0.70432 | 4.550672 | false | false | false | false |
mglukhikh/intellij-community | platform/configuration-store-impl/src/ComponentStoreImpl.kt | 1 | 23658 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.configurationStore
import com.intellij.configurationStore.StateStorageManager.ExternalizationSession
import com.intellij.notification.NotificationsManager
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ex.DecodeDefaultsUtil
import com.intellij.openapi.application.runUndoTransparentWriteAction
import com.intellij.openapi.components.*
import com.intellij.openapi.components.StateStorage.SaveSession
import com.intellij.openapi.components.StateStorageChooserEx.Resolution
import com.intellij.openapi.components.impl.ComponentManagerImpl
import com.intellij.openapi.components.impl.stores.IComponentStore
import com.intellij.openapi.components.impl.stores.StoreUtil
import com.intellij.openapi.components.impl.stores.UnknownMacroNotification
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.*
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.newvfs.impl.VfsRootAccess
import com.intellij.project.isDirectoryBased
import com.intellij.ui.AppUIUtil
import com.intellij.util.ArrayUtilRt
import com.intellij.util.SmartList
import com.intellij.util.containers.SmartHashSet
import com.intellij.util.containers.isNullOrEmpty
import com.intellij.util.lang.CompoundRuntimeException
import com.intellij.util.messages.MessageBus
import com.intellij.util.xmlb.JDOMXIncluder
import com.intellij.util.xmlb.XmlSerializerUtil
import gnu.trove.THashMap
import io.netty.util.internal.SystemPropertyUtil
import org.jdom.Element
import org.jetbrains.annotations.TestOnly
import java.io.IOException
import java.nio.file.Paths
import java.util.*
import com.intellij.openapi.util.Pair as JBPair
internal val LOG = Logger.getInstance(ComponentStoreImpl::class.java)
internal val deprecatedComparator = Comparator<Storage> { o1, o2 ->
val w1 = if (o1.deprecated) 1 else 0
val w2 = if (o2.deprecated) 1 else 0
w1 - w2
}
private class PersistenceStateAdapter(val component: Any) : PersistentStateComponent<Any> {
override fun getState() = component
override fun loadState(state: Any) {
XmlSerializerUtil.copyBean(state, component)
}
}
abstract class ComponentStoreImpl : IComponentStore {
private val components = Collections.synchronizedMap(THashMap<String, ComponentInfo>())
private val settingsSavingComponents = com.intellij.util.containers.ContainerUtil.createLockFreeCopyOnWriteList<SettingsSavingComponent>()
internal open val project: Project?
get() = null
open val loadPolicy: StateLoadPolicy
get() = StateLoadPolicy.LOAD
abstract val storageManager: StateStorageManager
override final fun getStateStorageManager() = storageManager
override final fun initComponent(component: Any, isService: Boolean) {
if (component is SettingsSavingComponent) {
settingsSavingComponents.add(component)
}
var componentName = ""
try {
@Suppress("DEPRECATION")
if (component is PersistentStateComponent<*>) {
componentName = initPersistenceStateComponent(component, StoreUtil.getStateSpec(component), isService)
}
else if (component is JDOMExternalizable) {
componentName = ComponentManagerImpl.getComponentName(component)
@Suppress("DEPRECATION")
initJdomExternalizable(component, componentName)
}
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: Exception) {
LOG.error("Cannot init $componentName component state", e)
return
}
}
override fun initPersistencePlainComponent(component: Any, key: String) {
initPersistenceStateComponent(PersistenceStateAdapter(component), StateAnnotation(key, FileStorageAnnotation(StoragePathMacros.WORKSPACE_FILE, false)), false)
}
private fun initPersistenceStateComponent(component: PersistentStateComponent<*>, stateSpec: State, isService: Boolean): String {
val componentName = stateSpec.name
val info = doAddComponent(componentName, component, stateSpec)
if (initComponent(info, null, false) && isService) {
// if not service, so, component manager will check it later for all components
project?.let {
val app = ApplicationManager.getApplication()
if (!app.isHeadlessEnvironment && !app.isUnitTestMode && it.isInitialized) {
notifyUnknownMacros(this, it, componentName)
}
}
}
return componentName
}
override fun save(readonlyFiles: MutableList<JBPair<StateStorage.SaveSession, VirtualFile>>) {
var errors: MutableList<Throwable>? = null
// component state uses scheme manager in an ipr project, so, we must save it before
val isIprProject = project?.let { !it.isDirectoryBased } ?: false
if (isIprProject) {
settingsSavingComponents.firstOrNull { it is SchemeManagerFactoryBase }?.let {
try {
it.save()
}
catch (e: Throwable) {
if (errors == null) {
errors = SmartList<Throwable>()
}
errors!!.add(e)
}
}
}
val isUseModificationCount = Registry.`is`("store.save.use.modificationCount", true)
val externalizationSession = if (components.isEmpty()) null else storageManager.startExternalization()
if (externalizationSession != null) {
val names = ArrayUtilRt.toStringArray(components.keys)
Arrays.sort(names)
val timeLogPrefix = "Saving"
val timeLog = if (LOG.isDebugEnabled) StringBuilder(timeLogPrefix) else null
for (name in names) {
val start = if (timeLog == null) 0 else System.currentTimeMillis()
try {
val info = components.get(name)!!
var currentModificationCount = -1L
if (info.isModificationTrackingSupported) {
currentModificationCount = info.currentModificationCount
if (currentModificationCount == info.lastModificationCount) {
LOG.debug { "${if (isUseModificationCount) "Skip " else ""}$name: modificationCount ${currentModificationCount} equals to last saved" }
if (isUseModificationCount) {
continue
}
}
}
commitComponent(externalizationSession, info, name)
info.updateModificationCount(currentModificationCount)
}
catch (e: Throwable) {
if (errors == null) {
errors = SmartList<Throwable>()
}
errors!!.add(Exception("Cannot get $name component state", e))
}
timeLog?.let {
val duration = System.currentTimeMillis() - start
if (duration > 10) {
it.append("\n").append(name).append(" took ").append(duration).append(" ms: ").append((duration / 60000)).append(" min ").append(((duration % 60000) / 1000)).append("sec")
}
}
}
if (timeLog != null && timeLog.length > timeLogPrefix.length) {
LOG.debug(timeLog.toString())
}
}
for (settingsSavingComponent in settingsSavingComponents) {
try {
if (!isIprProject || settingsSavingComponent !is SchemeManagerFactoryBase) {
settingsSavingComponent.save()
}
}
catch (e: Throwable) {
if (errors == null) {
errors = SmartList<Throwable>()
}
errors!!.add(e)
}
}
if (externalizationSession != null) {
errors = doSave(externalizationSession.createSaveSessions(), readonlyFiles, errors)
}
CompoundRuntimeException.throwIfNotEmpty(errors)
}
override @TestOnly fun saveApplicationComponent(component: PersistentStateComponent<*>) {
val externalizationSession = storageManager.startExternalization() ?: return
val stateSpec = StoreUtil.getStateSpec(component)
commitComponent(externalizationSession, ComponentInfoImpl(component, stateSpec), null)
val sessions = externalizationSession.createSaveSessions()
if (sessions.isEmpty()) {
return
}
val absolutePath = Paths.get(storageManager.expandMacros(findNonDeprecated(stateSpec.storages).path)).toAbsolutePath().toString()
runUndoTransparentWriteAction {
try {
VfsRootAccess.allowRootAccess(absolutePath)
CompoundRuntimeException.throwIfNotEmpty(doSave(sessions))
}
finally {
VfsRootAccess.disallowRootAccess(absolutePath)
}
}
}
private fun commitComponent(session: ExternalizationSession, info: ComponentInfo, componentName: String?) {
val component = info.component
@Suppress("DEPRECATION")
if (component is PersistentStateComponent<*>) {
component.state?.let {
val stateSpec = info.stateSpec!!
session.setState(getStorageSpecs(component, stateSpec, StateStorageOperation.WRITE), component, componentName ?: stateSpec.name, it)
}
}
else if (component is JDOMExternalizable) {
session.setStateInOldStorage(component, componentName ?: ComponentManagerImpl.getComponentName(component), component)
}
}
protected open fun doSave(saveSessions: List<SaveSession>, readonlyFiles: MutableList<JBPair<SaveSession, VirtualFile>> = arrayListOf(), prevErrors: MutableList<Throwable>? = null): MutableList<Throwable>? {
var errors = prevErrors
for (session in saveSessions) {
errors = executeSave(session, readonlyFiles, prevErrors)
}
return errors
}
private fun initJdomExternalizable(@Suppress("DEPRECATION") component: JDOMExternalizable, componentName: String): String? {
doAddComponent(componentName, component, null)
if (loadPolicy != StateLoadPolicy.LOAD) {
return null
}
try {
getDefaultState(component, componentName, Element::class.java)?.let { component.readExternal(it) }
}
catch (e: Throwable) {
LOG.error(e)
}
val element = storageManager.getOldStorage(component, componentName, StateStorageOperation.READ)?.getState(component, componentName, Element::class.java, null, false) ?: return null
try {
component.readExternal(element)
}
catch (e: InvalidDataException) {
LOG.error(e)
return null
}
return componentName
}
private fun doAddComponent(name: String, component: Any, stateSpec: State?): ComponentInfo {
val newInfo = when (component) {
is ModificationTracker -> ComponentWithModificationTrackerInfo(component, stateSpec)
is PersistentStateComponentWithModificationTracker<*> -> ComponentWithStateModificationTrackerInfo(component, stateSpec!!)
else -> ComponentInfoImpl(component, stateSpec)
}
val existing = components.put(name, newInfo)
if (existing != null && existing.component !== component) {
components.put(name, existing)
LOG.error("Conflicting component name '$name': ${existing.component.javaClass} and ${component.javaClass}")
return existing
}
return newInfo
}
private fun initComponent(info: ComponentInfo, changedStorages: Set<StateStorage>?, reloadData: Boolean): Boolean {
if (loadPolicy == StateLoadPolicy.NOT_LOAD) {
return false
}
@Suppress("UNCHECKED_CAST")
if (doInitComponent(info.stateSpec!!, info.component as PersistentStateComponent<Any>, changedStorages, reloadData)) {
// if component was initialized, update lastModificationCount
info.updateModificationCount()
return true
}
return false
}
private fun doInitComponent(stateSpec: State, component: PersistentStateComponent<Any>, changedStorages: Set<StateStorage>?, reloadData: Boolean): Boolean {
val name = stateSpec.name
@Suppress("UNCHECKED_CAST")
val stateClass: Class<Any> = if (component is PersistenceStateAdapter) component.component::class.java as Class<Any> else ComponentSerializationUtil.getStateClass<Any>(component.javaClass)
if (!stateSpec.defaultStateAsResource && LOG.isDebugEnabled && getDefaultState(component, name, stateClass) != null) {
LOG.error("$name has default state, but not marked to load it")
}
val defaultState = if (stateSpec.defaultStateAsResource) getDefaultState(component, name, stateClass) else null
if (loadPolicy == StateLoadPolicy.LOAD) {
val storageChooser = component as? StateStorageChooserEx
for (storageSpec in getStorageSpecs(component, stateSpec, StateStorageOperation.READ)) {
if (storageChooser?.getResolution(storageSpec, StateStorageOperation.READ) == Resolution.SKIP) {
continue
}
val storage = storageManager.getStateStorage(storageSpec)
val stateGetter = if (isUseLoadedStateAsExisting(storage, name)) (storage as? StorageBaseEx<*>)?.createGetSession(component, name, stateClass) else null
var state = if (stateGetter == null) storage.getState(component, name, stateClass, defaultState, reloadData) else stateGetter.getState(defaultState)
if (state == null) {
if (changedStorages != null && changedStorages.contains(storage)) {
// state will be null if file deleted
// we must create empty (initial) state to reinit component
state = deserializeState(Element("state"), stateClass, null)!!
}
else {
continue
}
}
try {
component.loadState(state)
}
finally {
stateGetter?.close()
}
return true
}
}
// we load default state even if isLoadComponentState false - required for app components (for example, at least one color scheme must exists)
if (defaultState == null) {
component.noStateLoaded()
}
else {
component.loadState(defaultState)
}
return true
}
// todo "ProjectModuleManager" investigate why after loadState we get empty state on getState, test CMakeWorkspaceContentRootsTest
// todo fix FacetManager
// use.loaded.state.as.existing used in upsource
private fun isUseLoadedStateAsExisting(storage: StateStorage, name: String): Boolean {
return isUseLoadedStateAsExisting(storage) &&
name != "AntConfiguration" &&
name != "ProjectModuleManager" &&
name != "FacetManager" &&
name != "ProjectRunConfigurationManager" && /* ProjectRunConfigurationManager is used only for IPR, avoid relatively cost call getState */
name != "NewModuleRootManager" /* will be changed only on actual user change, so, to speed up module loading, skip it */ &&
name != "DeprecatedModuleOptionManager" /* doesn't make sense to check it */ &&
SystemPropertyUtil.getBoolean("use.loaded.state.as.existing", true)
}
protected open fun isUseLoadedStateAsExisting(storage: StateStorage): Boolean = (storage as? XmlElementStorage)?.roamingType != RoamingType.DISABLED
protected open fun getPathMacroManagerForDefaults(): PathMacroManager? = null
private fun <T : Any> getDefaultState(component: Any, componentName: String, stateClass: Class<T>): T? {
val url = DecodeDefaultsUtil.getDefaults(component, componentName) ?: return null
try {
val documentElement = JDOMXIncluder.resolve(JDOMUtil.loadDocument(url), url.toExternalForm()).detachRootElement()
getPathMacroManagerForDefaults()?.expandPaths(documentElement)
return deserializeState(documentElement, stateClass, null)
}
catch (e: Throwable) {
throw IOException("Error loading default state from $url", e)
}
}
protected open fun <T> getStorageSpecs(component: PersistentStateComponent<T>, stateSpec: State, operation: StateStorageOperation): List<Storage> {
val storages = stateSpec.storages
if (storages.size == 1 || component is StateStorageChooserEx) {
return storages.toList()
}
if (storages.isEmpty()) {
if (stateSpec.defaultStateAsResource) {
return emptyList()
}
throw AssertionError("No storage specified")
}
return storages.sortByDeprecated()
}
final override fun isReloadPossible(componentNames: MutableSet<String>) = !componentNames.any { isNotReloadable(it) }
private fun isNotReloadable(name: String): Boolean {
val component = components.get(name)?.component ?: return false
return component !is PersistentStateComponent<*> || !StoreUtil.getStateSpec(component).reloadable
}
fun getNotReloadableComponents(componentNames: Collection<String>): Collection<String> {
var notReloadableComponents: MutableSet<String>? = null
for (componentName in componentNames) {
if (isNotReloadable(componentName)) {
if (notReloadableComponents == null) {
notReloadableComponents = LinkedHashSet()
}
notReloadableComponents.add(componentName)
}
}
return notReloadableComponents ?: emptySet()
}
override final fun reloadStates(componentNames: MutableSet<String>, messageBus: MessageBus) {
runBatchUpdate(messageBus) {
reinitComponents(componentNames)
}
}
override final fun reloadState(componentClass: Class<out PersistentStateComponent<*>>) {
val stateSpec = StoreUtil.getStateSpecOrError(componentClass)
val info = components.get(stateSpec.name) ?: return
(info.component as? PersistentStateComponent<*>)?.let {
initComponent(info, emptySet(), true)
}
}
private fun reloadState(componentName: String, changedStorages: Set<StateStorage>): Boolean {
val info = components.get(componentName) ?: return false
if (info.component !is PersistentStateComponent<*>) {
return false
}
val changedStoragesEmpty = changedStorages.isEmpty()
initComponent(info, if (changedStoragesEmpty) null else changedStorages, changedStoragesEmpty)
return true
}
/**
* null if reloaded
* empty list if nothing to reload
* list of not reloadable components (reload is not performed)
*/
fun reload(changedStorages: Set<StateStorage>): Collection<String>? {
if (changedStorages.isEmpty()) {
return emptySet()
}
val componentNames = SmartHashSet<String>()
for (storage in changedStorages) {
try {
// we must update (reload in-memory storage data) even if non-reloadable component will be detected later
// not saved -> user does own modification -> new (on disk) state will be overwritten and not applied
storage.analyzeExternalChangesAndUpdateIfNeed(componentNames)
}
catch (e: Throwable) {
LOG.error(e)
}
}
if (componentNames.isEmpty) {
return emptySet()
}
val notReloadableComponents = getNotReloadableComponents(componentNames)
reinitComponents(componentNames, changedStorages, notReloadableComponents)
return if (notReloadableComponents.isEmpty()) null else notReloadableComponents
}
// used in settings repository plugin
/**
* You must call it in batch mode (use runBatchUpdate)
*/
fun reinitComponents(componentNames: Set<String>, changedStorages: Set<StateStorage> = emptySet(), notReloadableComponents: Collection<String> = emptySet()) {
for (componentName in componentNames) {
if (!notReloadableComponents.contains(componentName)) {
reloadState(componentName, changedStorages)
}
}
}
@TestOnly fun removeComponent(name: String) {
components.remove(name)
}
}
internal fun executeSave(session: SaveSession, readonlyFiles: MutableList<JBPair<SaveSession, VirtualFile>>, previousErrors: MutableList<Throwable>?): MutableList<Throwable>? {
var errors = previousErrors
try {
session.save()
}
catch (e: ReadOnlyModificationException) {
LOG.warn(e)
readonlyFiles.add(JBPair.create<SaveSession, VirtualFile>(e.session ?: session, e.file))
}
catch (e: Exception) {
if (errors == null) {
errors = SmartList<Throwable>()
}
errors.add(e)
}
return errors
}
private fun findNonDeprecated(storages: Array<Storage>) = storages.firstOrNull { !it.deprecated } ?: throw AssertionError("All storages are deprecated")
enum class StateLoadPolicy {
LOAD, LOAD_ONLY_DEFAULT, NOT_LOAD
}
internal fun Array<out Storage>.sortByDeprecated(): List<Storage> {
if (size < 2) {
return toList()
}
if (!first().deprecated) {
val othersAreDeprecated = (1 until size).any { get(it).deprecated }
if (othersAreDeprecated) {
return toList()
}
}
return sortedWith(deprecatedComparator)
}
private fun notifyUnknownMacros(store: IComponentStore, project: Project, componentName: String) {
val substitutor = store.stateStorageManager.macroSubstitutor ?: return
val immutableMacros = substitutor.getUnknownMacros(componentName)
if (immutableMacros.isEmpty()) {
return
}
val macros = LinkedHashSet(immutableMacros)
AppUIUtil.invokeOnEdt(Runnable {
var notified: MutableList<String>? = null
val manager = NotificationsManager.getNotificationsManager()
for (notification in manager.getNotificationsOfType(UnknownMacroNotification::class.java, project)) {
if (notified == null) {
notified = SmartList<String>()
}
notified.addAll(notification.macros)
}
if (!notified.isNullOrEmpty()) {
macros.removeAll(notified!!)
}
if (macros.isEmpty()) {
return@Runnable
}
LOG.debug("Reporting unknown path macros $macros in component $componentName")
doNotify(macros, project, Collections.singletonMap(substitutor, store))
}, project.disposed)
}
private interface ComponentInfo {
val component: Any
val stateSpec: State?
val lastModificationCount: Long
val currentModificationCount: Long
val isModificationTrackingSupported: Boolean
fun updateModificationCount(newCount: Long = currentModificationCount) {
}
}
private class ComponentInfoImpl(override val component: Any, override val stateSpec: State?) : ComponentInfo {
override val isModificationTrackingSupported = false
override val lastModificationCount: Long
get() = -1
override val currentModificationCount: Long
get() = -1
}
private abstract class ModificationTrackerAwareComponentInfo : ComponentInfo {
override final val isModificationTrackingSupported = true
override abstract var lastModificationCount: Long
override final fun updateModificationCount(newCount: Long) {
lastModificationCount = newCount
}
}
private class ComponentWithStateModificationTrackerInfo(override val component: PersistentStateComponentWithModificationTracker<*>, override val stateSpec: State) : ModificationTrackerAwareComponentInfo() {
override val currentModificationCount: Long
get() = component.stateModificationCount
override var lastModificationCount = currentModificationCount
}
private class ComponentWithModificationTrackerInfo(override val component: ModificationTracker, override val stateSpec: State?) : ModificationTrackerAwareComponentInfo() {
override val currentModificationCount: Long
get() = component.modificationCount
override var lastModificationCount = currentModificationCount
} | apache-2.0 | e4c79953a4254714e468521b0ec767df | 37.036977 | 209 | 0.719122 | 5.083369 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/jvm-debugger/util/src/org/jetbrains/kotlin/idea/debugger/NoStrataPositionManagerHelper.kt | 2 | 5759 | // 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.debugger
import com.intellij.debugger.SourcePosition
import com.intellij.debugger.engine.DebugProcess
import com.intellij.debugger.impl.DebuggerUtilsAsync
import com.intellij.debugger.jdi.VirtualMachineProxyImpl
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.util.containers.ConcurrentFactoryMap
import com.sun.jdi.Location
import com.sun.jdi.ReferenceType
import com.sun.jdi.VirtualMachine
import org.jetbrains.kotlin.codegen.inline.SMAP
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.core.util.getLineCount
import org.jetbrains.kotlin.idea.core.util.getLineStartOffset
import org.jetbrains.kotlin.idea.core.util.toPsiFile
import org.jetbrains.kotlin.idea.debugger.evaluate.KotlinDebuggerCaches
import org.jetbrains.kotlin.idea.util.ProjectRootsUtil
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.parents
import org.jetbrains.kotlin.resolve.inline.InlineUtil
import org.jetbrains.kotlin.resolve.jvm.JvmClassName
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
import java.util.concurrent.ConcurrentMap
fun isInlineFunctionLineNumber(file: VirtualFile, lineNumber: Int, project: Project): Boolean {
if (ProjectRootsUtil.isProjectSourceFile(project, file)) {
val linesInFile = file.toPsiFile(project)?.getLineCount() ?: return false
return lineNumber > linesInFile
}
return true
}
fun createWeakBytecodeDebugInfoStorage(): ConcurrentMap<BinaryCacheKey, SMAP?> {
return ConcurrentFactoryMap.createWeakMap<BinaryCacheKey, SMAP?> { key ->
val bytes = ClassBytecodeFinder(key.project, key.jvmName, key.file).find() ?: return@createWeakMap null
return@createWeakMap readDebugInfo(bytes)
}
}
data class BinaryCacheKey(val project: Project, val jvmName: JvmClassName, val file: VirtualFile)
fun getLocationsOfInlinedLine(type: ReferenceType, position: SourcePosition, sourceSearchScope: GlobalSearchScope): List<Location> {
val line = position.line
val file = position.file
val project = position.file.project
val lineStartOffset = file.getLineStartOffset(line) ?: return listOf()
val element = file.findElementAt(lineStartOffset) ?: return listOf()
val ktElement = element.parents.firstIsInstanceOrNull<KtElement>() ?: return listOf()
val isInInline = runReadAction { element.parents.any { it is KtFunction && it.hasModifier(KtTokens.INLINE_KEYWORD) } }
if (!isInInline) {
// Lambdas passed to crossinline arguments are inlined when they are used in non-inlined lambdas
val isInCrossinlineArgument = isInCrossinlineArgument(ktElement)
if (!isInCrossinlineArgument) {
return listOf()
}
}
val lines = inlinedLinesNumbers(line + 1, position.file.name, FqName(type.name()), type.sourceName(), project, sourceSearchScope)
return lines.flatMap { DebuggerUtilsAsync.locationsOfLineSync(type, it) }
}
fun isInCrossinlineArgument(ktElement: KtElement): Boolean {
val argumentFunctions = runReadAction {
ktElement.parents.filter {
when (it) {
is KtFunctionLiteral -> it.parent is KtLambdaExpression &&
(it.parent.parent is KtValueArgument || it.parent.parent is KtLambdaArgument)
is KtFunction -> it.parent is KtValueArgument
else -> false
}
}.filterIsInstance<KtFunction>()
}
val bindingContext = ktElement.analyze(BodyResolveMode.PARTIAL)
return argumentFunctions.any {
val argumentDescriptor = InlineUtil.getInlineArgumentDescriptor(it, bindingContext)
argumentDescriptor?.isCrossinline ?: false
}
}
private fun inlinedLinesNumbers(
inlineLineNumber: Int, inlineFileName: String,
destinationTypeFqName: FqName, destinationFileName: String,
project: Project, sourceSearchScope: GlobalSearchScope
): List<Int> {
val internalName = destinationTypeFqName.asString().replace('.', '/')
val jvmClassName = JvmClassName.byInternalName(internalName)
val file = DebuggerUtils.findSourceFileForClassIncludeLibrarySources(project, sourceSearchScope, jvmClassName, destinationFileName)
?: return listOf()
val virtualFile = file.virtualFile ?: return listOf()
val smapData = KotlinDebuggerCaches.getSmapCached(project, jvmClassName, virtualFile) ?: return listOf()
val mappingsToInlinedFile = smapData.fileMappings.filter { it.name == inlineFileName }
val mappingIntervals = mappingsToInlinedFile.flatMap { it.lineMappings }
return mappingIntervals.asSequence().filter { rangeMapping -> rangeMapping.hasMappingForSource(inlineLineNumber) }
.map { rangeMapping -> rangeMapping.mapSourceToDest(inlineLineNumber) }.filter { line -> line != -1 }.toList()
}
@Volatile
var emulateDexDebugInTests: Boolean = false
fun DebugProcess.isDexDebug(): Boolean {
val virtualMachine = (this.virtualMachineProxy as? VirtualMachineProxyImpl)?.virtualMachine
return virtualMachine.isDexDebug()
}
fun VirtualMachine?.isDexDebug(): Boolean {
// TODO: check other machine names
return (emulateDexDebugInTests && isUnitTestMode()) || this?.name() == "Dalvik"
}
| apache-2.0 | c0cb34f3a40264a77b47ca45f7bd5239 | 43.3 | 158 | 0.764542 | 4.588845 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/codeInsight/lineMarker/overrideImplement/FakeOverrideToStringInTrait.kt | 8 | 395 | interface <lineMarker descr="*">A</lineMarker> {
override fun <lineMarker descr="<html><body>Is overridden in <br> C</body></html>"><lineMarker descr="*">toString</lineMarker></lineMarker>() = "A"
}
abstract class <lineMarker descr="*">B</lineMarker> : A
class C : B() {
override fun <lineMarker descr="Overrides function in 'A'">toString</lineMarker>() = "B"
}
| apache-2.0 | ef457b0c0e38ace6b92e7253e91767ff | 42.888889 | 174 | 0.673418 | 3.726415 | false | false | false | false |
android/compose-samples | Crane/app/src/main/java/androidx/compose/samples/crane/calendar/CalendarScreen.kt | 1 | 4300 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.samples.crane.calendar
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.WindowInsetsSides
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.only
import androidx.compose.foundation.layout.statusBars
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.foundation.layout.windowInsetsTopHeight
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.samples.crane.R
import androidx.compose.samples.crane.calendar.model.CalendarState
import androidx.compose.samples.crane.home.MainViewModel
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import java.time.LocalDate
@Composable
fun CalendarScreen(
onBackPressed: () -> Unit,
mainViewModel: MainViewModel
) {
val calendarState = remember {
mainViewModel.calendarState
}
CalendarContent(
calendarState = calendarState,
onDayClicked = { dateClicked ->
mainViewModel.onDaySelected(dateClicked)
},
onBackPressed = onBackPressed
)
}
@Composable
private fun CalendarContent(
calendarState: CalendarState,
onDayClicked: (LocalDate) -> Unit,
onBackPressed: () -> Unit
) {
Scaffold(
modifier = Modifier.windowInsetsPadding(
WindowInsets.navigationBars.only(WindowInsetsSides.Start + WindowInsetsSides.End)
),
backgroundColor = MaterialTheme.colors.primary,
topBar = {
CalendarTopAppBar(calendarState, onBackPressed)
}
) { contentPadding ->
Calendar(
calendarState = calendarState,
onDayClicked = onDayClicked,
contentPadding = contentPadding
)
}
}
@Composable
private fun CalendarTopAppBar(calendarState: CalendarState, onBackPressed: () -> Unit) {
val calendarUiState = calendarState.calendarUiState.value
Column {
Spacer(
modifier = Modifier
.windowInsetsTopHeight(WindowInsets.statusBars)
.fillMaxWidth()
.background(MaterialTheme.colors.primaryVariant)
)
TopAppBar(
title = {
Text(
text = if (!calendarUiState.hasSelectedDates) {
stringResource(id = R.string.calendar_select_dates_title)
} else {
calendarUiState.selectedDatesFormatted
}
)
},
navigationIcon = {
IconButton(onClick = { onBackPressed() }) {
Icon(
imageVector = Icons.Default.ArrowBack,
contentDescription = stringResource(id = R.string.cd_back),
tint = MaterialTheme.colors.onSurface
)
}
},
backgroundColor = MaterialTheme.colors.primaryVariant,
elevation = 0.dp
)
}
}
| apache-2.0 | 5d73eb3f0fdb8600c7513061aca3c384 | 34.245902 | 93 | 0.687209 | 5.011655 | false | false | false | false |
80998062/Fank | domain/src/main/java/com/sinyuk/fanfou/domain/util/LiveDataCallAdapterFactory.kt | 1 | 1818 | /*
*
* * Apache License
* *
* * Copyright [2017] Sinyuk
* *
* * 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.sinyuk.fanfou.domain.util
import android.arch.lifecycle.LiveData
import com.sinyuk.fanfou.domain.api.ApiResponse
import retrofit2.CallAdapter
import retrofit2.Retrofit
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
class LiveDataCallAdapterFactory : CallAdapter.Factory() {
override fun get(returnType: Type, annotations: Array<Annotation>, retrofit: Retrofit): CallAdapter<*, *>? {
if (CallAdapter.Factory.getRawType(returnType) != LiveData::class.java) {
return null
}
val observableType = CallAdapter.Factory.getParameterUpperBound(0, returnType as ParameterizedType)
val rawObservableType = CallAdapter.Factory.getRawType(observableType)
if (rawObservableType != ApiResponse::class.java) {
throw IllegalArgumentException("type must be a resource")
}
if (observableType !is ParameterizedType) {
throw IllegalArgumentException("resource must be parameterized")
}
val bodyType = CallAdapter.Factory.getParameterUpperBound(0, observableType)
return LiveDataCallAdapter<Type>(bodyType)
}
} | mit | 3db0036e8de246f4133f6b5686958a07 | 37.702128 | 112 | 0.711771 | 4.401937 | false | false | false | false |
80998062/Fank | domain/src/main/java/com/sinyuk/fanfou/domain/repo/AccountRepository.kt | 1 | 5653 | /*
*
* * Apache License
* *
* * Copyright [2017] Sinyuk
* *
* * 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.sinyuk.fanfou.domain.repo
import android.app.Application
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MutableLiveData
import android.arch.lifecycle.Transformations.map
import android.content.SharedPreferences
import com.sinyuk.fanfou.domain.*
import com.sinyuk.fanfou.domain.DO.Authorization
import com.sinyuk.fanfou.domain.DO.Player
import com.sinyuk.fanfou.domain.DO.Resource
import com.sinyuk.fanfou.domain.api.Endpoint
import com.sinyuk.fanfou.domain.api.Oauth1SigningInterceptor
import com.sinyuk.fanfou.domain.db.LocalDatabase
import com.sinyuk.fanfou.domain.repo.base.AbstractRepository
import com.sinyuk.fanfou.domain.util.stringLiveData
import java.util.*
import javax.inject.Inject
import javax.inject.Named
import javax.inject.Singleton
/**
* Created by sinyuk on 2017/12/6.
*
*/
@Singleton
class AccountRepository
@Inject constructor(
application: Application,
url: Endpoint,
interceptor: Oauth1SigningInterceptor,
private val appExecutors: AppExecutors,
@Named(DATABASE_IN_DISK) private val db: LocalDatabase,
@Named(TYPE_GLOBAL) private val sharedPreferences: SharedPreferences) : AbstractRepository(application, url, interceptor) {
private fun accessToken(): String? = sharedPreferences.getString(ACCESS_TOKEN, null)
private fun accessSecret(): String? = sharedPreferences.getString(ACCESS_SECRET, null)
/**
* authorization
*/
fun authorization(account: String, password: String): MutableLiveData<Resource<Authorization>> {
val task = SignInTask(account, password, okHttpClient, sharedPreferences)
appExecutors.diskIO().execute(task)
return task.liveData
}
/**
* 验证Token
*
*/
fun verifyCredentials(authorization: Authorization): LiveData<Resource<Player>> {
val liveData = MutableLiveData<Resource<Player>>()
liveData.postValue(Resource.loading(null))
setTokenAndSecret(authorization.token, authorization.secret)
appExecutors.networkIO().execute {
val response = restAPI.fetch_profile().execute()
if (response.isSuccessful) {
savePlayerInDb(response.body(), authorization)
liveData.postValue(Resource.success(response.body()))
} else {
setTokenAndSecret(null, null)
liveData.postValue(Resource.error("error: ${response.message()}", null))
}
}
return liveData
}
/**
* 返回所有登录过的用户
*/
fun admins() = db.playerDao().byPath(convertPlayerPathToFlag(USERS_ADMIN))
fun logout() {
}
private val uniqueIdLive = sharedPreferences.stringLiveData(UNIQUE_ID, "")
fun accountLive(): LiveData<Player?> = map(uniqueIdLive, {
if (it.isBlank()) {
null
} else {
db.playerDao().query(it)
}
})
fun signIn(uniqueId: String): LiveData<Resource<Player>> {
val liveData = MutableLiveData<Resource<Player>>()
liveData.postValue(Resource.loading(null))
val oldToken = accessToken()
val oldSecret = accessSecret()
appExecutors.diskIO().execute {
if (db.playerDao().query(uniqueId) != null) {
val player = db.playerDao().query(uniqueId)!!
setTokenAndSecret(player.authorization?.token, player.authorization?.secret)
appExecutors.networkIO().execute {
val response = restAPI.fetch_profile().execute()
if (response.isSuccessful) {
savePlayerInDb(response.body(), player.authorization)
liveData.postValue(Resource.success(response.body()))
} else {
setTokenAndSecret(oldToken, oldSecret)
liveData.postValue(Resource.error("error: ${response.message()}", null))
}
}
} else {
setTokenAndSecret(oldToken, oldSecret)
liveData.postValue(Resource.error("error: user: $uniqueId is not recorded", null))
}
}
return liveData
}
private fun setTokenAndSecret(token: String?, secret: String?) {
sharedPreferences.edit().putString(ACCESS_TOKEN, token).putString(ACCESS_SECRET, secret).apply()
}
private fun savePlayerInDb(item: Player?, authorization: Authorization? = null) {
item?.let {
sharedPreferences.edit().apply { putString(UNIQUE_ID, it.uniqueId) }.apply()
it.authorization = authorization ?: Authorization(accessToken(), accessSecret())
it.addPathFlag(USERS_ADMIN)
it.updatedAt = Date(System.currentTimeMillis())
db.playerDao().insert(it)
}
}
fun delete(uniqueId: String) {
appExecutors.diskIO().execute { db.playerDao().delete(Player(uniqueId = uniqueId)) }
}
} | mit | f2e46c9bbd34216679e6a0473384164a | 34.1875 | 131 | 0.650737 | 4.5032 | false | false | false | false |
Duke1/UnrealMedia | UnrealMedia/app/src/main/java/com/qfleng/um/adapter/ArtistGridAdapter.kt | 1 | 3470 | package com.qfleng.um.adapter
import android.graphics.Color
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.PopupMenu
import androidx.core.view.ViewCompat
import androidx.core.view.setPadding
import androidx.recyclerview.widget.RecyclerView
import com.qfleng.um.ArtistDetailActivity
import com.qfleng.um.BaseActivity
import com.qfleng.um.R
import com.qfleng.um.UmApp
import com.qfleng.um.bean.ArtistMedia
import com.qfleng.um.databinding.ListGridLayoutItemBinding
import com.qfleng.um.audio.MusicUtils
import com.qfleng.um.util.FrescoHelper
import com.qfleng.um.util.dpToPx
/**
* Created by Duke
* 歌手
*/
class ArtistGridAdapter constructor(val listener: (view: View, bean: ArtistMedia, position: Int, targetView: View) -> Unit)
: RecyclerView.Adapter<ArtistGridAdapter.ViewHolder>() {
val list: ArrayList<ArtistMedia> = ArrayList()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val vBinding = ListGridLayoutItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return ViewHolder(vBinding, listener)
}
override fun getItemCount(): Int {
return list.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val bean: ArtistMedia = list[position]
holder.bind(bean)
}
class ViewHolder(val vBinding: ListGridLayoutItemBinding, val listener: (view: View, bean: ArtistMedia, position: Int, targetView: View) -> Unit)
: RecyclerView.ViewHolder(vBinding.root) {
var curBean: ArtistMedia? = null
init {
vBinding.moreOptMenu.setOnClickListener { view ->
val menu = PopupMenu(view.context, view)
val adapterPosition = getAdapterPosition()
menu.setOnMenuItemClickListener { item ->
when (item.itemId) {
}
true
}
menu.inflate(R.menu.popup_menu_artist)
menu.show()
}
}
fun bind(am: ArtistMedia) {
this.curBean = am
val activity = itemView.context as BaseActivity
vBinding.titleView.text = am.artistName
vBinding.subTitleView.text = am.artistName
ViewCompat.setTransitionName(vBinding.image, ArtistDetailActivity.TRANSITION_NAME)
vBinding.root.setOnClickListener {
listener(vBinding.root, am, bindingAdapterPosition, vBinding.image)
}
vBinding.image.setPadding(0)
FrescoHelper.loadBitmap(am.artistCover,
loadCallback = {
activity.doOnUi {
vBinding.image.setBackgroundColor(Color.WHITE)
vBinding.image.setImageBitmap(it)
}
},
onFailure = {
activity.doOnUi {
val app = activity.applicationContext as UmApp
vBinding.image.setBackgroundColor(Color.LTGRAY)
vBinding.image.setPadding(dpToPx(activity, 32f))
vBinding.image.setImageBitmap(app.rawImageLoader.loadImage(activity, R.raw.music_note_white_48))
}
}
)
}
}
} | mit | 216fd269dedeeab7592ca0f6c87e9e2d | 31.101852 | 149 | 0.617138 | 4.807212 | false | false | false | false |
luhaoaimama1/JavaZone | JavaTest_Zone/src/算法/算法书籍/压缩/Compress.kt | 1 | 4604 | package 算法.算法书籍.压缩
import java.io.*
import java.util.*
val file = File(".", "JavaTest_Zone\\src\\算法\\算法书籍\\压缩\\content.txt")
fun main(args: Array<String>) {
//字符串转化成整形
println("字符串转化成整形:${Integer.parseInt("00000101", 2)}")
weakMap()
// writeBit()
// writeBit2()
// readBit2()
// print(" \n Byte 5 的byte.toBit方法=>")
// readBit()
}
private fun weakMap() {
var key: Any? = Any()
exMaps.put(key, Property())
println("Map size :" + exMaps.size)
key = null
System.gc()
Thread.sleep(500) //需要点延时 不没清除完毕
println("Map size :" + exMaps.size)
}
private fun readBit2() {
val ins = BufferedInputStream(FileInputStream(file))
var value = 0
while (ins.readBit().apply {
value = this
} != -1) {
print(value)
}
}
private fun readBit() {
val a = BooleanArray(8) { false }
5.toByte().toBits(a) //101
a.forEachIndexed { index, b ->
print("${if (b) "1" else "0"}")
}
}
private fun writeBit() {
val file = File(".", "JavaTest_Zone\\src\\算法\\算法书籍\\压缩\\content.txt")
val out = BufferedOutputStream(FileOutputStream(file))
out.writeBit(true)
out.writeBit(false)
out.writeBit(true)
out.writeBit(true)
out.writeBitFlush()
// 结果应该是00001011
// 结果就是
out.flush()
out.close()
}
private fun writeBit2() {
val file = File(".", "JavaTest_Zone\\src\\算法\\算法书籍\\压缩\\content.txt")
val out = BufferedOutputStream(FileOutputStream(file))
out.writeBit(5, 16)
out.writeBitFlush()
// 结果应该是00001011
// 结果就是
out.flush()
out.close()
}
//数组是逆序的。这样迭代的时候 就能是从第一位开始迭代了
fun Byte.toBits(a: BooleanArray): Unit {
if (a.size < 8) throw IllegalStateException("must be > 8")
for (i in 7 downTo 0) {
//00000101取出倒数第三位的时候 向右移动2位00000001 得到1 。但是取出最后一位的时候如果也想上面的话那么就是00000101我只想看最后一位所以&00000001就能得到了
a[7 - i] = (this.toInt() shr i and 1) == 1
}
}
//扩展属性的值
class Property : HashMap<String, Any>()
var exMaps = object : WeakHashMap<Any, Property>() {
override fun get(key: Any): Property? {
var get = super.get(key)
if (get == null) get = Property()
set(key, get)
return get
}
}
var BufferedOutputStream.n: Int
get() = exMaps[this]?.get("n") as? Int ?: 0
set(value) {
exMaps[this]?.set("n", value)
}
var BufferedOutputStream.buffer2: Int
get() = exMaps[this]?.get("buffer2") as? Int ?: 0
set(value) {
exMaps[this]?.set("buffer2", value)
}
var BufferedOutputStream.a: BooleanArray
get() {
var get = exMaps[this]?.get("a")
if (get == null) {
get = BooleanArray(8) { false }
exMaps[this]?.set("a", get)
}
return get as BooleanArray
}
set(value) {
exMaps[this]?.set("a", value)
}
fun BufferedOutputStream.writeBitFlush(): Unit {
if (n != 0) {
write(buffer2)
buffer2 = 0
n = 0
}
}
fun BufferedOutputStream.writeBit(content: Int, bitCount: Int): Unit {
for (i in bitCount - 1 downTo 0) {
val value = (content shr i and 1) == 1
writeBit(value)
}
}
fun BufferedOutputStream.writeBit(bit: Boolean): Unit {
// 范例 val i = (1 shl 4) + 1 //00010001
//左移一位 然后加上 bit.计数n
buffer2 = buffer2 shl 1
buffer2 += if (bit) 1 else 0
n++
//满8位 写进去 然后清空
if (n == 8) {
writeBitFlush()
}
}
var BufferedInputStream.n: Int
get() = exMaps[this]?.get("n") as? Int ?: 0
set(value) {
exMaps[this]?.set("n", value)
}
var BufferedInputStream.buffer2: Int
get() = exMaps[this]?.get("buffer2") as? Int ?: 0
set(value) {
exMaps[this]?.set("buffer2", value)
}
/**
* @return -1 0 1 .-1代表结尾了
*/
fun BufferedInputStream.readBit(): Int {
if (n == 0) {
buffer2 = read()
if (buffer2 == -1) {
buffer2 = 0
return -1
}
n = 8
}
n--
return buffer2 shr n and 1 //使用的n:7-0
}
fun BufferedInputStream.readBit(count: Int): String {
val sb = StringBuilder()
for (i in 0 until count) {
val readBit = readBit()
if (readBit != -1) sb.append(readBit)
}
return sb.toString()
}
| epl-1.0 | 16ecd2e814549b37fd76e36e086423a5 | 22.131868 | 104 | 0.568884 | 3.08651 | false | false | false | false |
kvnxiao/meirei | meirei-d4j/src/main/kotlin/com/github/kvnxiao/discord/meirei/d4j/MeireiD4J.kt | 1 | 9691 | /*
* Copyright (C) 2017-2018 Ze Hao Xiao
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.kvnxiao.discord.meirei.d4j
import com.github.kvnxiao.discord.meirei.Meirei
import com.github.kvnxiao.discord.meirei.command.CommandContext
import com.github.kvnxiao.discord.meirei.command.database.CommandRegistry
import com.github.kvnxiao.discord.meirei.command.database.CommandRegistryImpl
import com.github.kvnxiao.discord.meirei.d4j.command.CommandD4J
import com.github.kvnxiao.discord.meirei.d4j.command.CommandParserD4J
import com.github.kvnxiao.discord.meirei.d4j.command.DefaultErrorHandler
import com.github.kvnxiao.discord.meirei.d4j.command.ErrorHandler
import com.github.kvnxiao.discord.meirei.d4j.permission.PermissionPropertiesD4J
import com.github.kvnxiao.discord.meirei.utility.SplitString.Companion.splitString
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import reactor.core.scheduler.Scheduler
import reactor.core.scheduler.Schedulers
import sx.blah.discord.api.IDiscordClient
import sx.blah.discord.api.events.IListener
import sx.blah.discord.handle.impl.events.ReadyEvent
import sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent
import sx.blah.discord.handle.obj.IMessage
import java.util.EnumSet
class MeireiD4J(client: IDiscordClient, registry: CommandRegistry) : Meirei(commandParser = CommandParserD4J(), registry = registry) {
private var botOwnerId: Long = 0
private val errorHandler: ErrorHandler = DefaultErrorHandler()
private val scheduler: Scheduler = Schedulers.newParallel("MeireiExec-pool")
constructor(client: IDiscordClient) : this(client, CommandRegistryImpl())
init {
// Register message-received event listener
Flux.create<MessageReceivedEvent> {
client.dispatcher.registerListener(IListener { event: MessageReceivedEvent -> it.next(event) })
}.publishOn(scheduler)
.doOnNext { Meirei.LOGGER.debug { "Received message ${it.message.content} from ${it.author.stringID} ${if (it.channel.isPrivate) "in direct message." else "in guild ${it.guild.stringID}"}" } }
.doOnError { Meirei.LOGGER.error(it) { "An error occurred in processing a MessageReceivedEvent!" } }
.subscribe(this::consumeMessage)
// Register ready-event listener
Mono.create<ReadyEvent> {
client.dispatcher.registerListener(IListener { event: ReadyEvent -> it.success(event) })
}.publishOn(scheduler)
.doOnSuccess(this::setBotOwner)
.doOnError { Meirei.LOGGER.error(it) { "An error occurred in processing the ReadyEvent!" } }
.subscribe()
}
private fun setBotOwner(event: ReadyEvent) {
// Set bot owner ID
botOwnerId = event.client.applicationOwner.longID
Meirei.LOGGER.debug { "Bot owner ID found: ${java.lang.Long.toUnsignedString(botOwnerId)}" }
}
override fun registerEventListeners(client: Any) {
val dispatcher = (client as IDiscordClient).dispatcher
commandParser.commandEventListeners.values.forEach {
dispatcher.registerListener(it)
}
}
private fun consumeMessage(event: MessageReceivedEvent) {
val message = event.message
val rawContent = message.content
val isPrivate = event.channel.isPrivate
// Split to check for bot mention
val (firstStr, secondStr) = splitString(rawContent)
firstStr.let {
// Check for bot mention
val hasBotMention = hasBotMention(it, message)
// Process for command alias and arguments
val content = if (hasBotMention) secondStr else rawContent
content?.let { process(it, event, isPrivate, hasBotMention) }
}
}
private fun process(input: String, event: MessageReceivedEvent, isDirectMsg: Boolean, hasBotMention: Boolean) {
val (alias, args) = splitString(input)
alias.let {
val command = registry.getCommandByAlias(it) as CommandD4J?
command?.let {
val properties = registry.getPropertiesById(it.id)
val permissions = registry.getPermissionsById(it.id)
if (properties != null && permissions != null) {
// Execute command
val context = CommandContext(alias, args, properties, permissions,
isDirectMsg, hasBotMention, if (it.registryAware) registry else null)
Meirei.LOGGER.debug { "Evaluating input for potential commands: $input" }
execute(it, context, event)
}
}
}
}
private fun execute(command: CommandD4J, context: CommandContext, event: MessageReceivedEvent): Boolean {
if (!context.properties.isDisabled) {
// Check sub-commands
val args = context.args
if (args != null && registry.hasSubCommands(command.id)) {
// Try getting a sub-command from the args
val (subAlias, subArgs) = splitString(args)
val subCommand = registry.getSubCommandByAlias(subAlias, command.id) as CommandD4J?
if (subCommand != null) {
val subProperties = registry.getPropertiesById(subCommand.id)
val subPermissions = registry.getPermissionsById(subCommand.id)
if (subProperties != null && subPermissions != null) {
// Execute sub-command
val subContext = CommandContext(subAlias, subArgs, subProperties, subPermissions,
context.isDirectMessage, context.hasBotMention, if (subCommand.registryAware) registry else null)
// Execute parent-command if the boolean value is true
if (context.properties.execWithSubCommands) command.execute(context, event)
return execute(subCommand, subContext, event)
}
}
}
return executeCommand(command, context, event)
}
return false
}
private fun executeCommand(command: CommandD4J, context: CommandContext, event: MessageReceivedEvent): Boolean {
// Validate mention-only command
if (!validateMentionOnly(context)) return false
// Validate permissions
if (!validatePermissions(context, event)) return false
// Validate rate-limits
if (!validateRateLimits(command, context, event)) return false
// Remove call msg if set to true
if (context.permissions.data.removeCallMsg) {
event.message.delete()
}
try {
Meirei.LOGGER.debug { "Executing command $command" }
command.execute(context, event)
} catch (e: Exception) {
Meirei.LOGGER.error(e) { "An error occurred in executing the command $command" }
}
return true
}
private fun hasBotMention(content: String, message: IMessage): Boolean {
return content == message.client.ourUser.mention(false) || content == message.client.ourUser.mention(true)
}
// Validation
private fun validateRateLimits(command: CommandD4J, context: CommandContext, event: MessageReceivedEvent): Boolean {
val isNotRateLimited = if (event.channel.isPrivate) {
command.isNotUserLimited(event.author.longID, context.permissions.data)
} else {
command.isNotRateLimited(event.guild.longID, event.author.longID, context.permissions.data)
}
if (!isNotRateLimited) {
errorHandler.onRateLimit(context, event)
return false
}
return true
}
private fun validateMentionOnly(context: CommandContext): Boolean {
return context.permissions.data.requireMention == context.hasBotMention
}
private fun validatePermissions(context: CommandContext, event: MessageReceivedEvent): Boolean {
val permissions = context.permissions as PermissionPropertiesD4J
if (context.isDirectMessage) {
if (!permissions.data.allowDmFromSender)
errorHandler.onDirectMessageInvalid(context, event)
else return permissions.data.allowDmFromSender
}
// Check if command requires to be guild owner
val isGuildOwner = event.guild.owner.longID == event.author.longID
// Check if command requires to be bot owner
val isBotOwner = botOwnerId == event.author.longID
// Check for required user permissions in current channel
val requiredPerms = EnumSet.copyOf(permissions.level)
val userPerms = event.channel.getModifiedPermissions(event.author)
requiredPerms.removeAll(userPerms)
val hasUserPerms = requiredPerms.isEmpty() && (!permissions.data.reqGuildOwner || isGuildOwner) && (!permissions.data.reqBotOwner || isBotOwner)
return if (hasUserPerms) {
true
} else {
errorHandler.onMissingPermissions(context, event, requiredPerms)
false
}
}
}
| apache-2.0 | 8fc1d45dfc4afe4ad679418b730dd58a | 44.712264 | 204 | 0.668558 | 4.608179 | false | false | false | false |
Adven27/Exam | exam-db/src/main/java/io/github/adven27/concordion/extensions/exam/db/TableData.kt | 1 | 2800 | package io.github.adven27.concordion.extensions.exam.db
import io.github.adven27.concordion.extensions.exam.db.builder.DataSetBuilder
import io.github.adven27.concordion.extensions.exam.db.builder.ExamTable
import org.concordion.api.Evaluator
import org.dbunit.dataset.Column
import org.dbunit.dataset.DefaultTable
import org.dbunit.dataset.ITable
import org.dbunit.dataset.datatype.DataType.UNKNOWN
class TableData(private val table: String, private val columns: Map<String, Any?>) {
private var dataSetBuilder = DataSetBuilder()
private var currentRow = 0
fun row(vararg values: Any?): TableData {
val colsToSet = columns.filterValues { it is MarkedHasNoDefaultValue }.keys
validate(values, colsToSet)
dataSetBuilder = dataSetBuilder.newRowTo(table)
.withFields(columns + colsToSet.zip(values).toMap())
.add()
currentRow++
return this
}
private fun validate(values: Array<out Any?>, columns: Set<String>) {
if (values.size != columns.size) {
fun breakReason(cols: List<String>, vals: List<Any?>) =
if (cols.size > vals.size) "column '${cols[vals.size]}' has no value" else "value '${vals[cols.size]}' has no column"
fun msg(columns: Set<String>, values: Array<out Any?>) =
"Zipped " + columns.zip(values) { a, b -> "$a=$b" } + " then breaks because " + breakReason(columns.toList(), values.toList())
throw IllegalArgumentException(
String.format(
"Number of columns (%s) for the table %s is different from the number of provided values (%s):\n %s",
columns.size,
table,
values.size,
msg(columns, values)
)
)
}
}
@Suppress("SpreadOperator")
fun rows(rows: List<List<Any?>>): TableData {
rows.forEachIndexed { index, list ->
try {
row(*list.toTypedArray())
} catch (expected: Exception) {
throw IllegalArgumentException("Table parsing breaks on row ${index + 1} : $list", expected)
}
}
return this
}
fun build() = dataSetBuilder.build()
fun table(eval: Evaluator): ITable = build().let {
ExamTable(
if (it.tableNames.isEmpty()) DefaultTable(table, columns(columns.keys)) else it.getTable(table),
eval
)
}
private fun columns(c: Set<String>): Array<Column?> = c.map { Column(it, UNKNOWN) }.toTypedArray()
companion object {
fun filled(table: String, rows: List<List<Any?>>, cols: Map<String, Any?>, eval: Evaluator) = TableData(table, cols).rows(rows).table(eval)
}
}
class MarkedHasNoDefaultValue
| mit | 84cde9333a0a9588000c4639e74cd2c9 | 37.888889 | 147 | 0.6125 | 4.179104 | false | false | false | false |
Bambooin/trime | app/src/main/java/com/osfans/trime/settings/fragments/OtherFragment.kt | 1 | 4021 | package com.osfans.trime.settings.fragments
import android.content.ComponentName
import android.content.Context
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.Menu
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.view.forEach
import androidx.preference.ListPreference
import androidx.preference.PreferenceFragmentCompat
import com.osfans.trime.R
import com.osfans.trime.data.AppPrefs
import com.osfans.trime.data.Config
import com.osfans.trime.ime.core.Trime
class OtherFragment :
PreferenceFragmentCompat(),
SharedPreferences.OnSharedPreferenceChangeListener {
private val prefs get() = AppPrefs.defaultInstance()
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
addPreferencesFromResource(R.xml.other_preference)
findPreference<ListPreference>("other__ui_mode")?.setOnPreferenceChangeListener { _, newValue ->
val uiMode = when (newValue) {
"auto" -> AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM
"light" -> AppCompatDelegate.MODE_NIGHT_NO
"dark" -> AppCompatDelegate.MODE_NIGHT_YES
else -> AppCompatDelegate.MODE_NIGHT_UNSPECIFIED
}
AppCompatDelegate.setDefaultNightMode(uiMode)
true
}
setHasOptionsMenu(true)
}
override fun onPrepareOptionsMenu(menu: Menu) {
menu.forEach { item -> item.isVisible = false }
super.onPrepareOptionsMenu(menu)
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) {
val trime = Trime.getServiceOrNull()
when (key) {
"other__show_status_bar_icon" -> {
if (sharedPreferences?.getBoolean(key, false) == true) {
trime?.showStatusIcon(R.drawable.ic_trime_status)
} else { trime?.hideStatusIcon() }
}
"other__clipboard_compare" -> {
Config.get(context).setClipBoardCompare(
sharedPreferences?.getString(key, "")
)
}
"other__clipboard_output" -> {
Config.get(context).setClipBoardOutput(
sharedPreferences?.getString(key, "")
)
}
"other__draft_output" -> {
Config.get(context).setDraftOutput(
sharedPreferences?.getString(key, "")
)
}
}
}
override fun onResume() {
super.onResume()
preferenceScreen.sharedPreferences.registerOnSharedPreferenceChangeListener(this)
}
override fun onPause() {
super.onPause()
updateLauncherIconStatus()
preferenceScreen.sharedPreferences.unregisterOnSharedPreferenceChangeListener(this)
}
private fun updateLauncherIconStatus() {
// Set LauncherAlias enabled/disabled state just before destroying/pausing this activity
if (prefs.other.showAppIcon) {
showAppIcon(requireContext())
} else {
hideAppIcon(requireContext())
}
}
companion object {
private const val SETTINGS_ACTIVITY_NAME = "com.osfans.trime.PrefLauncherAlias"
fun hideAppIcon(context: Context) {
val pkg: PackageManager = context.packageManager
pkg.setComponentEnabledSetting(
ComponentName(context, SETTINGS_ACTIVITY_NAME),
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP
)
}
fun showAppIcon(context: Context) {
val pkg: PackageManager = context.packageManager
pkg.setComponentEnabledSetting(
ComponentName(context, SETTINGS_ACTIVITY_NAME),
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP
)
}
}
}
| gpl-3.0 | ab35553cb053b001a391804b18f16d1e | 34.584071 | 104 | 0.633922 | 5.318783 | false | false | false | false |
blastrock/kaqui | app/src/main/java/org/kaqui/model/Database.kt | 1 | 25515 | package org.kaqui.model
import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.graphics.Path
import android.util.Log
import androidx.core.database.sqlite.transaction
import org.kaqui.LocaleManager
import org.kaqui.asUnicodeCodePoint
import org.kaqui.roundToPreviousDay
import java.util.*
import kotlin.collections.HashSet
class Database private constructor(context: Context, private val database: SQLiteDatabase) {
private val locale: String get() = LocaleManager.getDictionaryLocale()
init {
// the app can be restored from android without going through the main activity,
// we need a locale here though and we can't try to fetch it every time we need it
if (!LocaleManager.isReady())
LocaleManager.updateDictionaryLocale(context)
}
fun getHiraganaView(knowledgeType: KnowledgeType? = null) =
LearningDbView(database, KANAS_TABLE_NAME, knowledgeType, filter = "$KANAS_TABLE_NAME.id BETWEEN ${HiraganaRange.first} AND ${HiraganaRange.last}", itemGetter = this::getKana)
fun getKatakanaView(knowledgeType: KnowledgeType? = null) =
LearningDbView(database, KANAS_TABLE_NAME, knowledgeType, filter = "$KANAS_TABLE_NAME.id BETWEEN ${KatakanaRange.first} AND ${KatakanaRange.last}", itemGetter = this::getKana)
fun getKanjiView(knowledgeType: KnowledgeType? = null, classifier: Classifier? = null): LearningDbView =
LearningDbView(database, KANJIS_TABLE_NAME, knowledgeType, filter = "radical = 0", classifier = classifier, itemGetter = this::getKanji, itemSearcher = this::searchKanji)
fun getWordView(knowledgeType: KnowledgeType? = null, classifier: Classifier? = null, withKanaAlone: Boolean = true): LearningDbView =
LearningDbView(database, WORDS_TABLE_NAME, knowledgeType, classifier = classifier, itemGetter = this::getWord, itemSearcher = this::searchWord, filter = if (!withKanaAlone) "kana_alone = 0" else "1")
fun getOtherCompositionAnswerIds(kanjiId: Int): List<Int> {
database.rawQuery("""
SELECT c3.id_kanji2
FROM $KANJIS_COMPOSITION_TABLE_NAME c1
JOIN $KANJIS_COMPOSITION_TABLE_NAME c2 ON c1.id_kanji2 = c2.id_kanji2
JOIN $KANJIS_TABLE_NAME k2 ON c2.id_kanji1 = k2.id AND k2.enabled = 1
JOIN $KANJIS_COMPOSITION_TABLE_NAME c3 ON c2.id_kanji1 = c3.id_kanji1
WHERE c1.id_kanji1 = ?
UNION
SELECT c.id_kanji1
FROM $KANJIS_COMPOSITION_TABLE_NAME c
JOIN $KANJIS_TABLE_NAME k ON c.id_kanji1 = k.id AND k.enabled = 1
WHERE c.id_kanji2 = ?
""", arrayOf(kanjiId.toString(), kanjiId.toString())).use { cursor ->
val ret = mutableListOf<Int>()
while (cursor.moveToNext()) {
ret.add(cursor.getInt(0))
}
return ret
}
}
fun getSimilarCompositionAnswerIds(kanjiId: Int): List<Int> {
database.rawQuery("""
SELECT DISTINCT c.id_kanji2
FROM $SIMILAR_ITEMS_TABLE_NAME s
JOIN $KANJIS_TABLE_NAME sk ON s.id_item2 = sk.id AND sk.enabled = 1
JOIN $KANJIS_COMPOSITION_TABLE_NAME c ON c.id_kanji1 = s.id_item2
WHERE s.id_item1 = ?
""", arrayOf(kanjiId.toString())).use { cursor ->
val ret = mutableListOf<Int>()
while (cursor.moveToNext()) {
ret.add(cursor.getInt(0))
}
return ret
}
}
private fun searchKanji(text: String): List<Int> {
val firstCodePoint =
if (text.isNotEmpty())
text.codePointAt(0).toString()
else
""
database.rawQuery(
"""SELECT id
FROM $KANJIS_TABLE_NAME
WHERE (id = ? OR on_readings LIKE ? OR kun_readings LIKE ? OR (meanings_$locale <> '' AND meanings_$locale LIKE ? OR meanings_$locale == '' AND meanings_en LIKE ?)) AND radical = 0""",
arrayOf(firstCodePoint, "%$text%", "%$text%", "%$text%", "%$text%")).use { cursor ->
val ret = mutableListOf<Int>()
while (cursor.moveToNext()) {
ret.add(cursor.getInt(0))
}
return ret
}
}
private fun searchWord(text: String): List<Int> {
database.rawQuery(
"""SELECT id
FROM $WORDS_TABLE_NAME
WHERE item LIKE ? OR reading LIKE ? OR (meanings_$locale <> '' AND meanings_$locale LIKE ? OR meanings_$locale == '' AND meanings_en LIKE ?)""",
arrayOf("%$text%", "%$text%", "%$text%", "%$text%")).use { cursor ->
val ret = mutableListOf<Int>()
while (cursor.moveToNext()) {
ret.add(cursor.getInt(0))
}
return ret
}
}
fun getStrokes(id: Int): List<Path> {
val strokes = mutableListOf<Path>()
database.query(ITEM_STROKES_TABLE_NAME, arrayOf("path"), "id_item = ?", arrayOf(id.toString()), null, null, "ordinal").use { cursor ->
val PathParser = Class.forName("androidx.core.graphics.PathParser")
val createPathFromPathData = PathParser.getMethod("createPathFromPathData", String::class.java)
while (cursor.moveToNext()) {
strokes.add(createPathFromPathData.invoke(null, cursor.getString(0)) as Path)
}
}
return strokes
}
private fun getOnClause(knowledgeType: KnowledgeType?) =
if (knowledgeType != null)
" AND s.type = ${knowledgeType.value} "
else
""
private fun getKana(id: Int, knowledgeType: KnowledgeType?): Item {
val similarities = mutableListOf<Item>()
database.query(SIMILAR_ITEMS_TABLE_NAME, arrayOf("id_item2"), "id_item1 = ?", arrayOf(id.toString()), null, null, null).use { cursor ->
while (cursor.moveToNext())
similarities.add(Item(cursor.getInt(0), Kana("", "", "", listOf()), 0.0, 0.0, 0, false))
}
val contents = Kana("", "", "", similarities)
val item = Item(id, contents, 0.0, 0.0, 0, false)
database.rawQuery("""
SELECT romaji, MAX(ifnull(short_score, 0.0)), MAX(ifnull(long_score, 0.0)), ifnull(last_correct, 0), enabled, unique_romaji
FROM $KANAS_TABLE_NAME k
LEFT JOIN $ITEM_SCORES_TABLE_NAME s ON k.id = s.id ${getOnClause(knowledgeType)}
WHERE k.id = $id
GROUP BY k.id
""", null).use { cursor ->
if (cursor.count == 0)
throw RuntimeException("Can't find kana with id $id")
cursor.moveToFirst()
contents.kana = id.asUnicodeCodePoint()
contents.romaji = cursor.getString(0)
contents.uniqueRomaji = cursor.getString(5)
item.shortScore = cursor.getDouble(1)
item.longScore = cursor.getDouble(2)
item.lastAsked = cursor.getLong(3)
item.enabled = cursor.getInt(4) != 0
}
return item
}
fun getKanji(id: Int, knowledgeType: KnowledgeType?): Item {
val similarities = mutableListOf<Item>()
database.query(SIMILAR_ITEMS_TABLE_NAME, arrayOf("id_item2"), "id_item1 = ?", arrayOf(id.toString()), null, null, null).use { cursor ->
while (cursor.moveToNext())
similarities.add(Item(cursor.getInt(0), Kanji("", listOf(), listOf(), listOf(), listOf(), listOf(), 0), 0.0, 0.0, 0, false))
}
val parts = mutableListOf<Item>()
database.query(KANJIS_COMPOSITION_TABLE_NAME, arrayOf("id_kanji2"), "id_kanji1 = ?", arrayOf(id.toString()), null, null, null).use { cursor ->
while (cursor.moveToNext())
parts.add(Item(cursor.getInt(0), Kanji("", listOf(), listOf(), listOf(), listOf(), listOf(), 0), 0.0, 0.0, 0, false))
}
val contents = Kanji("", listOf(), listOf(), listOf(), similarities, parts, 0)
val item = Item(id, contents, 0.0, 0.0, 0, false)
database.rawQuery("""
SELECT jlpt_level, MAX(ifnull(short_score, 0.0)), MAX(ifnull(long_score, 0.0)), ifnull(last_correct, 0), enabled, on_readings, kun_readings, meanings_$locale, meanings_en
FROM $KANJIS_TABLE_NAME k
LEFT JOIN $ITEM_SCORES_TABLE_NAME s ON k.id = s.id ${getOnClause(knowledgeType)}
WHERE k.id = $id
GROUP BY k.id
""", null).use { cursor ->
if (cursor.count == 0)
throw RuntimeException("Can't find kanji with id $id")
cursor.moveToFirst()
contents.kanji = id.asUnicodeCodePoint()
contents.on_readings = cursor.getString(5).split('_')
contents.kun_readings = cursor.getString(6).split('_')
val localMeaning = cursor.getString(7)
if (localMeaning != "")
contents.meanings = localMeaning.split('_')
else
contents.meanings = cursor.getString(8).split('_')
contents.jlptLevel = cursor.getInt(0)
item.shortScore = cursor.getDouble(1)
item.longScore = cursor.getDouble(2)
item.lastAsked = cursor.getLong(3)
item.enabled = cursor.getInt(4) != 0
}
return item
}
fun getWord(id: Int, knowledgeType: KnowledgeType?): Item {
val contents = Word("", "", listOf(), listOf(), false)
val item = Item(id, contents, 0.0, 0.0, 0, false)
var similarityClass = 0
database.rawQuery("""
SELECT item, reading, meanings_$locale, MAX(ifnull(short_score, 0.0)), MAX(ifnull(long_score, 0.0)), ifnull(last_correct, 0), enabled, similarity_class, meanings_en, kana_alone
FROM $WORDS_TABLE_NAME k
LEFT JOIN $ITEM_SCORES_TABLE_NAME s ON k.id = s.id ${getOnClause(knowledgeType)}
WHERE k.id = $id
GROUP BY k.id
""", null).use { cursor ->
if (cursor.count == 0)
throw RuntimeException("Can't find word with id $id")
cursor.moveToFirst()
contents.word = cursor.getString(0)
contents.reading = cursor.getString(1)
val localMeaning = cursor.getString(2)
if (localMeaning != "")
contents.meanings = localMeaning.split('_')
else
contents.meanings = cursor.getString(8).split('_')
contents.kanaAlone = cursor.getInt(9) != 0
item.shortScore = cursor.getDouble(3)
item.longScore = cursor.getDouble(4)
item.lastAsked = cursor.getLong(5)
item.enabled = cursor.getInt(6) != 0
similarityClass = cursor.getInt(7)
}
val similarWords = mutableListOf<Item>()
database.query(WORDS_TABLE_NAME, arrayOf("id"),
"similarity_class = ? AND id <> ?", arrayOf(similarityClass.toString(), id.toString()),
null, null, "RANDOM()", "20").use { cursor ->
while (cursor.moveToNext())
similarWords.add(Item(cursor.getInt(0), Word("", "", listOf(), listOf(), false), 0.0, 0.0, 0, false))
}
contents.similarities = similarWords
return item
}
fun setKanjiSelection(kanjis: String) {
database.transaction {
val cv = ContentValues()
cv.put("enabled", true)
for (i in 0 until kanjis.codePointCount(0, kanjis.length)) {
database.update(KANJIS_TABLE_NAME, cv, "id = ?", arrayOf(kanjis.codePointAt(i).toString()))
}
}
}
fun setWordSelection(wordsString: String) {
val words = wordsString.split("\n")
database.transaction {
val cv = ContentValues()
cv.put("enabled", true)
for (word in words) {
val trimmedWord = word.trim()
database.update(WORDS_TABLE_NAME, cv, "item = ? OR (kana_alone = 1 AND reading = ?)", arrayOf(trimmedWord, trimmedWord))
}
}
}
fun autoSelectWords(classifier: Classifier? = null) {
val enabledKanjis = HashSet<Char>()
database.query(KANJIS_TABLE_NAME, arrayOf("id"), "enabled = 1", null, null, null, null).use { cursor ->
while (cursor.moveToNext()) {
enabledKanjis.add(Character.toChars(cursor.getInt(0))[0])
}
}
var allWords =
database.query(WORDS_TABLE_NAME, arrayOf("id, item"), classifier?.whereClause(), classifier?.whereArguments(), null, null, null).use { cursor ->
val ret = mutableListOf<Pair<Long, String>>()
while (cursor.moveToNext()) {
ret.add(Pair(cursor.getLong(0), cursor.getString(1)))
}
ret.toList()
}
allWords = allWords.map { Pair(it.first, it.second.filter { isKanji(it) }) }
allWords = allWords.filter { it.second.all { it in enabledKanjis } }
database.transaction {
val cv = ContentValues()
cv.put("enabled", false)
database.update(WORDS_TABLE_NAME, cv, classifier?.whereClause(), classifier?.whereArguments())
cv.put("enabled", true)
for (word in allWords) {
database.update(WORDS_TABLE_NAME, cv, "id = ?", arrayOf(word.first.toString()))
}
}
}
data class SavedSelection(
val id: Long,
val name: String,
val count: Int
)
fun listKanjiSelections(): List<SavedSelection> {
val out = mutableListOf<SavedSelection>()
database.rawQuery("""
SELECT id_selection, name, (
SELECT COUNT(*)
FROM $KANJIS_ITEM_SELECTION_TABLE_NAME ss WHERE ss.id_selection = s.id_selection
)
FROM $KANJIS_SELECTION_TABLE_NAME s
""", arrayOf()).use { cursor ->
while (cursor.moveToNext())
out.add(SavedSelection(cursor.getLong(0), cursor.getString(1), cursor.getInt(2)))
}
return out
}
fun saveKanjiSelectionTo(name: String) {
database.transaction {
val idSelection = database.query(KANJIS_SELECTION_TABLE_NAME, arrayOf("id_selection"), "name = ?", arrayOf(name), null, null, null).use { cursor ->
if (cursor.count == 0) {
val cv = ContentValues()
cv.put("name", name)
return@use database.insert(KANJIS_SELECTION_TABLE_NAME, null, cv)
} else {
cursor.moveToFirst()
return@use cursor.getInt(0)
}
}
database.delete(KANJIS_ITEM_SELECTION_TABLE_NAME, "id_selection = ?", arrayOf(idSelection.toString()))
database.execSQL("""
INSERT INTO $KANJIS_ITEM_SELECTION_TABLE_NAME (id_selection, id_kanji)
SELECT ?, id FROM $KANJIS_TABLE_NAME WHERE enabled = 1
""", arrayOf(idSelection.toString()))
}
}
fun restoreKanjiSelectionFrom(idSelection: Long) {
database.transaction {
database.execSQL("""
UPDATE $KANJIS_TABLE_NAME
SET enabled = 0
""")
database.execSQL("""
UPDATE $KANJIS_TABLE_NAME
SET enabled = 1
WHERE id IN (
SELECT id_kanji
FROM $KANJIS_ITEM_SELECTION_TABLE_NAME
WHERE id_selection = ?
)
""", arrayOf(idSelection.toString()))
}
}
fun deleteKanjiSelection(idSelection: Long) {
database.transaction {
database.delete(KANJIS_ITEM_SELECTION_TABLE_NAME, "id_selection = ?", arrayOf(idSelection.toString()))
database.delete(KANJIS_SELECTION_TABLE_NAME, "id_selection = ?", arrayOf(idSelection.toString()))
}
}
fun listWordSelections(): List<SavedSelection> {
val out = mutableListOf<SavedSelection>()
database.rawQuery("""
SELECT id_selection, name, (
SELECT COUNT(*)
FROM $WORDS_ITEM_SELECTION_TABLE_NAME ss WHERE ss.id_selection = s.id_selection
)
FROM $WORDS_SELECTION_TABLE_NAME s
""", arrayOf()).use { cursor ->
while (cursor.moveToNext())
out.add(SavedSelection(cursor.getLong(0), cursor.getString(1), cursor.getInt(2)))
}
return out
}
fun saveWordSelectionTo(name: String) {
database.transaction {
val idSelection = database.query(WORDS_SELECTION_TABLE_NAME, arrayOf("id_selection"), "name = ?", arrayOf(name), null, null, null).use { cursor ->
if (cursor.count == 0) {
val cv = ContentValues()
cv.put("name", name)
return@use database.insert(WORDS_SELECTION_TABLE_NAME, null, cv)
} else {
cursor.moveToFirst()
return@use cursor.getInt(0)
}
}
database.delete(WORDS_ITEM_SELECTION_TABLE_NAME, "id_selection = ?", arrayOf(idSelection.toString()))
database.execSQL("""
INSERT INTO $WORDS_ITEM_SELECTION_TABLE_NAME (id_selection, id_word)
SELECT ?, id FROM $WORDS_TABLE_NAME WHERE enabled = 1
""", arrayOf(idSelection.toString()))
}
}
fun restoreWordSelectionFrom(idSelection: Long) {
database.transaction {
database.execSQL("""
UPDATE $WORDS_TABLE_NAME
SET enabled = 0
""")
database.execSQL("""
UPDATE $WORDS_TABLE_NAME
SET enabled = 1
WHERE id IN (
SELECT id_word
FROM $WORDS_ITEM_SELECTION_TABLE_NAME
WHERE id_selection = ?
)
""", arrayOf(idSelection.toString()))
}
}
fun deleteWordSelection(idSelection: Long) {
database.transaction {
database.delete(WORDS_ITEM_SELECTION_TABLE_NAME, "id_selection = ?", arrayOf(idSelection.toString()))
database.delete(WORDS_SELECTION_TABLE_NAME, "id_selection = ?", arrayOf(idSelection.toString()))
}
}
private fun takeLastSnapshot(testTypes: List<TestType>) {
database.transaction {
val byItemAndKnowledge = testTypes.map { Pair(getItemType(it), getKnowledgeType(it)) }
byItemAndKnowledge.forEach { (itemType, knowledgeType) ->
val view = when (itemType) {
ItemType.Hiragana -> getHiraganaView(knowledgeType)
ItemType.Katakana -> getKatakanaView(knowledgeType)
ItemType.Kanji -> getKanjiView(knowledgeType)
ItemType.Word -> getWordView(knowledgeType)
}
val stats = view.getLongStats(knowledgeType)
val testTypesStr = itemAndKnowledgeTypeToTestType(itemType, knowledgeType).joinToString(",") { it.value.toString() }
// Get the last time the corresponding stats are updated so that we can make a snapshot for that date
var lastQuestion = database.query(SESSION_ITEMS_TABLE_NAME, arrayOf("MAX(time)"), "test_type IN ($testTypesStr)", null, null, null, null).use { cursor ->
cursor.moveToFirst()
cursor.getLong(0)
}
val calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
// If this is the first run, just take today
if (lastQuestion != 0L)
calendar.timeInMillis = lastQuestion * 1000
calendar.roundToPreviousDay()
lastQuestion = calendar.timeInMillis / 1000
Log.d(TAG, "Taking snapshot for $itemType $knowledgeType, last question was $lastQuestion")
val cv = ContentValues()
cv.put("item_type", itemType.value)
cv.put("knowledge_type", knowledgeType.value)
cv.put("time", lastQuestion / 3600 / 24 * 3600 * 24)
cv.put("good_count", stats.good)
cv.put("meh_count", stats.meh)
cv.put("bad_count", stats.bad)
cv.put("long_score_sum", stats.longScoreSum)
cv.put("long_score_partition", stats.longPartition.joinToString(","))
// If multiple snapshots were taken for the same day, the last one is the most up to date, so we replace
database.insertWithOnConflict(STATS_SNAPSHOT_TABLE_NAME, null, cv, SQLiteDatabase.CONFLICT_REPLACE)
}
}
}
fun initSession(itemType: ItemType, testTypes: List<TestType>): Long {
takeLastSnapshot(testTypes)
val cv = ContentValues()
cv.put("item_type", itemType.value)
cv.put("test_types", testTypes.joinToString(",") { it.value.toString() })
cv.put("start_time", Calendar.getInstance().timeInMillis / 1000)
return database.insertOrThrow(SESSIONS_TABLE_NAME, null, cv)
}
private fun commitAllSessions() {
// Delete empty sessions
val emptySessions = mutableListOf<Long>()
database.rawQuery("""
SELECT s.id
FROM $SESSIONS_TABLE_NAME s
LEFT JOIN $SESSION_ITEMS_TABLE_NAME si ON si.id_session = s.id
WHERE si.id_session IS NULL
""", arrayOf()).use { cursor ->
while (cursor.moveToNext())
emptySessions.add(cursor.getLong(0))
}
database.delete(SESSIONS_TABLE_NAME, "id in (${emptySessions.joinToString(",")})", null)
// Update end_time and item_count for all not committed sessions
database.transaction {
val openSessions = mutableListOf<Long>()
database.query(SESSIONS_TABLE_NAME, arrayOf("id"), "end_time IS NULL", null, null, null, null).use { cursor ->
while (cursor.moveToNext())
openSessions.add(cursor.getLong(0))
}
data class Session(val id: Long, val totalCount: Int, val correctCount: Int, val endTime: Long)
val sessions = mutableListOf<Session>()
database.query(
SESSION_ITEMS_TABLE_NAME,
arrayOf("id_session, COUNT(*), MAX(time), SUM(CASE WHEN certainty != ${Certainty.DONTKNOW.value} THEN 1 ELSE 0 END)"),
"id_session IN (${openSessions.joinToString(",")})",
null,
"id_session", null, null).use { cursor ->
while (cursor.moveToNext())
sessions.add(Session(cursor.getLong(0), cursor.getInt(1), cursor.getInt(3), cursor.getLong(2)))
}
for (session in sessions) {
val cv = ContentValues()
cv.put("item_count", session.totalCount)
cv.put("correct_count", session.correctCount)
cv.put("end_time", session.endTime)
database.update(SESSIONS_TABLE_NAME, cv, "id = ?", arrayOf(session.id.toString()))
}
}
}
data class DayStatistics(val timestamp: Long, val askedCount: Int, val correctCount: Int)
fun getAskedItem(): List<DayStatistics> {
commitAllSessions()
val stats = mutableListOf<DayStatistics>()
database.query(SESSIONS_TABLE_NAME, arrayOf("start_time", "item_count", "correct_count"), null, null, null, null, "start_time").use { cursor ->
while (cursor.moveToNext())
stats.add(DayStatistics(cursor.getLong(0), cursor.getInt(1), cursor.getInt(2)))
}
return stats
}
companion object {
private const val TAG = "Database"
const val DATABASE_NAME = "kanjis"
const val KANAS_TABLE_NAME = "kanas"
const val KANJIS_TABLE_NAME = "kanjis"
const val KANJIS_COMPOSITION_TABLE_NAME = "kanjis_composition"
const val SIMILAR_ITEMS_TABLE_NAME = "similar_items"
const val ITEM_STROKES_TABLE_NAME = "item_strokes"
const val ITEM_SCORES_TABLE_NAME = "item_scores"
const val SESSIONS_TABLE_NAME = "sessions"
const val SESSION_ITEMS_TABLE_NAME = "session_items"
const val STATS_SNAPSHOT_TABLE_NAME = "stats_snapshots"
const val KANJIS_SELECTION_TABLE_NAME = "kanjis_selection"
const val KANJIS_ITEM_SELECTION_TABLE_NAME = "kanjis_item_selection"
const val WORDS_SELECTION_TABLE_NAME = "word_selection"
const val WORDS_ITEM_SELECTION_TABLE_NAME = "word_item_selection"
const val WORDS_TABLE_NAME = "words"
private var singleton: Database? = null
private fun isKanji(c: Char): Boolean {
// This is the hiragana/katakana range
return c.code !in 0x3040..0x3100
}
fun getInstance(context: Context): Database {
if (singleton == null) {
val db = SQLiteDatabase.openDatabase(context.getDatabasePath(DATABASE_NAME).absolutePath, null, SQLiteDatabase.OPEN_READWRITE)
singleton = Database(context, db)
}
return singleton!!
}
}
}
| mit | ad20f01021434aa4b7c344f5a9f5dfe4 | 44.481283 | 211 | 0.571899 | 4.275302 | false | false | false | false |
bropane/Job-Seer | app/src/main/java/com/taylorsloan/jobseer/data/job/repo/sources/DataSourceFactory.kt | 1 | 4117 | package com.taylorsloan.jobseer.data.job.repo.sources
import com.jakewharton.rxrelay2.BehaviorRelay
import com.taylorsloan.jobseer.data.DataModule
import com.taylorsloan.jobseer.data.DataModuleImpl
import com.taylorsloan.jobseer.data.common.AppDatabase
import com.taylorsloan.jobseer.data.common.model.DataResult
import com.taylorsloan.jobseer.data.job.util.JobMapper
import com.taylorsloan.jobseer.domain.job.models.Job
import io.reactivex.BackpressureStrategy
import io.reactivex.Flowable
import io.reactivex.disposables.Disposable
import timber.log.Timber
import javax.inject.Inject
/**
* Data source wrapper for jobs being returned from local or online sources
* Created by taylorsloan on 10/28/17.
*/
class DataSourceFactory(dataModule: DataModule) : DataSource {
@Inject
lateinit var appDb : AppDatabase
private val localDataStore : DataSource = LocalDataSource(dataModule)
private val cloudDataStore : DataSource = CloudDataSource(dataModule)
private var localJobsDisposable : Disposable? = null
private val subject: BehaviorRelay<DataResult<List<Job>>> = BehaviorRelay.create()
private var previousSearchParams : SearchParams? = null
private data class SearchParams(val description: String? = null,
val location: String? = null,
val lat: Double? = null,
val long: Double? = null,
val fullTime: Boolean? = null,
val saved: Boolean? = null)
init {
DataModuleImpl.storageComponent().inject(this)
}
override fun jobs(description: String?,
location: String?,
lat: Double?,
long: Double?,
fullTime: Boolean?,
page: Int,
saved: Boolean?): Flowable<DataResult<List<Job>>> {
val searchParams = SearchParams(description, location, lat, long, fullTime, saved)
if (previousSearchParams?.hashCode() != searchParams.hashCode()){
localJobsDisposable?.dispose()
localJobsDisposable = localDataStore
.jobs(description, location, lat, long, fullTime, page, saved)
.subscribe(subject)
}
previousSearchParams = searchParams
return subject.toFlowable(BackpressureStrategy.BUFFER)
}
fun getMoreJobs(page: Int) {
previousSearchParams?.let {
cloudDataStore.jobs(it.description, it.location, it.lat, it.long, it.fullTime, page)
.doOnNext{
it.data?.let {
appDb.jobDao().insertJobs(JobMapper.mapDomainListToLocal(it))
}
}
.subscribe(
{
Timber.d("Received Jobs: %s", it.data?.size.toString())
subject.accept(DataResult(loading = false))
},
{
Timber.e(it)
subject.accept(DataResult(error = it))
}
)
}
}
override fun job(id: String): Flowable<DataResult<Job>> {
cloudDataStore.job(id)
.subscribe(
{
it.data?.let {
appDb.jobDao().insertJob(JobMapper.mapToLocal(it))
}
},
{
Timber.e(it)
}
)
return localDataStore.job(id)
}
override fun savedJobs(description: String?,
location: String?,
fullTime: Boolean?): Flowable<DataResult<List<Job>>> {
return localDataStore.savedJobs(description, location, fullTime)
}
override fun clearJobs() {
localDataStore.clearJobs()
}
} | mit | 7406ec489b5d969ddc4d11389ba1a656 | 37.12963 | 96 | 0.542871 | 5.305412 | false | false | false | false |
EMResearch/EvoMaster | core/src/main/kotlin/org/evomaster/core/search/gene/collection/ArrayGene.kt | 1 | 12593 | package org.evomaster.core.search.gene.collection
import org.evomaster.core.logging.LoggingUtil
import org.evomaster.core.output.OutputFormat
import org.evomaster.core.search.gene.*
import org.evomaster.core.search.gene.interfaces.CollectionGene
import org.evomaster.core.search.gene.optional.OptionalGene
import org.evomaster.core.search.gene.placeholder.CycleObjectGene
import org.evomaster.core.search.gene.placeholder.LimitObjectGene
import org.evomaster.core.search.gene.root.CompositeGene
import org.evomaster.core.search.gene.utils.GeneUtils
import org.evomaster.core.search.impact.impactinfocollection.ImpactUtils
import org.evomaster.core.search.service.AdaptiveParameterControl
import org.evomaster.core.search.service.Randomness
import org.evomaster.core.search.service.mutator.MutationWeightControl
import org.evomaster.core.search.service.mutator.genemutation.AdditionalGeneMutationInfo
import org.evomaster.core.search.service.mutator.genemutation.SubsetGeneMutationSelectionStrategy
import org.slf4j.Logger
import org.slf4j.LoggerFactory
/**
* A representation of typical array, for a fixed type T, ie, no mixed types are allowed here.
*/
class ArrayGene<T>(
/**
* The name of this gene
*/
name: String,
/**
* The type for this array. Every time we create a new element to add, it has to be based
* on this template.
*
* Note: here the template cannot be a KClass, because we might need to specify constraints on
* the template (eg ranges for numbers)
*/
val template: T,
/**
* How max elements to have in this array. Usually arrays are unbound, till the maximum int size (ie, 2 billion
* elements on the JVM). But, for search reasons, too large arrays are impractical
*
* note that null maxSize means that the maxSize is not restricted,
* then we employ the default max size [MAX_SIZE] for handling mutation and randomizing values
*/
var maxSize: Int? = null,
var minSize: Int? = null,
/**
* The actual elements in the array, based on the template. Ie, usually those elements will be clones
* of the templated, and then mutated/randomized
*
* Man: change var to val to maintain list reference as its children
*
*/
elements: MutableList<T> = mutableListOf(),
private val openingTag : String = "[",
private val closingTag : String = "]",
private val separatorTag : String = ", "
) : CollectionGene, CompositeGene(name, elements)
where T : Gene {
protected val elements : List<T>
get() = children as List<T>
init {
if(template is CycleObjectGene || template is LimitObjectGene){
minSize = 0
maxSize = 0
killAllChildren()
}
if (minSize != null && maxSize != null && minSize!! > maxSize!!){
throw IllegalArgumentException(
"ArrayGene "+name+": minSize (${minSize}) is greater than maxSize ($maxSize)") }
if (maxSize != null && elements.size > maxSize!!) {
throw IllegalArgumentException(
"ArrayGene "+name+": More elements (${elements.size}) than allowed ($maxSize)")
}
if(initialized && elements.any { !it.initialized }){
throw IllegalArgumentException("Creating array marked as initialized but at least one child is not")
}
}
companion object{
val log : Logger = LoggerFactory.getLogger(ArrayGene::class.java)
const val MAX_SIZE = 5
}
fun forceToOnlyEmpty(){
maxSize = 0
killAllChildren()
}
override fun isLocallyValid() : Boolean{
return elements.size >= (minSize ?: 0) && elements.size <= (maxSize ?: Int.MAX_VALUE)
&& elements.all { it.isLocallyValid() }
}
override fun copyContent(): Gene {
val copy = ArrayGene(
name,
template.copy() as T,
maxSize,
minSize,
elements.map { e -> e.copy() as T }.toMutableList(),
openingTag = openingTag,
closingTag = closingTag,
separatorTag = separatorTag
)
if (copy.children.size!=this.children.size) {
throw IllegalStateException("copy and its template have different size of children, e.g., copy (${copy.children.size}) vs. template (${this.children.size})")
}
return copy
}
override fun copyValueFrom(other: Gene) {
if (other !is ArrayGene<*>) {
throw IllegalArgumentException("Invalid gene type ${other.javaClass}")
}
killAllChildren()
// check maxSize
val elements = (if(maxSize!= null && other.elements.size > maxSize!!) other.elements.subList(0, maxSize!!) else other.elements).map { e -> e.copy() as T }.toMutableList()
// build parents for [element]
addChildren(elements)
}
override fun containsSameValueAs(other: Gene): Boolean {
if (other !is ArrayGene<*>) {
throw IllegalArgumentException("Invalid gene type ${other.javaClass}")
}
return this.elements.zip(other.elements) { thisElem, otherElem ->
thisElem.containsSameValueAs(otherElem)
}.all { it }
}
override fun isMutable(): Boolean {
/*
if maxSize is 0, then array cannot be mutated, as it will always be empty.
If it is greater than 0, it can always be mutated, regardless of whether the
elements can be mutated: we can mutate between empty and 1-element arrays
*/
return getMaxSizeOrDefault() > 0
// it is not mutable if the size could not be changed and none of the element is mutable
&& (!(getMinSizeOrDefault() == getMaxSizeOrDefault() && elements.size == getMinSizeOrDefault() && elements.none { it.isMutable() }))
}
override fun randomize(randomness: Randomness, tryToForceNewValue: Boolean) {
if(maxSize == 0){
return
}
//maybe not so important here to complicate code to enable forceNewValue
killAllChildren()
log.trace("Randomizing ArrayGene")
val n = randomness.nextInt(getMinSizeOrDefault(), getMaxSizeUsedInRandomize())
repeat(n) {
val gene = template.copy() as T
if(this.initialized){
gene.doInitialize(randomness)
} else if(gene.isMutable()) {
gene.randomize(randomness, false)
}
addChild(gene)
}
assert(minSize==null || (minSize!! <= elements.size))
assert(maxSize==null || (elements.size <= maxSize!!))
}
override fun customShouldApplyShallowMutation(
randomness: Randomness,
selectionStrategy: SubsetGeneMutationSelectionStrategy,
enableAdaptiveGeneMutation: Boolean,
additionalGeneMutationInfo: AdditionalGeneMutationInfo?
) : Boolean {
//shallow mutation changes the size
// if min == max, the size is not mutable
if(getMinSizeOrDefault() == getMaxSizeOrDefault() && elements.size == getMinSizeOrDefault()){
return false
}
val p = probabilityToModifySize(selectionStrategy, additionalGeneMutationInfo?.impact)
return randomness.nextBoolean(p)
}
override fun adaptiveSelectSubsetToMutate(randomness: Randomness, internalGenes: List<Gene>, mwc: MutationWeightControl, additionalGeneMutationInfo: AdditionalGeneMutationInfo): List<Pair<Gene, AdditionalGeneMutationInfo?>> {
/*
element is dynamically modified, then we do not collect impacts for it now.
thus for the internal genes, adaptive gene selection for mutation is not applicable
*/
val s = randomness.choose(internalGenes)
/*
TODO impact for an element in ArrayGene
*/
return listOf(s to additionalGeneMutationInfo.copyFoInnerGene(ImpactUtils.createGeneImpact(s, s.name), s))
}
/**
* leaf mutation for arrayGene is size mutation, i.e., 'remove' or 'add'
*/
override fun shallowMutate(randomness: Randomness, apc: AdaptiveParameterControl, mwc: MutationWeightControl, selectionStrategy: SubsetGeneMutationSelectionStrategy, enableAdaptiveGeneMutation: Boolean, additionalGeneMutationInfo: AdditionalGeneMutationInfo?) : Boolean{
if(elements.size < getMaxSizeOrDefault() && (elements.size == getMinSizeOrDefault() || elements.isEmpty() || randomness.nextBoolean())){
val gene = template.copy() as T
gene.doInitialize(randomness)
addElement(gene)
}else{
log.trace("Removing gene in mutation")
val removed = killChildByIndex(randomness.nextInt(elements.size)) as T
// remove binding if any other bound with
removed.removeThisFromItsBindingGenes()
}
return true
}
override fun getValueAsPrintableString(previousGenes: List<Gene>, mode: GeneUtils.EscapeMode?, targetFormat: OutputFormat?, extraCheck: Boolean): String {
return openingTag +
elements.map { g ->
if (GeneUtils.isGraphQLModes(mode)) {
if (g is EnumGene<*> || (g is OptionalGene && g.gene is EnumGene<*>))
g.getValueAsRawString() else {
g.getValueAsPrintableString(previousGenes, mode, targetFormat)
}
} else {
g.getValueAsPrintableString(previousGenes, mode, targetFormat)
}
}.joinToString(separatorTag) +
closingTag
}
/**
* 1 is for 'remove' or 'add' element
*/
override fun mutationWeight(): Double {
return 1.0 + elements.map { it.mutationWeight() }.sum()
}
/*
Note that value binding cannot be performed on the [elements]
TODO might bind based on value instead of replacing them
*/
override fun bindValueBasedOn(gene: Gene): Boolean {
if(gene is ArrayGene<*> && gene.template::class.java.simpleName == template::class.java.simpleName){
killAllChildren()
val elements = gene.elements.mapNotNull { it.copy() as? T}.toMutableList()
addChildren(elements)
return true
}
LoggingUtil.uniqueWarn(
log,
"cannot bind ArrayGene with the template (${template::class.java.simpleName}) with ${gene::class.java.simpleName}"
)
return false
}
/**
* remove an existing element [element] from [elements]
*/
fun removeExistingElement(element: T){
//this is a reference heap check, not based on `equalsTo`
if (elements.contains(element)){
killChild(element)
element.removeThisFromItsBindingGenes()
}else{
log.warn("the specified element (${if (element.isPrintable()) element.getValueAsPrintableString() else "not printable"})) does not exist in this array")
}
}
/**
* add an element [element] to [elements]
*/
fun addElement(element: T){
checkConstraintsForAdd()
addChild(element)
}
/**
* add an element [element] to [elements],
* if the [element] does not conform with the [template], the addition could fail
*
* @return whether the element could be added into this elements
*
*/
fun addElement(element: Gene) : Boolean{
element as? T ?: return false
checkConstraintsForAdd()
addChild(element)
return true
}
fun getViewOfElements() = elements.toList()
override fun isEmpty(): Boolean {
return elements.isEmpty()
}
override fun getSpecifiedMaxSize() = maxSize
override fun getSpecifiedMinSize() = minSize
override fun getGeneName() = name
override fun getSizeOfElements(filterMutable: Boolean): Int {
if (!filterMutable) return elements.size
return elements.count { it.isMutable() }
}
override fun getMaxSizeOrDefault() = maxSize?: getDefaultMaxSize()
override fun getMinSizeOrDefault() = minSize?: 0
override fun getDefaultMaxSize() = (if (getMinSizeOrDefault() >= MAX_SIZE) (getMinSizeOrDefault() + MAX_SIZE) else MAX_SIZE)
override fun isPrintable(): Boolean {
return getViewOfChildren().all { it.isPrintable() }
}
} | lgpl-3.0 | e7dbaf078f317f8c8b8c746c2d9dc1ca | 37.631902 | 274 | 0.6317 | 4.89619 | false | false | false | false |
BlueBoxWare/LibGDXPlugin | src/main/kotlin/com/gmail/blueboxware/libgdxplugin/filetypes/skin/psi/SkinFile.kt | 1 | 1779 | package com.gmail.blueboxware.libgdxplugin.filetypes.skin.psi
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
/*
* Copyright 2016 Blue Box Ware
*
* 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.
*/
interface SkinFile : SkinElement, PsiFile {
fun getClassSpecifications(
classNames: Collection<String>? = null
): Collection<SkinClassSpecification>
fun getClassSpecifications(
className: String,
): Collection<SkinClassSpecification>
fun getResources(
classNames: Collection<String>?,
resourceName: String? = null,
beforeElement: PsiElement? = null
): Collection<SkinResource>
fun getResources(
className: String,
resourceName: String? = null,
beforeElement: PsiElement? = null
): Collection<SkinResource>
fun getResources(
resourceClass: PsiClass,
resourceName: String? = null,
beforeElement: PsiElement? = null,
includingSuperClasses: Boolean = false,
includeAll: Boolean = false,
): Collection<SkinResource>
fun addComment(comment: PsiComment)
fun replacePackage(className: String, oldPackage: String, newPackage: String)
}
| apache-2.0 | bbcd457f2df02415436e162e9ffb9908 | 30.210526 | 81 | 0.715008 | 4.573265 | false | false | false | false |
BlueBoxWare/LibGDXPlugin | src/test/testdata/inspections/nonExistingAsset/Test.kt | 1 | 3964 | import com.badlogic.gdx.graphics.g2d.TextureAtlas
import com.badlogic.gdx.scenes.scene2d.ui.Button
import com.badlogic.gdx.scenes.scene2d.ui.Skin
import com.badlogic.gdx.scenes.scene2d.ui.TextButton
import com.gmail.blueboxware.libgdxplugin.annotations.GDXAssets
import com.gmail.blueboxware.libgdxplugin.annotations.GDXTag
@GDXTag("kotlinTag1", "kotlinTag2")
class KotlinClass
@GDXAssets(skinFiles = arrayOf("src/libgdx.skin"), atlasFiles = arrayOf("src/dir/holo.atlas"))
val skin1 = Skin()
@GDXAssets(atlasFiles = ["src/dir/holo.atlas"])
val atlas = TextureAtlas()
val atlas2 = TextureAtlas()
val c1 = skin1.getColor("yellow")
val c2 = skin1.getColor(<error descr="Resource \"blue\" with type \"com.badlogic.gdx.graphics.Color\" does not exist in files \"libgdx.skin\", \"holo.atlas\" or \"libgdx.atlas\"">"blue"</error>)
val c3 = skin1.getColor(<error descr="Resource \"button\" with type \"com.badlogic.gdx.graphics.Color\" does not exist in files \"libgdx.skin\", \"holo.atlas\" or \"libgdx.atlas\"">"button"</error>)
val blue = ""
val c4 = skin1.getColor("$blue")
val c5 = skin1.getColor("${"blue"}")
fun f() {
@GDXAssets(skinFiles = arrayOf("src/libgdx.skin"))
val skin2 = Skin()
val skin3 = Skin()
skin1.get(<error descr="Resource \"kt1\" with type \"KotlinClass\" does not exist in files \"libgdx.skin\", \"holo.atlas\" or \"libgdx.atlas\"">"kt1"</error>, KotlinClass::class.java)
skin1.get("kt2", KotlinClass::class.java)
skin1.get(TextButton.TextButtonStyle::class.java)
skin3.get(TextButton.TextButtonStyle::class.java)
skin1.get(<error descr="Resource \"\" with type \"com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle\" does not exist in files \"libgdx.skin\", \"holo.atlas\" or \"libgdx.atlas\"">""</error>, TextButton.TextButtonStyle::class.java)
skin1.get("toggle", TextButton.TextButtonStyle::class.java)
val userred = ""
skin1.get("$userred", TextButton.TextButtonStyle::class.java)
skin1.get("${userred}", TextButton.TextButtonStyle::class.java)
skin1.get("${"userred"}", TextButton.TextButtonStyle::class.java)
skin1.get(<error descr="Resource \"user-red\" with type \"com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle\" does not exist in files \"libgdx.skin\", \"holo.atlas\" or \"libgdx.atlas\"">"user-red"</error>, TextButton.TextButtonStyle::class.java)
skin1.get("taggedStyle1", TextButton.TextButtonStyle::class.java)
skin1.get(<error descr="Resource \"taggedStyle2\" with type \"com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle\" does not exist in files \"libgdx.skin\", \"holo.atlas\" or \"libgdx.atlas\"">"taggedStyle2"</error>, TextButton.TextButtonStyle::class.java)
skin1.get("user-red", Skin.TintedDrawable::class.java)
skin1.getDrawable("button-left")
skin1.getDrawable("user-red")
skin3.getDrawable("user-red")
skin1.getRegion("button-left")
skin1.getRegion(<error descr="Resource \"green\" with type \"com.badlogic.gdx.graphics.g2d.TextureRegion\" does not exist in files \"libgdx.skin\", \"holo.atlas\" or \"libgdx.atlas\"">"green"</error>)
skin1.get("taggedStyle2", Button.ButtonStyle::class.java)
skin1.get(<error descr="Resource \"taggedStyle1\" with type \"com.badlogic.gdx.scenes.scene2d.ui.Button.ButtonStyle\" does not exist in files \"libgdx.skin\", \"holo.atlas\" or \"libgdx.atlas\"">"taggedStyle1"</error>, Button.ButtonStyle::class.java)
@Suppress("GDXKotlinNonExistingAsset")
skin1.get("taggedStyle1", Button.ButtonStyle::class.java)
atlas.findRegion("button-left")
atlas2.findRegion("button-left")
atlas.findRegion(<error descr="Resource \"button-foo\" with type \"com.badlogic.gdx.graphics.g2d.TextureRegion\" does not exist in file \"holo.atlas\"">"button-foo"</error>)
skin2.getRegion("button-back-disabled")
skin2.getRegion(<error descr="Resource \"toolbar\" with type \"com.badlogic.gdx.graphics.g2d.TextureRegion\" does not exist in files \"libgdx.skin\" or \"libgdx.atlas\"">"toolbar"</error>)
} | apache-2.0 | 9df0b964681f47ffc722909bf5ae1adf | 61.936508 | 268 | 0.734107 | 3.492511 | false | false | false | false |
savoirfairelinux/ring-client-android | ring-android/app/src/main/java/cx/ring/settings/pluginssettings/PathListAdapter.kt | 1 | 3274 | /*
* Copyright (C) 2004-2021 Savoir-faire Linux Inc.
*
* Author: Aline Gondim Santos <[email protected]>
* Author: Adrien Béraud <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package cx.ring.settings.pluginssettings
import android.graphics.drawable.Drawable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import cx.ring.R
import cx.ring.utils.AndroidFileUtils
import java.io.File
class PathListAdapter internal constructor(
private var mList: List<String>,
private val mListener: PathListItemListener
) : RecyclerView.Adapter<PathListAdapter.PathViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PathViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.frag_path_list_item, parent, false)
return PathViewHolder(view, mListener)
}
override fun onBindViewHolder(holder: PathViewHolder, position: Int) {
holder.setDetails(mList[position])
}
override fun getItemCount(): Int {
return mList.size
}
fun updatePluginsList(listPaths: List<String>) {
mList = listPaths
notifyDataSetChanged()
}
inner class PathViewHolder(itemView: View, listener: PathListItemListener) : RecyclerView.ViewHolder(itemView) {
private val pathIcon: ImageView = itemView.findViewById(R.id.path_item_icon)
private val pathTextView: TextView = itemView.findViewById(R.id.path_item_name)
private var path: String? = null
// update the viewHolder view
fun update(s: String) {
// Set the plugin icon
val file = File(s)
if (file.exists()) {
if (AndroidFileUtils.isImage(s)) {
pathTextView.visibility = View.GONE
Drawable.createFromPath(s)?.let { icon -> pathIcon.setImageDrawable(icon) }
} else {
pathTextView.visibility = View.VISIBLE
pathTextView.text = file.name
}
}
}
fun setDetails(path: String) {
this.path = path
update(path)
}
init {
itemView.setOnClickListener { path?.let { path -> listener.onPathItemClicked(path) }}
}
}
interface PathListItemListener {
fun onPathItemClicked(path: String)
}
companion object {
val TAG = PathListAdapter::class.simpleName!!
}
} | gpl-3.0 | 4cb3a689a99ef48cb4577087af68cd28 | 34.204301 | 116 | 0.672166 | 4.417004 | false | false | false | false |
ibinti/intellij-community | platform/editor-ui-api/src/com/intellij/ide/ui/UISettings.kt | 2 | 19573 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.ui
import com.intellij.ide.WelcomeWizardUtil
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.*
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.IconLoader
import com.intellij.openapi.util.Pair
import com.intellij.openapi.util.SystemInfo
import com.intellij.util.ComponentTreeEventDispatcher
import com.intellij.util.PlatformUtils
import com.intellij.util.SystemProperties
import com.intellij.util.ui.GraphicsUtil
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.UIUtil.isValidFont
import com.intellij.util.xmlb.Accessor
import com.intellij.util.xmlb.SerializationFilter
import com.intellij.util.xmlb.XmlSerializerUtil
import com.intellij.util.xmlb.annotations.OptionTag
import com.intellij.util.xmlb.annotations.Property
import com.intellij.util.xmlb.annotations.Transient
import java.awt.Font
import java.awt.Graphics
import java.awt.Graphics2D
import java.awt.RenderingHints
import javax.swing.JComponent
import javax.swing.SwingConstants
@State(name = "UISettings", storages = arrayOf(Storage("ui.lnf.xml")))
class UISettings : BaseState(), PersistentStateComponent<UISettings> {
// These font properties should not be set in the default ctor,
// so that to make the serialization logic judge if a property
// should be stored or shouldn't by the provided filter only.
@get:Property(filter = FontFilter::class)
@get:OptionTag("FONT_FACE")
var fontFace by string()
@get:Property(filter = FontFilter::class)
@get:OptionTag("FONT_SIZE")
var fontSize by storedProperty(defFontSize)
@get:Property(filter = FontFilter::class)
@get:OptionTag("FONT_SCALE")
var fontScale by storedProperty(0f)
@get:OptionTag("RECENT_FILES_LIMIT") var recentFilesLimit by storedProperty(50)
@get:OptionTag("CONSOLE_COMMAND_HISTORY_LIMIT") var consoleCommandHistoryLimit by storedProperty(300)
@get:OptionTag("OVERRIDE_CONSOLE_CYCLE_BUFFER_SIZE") var overrideConsoleCycleBufferSize by storedProperty(false)
@get:OptionTag("CONSOLE_CYCLE_BUFFER_SIZE_KB") var consoleCycleBufferSizeKb by storedProperty(1024)
@get:OptionTag("EDITOR_TAB_LIMIT") var editorTabLimit by storedProperty(10)
@get:OptionTag("REUSE_NOT_MODIFIED_TABS") var reuseNotModifiedTabs by storedProperty(false)
@get:OptionTag("ANIMATE_WINDOWS") var animateWindows by storedProperty(true)
@get:OptionTag("SHOW_TOOL_WINDOW_NUMBERS") var showToolWindowsNumbers by storedProperty(true)
@get:OptionTag("HIDE_TOOL_STRIPES") var hideToolStripes by storedProperty(true)
@get:OptionTag("WIDESCREEN_SUPPORT") var wideScreenSupport by storedProperty(false)
@get:OptionTag("LEFT_HORIZONTAL_SPLIT") var leftHorizontalSplit by storedProperty(false)
@get:OptionTag("RIGHT_HORIZONTAL_SPLIT") var rightHorizontalSplit by storedProperty(false)
@get:OptionTag("SHOW_EDITOR_TOOLTIP") var showEditorToolTip by storedProperty(true)
@get:OptionTag("SHOW_MEMORY_INDICATOR") var showMemoryIndicator by storedProperty(false)
@get:OptionTag("ALLOW_MERGE_BUTTONS") var allowMergeButtons by storedProperty(true)
@get:OptionTag("SHOW_MAIN_TOOLBAR") var showMainToolbar by storedProperty(false)
@get:OptionTag("SHOW_STATUS_BAR") var showStatusBar by storedProperty(true)
@get:OptionTag("SHOW_NAVIGATION_BAR") var showNavigationBar by storedProperty(true)
@get:OptionTag("ALWAYS_SHOW_WINDOW_BUTTONS") var alwaysShowWindowsButton by storedProperty(false)
@get:OptionTag("CYCLE_SCROLLING") var cycleScrolling by storedProperty(true)
@get:OptionTag("SCROLL_TAB_LAYOUT_IN_EDITOR") var scrollTabLayoutInEditor by storedProperty(true)
@get:OptionTag("HIDE_TABS_IF_NEED") var hideTabsIfNeed by storedProperty(true)
@get:OptionTag("SHOW_CLOSE_BUTTON") var showCloseButton by storedProperty(true)
@get:OptionTag("EDITOR_TAB_PLACEMENT") var editorTabPlacement by storedProperty(1)
@get:OptionTag("HIDE_KNOWN_EXTENSION_IN_TABS") var hideKnownExtensionInTabs by storedProperty(false)
@get:OptionTag("SHOW_ICONS_IN_QUICK_NAVIGATION") var showIconInQuickNavigation by storedProperty(true)
@get:OptionTag("CLOSE_NON_MODIFIED_FILES_FIRST") var closeNonModifiedFilesFirst by storedProperty(false)
@get:OptionTag("ACTIVATE_MRU_EDITOR_ON_CLOSE") var activeMruEditorOnClose by storedProperty(false)
// TODO[anton] consider making all IDEs use the same settings
@get:OptionTag("ACTIVATE_RIGHT_EDITOR_ON_CLOSE") var activeRightEditorOnClose by storedProperty(PlatformUtils.isAppCode())
@get:OptionTag("IDE_AA_TYPE") var ideAAType by storedProperty(AntialiasingType.SUBPIXEL)
@get:OptionTag("EDITOR_AA_TYPE") var editorAAType by storedProperty(AntialiasingType.SUBPIXEL)
@get:OptionTag("COLOR_BLINDNESS") var colorBlindness by storedProperty<ColorBlindness?>()
@get:OptionTag("MOVE_MOUSE_ON_DEFAULT_BUTTON") var moveMouseOnDefaultButton by storedProperty(false)
@get:OptionTag("ENABLE_ALPHA_MODE") var enableAlphaMode by storedProperty(false)
@get:OptionTag("ALPHA_MODE_DELAY") var alphaModeDelay by storedProperty(1500)
@get:OptionTag("ALPHA_MODE_RATIO") var alphaModeRatio by storedProperty(0.5f)
@get:OptionTag("MAX_CLIPBOARD_CONTENTS") var maxClipboardContents by storedProperty(5)
@get:OptionTag("OVERRIDE_NONIDEA_LAF_FONTS") var overrideLafFonts by storedProperty(false)
@get:OptionTag("SHOW_ICONS_IN_MENUS") var showIconsInMenus by storedProperty(!PlatformUtils.isAppCode())
// IDEADEV-33409, should be disabled by default on MacOS
@get:OptionTag("DISABLE_MNEMONICS") var disableMnemonics by storedProperty(SystemInfo.isMac)
@get:OptionTag("DISABLE_MNEMONICS_IN_CONTROLS") var disableMnemonicsInControls by storedProperty(false)
@get:OptionTag("USE_SMALL_LABELS_ON_TABS") var useSmallLabelsOnTabs by storedProperty(SystemInfo.isMac)
@get:OptionTag("MAX_LOOKUP_WIDTH2") var maxLookupWidth by storedProperty(500)
@get:OptionTag("MAX_LOOKUP_LIST_HEIGHT") var maxLookupListHeight by storedProperty(11)
@get:OptionTag("HIDE_NAVIGATION_ON_FOCUS_LOSS") var hideNavigationOnFocusLoss by storedProperty(true)
@get:OptionTag("DND_WITH_PRESSED_ALT_ONLY") var dndWithPressedAltOnly by storedProperty(false)
@get:OptionTag("DEFAULT_AUTOSCROLL_TO_SOURCE") var defaultAutoScrollToSource by storedProperty(false)
@Transient var presentationMode = false
@get:OptionTag("PRESENTATION_MODE_FONT_SIZE") var presentationModeFontSize by storedProperty(24)
@get:OptionTag("MARK_MODIFIED_TABS_WITH_ASTERISK") var markModifiedTabsWithAsterisk by storedProperty(false)
@get:OptionTag("SHOW_TABS_TOOLTIPS") var showTabsTooltips by storedProperty(true)
@get:OptionTag("SHOW_DIRECTORY_FOR_NON_UNIQUE_FILENAMES") var showDirectoryForNonUniqueFilenames by storedProperty(true)
var smoothScrolling by storedProperty(SystemInfo.isMac && (SystemInfo.isJetBrainsJvm || SystemInfo.isJavaVersionAtLeast("9")))
@get:OptionTag("NAVIGATE_TO_PREVIEW") var navigateToPreview by storedProperty(false)
@get:OptionTag("SORT_LOOKUP_ELEMENTS_LEXICOGRAPHICALLY") var sortLookupElementsLexicographically by storedProperty(false)
@get:OptionTag("MERGE_EQUAL_STACKTRACES") var mergeEqualStackTraces by storedProperty(true)
@get:OptionTag("SORT_BOOKMARKS") var sortBookmarks by storedProperty(false)
private val myTreeDispatcher = ComponentTreeEventDispatcher.create(UISettingsListener::class.java)
init {
WelcomeWizardUtil.getAutoScrollToSource()?.let {
defaultAutoScrollToSource = it
}
}
private fun withDefFont(): UISettings {
initDefFont()
return this
}
@Suppress("DeprecatedCallableAddReplaceWith")
@Deprecated("Please use {@link UISettingsListener#TOPIC}")
fun addUISettingsListener(listener: UISettingsListener, parentDisposable: Disposable) {
ApplicationManager.getApplication().messageBus.connect(parentDisposable).subscribe(UISettingsListener.TOPIC, listener)
}
/**
* Notifies all registered listeners that UI settings has been changed.
*/
fun fireUISettingsChanged() {
updateDeprecatedProperties()
// todo remove when all old properties will be converted
incrementModificationCount()
IconLoader.setFilter(ColorBlindnessSupport.get(colorBlindness)?.filter)
// if this is the main UISettings instance (and not on first call to getInstance) push event to bus and to all current components
if (this === _instance) {
myTreeDispatcher.multicaster.uiSettingsChanged(this)
ApplicationManager.getApplication().messageBus.syncPublisher(UISettingsListener.TOPIC).uiSettingsChanged(this)
}
}
@Suppress("DEPRECATION")
private fun updateDeprecatedProperties() {
HIDE_TOOL_STRIPES = hideToolStripes
SHOW_MAIN_TOOLBAR = showMainToolbar
CYCLE_SCROLLING = cycleScrolling
SHOW_CLOSE_BUTTON = showCloseButton
EDITOR_AA_TYPE = editorAAType
PRESENTATION_MODE = presentationMode
OVERRIDE_NONIDEA_LAF_FONTS = overrideLafFonts
PRESENTATION_MODE_FONT_SIZE = presentationModeFontSize
CONSOLE_COMMAND_HISTORY_LIMIT = consoleCommandHistoryLimit
FONT_SIZE = fontSize
FONT_FACE = fontFace
EDITOR_TAB_LIMIT = editorTabLimit
OVERRIDE_CONSOLE_CYCLE_BUFFER_SIZE = overrideConsoleCycleBufferSize
CONSOLE_CYCLE_BUFFER_SIZE_KB = consoleCycleBufferSizeKb
}
private fun initDefFont() {
val fontData = systemFontFaceAndSize
if (fontFace == null) fontFace = fontData.first
if (fontSize <= 0) fontSize = fontData.second
if (fontScale <= 0) fontScale = defFontScale
}
class FontFilter : SerializationFilter {
override fun accepts(accessor: Accessor, bean: Any): Boolean {
val settings = bean as UISettings
val fontData = systemFontFaceAndSize
if ("fontFace" == accessor.name) {
return fontData.first != settings.fontFace
}
// fontSize/fontScale should either be stored in pair or not stored at all
// otherwise the fontSize restore logic gets broken (see loadState)
return !(fontData.second == settings.fontSize && 1f == settings.fontScale)
}
}
override fun getState() = this
override fun loadState(state: UISettings) {
XmlSerializerUtil.copyBean(state, this)
resetModificationCount()
updateDeprecatedProperties()
// Check tab placement in editor
if (editorTabPlacement != TABS_NONE &&
editorTabPlacement != SwingConstants.TOP &&
editorTabPlacement != SwingConstants.LEFT &&
editorTabPlacement != SwingConstants.BOTTOM &&
editorTabPlacement != SwingConstants.RIGHT) {
editorTabPlacement = SwingConstants.TOP
}
// Check that alpha delay and ratio are valid
if (alphaModeDelay < 0) {
alphaModeDelay = 1500
}
if (alphaModeRatio < 0.0f || alphaModeRatio > 1.0f) {
alphaModeRatio = 0.5f
}
fontSize = restoreFontSize(fontSize, fontScale)
fontScale = defFontScale
initDefFont()
// 1. Sometimes system font cannot display standard ASCII symbols. If so we have
// find any other suitable font withing "preferred" fonts first.
var fontIsValid = isValidFont(Font(fontFace, Font.PLAIN, fontSize))
if (!fontIsValid) {
for (preferredFont in arrayOf("dialog", "Arial", "Tahoma")) {
if (isValidFont(Font(preferredFont, Font.PLAIN, fontSize))) {
fontFace = preferredFont
fontIsValid = true
break
}
}
// 2. If all preferred fonts are not valid in current environment
// we have to find first valid font (if any)
if (!fontIsValid) {
val fontNames = UIUtil.getValidFontNames(false)
if (fontNames.isNotEmpty()) {
fontFace = fontNames[0]
}
}
}
if (maxClipboardContents <= 0) {
maxClipboardContents = 5
}
fireUISettingsChanged()
}
companion object {
private val LOG = Logger.getInstance(UISettings::class.java)
const val ANIMATION_DURATION = 300 // Milliseconds
/** Not tabbed pane. */
const val TABS_NONE = 0
private @Volatile var _instance: UISettings? = null
@JvmStatic
val instance: UISettings
get() = instanceOrNull!!
@JvmStatic
val instanceOrNull: UISettings?
get() {
var result = _instance
if (result == null) {
if (ApplicationManager.getApplication() == null) {
return null
}
result = ServiceManager.getService(UISettings::class.java)
_instance = result
}
return result
}
/**
* Use this method if you are not sure whether the application is initialized.
* @return persisted UISettings instance or default values.
*/
@JvmStatic
val shadowInstance: UISettings
get() {
val app = ApplicationManager.getApplication()
return (if (app == null) null else instanceOrNull) ?: UISettings().withDefFont()
}
private val systemFontFaceAndSize: Pair<String, Int>
get() {
val fontData = UIUtil.getSystemFontData()
if (fontData != null) {
return fontData
}
return Pair.create("Dialog", 12)
}
@JvmField
val FORCE_USE_FRACTIONAL_METRICS = SystemProperties.getBooleanProperty("idea.force.use.fractional.metrics", false)
@JvmStatic
fun setupFractionalMetrics(g2d: Graphics2D) {
if (FORCE_USE_FRACTIONAL_METRICS) {
g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON)
}
}
/**
* This method must not be used for set up antialiasing for editor components. To make sure antialiasing settings are taken into account
* when preferred size of component is calculated, [.setupComponentAntialiasing] method should be called from
* `updateUI()` or `setUI()` method of component.
*/
@JvmStatic
fun setupAntialiasing(g: Graphics) {
val g2d = g as Graphics2D
g2d.setRenderingHint(RenderingHints.KEY_TEXT_LCD_CONTRAST, UIUtil.getLcdContrastValue())
val application = ApplicationManager.getApplication()
if (application == null) {
// We cannot use services while Application has not been loaded yet
// So let's apply the default hints.
UIUtil.applyRenderingHints(g)
return
}
val uiSettings = ServiceManager.getService(UISettings::class.java)
if (uiSettings != null) {
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, AntialiasingType.getKeyForCurrentScope(false))
}
else {
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF)
}
setupFractionalMetrics(g2d)
}
/**
* @see #setupAntialiasing(Graphics)
*/
@JvmStatic
fun setupComponentAntialiasing(component: JComponent) {
com.intellij.util.ui.GraphicsUtil.setAntialiasingType(component, AntialiasingType.getAAHintForSwingComponent())
}
@JvmStatic
fun setupEditorAntialiasing(component: JComponent) {
instance.editorAAType?.let { GraphicsUtil.setAntialiasingType(component, it.textInfo) }
}
/**
* Returns the default font scale, which depends on the HiDPI mode (see JBUI#ScaleType).
* <p>
* The font is represented:
* - in relative (dpi-independent) points in the JRE-managed HiDPI mode, so the method returns 1.0f
* - in absolute (dpi-dependent) points in the IDE-managed HiDPI mode, so the method returns the default screen scale
*
* @return the system font scale
*/
@JvmStatic
val defFontScale: Float
get() = if (UIUtil.isJreHiDPIEnabled()) 1f else JBUI.sysScale()
/**
* Returns the default font size scaled by #defFontScale
*
* @return the default scaled font size
*/
@JvmStatic
val defFontSize: Int
get() = Math.round(UIUtil.DEF_SYSTEM_FONT_SIZE * defFontScale)
@JvmStatic
fun restoreFontSize(readSize: Int, readScale: Float?): Int {
var size = readSize
if (readScale == null || readScale <= 0) {
// Reset font to default on switch from IDE-managed HiDPI to JRE-managed HiDPI. Doesn't affect OSX.
if (UIUtil.isJreHiDPIEnabled() && !SystemInfo.isMac) size = defFontSize
}
else {
if (readScale != defFontScale) size = Math.round((readSize / readScale) * defFontScale)
}
LOG.info("Loaded: fontSize=$readSize, fontScale=$readScale; restored: fontSize=$size, fontScale=$defFontScale")
return size
}
}
//<editor-fold desc="Deprecated stuff.">
@Suppress("unused")
@Deprecated("Use fontFace", replaceWith = ReplaceWith("fontFace"))
@JvmField
@Transient
var FONT_FACE: String? = null
@Suppress("unused")
@Deprecated("Use fontSize", replaceWith = ReplaceWith("fontSize"))
@JvmField
@Transient
var FONT_SIZE: Int? = 0
@Suppress("unused")
@Deprecated("Use hideToolStripes", replaceWith = ReplaceWith("hideToolStripes"))
@JvmField
@Transient
var HIDE_TOOL_STRIPES = true
@Suppress("unused")
@Deprecated("Use consoleCommandHistoryLimit", replaceWith = ReplaceWith("consoleCommandHistoryLimit"))
@JvmField
@Transient
var CONSOLE_COMMAND_HISTORY_LIMIT = 300
@Suppress("unused")
@Deprecated("Use cycleScrolling", replaceWith = ReplaceWith("cycleScrolling"))
@JvmField
@Transient
var CYCLE_SCROLLING = true
@Suppress("unused")
@Deprecated("Use showMainToolbar", replaceWith = ReplaceWith("showMainToolbar"))
@JvmField
@Transient
var SHOW_MAIN_TOOLBAR = false
@Suppress("unused")
@Deprecated("Use showCloseButton", replaceWith = ReplaceWith("showCloseButton"))
@JvmField
@Transient
var SHOW_CLOSE_BUTTON = true
@Suppress("unused")
@Deprecated("Use editorAAType", replaceWith = ReplaceWith("editorAAType"))
@JvmField
@Transient
var EDITOR_AA_TYPE: AntialiasingType? = AntialiasingType.SUBPIXEL
@Suppress("unused")
@Deprecated("Use presentationMode", replaceWith = ReplaceWith("presentationMode"))
@JvmField
@Transient
var PRESENTATION_MODE = false
@Suppress("unused")
@Deprecated("Use overrideLafFonts", replaceWith = ReplaceWith("overrideLafFonts"))
@JvmField
@Transient
var OVERRIDE_NONIDEA_LAF_FONTS = false
@Suppress("unused")
@Deprecated("Use presentationModeFontSize", replaceWith = ReplaceWith("presentationModeFontSize"))
@JvmField
@Transient
var PRESENTATION_MODE_FONT_SIZE = 24
@Suppress("unused")
@Deprecated("Use editorTabLimit", replaceWith = ReplaceWith("editorTabLimit"))
@JvmField
@Transient
var EDITOR_TAB_LIMIT = editorTabLimit
@Suppress("unused")
@Deprecated("Use overrideConsoleCycleBufferSize", replaceWith = ReplaceWith("overrideConsoleCycleBufferSize"))
@JvmField
@Transient
var OVERRIDE_CONSOLE_CYCLE_BUFFER_SIZE = false
@Suppress("unused")
@Deprecated("Use consoleCycleBufferSizeKb", replaceWith = ReplaceWith("consoleCycleBufferSizeKb"))
@JvmField
@Transient
var CONSOLE_CYCLE_BUFFER_SIZE_KB = consoleCycleBufferSizeKb
//</editor-fold>
} | apache-2.0 | 304893cfb99fd12cadcdcecc7145f8a6 | 39.52588 | 140 | 0.737547 | 4.496439 | false | false | false | false |
proxer/ProxerLibAndroid | library/src/main/kotlin/me/proxer/library/entity/info/Comment.kt | 2 | 1664 | package me.proxer.library.entity.info
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import me.proxer.library.entity.ProxerDateItem
import me.proxer.library.entity.ProxerIdItem
import me.proxer.library.entity.ProxerImageItem
import me.proxer.library.enums.UserMediaProgress
import java.util.Date
/**
* The complete details of a comment associated with an [Entry].
*
* @property entryId The id of the associated entry.
* @property authorId The id of the author.
* @property mediaProgress The progress, the user has made on the associated media.
* @property ratingDetails Finer grained ratings for e.g. music.
* @property content The actual content of the comment.
* @property overallRating The overall rating.
* @property episode The episode, the user is currently at.
* @property helpfulVotes The mount of helpful votes by other users.
* @property author The username of the author.
*
* @author Desnoo
*/
@JsonClass(generateAdapter = true)
data class Comment(
@Json(name = "id") override val id: String,
@Json(name = "tid") val entryId: String,
@Json(name = "uid") val authorId: String,
@Json(name = "state") val mediaProgress: UserMediaProgress,
@Json(name = "data") val ratingDetails: RatingDetails,
@Json(name = "comment") val content: String,
@Json(name = "rating") val overallRating: Int,
@Json(name = "episode") val episode: Int,
@Json(name = "positive") val helpfulVotes: Int,
@Json(name = "timestamp") override val date: Date,
@Json(name = "username") val author: String,
@Json(name = "avatar") override val image: String
) : ProxerIdItem, ProxerImageItem, ProxerDateItem
| gpl-3.0 | dd06ab9d9e2afdd9cbccd3bb42a61980 | 40.6 | 83 | 0.733774 | 3.825287 | false | false | false | false |
wiryls/HomeworkCollectionOfMYLS | 2017.AndroidApplicationDevelopment/Rehtaew/app/src/main/java/com/myls/rehtaew/database/CityDatabaseHelper.kt | 1 | 1755 | package com.myls.rehtaew.database
import android.content.Context
import android.database.Cursor
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper
/**
* Created by myls on 10/25/17.
*/
// [Create a Database Using a SQL Extension]
// (https://developer.android.com/training/basics/data-storage/databases.html)
// [Reading sqlite file from asset folder]
// (https://stackoverflow.com/a/20858393)
// [Android SQLiteAssetHelper]
// (https://github.com/jgilfelt/android-sqlite-asset-helper)
class CityDatabaseHelper(context: Context)
: SQLiteAssetHelper(context, CityContract.DATABASE_NAME, null, CityContract.DATABASE_VERSION)
{
var constraint : CharSequence = EMPTY
val cursor: Cursor
get() {
val name = when {
constraint.isBlank() -> EMPTY
else -> "$constraint%"
}
val piny = when {
constraint.isBlank() -> EMPTY
constraint.contains(REGEX) -> name
else -> constraint.asIterable().joinToString(separator = "%", postfix = "%")
}
return readableDatabase.rawQuery(CityContract.CityEntry.SELECT_CITY, arrayOf(name, piny))
}
companion object {
private val REGEX = "[^0-9A-z]".toRegex()
private val EMPTY = ""
}
}
// [What's the Kotlin equivalent of Java's String[]?]
// (https://stackoverflow.com/a/44239940)
// [How to add sub query in SQLITE Android along with 'IN'?]
// (https://stackoverflow.com/a/18916015)
// [rawQuery(query, selectionArgs)]
// (https://stackoverflow.com/a/10598193)
// [Kotlin: joinToString]
// (https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/join-to-string.html) | mit | 2ada6e5d1291ae2d74b55ed21de32e31 | 30.927273 | 114 | 0.639886 | 3.926174 | false | false | false | false |
Esri/arcgis-runtime-samples-android | kotlin/perform-spatial-operations/src/main/java/com/esri/arcgisruntime/sample/performspatialoperations/MainActivity.kt | 1 | 8635 | /*
* Copyright 2020 Esri
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.esri.arcgisruntime.sample.performspatialoperations
import android.graphics.Color
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import com.esri.arcgisruntime.ArcGISRuntimeEnvironment
import com.esri.arcgisruntime.geometry.Geometry
import com.esri.arcgisruntime.geometry.GeometryEngine
import com.esri.arcgisruntime.geometry.Part
import com.esri.arcgisruntime.geometry.PartCollection
import com.esri.arcgisruntime.geometry.Point
import com.esri.arcgisruntime.geometry.PointCollection
import com.esri.arcgisruntime.geometry.Polygon
import com.esri.arcgisruntime.geometry.SpatialReferences
import com.esri.arcgisruntime.mapping.ArcGISMap
import com.esri.arcgisruntime.mapping.BasemapStyle
import com.esri.arcgisruntime.mapping.view.Graphic
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay
import com.esri.arcgisruntime.mapping.view.MapView
import com.esri.arcgisruntime.sample.performspatialoperations.databinding.ActivityMainBinding
import com.esri.arcgisruntime.symbology.SimpleFillSymbol
import com.esri.arcgisruntime.symbology.SimpleLineSymbol
class MainActivity : AppCompatActivity() {
private val activityMainBinding by lazy {
ActivityMainBinding.inflate(layoutInflater)
}
private val mapView: MapView by lazy {
activityMainBinding.mapView
}
private val inputGeometryGraphicsOverlay: GraphicsOverlay by lazy { GraphicsOverlay() }
private val resultGeometryGraphicsOverlay: GraphicsOverlay by lazy { GraphicsOverlay() }
// simple black line symbol for outlines
private val lineSymbol = SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.BLACK, 1f)
private val resultFillSymbol = SimpleFillSymbol(
SimpleFillSymbol.Style.SOLID, Color.RED, lineSymbol
)
private lateinit var inputPolygon1: Polygon
private lateinit var inputPolygon2: Polygon
// the spatial operation switching menu items.
private var noOperationMenuItem: MenuItem? = null
private var intersectionMenuItem: MenuItem? = null
private var unionMenuItem: MenuItem? = null
private var differenceMenuItem: MenuItem? = null
private var symmetricDifferenceMenuItem: MenuItem? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(activityMainBinding.root)
// authentication with an API key or named user is required to access basemaps and other
// location services
ArcGISRuntimeEnvironment.setApiKey(BuildConfig.API_KEY)
mapView.apply {
// create an ArcGISMap with a light gray basemap
map = ArcGISMap(BasemapStyle.ARCGIS_LIGHT_GRAY)
// create graphics overlays to show the inputs and results of the spatial operation
graphicsOverlays.add(inputGeometryGraphicsOverlay)
graphicsOverlays.add(resultGeometryGraphicsOverlay)
}
// create input polygons and add graphics to display these polygons in an overlay
createPolygons()
// center the map view on the input geometries
val envelope = GeometryEngine.union(inputPolygon1, inputPolygon2).extent
mapView.setViewpointGeometryAsync(envelope, 20.0)
}
private fun showGeometry(resultGeometry: Geometry) {
// add a graphic from the result geometry, showing result in red (0xFFE91F1F)
val graphic = Graphic(resultGeometry, resultFillSymbol).also {
// select the result to highlight it
it.isSelected = true
}
resultGeometryGraphicsOverlay.graphics.add(graphic)
}
private fun createPolygons() {
// create input polygon 1
inputPolygon1 = Polygon(PointCollection(SpatialReferences.getWebMercator()).apply {
add(Point(-13160.0, 6710100.0))
add(Point(-13300.0, 6710500.0))
add(Point(-13760.0, 6710730.0))
add(Point(-14660.0, 6710000.0))
add(Point(-13960.0, 6709400.0))
})
// create and add a blue graphic to show input polygon 1
val blueFill = SimpleFillSymbol(SimpleFillSymbol.Style.SOLID, Color.BLUE, lineSymbol)
inputGeometryGraphicsOverlay.graphics.add(Graphic(inputPolygon1, blueFill))
// outer ring
val outerRing = Part(PointCollection(SpatialReferences.getWebMercator()).apply {
add(Point(-13060.0, 6711030.0))
add(Point(-12160.0, 6710730.0))
add(Point(-13160.0, 6709700.0))
add(Point(-14560.0, 6710730.0))
add(Point(-13060.0, 6711030.0))
})
// inner ring
val innerRing = Part(PointCollection(SpatialReferences.getWebMercator()).apply {
add(Point(-13060.0, 6710910.0))
add(Point(-12450.0, 6710660.0))
add(Point(-13160.0, 6709900.0))
add(Point(-14160.0, 6710630.0))
add(Point(-13060.0, 6710910.0))
})
// add both parts (rings) to a part collection and create a geometry from it
PartCollection(outerRing).run {
add(innerRing)
inputPolygon2 = Polygon(this)
}
// create and add a green graphic to show input polygon 2
val greenFill = SimpleFillSymbol(SimpleFillSymbol.Style.SOLID, Color.GREEN, lineSymbol)
inputGeometryGraphicsOverlay.graphics.add(Graphic(inputPolygon2, greenFill))
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
// inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.menu_main, menu)
// Get the menu items that perform spatial operations.
noOperationMenuItem = menu?.getItem(0)
intersectionMenuItem = menu?.getItem(1)
unionMenuItem = menu?.getItem(2)
differenceMenuItem = menu?.getItem(3)
symmetricDifferenceMenuItem = menu?.getItem(4)
// set the 'no-op' menu item checked by default
noOperationMenuItem?.isChecked = true
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// handle menu item selection
val itemId = item.itemId
// clear previous operation result
resultGeometryGraphicsOverlay.graphics.clear()
// perform spatial operations and add results as graphics, depending on the option selected
when (itemId) {
R.id.action_no_operation -> {
// no spatial operation - graphics have been cleared previously
noOperationMenuItem?.isChecked = true
return true
}
R.id.action_intersection -> {
intersectionMenuItem?.isChecked = true
showGeometry(GeometryEngine.intersection(inputPolygon1, inputPolygon2))
return true
}
R.id.action_union -> {
unionMenuItem?.isChecked = true
showGeometry(GeometryEngine.union(inputPolygon1, inputPolygon2))
return true
}
R.id.action_difference -> {
differenceMenuItem?.isChecked = true
// note that the difference method gives different results depending on the order of input geometries
showGeometry(GeometryEngine.difference(inputPolygon1, inputPolygon2))
return true
}
R.id.action_symmetric_difference -> {
symmetricDifferenceMenuItem?.isChecked = true
showGeometry(GeometryEngine.symmetricDifference(inputPolygon1, inputPolygon2))
return true
}
else -> {
return super.onOptionsItemSelected(item)
}
}
}
override fun onResume() {
super.onResume()
mapView.resume()
}
override fun onPause() {
mapView.pause()
super.onPause()
}
override fun onDestroy() {
mapView.dispose()
super.onDestroy()
}
}
| apache-2.0 | 9cc0852daa5eab79aac9f7fd55d2eb19 | 37.549107 | 117 | 0.678749 | 4.721159 | false | false | false | false |
gradle/gradle | subprojects/configuration-cache/src/main/kotlin/org/gradle/configurationcache/serialization/Codec.kt | 3 | 8074 | /*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.configurationcache.serialization
import org.gradle.api.Task
import org.gradle.api.internal.GradleInternal
import org.gradle.api.internal.project.ProjectInternal
import org.gradle.api.invocation.Gradle
import org.gradle.api.logging.Logger
import org.gradle.configurationcache.DefaultConfigurationCache
import org.gradle.configurationcache.extensions.uncheckedCast
import org.gradle.configurationcache.problems.PropertyProblem
import org.gradle.configurationcache.problems.PropertyTrace
import org.gradle.configurationcache.problems.StructuredMessageBuilder
import org.gradle.configurationcache.serialization.beans.BeanStateReader
import org.gradle.configurationcache.serialization.beans.BeanStateWriter
import org.gradle.internal.serialize.Decoder
import org.gradle.internal.serialize.Encoder
/**
* Binary encoding for type [T].
*/
interface Codec<T> : EncodingProvider<T>, DecodingProvider<T>
interface WriteContext : IsolateContext, MutableIsolateContext, Encoder {
val tracer: Tracer?
val sharedIdentities: WriteIdentities
val circularReferences: CircularReferences
override val isolate: WriteIsolate
fun beanStateWriterFor(beanType: Class<*>): BeanStateWriter
suspend fun write(value: Any?)
fun writeClass(type: Class<*>)
}
interface Tracer {
fun open(frame: String)
fun close(frame: String)
}
interface ReadContext : IsolateContext, MutableIsolateContext, Decoder {
val sharedIdentities: ReadIdentities
override val isolate: ReadIsolate
val classLoader: ClassLoader
fun beanStateReaderFor(beanType: Class<*>): BeanStateReader
fun getProject(path: String): ProjectInternal
/**
* When in immediate mode, [read] calls are NOT suspending.
* Useful for bridging with non-suspending serialization protocols such as [java.io.Serializable].
*/
var immediateMode: Boolean // TODO:configuration-cache prevent StackOverflowErrors when crossing protocols
suspend fun read(): Any?
fun readClass(): Class<*>
/**
* Defers the given [action] until all objects have been read.
*/
fun onFinish(action: () -> Unit)
}
suspend fun <T : Any> ReadContext.readNonNull() = read()!!.uncheckedCast<T>()
interface IsolateContext {
val logger: Logger
val isolate: Isolate
val trace: PropertyTrace
fun onProblem(problem: PropertyProblem)
fun onError(error: Exception, message: StructuredMessageBuilder)
}
sealed class IsolateOwner {
abstract fun <T> service(type: Class<T>): T
abstract val delegate: Any
class OwnerTask(override val delegate: Task) : IsolateOwner() {
override fun <T> service(type: Class<T>): T = (delegate.project as ProjectInternal).services.get(type)
}
class OwnerGradle(override val delegate: Gradle) : IsolateOwner() {
override fun <T> service(type: Class<T>): T = (delegate as GradleInternal).services.get(type)
}
class OwnerHost(override val delegate: DefaultConfigurationCache.Host) : IsolateOwner() {
override fun <T> service(type: Class<T>): T = delegate.service(type)
}
}
interface Isolate {
val owner: IsolateOwner
}
interface WriteIsolate : Isolate {
/**
* Identities of objects that are shared within this isolate only.
*/
val identities: WriteIdentities
}
interface ReadIsolate : Isolate {
/**
* Identities of objects that are shared within this isolate only.
*/
val identities: ReadIdentities
}
interface MutableIsolateContext : IsolateContext {
override var trace: PropertyTrace
fun push(codec: Codec<Any?>)
fun push(owner: IsolateOwner, codec: Codec<Any?>)
fun pop()
suspend fun forIncompatibleType(action: suspend () -> Unit)
}
internal
inline fun <T : ReadContext, R> T.withImmediateMode(block: T.() -> R): R {
val immediateMode = this.immediateMode
try {
this.immediateMode = true
return block()
} finally {
this.immediateMode = immediateMode
}
}
internal
inline fun <T : MutableIsolateContext, R> T.withGradleIsolate(
gradle: Gradle,
codec: Codec<Any?>,
block: T.() -> R
): R =
withIsolate(IsolateOwner.OwnerGradle(gradle), codec) {
block()
}
internal
inline fun <T : MutableIsolateContext, R> T.withIsolate(owner: IsolateOwner, codec: Codec<Any?>, block: T.() -> R): R {
push(owner, codec)
try {
return block()
} finally {
pop()
}
}
internal
inline fun <T : MutableIsolateContext, R> T.withCodec(codec: Codec<Any?>, block: T.() -> R): R {
push(codec)
try {
return block()
} finally {
pop()
}
}
internal
inline fun <T : MutableIsolateContext, R> T.withBeanTrace(beanType: Class<*>, action: () -> R): R =
withPropertyTrace(PropertyTrace.Bean(beanType, trace)) {
action()
}
internal
inline fun <T : MutableIsolateContext, R> T.withPropertyTrace(trace: PropertyTrace, block: T.() -> R): R {
val previousTrace = this.trace
this.trace = trace
try {
return block()
} finally {
this.trace = previousTrace
}
}
internal
inline fun WriteContext.encodePreservingIdentityOf(reference: Any, encode: WriteContext.(Any) -> Unit) {
encodePreservingIdentityOf(isolate.identities, reference, encode)
}
internal
inline fun WriteContext.encodePreservingSharedIdentityOf(reference: Any, encode: WriteContext.(Any) -> Unit) =
encodePreservingIdentityOf(sharedIdentities, reference, encode)
internal
inline fun WriteContext.encodePreservingIdentityOf(identities: WriteIdentities, reference: Any, encode: WriteContext.(Any) -> Unit) {
val id = identities.getId(reference)
if (id != null) {
writeSmallInt(id)
} else {
val newId = identities.putInstance(reference)
writeSmallInt(newId)
circularReferences.enter(reference)
try {
encode(reference)
} finally {
circularReferences.leave(reference)
}
}
}
internal
inline fun <T> ReadContext.decodePreservingIdentity(decode: ReadContext.(Int) -> T): T =
decodePreservingIdentity(isolate.identities, decode)
internal
inline fun <T : Any> ReadContext.decodePreservingSharedIdentity(decode: ReadContext.(Int) -> T): T =
decodePreservingIdentity(sharedIdentities) { id ->
decode(id).also {
sharedIdentities.putInstance(id, it)
}
}
internal
inline fun <T> ReadContext.decodePreservingIdentity(identities: ReadIdentities, decode: ReadContext.(Int) -> T): T {
val id = readSmallInt()
val previousValue = identities.getInstance(id)
return when {
previousValue != null -> previousValue.uncheckedCast()
else -> {
decode(id).also {
require(identities.getInstance(id) === it) {
"`decode(id)` should register the decoded instance"
}
}
}
}
}
internal
suspend fun WriteContext.encodeBean(value: Any) {
val beanType = value.javaClass
withBeanTrace(beanType) {
writeClass(beanType)
beanStateWriterFor(beanType).run {
writeStateOf(value)
}
}
}
internal
suspend fun ReadContext.decodeBean(): Any {
val beanType = readClass()
return withBeanTrace(beanType) {
beanStateReaderFor(beanType).run {
newBean(false).also {
readStateOf(it)
}
}
}
}
| apache-2.0 | 67cd287cdf8507070e8580368a4cb718 | 24.713376 | 133 | 0.689869 | 4.292398 | false | false | false | false |
facebook/fresco | imagepipeline-backends/imagepipeline-okhttp3/src/main/java/com/facebook/imagepipeline/backends/okhttp3/OkHttpNetworkFetcher.kt | 2 | 6628 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.imagepipeline.backends.okhttp3
import android.os.Looper
import android.os.SystemClock
import com.facebook.imagepipeline.backends.okhttp3.OkHttpNetworkFetcher.OkHttpNetworkFetchState
import com.facebook.imagepipeline.common.BytesRange
import com.facebook.imagepipeline.common.BytesRange.Companion.fromContentRangeHeader
import com.facebook.imagepipeline.image.EncodedImage
import com.facebook.imagepipeline.producers.BaseNetworkFetcher
import com.facebook.imagepipeline.producers.BaseProducerContextCallbacks
import com.facebook.imagepipeline.producers.Consumer
import com.facebook.imagepipeline.producers.FetchState
import com.facebook.imagepipeline.producers.NetworkFetcher
import com.facebook.imagepipeline.producers.ProducerContext
import java.io.IOException
import java.lang.Exception
import java.util.concurrent.Executor
import okhttp3.CacheControl
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.ResponseBody
/**
* Network fetcher that uses OkHttp 3 as a backend.
* @param callFactory custom [Call.Factory] for fetching image from the network
* @param cancellationExecutor executor on which fetching cancellation is performed if cancellation
* is requested from the UI Thread
* @param disableOkHttpCache true if network requests should not be cached by OkHttp
*/
open class OkHttpNetworkFetcher
@JvmOverloads
constructor(
private val callFactory: Call.Factory,
private val cancellationExecutor: Executor,
disableOkHttpCache: Boolean = true
) : BaseNetworkFetcher<OkHttpNetworkFetchState>() {
/** @param okHttpClient client to use */
constructor(
okHttpClient: OkHttpClient
) : this(okHttpClient, okHttpClient.dispatcher().executorService())
class OkHttpNetworkFetchState(
consumer: Consumer<EncodedImage>,
producerContext: ProducerContext
) : FetchState(consumer, producerContext) {
@JvmField var submitTime: Long = 0
@JvmField var responseTime: Long = 0
@JvmField var fetchCompleteTime: Long = 0
}
private val cacheControl: CacheControl? =
if (disableOkHttpCache) CacheControl.Builder().noStore().build() else null
override fun createFetchState(
consumer: Consumer<EncodedImage>,
context: ProducerContext
): OkHttpNetworkFetchState = OkHttpNetworkFetchState(consumer, context)
override fun fetch(fetchState: OkHttpNetworkFetchState, callback: NetworkFetcher.Callback) {
fetchState.submitTime = SystemClock.elapsedRealtime()
val uri = fetchState.uri
try {
val requestBuilder = Request.Builder().url(uri.toString()).get()
cacheControl?.let(requestBuilder::cacheControl)
fetchState.context.imageRequest.bytesRange?.let {
requestBuilder.addHeader("Range", it.toHttpRangeHeaderValue())
}
fetchWithRequest(fetchState, callback, requestBuilder.build())
} catch (e: Exception) {
// handle error while creating the request
callback.onFailure(e)
}
}
override fun onFetchCompletion(fetchState: OkHttpNetworkFetchState, byteSize: Int) {
fetchState.fetchCompleteTime = SystemClock.elapsedRealtime()
}
override fun getExtraMap(fetchState: OkHttpNetworkFetchState, byteSize: Int) =
mapOf(
QUEUE_TIME to (fetchState.responseTime - fetchState.submitTime).toString(),
FETCH_TIME to (fetchState.fetchCompleteTime - fetchState.responseTime).toString(),
TOTAL_TIME to (fetchState.fetchCompleteTime - fetchState.submitTime).toString(),
IMAGE_SIZE to byteSize.toString())
protected fun fetchWithRequest(
fetchState: OkHttpNetworkFetchState,
callback: NetworkFetcher.Callback,
request: Request
) {
val call = callFactory.newCall(request)
fetchState.context.addCallbacks(
object : BaseProducerContextCallbacks() {
override fun onCancellationRequested() {
if (Looper.myLooper() != Looper.getMainLooper()) {
call.cancel()
} else {
cancellationExecutor.execute { call.cancel() }
}
}
})
call.enqueue(
object : Callback {
@Throws(IOException::class)
override fun onResponse(call: Call, response: Response) {
fetchState.responseTime = SystemClock.elapsedRealtime()
val responseBody: ResponseBody? = response.body()
responseBody?.use { body ->
try {
if (!response.isSuccessful) {
handleException(call, IOException("Unexpected HTTP code $response"), callback)
return@use
}
val responseRange = fromContentRangeHeader(response.header("Content-Range"))
if (responseRange != null &&
!(responseRange.from == 0 &&
responseRange.to == BytesRange.TO_END_OF_CONTENT)) {
// Only treat as a partial image if the range is not all of the content
fetchState.responseBytesRange = responseRange
fetchState.onNewResultStatusFlags = Consumer.IS_PARTIAL_RESULT
}
val contentLength =
if (body.contentLength() < 0) 0 else body.contentLength().toInt()
callback.onResponse(body.byteStream(), contentLength)
} catch (e: Exception) {
handleException(call, e, callback)
}
}
?: handleException(call, IOException("Response body null: $response"), callback)
}
override fun onFailure(call: Call, e: IOException) = handleException(call, e, callback)
})
}
/**
* Handles exceptions.
*
* OkHttp notifies callers of cancellations via an IOException. If IOException is caught after
* request cancellation, then the exception is interpreted as successful cancellation and
* onCancellation is called. Otherwise onFailure is called.
*/
private fun handleException(call: Call, e: Exception, callback: NetworkFetcher.Callback) {
if (call.isCanceled) {
callback.onCancellation()
} else {
callback.onFailure(e)
}
}
private companion object {
private const val QUEUE_TIME = "queue_time"
private const val FETCH_TIME = "fetch_time"
private const val TOTAL_TIME = "total_time"
private const val IMAGE_SIZE = "image_size"
}
}
| mit | f77c03bf3246d18b3694058e9a28d71d | 37.988235 | 99 | 0.699004 | 4.845029 | false | false | false | false |
shymmq/librus-client-kotlin | app/src/main/kotlin/com/wabadaba/dziennik/ui/events/EventsFragment.kt | 1 | 3591 | package com.wabadaba.dziennik.ui.events
import android.arch.lifecycle.Observer
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.wabadaba.dziennik.MainApplication
import com.wabadaba.dziennik.R
import com.wabadaba.dziennik.di.ViewModelFactory
import com.wabadaba.dziennik.ui.*
import com.wabadaba.dziennik.vo.Event
import eu.davidea.flexibleadapter.FlexibleAdapter
import eu.davidea.flexibleadapter.items.IFlexible
import kotlinx.android.synthetic.main.fragment_events.*
import javax.inject.Inject
class EventsFragment : Fragment() {
@Inject lateinit var viewModelFactory: ViewModelFactory
private lateinit var viewModel: EventsViewModel
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater.inflate(R.layout.fragment_events, container, false)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
MainApplication.mainComponent.inject(this)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel = viewModelFactory.create(EventsViewModel::class.java)
viewModel.eventData.observe(this, Observer { eventData ->
if (eventData != null && eventData.isNotEmpty()) {
fragment_events_message.gone()
fragment_events_recyclerview.visible()
val items = mutableListOf<IFlexible<*>>()
eventData.entries.forEach { (header, events) ->
val headerItem = HeaderItem(header.order, header.title)
val sectionItems = events.map { EventItem(it, headerItem) }
.sorted()
items.addAll(sectionItems)
}
val adapter = FlexibleAdapter(items)
adapter.setDisplayHeadersAtStartUp(true)
adapter.mItemClickListener = FlexibleAdapter.OnItemClickListener { position ->
val item = adapter.getItem(position)
if (item is EventItem) showDetailsDialog(item.event)
false
}
fragment_events_recyclerview.layoutManager = LinearLayoutManager(activity)
fragment_events_recyclerview.adapter = adapter
} else {
fragment_events_message.visible()
fragment_events_recyclerview.gone()
}
})
}
private fun showDetailsDialog(event: Event) {
val dateTimeFormat = activity?.getString(R.string.date_format_full) + ' ' + getString(R.string.timeFormat)
val ddb = DetailsDialogBuilder(activity as MainActivity)
.withTitle(getString(R.string.entry_description))
if (event.subject?.name != null)
ddb.addField(getString(R.string.subject), event.subject?.name)
if (event.category?.name != null)
ddb.addField(getString(R.string.category), event.category?.name)
if (event.content != null)
ddb.addField(getString(R.string.description), event.content)
if (event.addedBy?.fullName() != null)
ddb.addField(getString(R.string.added_by), event.addedBy?.fullName())
if (event.addDate != null)
ddb.addField(getString(R.string.date_added), event.addDate?.toString(dateTimeFormat))
ddb.build().show()
}
} | gpl-3.0 | 2a9b4688812942f299b8350a31d89e82 | 39.818182 | 177 | 0.666945 | 4.865854 | false | false | false | false |
FutureioLab/FastPeak | app/src/main/java/com/binlly/fastpeak/base/mvp/DelegateView.kt | 1 | 1360 | package com.binlly.gankee.base.mvp
import android.content.Context
import android.support.v7.widget.Toolbar
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import android.widget.LinearLayout
import com.binlly.fastpeak.R
/**
* Created by yy on 2017/11/15.
* 统一拦截处理setContentView()
*/
class DelegateView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
): LinearLayout(context, attrs, defStyleAttr) {
private val root: View
private val toolbar: Toolbar
private val content: FrameLayout
init {
orientation = LinearLayout.VERTICAL
root = LayoutInflater.from(context).inflate(R.layout.layout_root_delegate, this)
toolbar = root.findViewById(R.id.toolbar)
content = root.findViewById(R.id.content)
}
fun addContent(layoutId: Int) {
val contentView = LayoutInflater.from(context).inflate(layoutId, null)
content.addView(contentView, FrameLayout.LayoutParams(-1, -1))
}
fun getToolbar(): Toolbar {
return toolbar
}
fun hideToolbar() {
toolbar.visibility = View.GONE
}
fun showToolbar() {
toolbar.visibility = View.VISIBLE
}
fun getContentView(): View {
return content
}
} | mit | 196d0b6d921da3074881320ccc7303bf | 25.45098 | 88 | 0.698071 | 4.306709 | false | false | false | false |
joseph-roque/BowlingCompanion | app/src/main/java/ca/josephroque/bowlingcompanion/statistics/Statistic.kt | 1 | 4905 | package ca.josephroque.bowlingcompanion.statistics
import android.content.SharedPreferences
import android.content.res.Resources
import android.os.Parcel
import ca.josephroque.bowlingcompanion.common.interfaces.KParcelable
import ca.josephroque.bowlingcompanion.statistics.immutable.StatFrame
import ca.josephroque.bowlingcompanion.statistics.immutable.StatGame
import ca.josephroque.bowlingcompanion.statistics.immutable.StatSeries
import ca.josephroque.bowlingcompanion.statistics.list.StatisticListItem
import ca.josephroque.bowlingcompanion.statistics.unit.StatisticsUnit
import java.text.DecimalFormat
/**
* Copyright (C) 2018 Joseph Roque
*
* A statistic to display.
*/
interface Statistic : StatisticListItem, KParcelable {
companion object {
const val EMPTY_STATISTIC = "—"
}
val titleId: Int
val displayValue: String
val category: StatisticsCategory
val canBeGraphed: Boolean
val primaryGraphY: Float?
val secondaryGraphY: Float?
val primaryGraphDataLabelId: Int
get() = titleId
val secondaryGraphDataLabelId: Int?
fun updatePreferences(preferences: SharedPreferences) {}
fun getSubtitle(): String? { return null }
fun isModifiedBy(unit: StatisticsUnit) = false
fun modify(unit: StatisticsUnit) {}
fun isModifiedBy(series: StatSeries) = false
fun modify(series: StatSeries) {}
fun isModifiedBy(game: StatGame) = false
fun modify(game: StatGame) {}
fun isModifiedBy(frame: StatFrame) = false
fun modify(frame: StatFrame) {}
fun zero()
fun getTitle(resources: Resources): String {
return resources.getString(titleId)
}
override fun describeContents(): Int {
return titleId
}
}
interface PercentageStatistic : Statistic {
var numerator: Int
var denominator: Int
override val canBeGraphed
get() = true
override val primaryGraphY: Float?
get() = numerator.toFloat()
override val secondaryGraphY: Float?
get() = denominator.toFloat()
val percentage: Double
get() {
return if (denominator > 0) {
numerator.div(denominator.toDouble()).times(100)
} else {
0.0
}
}
override val displayValue: String
get() = if (denominator > 0) {
val formatter = DecimalFormat("#.##")
"${formatter.format(percentage)}% [$numerator/$denominator]"
} else {
Statistic.EMPTY_STATISTIC
}
override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) {
writeInt(numerator)
writeInt(denominator)
}
override fun zero() {
numerator = 0
denominator = 0
}
}
interface AverageStatistic : Statistic {
var total: Int
var divisor: Int
val average: Double
get() = if (divisor > 0) total.div(divisor.toDouble()) else 0.0
override val primaryGraphY: Float?
get() = average.toFloat()
override val secondaryGraphY: Float?
get() = null
override val secondaryGraphDataLabelId: Int?
get() = null
override val displayValue: String
get() {
val formatter = DecimalFormat("#.##")
return if (average > 0) formatter.format(average) else Statistic.EMPTY_STATISTIC
}
override val canBeGraphed
get() = true
override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) {
writeInt(total)
writeInt(divisor)
}
override fun zero() {
total = 0
divisor = 0
}
}
interface IntegerStatistic : Statistic {
var value: Int
override val displayValue: String
get() = value.toString()
override val canBeGraphed
get() = true
override val primaryGraphY: Float?
get() = value.toFloat()
override val secondaryGraphY: Float?
get() = null
override val secondaryGraphDataLabelId: Int?
get() = null
override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) {
writeInt(value)
}
override fun zero() {
value = 0
}
}
interface StringStatistic : Statistic {
var value: String
override val displayValue: String
get() = value
override val canBeGraphed
get() = false
override val primaryGraphY: Float?
get() = throw IllegalAccessException("StringStatistic does not have a primaryGraphY")
override val secondaryGraphY: Float?
get() = throw IllegalAccessException("StringStatistic does not have a secondaryGraphY")
override val secondaryGraphDataLabelId: Int?
get() = throw IllegalAccessException("StringStatistic does not have a secondaryGraphDataLabelId")
override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) {
writeString(value)
}
override fun zero() {
value = ""
}
}
| mit | bb4679d0ee1eb936bb0dbd159f90352e | 23.638191 | 105 | 0.655109 | 4.673975 | false | false | false | false |
rharter/windy-city-devcon-android | app/src/main/kotlin/com/gdgchicagowest/windycitydevcon/features/speakerdetail/SpeakerDetailView.kt | 1 | 2025 | package com.gdgchicagowest.windycitydevcon.features.speakerdetail
import android.app.Activity
import android.content.Context
import android.support.constraint.ConstraintLayout
import android.support.v4.view.ViewCompat
import android.util.AttributeSet
import android.view.LayoutInflater
import com.bumptech.glide.Glide
import com.gdgchicagowest.windycitydevcon.R
import com.gdgchicagowest.windycitydevcon.ext.getComponent
import com.gdgchicagowest.windycitydevcon.model.Speaker
import kotlinx.android.synthetic.main.view_speaker_detail.view.*
import javax.inject.Inject
class SpeakerDetailView(context: Context, attrs: AttributeSet? = null, defStyle: Int = 0) :
ConstraintLayout(context, attrs, defStyle), SpeakerDetailMvp.View {
@Inject lateinit var presenter: SpeakerDetailMvp.Presenter
constructor(context: Context, attrs: AttributeSet?): this(context, attrs, 0)
init {
context.getComponent<SpeakerDetailComponent>().inject(this)
LayoutInflater.from(context).inflate(R.layout.view_speaker_detail, this, true)
ViewCompat.setTransitionName(image, "image")
toolbar.setNavigationOnClickListener {
if (context is Activity) {
context.finish()
}
}
presenter.onAttach(this)
}
override fun onDetachedFromWindow() {
presenter.onDetach()
super.onDetachedFromWindow()
}
fun setSpeakerId(speakerId: String) {
presenter.setSpeakerId(speakerId)
}
override fun showSpeaker(speaker: Speaker) {
name.text = speaker.name
bio.text = speaker.bio
if (speaker.twitter != null && speaker.twitter!!.isNotEmpty()) {
twitter.visibility = VISIBLE
twitter.text = speaker.twitter
} else {
twitter.visibility = GONE
}
Glide.with(context)
.load(speaker.avatar)
.asBitmap()
.centerCrop()
.dontAnimate()
.into(image)
}
} | apache-2.0 | 268bcbe9101911d24db502ab51551b81 | 30.169231 | 91 | 0.677531 | 4.787234 | false | false | false | false |
FWDekker/intellij-randomness | src/main/kotlin/com/fwdekker/randomness/uuid/UuidScheme.kt | 1 | 4757 | package com.fwdekker.randomness.uuid
import com.fasterxml.uuid.EthernetAddress
import com.fasterxml.uuid.Generators
import com.fasterxml.uuid.UUIDClock
import com.fasterxml.uuid.UUIDTimer
import com.fwdekker.randomness.Bundle
import com.fwdekker.randomness.CapitalizationMode
import com.fwdekker.randomness.RandomnessIcons
import com.fwdekker.randomness.Scheme
import com.fwdekker.randomness.SchemeDecorator
import com.fwdekker.randomness.TypeIcon
import com.fwdekker.randomness.array.ArrayDecorator
import com.intellij.util.xmlb.annotations.Transient
import java.awt.Color
import kotlin.random.asJavaRandom
/**
* Contains settings for generating random UUIDs.
*
* @property type The type (or version) of UUIDs to generate.
* @property quotation The string that encloses the generated UUID on both sides.
* @property customQuotation The grouping separator defined in the custom option.
* @property capitalization The capitalization mode of the generated UUID.
* @property addDashes `true` if and only if the UUID should have dashes in it.
* @property arrayDecorator Settings that determine whether the output should be an array of values.
*/
data class UuidScheme(
var type: Int = DEFAULT_TYPE,
var quotation: String = DEFAULT_QUOTATION,
var customQuotation: String = DEFAULT_CUSTOM_QUOTATION,
var capitalization: CapitalizationMode = DEFAULT_CAPITALIZATION,
var addDashes: Boolean = DEFAULT_ADD_DASHES,
var arrayDecorator: ArrayDecorator = ArrayDecorator()
) : Scheme() {
@get:Transient
override val name = Bundle("uuid.title")
override val typeIcon = BASE_ICON
override val decorators: List<SchemeDecorator>
get() = listOf(arrayDecorator)
/**
* Returns random type 4 UUIDs.
*
* @param count the number of type 4 UUIDs to generate
* @return random type 4 UUIDs
*/
override fun generateUndecoratedStrings(count: Int): List<String> {
val generator = when (type) {
TYPE_1 ->
Generators.timeBasedGenerator(
EthernetAddress(random.nextLong()),
UUIDTimer(
random.asJavaRandom(),
null,
object : UUIDClock() {
override fun currentTimeMillis() = random.nextLong()
}
)
)
TYPE_4 -> Generators.randomBasedGenerator(random.asJavaRandom())
else -> error(Bundle("uuid.error.unknown_type", type))
}
return List(count) { generator.generate().toString() }
.map { capitalization.transform(it, random) }
.map {
if (addDashes) it
else it.replace("-", "")
}
.map { inQuotes(it) }
}
/**
* Encapsulates [string] in the quotes defined by [quotation].
*
* @param string the string to encapsulate
* @return [string] encapsulated in the quotes defined by [quotation]
*/
private fun inQuotes(string: String): String {
val startQuote = quotation.getOrNull(0) ?: ""
val endQuote = quotation.getOrNull(1) ?: startQuote
return "$startQuote$string$endQuote"
}
override fun doValidate() =
when {
type !in listOf(TYPE_1, TYPE_4) -> Bundle("uuid.error.unknown_type", type)
quotation.length > 2 -> Bundle("uuid.error.quotation_length")
else -> arrayDecorator.doValidate()
}
override fun deepCopy(retainUuid: Boolean) =
copy(arrayDecorator = arrayDecorator.deepCopy(retainUuid))
.also { if (retainUuid) it.uuid = this.uuid }
/**
* Holds constants.
*/
companion object {
/**
* The base icon for UUIDs.
*/
val BASE_ICON = TypeIcon(RandomnessIcons.SCHEME, "id", listOf(Color(185, 155, 248, 154)))
/**
* The default value of the [type] field.
*/
const val DEFAULT_TYPE = 4
/**
* The default value of the [quotation] field.
*/
const val DEFAULT_QUOTATION = "\""
/**
* The default value of the [quotation] field.
*/
const val DEFAULT_CUSTOM_QUOTATION = "<>"
/**
* The default value of the [capitalization] field.
*/
val DEFAULT_CAPITALIZATION = CapitalizationMode.LOWER
/**
* The default value of the [addDashes] field.
*/
const val DEFAULT_ADD_DASHES = true
/**
* Integer representing a type-1 UUID.
*/
const val TYPE_1 = 1
/**
* Integer representing a type-4 UUID.
*/
const val TYPE_4 = 4
}
}
| mit | b2984944e53231bf3e1357648b7afdd2 | 31.360544 | 100 | 0.613832 | 4.547801 | false | false | false | false |
EvidentSolutions/dalesbred | dalesbred/src/test/kotlin/org/dalesbred/internal/utils/ThrowablesTest.kt | 1 | 2634 | /*
* Copyright (c) 2017 Evident Solutions Oy
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.dalesbred.internal.utils
import org.junit.Assert.fail
import org.junit.Test
import java.io.IOException
import java.sql.SQLException
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class ThrowablesTest {
@Test
fun propagatingRuntimeExceptionReturnsIt() {
val exception = RuntimeException()
assertEquals(exception, Throwables.propagate(exception))
}
@Test
fun propagatingCheckedExceptionWrapsItIntoRuntimeException() {
val exception = Exception()
val propagated = Throwables.propagate(exception)
@Suppress("USELESS_IS_CHECK")
assertTrue { propagated is RuntimeException }
assertEquals(exception, propagated.cause)
}
@Test
fun propagatingErrorThrowsIt() {
val error = MyError()
try {
Throwables.propagate(error)
fail("Expected Error")
} catch (e: MyError) {
assertEquals(error, e)
}
}
@Test
fun propagatingAllowedCheckedExceptionReturnsIt() {
val exception = IOException()
assertEquals(exception, Throwables.propagate(exception, IOException::class.java))
}
@Test
fun propagatingDisallowedExceptionThrowsItWrapped() {
val exception = SQLException()
try {
throw Throwables.propagate(exception, IOException::class.java)
} catch (e: RuntimeException) {
assertEquals(exception, e.cause)
}
}
class MyError : Error()
}
| mit | 299beeaee1eb6fbb759a87065132e4e6 | 31.121951 | 89 | 0.703493 | 4.670213 | false | true | false | false |
ujpv/intellij-rust | src/main/kotlin/org/rust/ide/actions/RustExpandModuleAction.kt | 1 | 2314 | package org.rust.ide.actions
import com.intellij.lang.Language
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.io.FileUtil
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.impl.file.PsiFileImplUtil
import com.intellij.refactoring.RefactoringActionHandler
import com.intellij.refactoring.actions.BaseRefactoringAction
import com.intellij.refactoring.move.moveFilesOrDirectories.MoveFilesOrDirectoriesUtil
import org.rust.ide.utils.checkWriteAccessAllowed
import backcompat.runWriteAction
import org.rust.lang.RustLanguage
import org.rust.lang.core.psi.RustMod
import org.rust.lang.core.psi.impl.RustFile
class RustExpandModuleAction : BaseRefactoringAction() {
override fun isEnabledOnElements(elements: Array<out PsiElement>): Boolean = elements.all { it is RustFile }
override fun getHandler(dataContext: DataContext): RefactoringActionHandler = Handler
override fun isAvailableInEditorOnly(): Boolean = false
override fun isAvailableForLanguage(language: Language): Boolean = language.`is`(RustLanguage)
private object Handler : RefactoringActionHandler {
override fun invoke(project: Project, editor: Editor, file: PsiFile, dataContext: DataContext?) {
if (file is RustFile) {
runWriteAction {
expandModule(file)
}
}
}
override fun invoke(project: Project, elements: Array<out PsiElement>, dataContext: DataContext?) {
runWriteAction {
for (element in elements.filterIsInstance<RustFile>()) {
expandModule(element)
}
}
}
}
companion object {
fun expandModule(file: RustFile) {
checkWriteAccessAllowed()
val dirName = FileUtil.getNameWithoutExtension(file.name)
val directory = file.containingDirectory?.createSubdirectory(dirName)
?: error("Can't expand file: no parent directory for $file at ${file.virtualFile.path}")
MoveFilesOrDirectoriesUtil.doMoveFile(file, directory)
PsiFileImplUtil.setName(file, RustMod.MOD_RS)
}
}
}
| mit | fc585f25509bd81fd7f0aa4cdd5b40ca | 38.220339 | 112 | 0.712619 | 4.987069 | false | false | false | false |
MichaelRocks/lightsaber | gradle-plugin/src/main/java/io/michaelrocks/lightsaber/plugin/JavaLightsaberPlugin.kt | 1 | 5619 | /*
* Copyright 2019 Michael Rozumyanskiy
*
* 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 io.michaelrocks.lightsaber.plugin
import org.gradle.api.GradleException
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.plugins.JavaPlugin
import org.gradle.api.tasks.SourceSet
import org.gradle.api.tasks.SourceSetOutput
import org.gradle.api.tasks.compile.JavaCompile
import java.io.File
class JavaLightsaberPlugin : BaseLightsaberPlugin() {
override fun apply(project: Project) {
super.apply(project)
val lightsaber = project.extensions.create("lightsaber", JavaLightsaberPluginExtension::class.java)
addDependencies()
project.afterEvaluate {
if (project.plugins.hasPlugin("java")) {
setupLightsaberForJava()
if (lightsaber.processTest) {
setupLightsaberForJavaTest()
}
} else {
throw GradleException("Project should use Java plugin")
}
}
}
private fun addDependencies() {
addDependencies(JavaPlugin.IMPLEMENTATION_CONFIGURATION_NAME)
addDependencies(JavaPlugin.TEST_IMPLEMENTATION_CONFIGURATION_NAME)
}
private fun setupLightsaberForJava() {
logger.info("Setting up Lightsaber task for Java project {}...", project.name)
createTasks(project.sourceSets.main, project.tasks.compileJava)
}
private fun setupLightsaberForJavaTest() {
logger.info("Setting up Lightsaber task for Java test project {}...", project.name)
createTasks(project.sourceSets.test, project.tasks.compileTestJava, "test")
}
private fun createTasks(sourceSet: SourceSet, compileTask: JavaCompile, nameSuffix: String = "") {
val suffix = nameSuffix.capitalize()
val lightsaberDir = File(project.buildDir, getLightsaberRelativePath(nameSuffix))
val classesDirs = getClassesDirs(sourceSet.output)
val backupDirs = getBackupDirs(project.buildDir, lightsaberDir, classesDirs)
val sourceDir = File(lightsaberDir, "src")
val classpath = compileTask.classpath.toList()
val bootClasspath =
compileTask.options.bootstrapClasspath?.toList()
?: System.getProperty("sun.boot.class.path")?.split(File.pathSeparator)?.map { File(it) }
?: emptyList()
val lightsaberTask =
createLightsaberProcessTask(
"lightsaberProcess$suffix",
classesDirs,
backupDirs,
sourceDir,
classpath,
bootClasspath
)
val backupTask =
createBackupClassFilesTask("lightsaberBackupClasses$suffix", classesDirs, backupDirs)
configureTasks(lightsaberTask, backupTask, compileTask)
}
private fun getLightsaberRelativePath(suffix: String): String {
return if (suffix.isEmpty()) LIGHTSABER_PATH else LIGHTSABER_PATH + File.separatorChar + suffix
}
private fun getClassesDirs(output: SourceSetOutput): List<File> {
return output.classesDirs.files.toList()
}
private fun getBackupDirs(buildDir: File, lightsaberDir: File, classesDirs: List<File>): List<File> {
return classesDirs.map { classesDir ->
val relativeFile = classesDir.relativeToOrSelf(buildDir)
// XXX: What if relativeFile is rooted? Maybe we need to remove the root part from it.
File(lightsaberDir, relativeFile.path)
}
}
private fun configureTasks(lightsaberTask: LightsaberTask, backupTask: BackupClassesTask, compileTask: Task) {
lightsaberTask.mustRunAfter(compileTask)
lightsaberTask.dependsOn(compileTask)
lightsaberTask.dependsOn(backupTask)
compileTask.finalizedBy(lightsaberTask)
val cleanBackupTask = project.tasks["clean${backupTask.name.capitalize()}"]!!
val cleanLightsaberTask = project.tasks["clean${lightsaberTask.name.capitalize()}"]!!
cleanBackupTask.doFirst {
backupTask.clean()
}
cleanLightsaberTask.doFirst {
lightsaberTask.clean()
}
cleanLightsaberTask.dependsOn(cleanBackupTask)
}
private fun createLightsaberProcessTask(
taskName: String,
classesDirs: List<File>,
backupDirs: List<File>,
sourceDir: File,
classpath: List<File>,
bootClasspath: List<File>
): LightsaberTask {
logger.info("Creating Lightsaber task {}...", taskName)
logger.info(" Source classes directories: {}", backupDirs)
logger.info(" Processed classes directories: {}", classesDirs)
return project.tasks.create(taskName, LightsaberTask::class.java) { task ->
task.description = "Processes .class files with Lightsaber Processor."
task.backupDirs = backupDirs
task.classesDirs = classesDirs
task.sourceDir = sourceDir
task.classpath = classpath
task.bootClasspath = bootClasspath
}
}
private fun createBackupClassFilesTask(
taskName: String,
classesDirs: List<File>,
backupDirs: List<File>
): BackupClassesTask {
return project.tasks.create(taskName, BackupClassesTask::class.java) { task ->
task.description = "Back up original .class files."
task.classesDirs = classesDirs
task.backupDirs = backupDirs
}
}
companion object {
private const val LIGHTSABER_PATH = "lightsaber"
}
}
| apache-2.0 | 90f8c0a0d06ce0b36cf69b189ec7a05b | 33.900621 | 112 | 0.723972 | 4.299158 | false | false | false | false |
spookyUnknownUser/PremiereDowngrader | src/main/kotlin/mainview/MainViewController.kt | 1 | 3456 | package mainview
import data.ChangeVersion
import de.jupf.staticlog.Log
import io.reactivex.rxjavafx.schedulers.JavaFxScheduler
import io.reactivex.rxkotlin.subscribeBy
import io.reactivex.schedulers.Schedulers
import javafx.scene.input.DragEvent
import javafx.stage.FileChooser
import tornadofx.*
import java.io.File
import javax.inject.Inject
/**
* Created on 27/08/2017.
*
* Should provide all logic needed for the MainView
*
* @property changeVersion is an injected interface of the [ChangeVersion] class that changes
* the premiere xml version number
*/
class MainViewController
@Inject constructor(private val changeVersion: ChangeVersion) : Controller() {
/**
* Provides access to the [MainView]
* */
private val mainView: MainView by inject()
/**
* Called after button press or drag, subscribes to the [ChangeVersion.To1] Completable
*
* If the Completable completes successfully, wait for the animation to finish a loop by listening for
* an alert created by the animation, see index.html
*
* @param fileToChange is the premiere [File] to change
* */
private fun changeVersion(fileToChange: File) {
setLoadingScreen()
changeVersion
.To1(fileToChange)
.subscribeOn(Schedulers.computation())
.observeOn(JavaFxScheduler.platform())
.subscribeBy(
onComplete = {
Log.info("Version changed")
mainView.defaultEngine.setOnAlert {
setDefaultScreen()
}
},
onError = { throwable -> Log.error(throwable.toString()) }
)
}
/**
* Sets the state of the screen to a spinner
* */
private fun setLoadingScreen() = with(mainView) {
defaultEngine.load(indexUrl)
root.center = webview
}
/**
* Sets the state of the screen to a the default state (drag and drop or browse)
* */
private fun setDefaultScreen() = with(mainView) {
root.center.opacity = 1.0
root.center = mainView.defaultCenter
defaultEngine.load(null)
}
/**
* Calls the local [changeVersion] function
*
* @param event a [DragEvent] that contains the file path string and other info, like the file extension
* */
fun onDragDropped(event: DragEvent) {
if (isAcceptableFile(event))
changeVersion(fileToChange = File(event.dragboard.files.first().path))
}
/**
* Checks if the file is acceptable input, at the moment that is only premiere files (.prproj)
*
* @param event a [DragEvent] that contains the file path string and other info, like the file extension
* */
fun isAcceptableFile(event: DragEvent): Boolean =
event.dragboard.hasFiles() && event.dragboard.files.first().name.toLowerCase().endsWith(".prproj")
/**
* Sends the premiere file to [changeVersion] by button click
* */
fun onButtonAction() {
val filepath: List<File>? = chooseFile(
title = "Pick a premiere project",
filters = arrayOf(FileChooser.ExtensionFilter("Premiere Projects", "*.prproj")),
mode = FileChooserMode.Single
)
filepath?.let { list -> if (list.isNotEmpty()) changeVersion(list.first()) }
}
} | mit | 57d4bd1a3e63ef3bce594f045538adb0 | 32.892157 | 110 | 0.622685 | 4.626506 | false | false | false | false |
jitsi/jibri | src/main/kotlin/org/jitsi/jibri/api/xmpp/JibriStatusExts.kt | 1 | 2886 | /*
* Copyright @ 2018 Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.jitsi.jibri.api.xmpp
import org.jitsi.xmpp.extensions.health.HealthStatusPacketExt
import org.jitsi.xmpp.extensions.jibri.JibriBusyStatusPacketExt
import org.jitsi.xmpp.extensions.jibri.JibriStatusPacketExt
import org.jitsi.jibri.status.ComponentBusyStatus
import org.jitsi.jibri.status.ComponentHealthStatus
import org.jitsi.jibri.status.JibriStatus
import java.lang.RuntimeException
/**
* Translate the Jibri busy status enum to the jitsi-protocol-jabber version
*/
private fun ComponentBusyStatus.toBusyStatusExt(): JibriBusyStatusPacketExt.BusyStatus {
return when (this) {
ComponentBusyStatus.BUSY -> JibriBusyStatusPacketExt.BusyStatus.BUSY
ComponentBusyStatus.IDLE -> JibriBusyStatusPacketExt.BusyStatus.IDLE
ComponentBusyStatus.EXPIRED -> throw RuntimeException("'EXPIRED' not supported in JibriBusyStatusPacketExt")
}
}
/**
* Translate the Jibri health status enum to the jitsi-protocol-jabber version
*/
private fun ComponentHealthStatus.toHealthStatusExt(): HealthStatusPacketExt.Health {
return when (this) {
ComponentHealthStatus.HEALTHY -> HealthStatusPacketExt.Health.HEALTHY
ComponentHealthStatus.UNHEALTHY -> HealthStatusPacketExt.Health.UNHEALTHY
}
}
/**
* Convert a [JibriStatus] to [JibriStatusPacketExt]
* [shouldBeSentToMuc] should be called before calling this function to ensure the
* status can be translated.
*/
fun JibriStatus.toJibriStatusExt(): JibriStatusPacketExt {
val jibriStatusExt = JibriStatusPacketExt()
val jibriBusyStatusExt = JibriBusyStatusPacketExt()
jibriBusyStatusExt.status = this.busyStatus.toBusyStatusExt()
jibriStatusExt.busyStatus = jibriBusyStatusExt
val jibriHealthStatusExt = HealthStatusPacketExt()
jibriHealthStatusExt.status = this.health.healthStatus.toHealthStatusExt()
jibriStatusExt.healthStatus = jibriHealthStatusExt
return jibriStatusExt
}
/**
* 'Expired' is not a state we reflect in the control MUC (and isn't
* defined by [JibriStatusPacketExt]), it's used only for the
* internal health status so for now we don't see it to the MUC.
*/
fun JibriStatus.shouldBeSentToMuc(): Boolean {
return when (this.busyStatus) {
ComponentBusyStatus.EXPIRED -> false
else -> true
}
}
| apache-2.0 | 90eba2133110c5192ae60ea4bfc55cac | 36.480519 | 116 | 0.767498 | 4.313901 | false | false | false | false |
shantstepanian/obevo | obevo-core/src/main/java/com/gs/obevo/impl/graph/GraphSorter.kt | 1 | 5158 | /**
* Copyright 2017 Goldman Sachs.
* 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.gs.obevo.impl.graph
import com.gs.obevo.util.CollectionUtil
import org.eclipse.collections.api.RichIterable
import org.eclipse.collections.api.list.ImmutableList
import org.eclipse.collections.impl.factory.Lists
import org.jgrapht.DirectedGraph
import org.jgrapht.graph.DefaultEdge
import org.jgrapht.graph.DirectedSubgraph
import org.jgrapht.traverse.TopologicalOrderIterator
import java.util.*
/**
* Iterates through the inputs and graph to come up w/ a proper topological sorting.
*
* We expect that the graph elements should either be Comparable, or a Comparator be provided. This is to guarantee a
* consistent topological order, which is much friendlier for clients to debug and for consistency across different
* environments.
*
* (Note that on a given graph, we could have many valid topological orders, which is what we want to get consistency
* on - see https://en.wikipedia.org/wiki/Topological_sorting).
*/
class GraphSorter {
/**
* Sorts the graph to provide a consistent topological ordering. The vertices of the graph must implement [Comparable]
*
* @param graph The input graph
* @param subsetVertices The subset vertices of the graph we want to sort
*/
fun <T> sortChanges(graph: DirectedGraph<T, DefaultEdge>, subsetVertices: RichIterable<T>): ImmutableList<T> {
return sortChanges(graph, subsetVertices, null)
}
/**
* Sorts the graph to provide a consistent topological ordering.
*
* @param graph The input graph
* @param subsetVertices The subset vertices of the graph we want to sort
* @param comparator The comparator on which to order the vertices to guarantee a consistent topological ordering
*/
fun <T> sortChanges(graph: DirectedGraph<T, DefaultEdge>, subsetVertices: RichIterable<T>, comparator: Comparator<in T>?): ImmutableList<T> {
if (subsetVertices.toSet().size != subsetVertices.size()) {
throw IllegalStateException("Unexpected state - have some dupe elements here: $subsetVertices")
}
val subsetGraph = DirectedSubgraph(
graph, subsetVertices.toSet(), null)
// At one point, we _thought_ that the DirectedSubGraph was dropping vertices that don't have edges, so we
// manually add them back to the graph to ensure that we can still order them.
// However, that no longer seems to be the case. We add a check here just in case this comes up again.
if (subsetVertices.size() != subsetGraph.vertexSet().size) {
throw IllegalArgumentException("This case should never happen! [subsetVertices: " + subsetVertices + ", subsetGraphVertices: " + subsetGraph.vertexSet())
}
return sortChanges(subsetGraph, comparator)
}
/**
* Sorts the graph to provide a consistent topological ordering. The vertices of the graph must implement [Comparable]
*
* @param graph The input graph - all vertices in the graph will be returned in the output list
*/
fun <T> sortChanges(graph: DirectedGraph<T, DefaultEdge>): ImmutableList<T> {
return sortChanges(graph, null as Comparator<T>?)
}
/**
* Sorts the graph to provide a consistent topological ordering.
*
* @param graph The input graph - all vertices in the graph will be returned in the output list
* @param comparator The comparator on which to order the vertices to guarantee a consistent topological ordering
*/
fun <T> sortChanges(graph: DirectedGraph<T, DefaultEdge>, comparator: Comparator<in T>?): ImmutableList<T> {
if (graph.vertexSet().isEmpty()) {
return Lists.immutable.empty()
}
GraphUtil.validateNoCycles(graph)
val iterator = getTopologicalOrderIterator(graph, comparator)
return CollectionUtil.iteratorToList(iterator)
}
private fun <T> getTopologicalOrderIterator(graph: DirectedGraph<T, DefaultEdge>, comparator: Comparator<in T>?): TopologicalOrderIterator<T, DefaultEdge> {
if (comparator != null) {
val queue = PriorityQueue(10, comparator)
return TopologicalOrderIterator(graph, queue)
} else if (graph.vertexSet().iterator().next() is Comparable<*>) {
val queue = PriorityQueue<T>()
return TopologicalOrderIterator(graph, queue)
} else {
throw IllegalArgumentException("Unsortable graph elements - either need to provide a Comparator or have Comparable vertices to guarantee a consistent topological order")
}
}
}
| apache-2.0 | 406e47b4afdb7fe59e04aa61fd015e39 | 45.053571 | 181 | 0.710353 | 4.508741 | false | false | false | false |
TheFallOfRapture/First-Game-Engine | src/main/kotlin/com/morph/engine/input/Keyboard.kt | 2 | 2529 | package com.morph.engine.input
import org.lwjgl.glfw.GLFW.*
object Keyboard {
// PRESS, REPEAT, RELEASE
private val keyEvents: MutableList<StdKeyEvent> = mutableListOf()
@JvmStatic val standardKeyEvents: MutableList<StdKeyEvent> = keyEvents
private val keyDowns: Array<Pair<Boolean, Int>> = Array(GLFW_KEY_LAST - GLFW_KEY_SPACE + 1) { false to 0 }
// UP, DOWN
@JvmStatic val binaryKeyEvents: List<BinKeyEvent>
get() = keyDowns
.mapIndexed { index, (keyDown, mods) ->
BinKeyEvent(if (keyDown) KeyDown else KeyUp, index + GLFW_KEY_SPACE, mods)
}
fun handleKeyEvent(window: Long, key: Int, scancode: Int, action: Int, mods: Int) {
if (key - GLFW_KEY_SPACE >= 0) {
keyEvents.add(StdKeyEvent(getKeyAction(action), key, mods))
if (action == GLFW_PRESS) keyDowns[key - GLFW_KEY_SPACE] = true to mods
if (action == GLFW_RELEASE) keyDowns[key - GLFW_KEY_SPACE] = false to 0
}
}
private fun getKeyAction(action: Int): StdKeyAction = when (action) {
GLFW_PRESS -> KeyPress
GLFW_REPEAT -> KeyRepeat
GLFW_RELEASE -> KeyRelease
else -> throw IllegalArgumentException("Argument is not a valid input action")
}
fun queryUpDown(key: Int, action: BinKeyAction): Boolean {
val e = binaryKeyEvents.last { event -> event.key == key }
return e.action == action
}
fun queryUpDownWithMods(key: Int, action: BinKeyAction, vararg mods: Int): Boolean {
val e = binaryKeyEvents.last { event -> event.key == key }
return e.action == action && mods.all { e.hasMod(it) }
}
fun clear() {
keyEvents.clear()
standardKeyEvents.clear()
}
fun update() {
}
}
sealed class KeyAction
sealed class StdKeyAction : KeyAction()
object KeyPress : StdKeyAction()
object KeyRepeat : StdKeyAction()
object KeyRelease : StdKeyAction()
sealed class BinKeyAction : KeyAction()
object KeyUp : BinKeyAction()
object KeyDown : BinKeyAction()
enum class KeyActions(val action: KeyAction) {
PRESS(KeyPress), REPEAT(KeyRepeat), RELEASE(KeyRelease),
UP(KeyUp), DOWN(KeyDown)
}
sealed class GenericKeyEvent(val key: Int, val mods: Int) {
fun hasMod(modCheck: Int): Boolean {
return mods and modCheck != 0
}
}
class StdKeyEvent(val action: StdKeyAction, key: Int, mods: Int) : GenericKeyEvent(key, mods)
class BinKeyEvent(val action: BinKeyAction, key: Int, mods: Int) : GenericKeyEvent(key, mods)
| mit | 12e4cec16a80f5cb1383cac7168c35cb | 32.72 | 110 | 0.654804 | 3.803008 | false | false | false | false |
vindkaldr/replicator | libreplicator-core/src/main/kotlin/org/libreplicator/core/locator/api/NodeLocatorSettings.kt | 2 | 2866 | /*
* Copyright (C) 2016 Mihály Szabó
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.libreplicator.core.locator.api
import java.net.Inet6Address
import java.net.InetAddress
import java.net.NetworkInterface
private const val DEFAULT_MULTICAST_PORT = 24816
private const val DEFAULT_MULTICAST_PERIOD_IN_MILLISECONDS = 10_000L
private const val DEFAULT_BUFFER_SIZE_IN_BYTES = 1024
class NodeLocatorSettings private constructor(
val multicastAddress: InetAddress,
val multicastPort: Int,
val multicastPeriodInMilliseconds: Long,
val bufferSizeInBytes: Int
) {
companion object {
operator fun invoke(
multicastAddress: String = "",
multicastPort: Int = DEFAULT_MULTICAST_PORT,
multicastPeriodInMilliseconds: Long = DEFAULT_MULTICAST_PERIOD_IN_MILLISECONDS,
bufferSizeInBytes: Int = DEFAULT_BUFFER_SIZE_IN_BYTES
): NodeLocatorSettings {
return NodeLocatorSettings(
getMulticastAddress(
multicastAddress,
fallbackIpv4BroadcastAddress = "255.255.255.255",
fallbackIpv6MulticastAddress = "ff02::1"
),
multicastPort,
multicastPeriodInMilliseconds,
bufferSizeInBytes
)
}
private fun getMulticastAddress(
multicastAddress: String,
fallbackIpv4BroadcastAddress: String,
fallbackIpv6MulticastAddress: String
): InetAddress {
if (multicastAddress.isNotBlank()) return getAddress(multicastAddress)
if (!isIpv6AddressAvailable()) return getAddress(fallbackIpv4BroadcastAddress)
return getAddress(fallbackIpv6MulticastAddress)
}
private fun getAddress(multicastAddress: String) = InetAddress.getByName(multicastAddress)
private fun isIpv6AddressAvailable(): Boolean {
return NetworkInterface.getNetworkInterfaces().asSequence()
.map { it.interfaceAddresses }
.flatten()
.map { it.address }
.any { Inet6Address::class.isInstance(it) }
}
}
}
| gpl-3.0 | d63b0a93a0d47594ba07a381cde45c61 | 38.232877 | 98 | 0.654679 | 4.781302 | false | false | false | false |
anton-okolelov/intellij-rust | src/main/kotlin/org/rust/ide/inspections/RsVariableMutableInspection.kt | 2 | 2484 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.inspections
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.PsiElement
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import org.rust.ide.inspections.fixes.RemoveMutableFix
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.descendantsOfType
import org.rust.lang.core.psi.ext.mutability
import org.rust.lang.core.psi.ext.ancestorStrict
import org.rust.lang.core.psi.ext.selfParameter
class RsVariableMutableInspection : RsLocalInspectionTool() {
override fun getDisplayName() = "No mutable required"
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) =
object : RsVisitor() {
override fun visitPatBinding(o: RsPatBinding) {
if (!o.mutability.isMut) return
val block = o.ancestorStrict<RsBlock>() ?: o.ancestorStrict<RsFunction>() ?: return
if (ReferencesSearch.search(o, LocalSearchScope(block))
.asSequence()
.any { checkOccurrenceNeedMutable(it.element.parent) }) return
if (block.descendantsOfType<RsMacroExpr>().any { checkExprPosition(o, it) }) return
holder.registerProblem(
o,
"Variable `${o.identifier.text}` does not need to be mutable",
RemoveMutableFix()
)
}
}
fun checkExprPosition(o: RsPatBinding, expr: RsMacroExpr) = o.textOffset < expr.textOffset
fun checkOccurrenceNeedMutable(occurrence: PsiElement): Boolean {
val parent = occurrence.parent
when (parent) {
is RsUnaryExpr -> return parent.isMutable || parent.mul != null
is RsBinaryExpr -> return parent.left == occurrence
is RsMethodCall -> {
val ref = parent.reference.resolve() as? RsFunction ?: return true
val self = ref.selfParameter ?: return true
return self.mutability.isMut
}
is RsTupleExpr -> {
val expr = parent.parent as? RsUnaryExpr ?: return true
return expr.isMutable
}
is RsValueArgumentList -> return false
}
return true
}
private val RsUnaryExpr.isMutable: Boolean get() = mut != null
}
| mit | 9c3fb716cc68ec6444a1368265b186f0 | 40.4 | 99 | 0.638486 | 4.851563 | false | false | false | false |
google/horologist | sample/src/main/java/com/google/android/horologist/navsample/NavMenuScreen.kt | 1 | 2801 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.horologist.navsample
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.wear.compose.material.AutoCenteringParams
import androidx.wear.compose.material.ScalingLazyColumn
import androidx.wear.compose.material.ScalingLazyListState
import com.google.android.horologist.compose.focus.RequestFocusWhenActive
import com.google.android.horologist.compose.rotaryinput.rotaryWithFling
import com.google.android.horologist.sample.SampleChip
@Composable
fun NavMenuScreen(
modifier: Modifier = Modifier,
navigateToRoute: (String) -> Unit,
scrollState: ScalingLazyListState
) {
val focusRequester = remember { FocusRequester() }
ScalingLazyColumn(
modifier = modifier.rotaryWithFling(focusRequester, scrollState),
state = scrollState,
horizontalAlignment = Alignment.CenterHorizontally,
autoCentering = AutoCenteringParams(itemIndex = 0)
) {
item {
SampleChip(
onClick = { navigateToRoute(NavScreen.ScalingLazyColumn.route) },
label = "ScalingLazyColumn"
)
}
item {
SampleChip(
onClick = { navigateToRoute(NavScreen.Column.route) },
label = "Column"
)
}
item {
SampleChip(
onClick = { navigateToRoute(NavScreen.Dialog.route) },
label = "Dialog"
)
}
item {
SampleChip(
onClick = { navigateToRoute(NavScreen.Pager.route) },
label = "Pager"
)
}
item {
SampleChip(
onClick = { navigateToRoute(NavScreen.Volume.route) },
label = "Volume (custom scrolling)"
)
}
item {
SampleChip(
onClick = { navigateToRoute(NavScreen.Snackbar.route) },
label = "Snackbar"
)
}
}
RequestFocusWhenActive(focusRequester)
}
| apache-2.0 | c4e3e52f114b53f93eef9a9a6f897130 | 32.345238 | 81 | 0.646555 | 4.771721 | false | false | false | false |
mbarta/scr-redesign | app/src/main/java/me/barta/stayintouch/ui/contactlist/ContactListActivity.kt | 1 | 3529 | package me.barta.stayintouch.ui.contactlist
import android.os.Bundle
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.snackbar.Snackbar
import com.google.android.material.tabs.TabLayoutMediator
import dagger.hilt.android.AndroidEntryPoint
import me.barta.stayintouch.R
import me.barta.stayintouch.common.utils.setNotImplementedClickListener
import me.barta.stayintouch.common.viewbinding.viewBinding
import me.barta.stayintouch.common.viewstate.Failure
import me.barta.stayintouch.common.viewstate.Loading
import me.barta.stayintouch.common.viewstate.Success
import me.barta.stayintouch.data.models.ContactCategory
import me.barta.stayintouch.databinding.ActivityContactListBinding
import me.barta.stayintouch.ui.contactlist.categorylist.CategoryListFragment
@AndroidEntryPoint
class ContactListActivity : AppCompatActivity() {
private val viewModel: ContactListViewModel by viewModels()
private val binding: ActivityContactListBinding by viewBinding(ActivityContactListBinding::inflate)
private var tabLayoutMediator: TabLayoutMediator? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
setUpToolbar()
viewModel.viewState.observe(this) { state ->
when (state) {
is Loading -> showLoading()
is Success -> {
hideLoading()
handleSuccess(state.data)
}
is Failure -> {
hideLoading()
handleError(state.throwable)
}
}
}
}
private fun setUpToolbar() {
setSupportActionBar(binding.toolbar)
actionBar?.title = ""
binding.appBar.addOnOffsetChangedListener(object : AppBarLayout.OnOffsetChangedListener {
var scrollRange = -1
override fun onOffsetChanged(appBarLayout: AppBarLayout, verticalOffset: Int) {
//Initialize the size of the scroll
if (scrollRange == -1) {
scrollRange = appBarLayout.totalScrollRange
}
binding.toolbarArcBackground.scale = 1 + verticalOffset / scrollRange.toFloat()
}
})
with(binding.toolbarContent) {
navigationMenu.setNotImplementedClickListener()
actionSearch.setNotImplementedClickListener()
}
}
private fun showLoading() {
binding.toolbarContent.categoryLoadingProgress.show()
}
private fun hideLoading() {
binding.toolbarContent.categoryLoadingProgress.hide()
}
private fun handleSuccess(categories: List<ContactCategory>) {
tabLayoutMediator?.detach()
binding.viewPager.adapter = SectionsPagerAdapter(this, categories) { pos -> CategoryListFragment.newInstance(pos) }
binding.viewPager.offscreenPageLimit = categories.size
tabLayoutMediator = TabLayoutMediator(binding.tabs, binding.viewPager, true) { tab, position ->
tab.text = categories[position].name
}
tabLayoutMediator?.attach()
}
private fun handleError(error: Throwable) {
Snackbar.make(binding.rootLayout, R.string.error_loading_categories, Snackbar.LENGTH_INDEFINITE)
.setAction(R.string.retry) { viewModel.loadCategories() }
.show()
}
} | mit | f4bcddb488947bc39a5ddd2d6a0c97bd | 35.770833 | 123 | 0.68603 | 5.077698 | false | false | false | false |
googlecodelabs/tv-watchnext | step_final/src/main/java/com/example/android/watchnextcodelab/VideoDetailsFragment.kt | 4 | 9039 | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.example.android.watchnextcodelab
import android.arch.lifecycle.Observer
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.support.v17.leanback.app.DetailsFragment
import android.support.v17.leanback.app.DetailsFragmentBackgroundController
import android.support.v17.leanback.widget.Action
import android.support.v17.leanback.widget.ArrayObjectAdapter
import android.support.v17.leanback.widget.ClassPresenterSelector
import android.support.v17.leanback.widget.DetailsOverviewRow
import android.support.v17.leanback.widget.FullWidthDetailsOverviewRowPresenter
import android.support.v17.leanback.widget.FullWidthDetailsOverviewSharedElementHelper
import android.support.v4.content.ContextCompat
import android.util.Log
import android.widget.Toast
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import com.example.android.watchnextcodelab.channels.scheduleAddingToWatchlist
import com.example.android.watchnextcodelab.channels.scheduleRemoveFromWatchlist
import com.example.android.watchnextcodelab.model.Category
import com.example.android.watchnextcodelab.model.Movie
import com.example.android.watchnextcodelab.presenter.DetailsDescriptionPresenter
import com.example.android.watchnextcodelab.watchlist.WatchlistManager
private const val TAG = "VideoDetailsFragment"
private const val ACTION_WATCH_TRAILER_ID = 1L
private const val ACTION_ADD_TO_LIST_ID = 2L
private const val ACTION_BUY_ID = 3L
private const val ACTION_ADD_TO_LIST_INDEX = 1
private const val DETAIL_THUMB_WIDTH = 274
private const val DETAIL_THUMB_HEIGHT = 274
/*
* LeanbackDetailsFragment extends DetailsFragment, a Wrapper fragment for leanback details screens.
* It shows a detailed view of video and its meta plus related videos.
*/
class VideoDetailsFragment : DetailsFragment() {
private lateinit var selectedMovie: Movie
private lateinit var rowAdapter: ArrayObjectAdapter
private lateinit var presenterSelector: ClassPresenterSelector
private val watchlistManager = WatchlistManager.get()
private var isMovieInWatchList: Boolean = false
private lateinit var detailsBackground: DetailsFragmentBackgroundController
private lateinit var actionAdapter: ArrayObjectAdapter
private lateinit var addToWatchlistAction: Action
private val watchlistObserver = Observer<Category> {
isMovieInWatchList = watchlistManager.isInWatchlist(context, selectedMovie)
addToWatchlistAction.label1 = watchlistActionLabel
actionAdapter.notifyArrayItemRangeChanged(ACTION_ADD_TO_LIST_INDEX, 1)
}
private val watchlistActionLabel: String
get() = if (isMovieInWatchList)
resources.getString(R.string.remove_from_list)
else
resources.getString(R.string.add_to_list)
override fun onCreate(savedInstanceState: Bundle?) {
Log.d(TAG, "onCreate DetailsFragment")
super.onCreate(savedInstanceState)
val param: Movie? = activity.intent.getParcelableExtra(MOVIE)
if( param == null ) {
Log.e(TAG, "Cannot show details for an invalid movie, returning to the MainActivity")
val intent = Intent(activity, MainActivity::class.java)
startActivity(intent)
activity.finish()
return
}
selectedMovie = param
detailsBackground = DetailsFragmentBackgroundController(this)
presenterSelector = ClassPresenterSelector()
rowAdapter = ArrayObjectAdapter(presenterSelector)
isMovieInWatchList = watchlistManager.isInWatchlist(context, selectedMovie)
setupDetailsOverviewRow()
setupDetailsOverviewRowPresenter()
adapter = rowAdapter
initializeBackground(selectedMovie)
watchlistManager.getLiveWatchlist().observeForever(watchlistObserver)
}
override fun onDestroy() {
super.onDestroy()
watchlistManager.getLiveWatchlist().removeObserver(watchlistObserver)
}
private fun initializeBackground(data: Movie) {
detailsBackground.enableParallax()
val options = RequestOptions()
.centerCrop()
.error(R.drawable.default_background)
Glide.with(activity)
.asBitmap()
.load(data.cardImageUrl)
.apply(options)
.into(object : SimpleTarget<Bitmap>() {
override fun onResourceReady(
resource: Bitmap, transition: Transition<in Bitmap>) {
detailsBackground.coverBitmap = resource
rowAdapter.notifyArrayItemRangeChanged(0, rowAdapter.size())
}
})
}
private fun setupDetailsOverviewRow() {
Log.d(TAG, "doInBackground: " + selectedMovie.toString())
val row = DetailsOverviewRow(selectedMovie)
row.imageDrawable = ContextCompat.getDrawable(context, R.drawable.default_background)
val width = convertDpToPixel(activity.applicationContext, DETAIL_THUMB_WIDTH)
val height = convertDpToPixel(activity.applicationContext, DETAIL_THUMB_HEIGHT)
val options = RequestOptions()
.centerCrop()
.error(R.drawable.default_background)
Glide.with(activity)
.asDrawable()
.load(selectedMovie.thumbnailUrl)
.apply(options)
.into(object : SimpleTarget<Drawable>(width, height) {
override fun onResourceReady(
resource: Drawable, transition: Transition<in Drawable>) {
Log.d(TAG, "details overview card image url ready: " + resource)
row.imageDrawable = resource
rowAdapter.notifyArrayItemRangeChanged(0, rowAdapter.size())
}
})
addToWatchlistAction = Action(ACTION_ADD_TO_LIST_ID, watchlistActionLabel)
val watchAction = Action(
ACTION_WATCH_TRAILER_ID,
resources.getString(R.string.watch_trailer_1),
resources.getString(R.string.watch_trailer_2))
val buyAction = Action(
ACTION_BUY_ID,
resources.getString(R.string.buy_1),
selectedMovie.offerPrice)
actionAdapter = listOf(watchAction, addToWatchlistAction, buyAction).toArrayObjectAdapter()
row.actionsAdapter = actionAdapter
rowAdapter += row
}
private fun setupDetailsOverviewRowPresenter() {
// Set detail background.
val detailsPresenter = FullWidthDetailsOverviewRowPresenter(DetailsDescriptionPresenter())
detailsPresenter.backgroundColor =
ContextCompat.getColor(context, R.color.selected_background)
// Hook up transition element.
val sharedElementHelper = FullWidthDetailsOverviewSharedElementHelper()
sharedElementHelper.setSharedElementEnterTransition(activity, SHARED_ELEMENT_NAME)
detailsPresenter.setListener(sharedElementHelper)
detailsPresenter.isParticipatingEntranceTransition = true
detailsPresenter.setOnActionClickedListener { action ->
when(action.id) {
ACTION_WATCH_TRAILER_ID -> {
val intent = Intent(activity, PlaybackActivity::class.java)
intent.putExtra(MOVIE, selectedMovie)
startActivity(intent)
}
ACTION_ADD_TO_LIST_ID -> {
if (isMovieInWatchList) {
scheduleRemoveFromWatchlist(context, selectedMovie)
} else {
scheduleAddingToWatchlist(context, selectedMovie)
}
}
else -> Toast.makeText(activity, action.toString(), Toast.LENGTH_SHORT).show()
}
}
presenterSelector.addClassPresenter(DetailsOverviewRow::class.java, detailsPresenter)
}
private fun convertDpToPixel(context: Context, dp: Int): Int {
val density = context.resources.displayMetrics.density
return Math.round(dp.toFloat() * density)
}
}
| apache-2.0 | 4b8262f1447468d496ea9159995793a9 | 41.04186 | 100 | 0.693108 | 5.092394 | false | false | false | false |
beyama/winter | winter/src/main/kotlin/io/jentz/winter/plugin/Plugins.kt | 1 | 1211 | package io.jentz.winter.plugin
/**
* Container for [Winter plugins][Plugin].
*/
class Plugins private constructor(
private val list: List<Plugin>
): Iterable<Plugin> {
constructor() : this(emptyList())
constructor(vararg plugins: Plugin) : this(plugins.toList())
/**
* The number of registered list.
*/
val size: Int get() = list.size
/**
* Returns true if the plugin is already registered.
*
* @param plugin The plugin to check for.
* @return true if the registry contains the plugin
*/
fun contains(plugin: Plugin): Boolean = list.contains(plugin)
/**
* Returns true if the registry contains no plugin.
*/
fun isEmpty(): Boolean = list.isEmpty()
/**
* Returns true if the registry contains list.
*/
fun isNotEmpty(): Boolean = list.isNotEmpty()
operator fun plus(plugin: Plugin): Plugins =
if (contains(plugin)) this else Plugins(list + plugin)
operator fun minus(plugin: Plugin): Plugins =
if (contains(plugin)) Plugins(list - plugin) else this
override fun iterator(): Iterator<Plugin> = list.iterator()
companion object {
val EMPTY = Plugins()
}
}
| apache-2.0 | 1c65e53c8b37251d65ebf37533920f9c | 23.22 | 65 | 0.631709 | 4.371841 | false | false | false | false |
JimSeker/ui | RecyclerViews/RecyclerViewDemo3_kt/app/src/main/java/edu/cs4730/recyclerviewdemo3_kt/Phonebook_Fragment.kt | 1 | 3102 | package edu.cs4730.recyclerviewdemo3_kt
import androidx.recyclerview.widget.RecyclerView
import androidx.coordinatorlayout.widget.CoordinatorLayout
import android.view.LayoutInflater
import android.view.ViewGroup
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.android.material.snackbar.Snackbar
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.DefaultItemAnimator
import java.util.ArrayList
/**
* heavily modified phonebook example, based on the listview named phone_frag example in the listview examples.
* design note
* yes the remove button is covered by the fab. this is not a great design example
* a swipe to delete should be used instead of a remove button to make this much better design.
*/
class Phonebook_Fragment : Fragment() {
var TAG = "Phone_Fragment"
lateinit var listOfPhonebook: MutableList<Phonebook_DataModel>
lateinit var mRecyclerView: RecyclerView
lateinit var mAdapter: Phonebook_myAdapter
//getting a cast except if I don't fully declare it.
var mCoordinatorLayout: CoordinatorLayout? = null
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val myView = inflater.inflate(R.layout.phonebook_fragment, container, false)
//setup a simple list of data to start with.
listOfPhonebook = setup()
//fab and coordinatorlayout setup.
var fab: FloatingActionButton
mCoordinatorLayout = myView.findViewById<View>(R.id.coordinatorlayout1) as CoordinatorLayout
myView.findViewById<View>(R.id.fab).setOnClickListener {
Snackbar.make(mCoordinatorLayout!!, "add is not implemented.", Snackbar.LENGTH_LONG)
.show()
}
//setup the RecyclerView
mRecyclerView = myView.findViewById(R.id.list)
mRecyclerView.layoutManager = LinearLayoutManager(requireContext())
mRecyclerView.itemAnimator = DefaultItemAnimator()
//setup the adapter, which is myAdapter, see the code.
mAdapter =
Phonebook_myAdapter(listOfPhonebook, R.layout.phonebook_rowlayout, requireContext())
//add the adapter to the recyclerview
mRecyclerView.adapter = mAdapter
return myView
}
fun setup(): MutableList<Phonebook_DataModel> {
val list: MutableList<Phonebook_DataModel> = ArrayList()
list.add(Phonebook_DataModel("Test", "9981728", "[email protected]"))
list.add(Phonebook_DataModel("Test1", "1234455", "[email protected]"))
list.add(Phonebook_DataModel("Test2", "00000", "[email protected]"))
list.add(Phonebook_DataModel("Test3", "00000", "[email protected]"))
list.add(Phonebook_DataModel("Test4", "00000", "test4test.com"))
list.add(Phonebook_DataModel("Test5", "00000", "[email protected]"))
list.add(Phonebook_DataModel("Test6", "00000", "[email protected]"))
return list
}
} | apache-2.0 | 8bf5b712326e142b49c1aa76c4596df7 | 43.328571 | 111 | 0.720181 | 4.463309 | false | true | false | false |
italoag/qksms | data/src/main/java/com/moez/QKSMS/blocking/CallControlBlockingClient.kt | 3 | 3609 | /*
* Copyright (C) 2017 Moez Bhatti <[email protected]>
*
* This file is part of QKSMS.
*
* QKSMS 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.
*
* QKSMS 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 QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.blocking
import android.content.Context
import android.content.Intent
import android.database.Cursor
import android.net.Uri
import androidx.core.database.getStringOrNull
import com.callcontrol.datashare.CallControl
import com.moez.QKSMS.common.util.extensions.isInstalled
import com.moez.QKSMS.extensions.map
import io.reactivex.Completable
import io.reactivex.Single
import timber.log.Timber
import javax.inject.Inject
class CallControlBlockingClient @Inject constructor(
private val context: Context
) : BlockingClient {
private val projection: Array<String> = arrayOf(
//CallControl.Lookup.DISPLAY_NAME, // This has a performance impact on the lookup, and we don't need it
CallControl.Lookup.BLOCK_REASON
)
class LookupResult(cursor: Cursor) {
val blockReason: String? = cursor.getStringOrNull(0)
}
override fun isAvailable(): Boolean = context.isInstalled("com.flexaspect.android.everycallcontrol")
override fun getClientCapability() = BlockingClient.Capability.BLOCK_WITH_PERMISSION
override fun shouldBlock(address: String): Single<BlockingClient.Action> = isBlacklisted(address)
override fun isBlacklisted(address: String): Single<BlockingClient.Action> = Single.fromCallable {
val uri = Uri.withAppendedPath(CallControl.LOOKUP_TEXT_URI, address)
return@fromCallable try {
val blockReason = context.contentResolver.query(uri, projection, null, null, null) // Query URI
?.use { cursor -> cursor.map(::LookupResult) } // Map to Result object
?.find { result -> result.blockReason != null } // Check if any are blocked
?.blockReason // If none are blocked or we errored at some point, return false
when (blockReason) {
null -> BlockingClient.Action.Unblock
else -> BlockingClient.Action.Block(blockReason)
}
} catch (e: Exception) {
Timber.w(e)
BlockingClient.Action.DoNothing
}
}
override fun block(addresses: List<String>): Completable = Completable.fromCallable {
val reports = addresses.map { CallControl.Report(it) }
val reportsArrayList = arrayListOf<CallControl.Report>().apply { addAll(reports) }
CallControl.addRule(context, reportsArrayList, Intent.FLAG_ACTIVITY_NEW_TASK)
}
override fun unblock(addresses: List<String>): Completable = Completable.fromCallable {
val reports = addresses.map { CallControl.Report(it, null, false) }
val reportsArrayList = arrayListOf<CallControl.Report>().apply { addAll(reports) }
CallControl.addRule(context, reportsArrayList, Intent.FLAG_ACTIVITY_NEW_TASK)
}
override fun openSettings() {
CallControl.openBlockedList(context, Intent.FLAG_ACTIVITY_NEW_TASK)
}
}
| gpl-3.0 | 10751164cc7d68936eadeca4e5d77195 | 40.482759 | 115 | 0.707398 | 4.390511 | false | false | false | false |
iluu/algs-progfun | src/main/kotlin/com/hackerrank/SaveThePrisoner.kt | 1 | 422 | package com.hackerrank
import java.util.*
fun main(args: Array<String>) {
val scan = Scanner(System.`in`)
val t = scan.nextInt()
for (i in 1..t) {
val n = scan.nextInt()
val m = scan.nextInt()
val s = scan.nextInt()
println(poisonedSweet(n, m, s))
}
}
fun poisonedSweet(n: Int, m: Int, s: Int): Int {
val idx = (s - 1 + m) % n
return if (idx == 0) n else idx
}
| mit | dc43c82d9505f67544cb5f610c4df17a | 19.095238 | 48 | 0.545024 | 2.930556 | false | false | false | false |
vitalybe/radio-stream | app/android/app/src/main/java/com/radiostream/player/Player.kt | 1 | 3138 | package com.radiostream.player
import com.facebook.react.bridge.Arguments
import com.facebook.react.bridge.WritableMap
import com.radiostream.javascript.bridge.PlayerEventsEmitter
import javax.inject.Inject
import timber.log.Timber
class Player @Inject
constructor(private val mPlaylistPlayerFactory: PlaylistPlayerFactory, private val mPlayerEventsEmitter: PlayerEventsEmitter) : PlaylistControls {
private var mCurrentPlaylistPlayer: PlaylistPlayer? = null
val isPlaying: Boolean
get() {
Timber.i("function start")
if (mCurrentPlaylistPlayer != null) {
Timber.i("returning value based on current song, if any")
return mCurrentPlaylistPlayer!!.isPlaying
} else {
Timber.i("no playlist selected - not playing")
return false
}
}
fun changePlaylist(playlistName: String) {
Timber.i("function start")
if (mCurrentPlaylistPlayer != null) {
mCurrentPlaylistPlayer!!.close()
}
mCurrentPlaylistPlayer = mPlaylistPlayerFactory.build(playlistName) { mPlayerEventsEmitter.sendPlayerStatus(this) }
}
var currentSong: Song? = null
get() = mCurrentPlaylistPlayer?.currentSong
var isLoading: Boolean = true
get() = if (mCurrentPlaylistPlayer == null) true else mCurrentPlaylistPlayer!!.isLoading
override suspend fun play() {
Timber.i("function start")
if (mCurrentPlaylistPlayer == null) {
throw IllegalStateException("playlist must be set")
}
return mCurrentPlaylistPlayer!!.play()
}
override fun pause() {
Timber.i("function start")
if (mCurrentPlaylistPlayer == null) {
throw IllegalStateException("playlist must be set")
}
mCurrentPlaylistPlayer!!.pause()
}
override suspend fun playNext() {
Timber.i("function start")
if (mCurrentPlaylistPlayer == null) {
throw IllegalStateException("playlist must be set")
}
mCurrentPlaylistPlayer!!.playNext()
}
override suspend fun skipToSongByIndex(index: Int) {
Timber.i("function start")
if (mCurrentPlaylistPlayer == null) {
throw IllegalStateException("playlist must be set")
}
mCurrentPlaylistPlayer!!.skipToSongByIndex(index)
}
fun close() {
Timber.i("function start")
if (mCurrentPlaylistPlayer != null) {
mCurrentPlaylistPlayer!!.close()
}
}
fun toBridgeObject(): WritableMap {
val map = Arguments.createMap()
map.putMap("playlistPlayer", if (mCurrentPlaylistPlayer != null) mCurrentPlaylistPlayer!!.toBridgeObject() else null)
return map
}
suspend fun updateSongRating(songId: Int, newRating: Int) {
Timber.i("function start")
if (mCurrentPlaylistPlayer != null) {
return mCurrentPlaylistPlayer!!.updateSongRating(songId, newRating)
} else {
Timber.w("playlist unavailable - song rating is unavailable")
}
}
}
| mit | 3e24a75b9682f75be47444054c859431 | 28.055556 | 146 | 0.640854 | 4.926217 | false | false | false | false |
http4k/http4k | http4k-serverless/tencent/src/main/kotlin/org/http4k/serverless/TencentCloudFunction.kt | 1 | 2352 | @file:Suppress("unused")
package org.http4k.serverless
import com.qcloud.scf.runtime.Context
import com.qcloud.services.scf.runtime.events.APIGatewayProxyRequestEvent
import com.qcloud.services.scf.runtime.events.APIGatewayProxyResponseEvent
import org.http4k.core.Body
import org.http4k.core.Filter
import org.http4k.core.HttpHandler
import org.http4k.core.MemoryBody
import org.http4k.core.Method
import org.http4k.core.Request
import org.http4k.core.RequestContexts
import org.http4k.core.Response
import org.http4k.core.Uri
import org.http4k.core.then
import org.http4k.filter.ServerFilters.CatchAll
import org.http4k.filter.ServerFilters.InitialiseRequestContext
const val TENCENT_REQUEST_KEY = "HTTP4K_TENCENT_REQUEST"
const val TENCENT_CONTEXT_KEY = "HTTP4K_TENCENT_CONTEXT"
abstract class TencentCloudFunction(appLoader: AppLoaderWithContexts) {
constructor(input: AppLoader) : this(AppLoaderWithContexts { env, _ -> input(env) })
constructor(input: HttpHandler) : this(AppLoader { input })
private val contexts = RequestContexts("tencent")
private val app = appLoader(System.getenv(), contexts)
fun handleRequest(request: APIGatewayProxyRequestEvent, context: Context?) =
CatchAll()
.then(InitialiseRequestContext(contexts))
.then(AddTencent(request, context, contexts))
.then(app)(request.asHttp4kRequest())
.asTencent()
}
private fun AddTencent(request: APIGatewayProxyRequestEvent, ctx: Context?, contexts: RequestContexts) = Filter { next ->
{
ctx?.apply { contexts[it][TENCENT_CONTEXT_KEY] = this }
contexts[it][TENCENT_REQUEST_KEY] = request
next(it)
}
}
private fun APIGatewayProxyRequestEvent.asHttp4kRequest(): Request {
val withHeaders = (headers ?: emptyMap()).toList().fold(
Request(Method.valueOf(httpMethod), buildUri())
.body(body?.let(::MemoryBody) ?: Body.EMPTY)) { memo, (first, second) ->
memo.header(first, second)
}
return queryStringParameters.entries.fold(withHeaders) { acc, (first, second) -> acc.query(first, second) }
}
private fun APIGatewayProxyRequestEvent.buildUri() =
Uri.of(path)
private fun Response.asTencent() = APIGatewayProxyResponseEvent().also {
it.statusCode = status.code
it.headers = headers.toMap()
it.body = bodyString()
}
| apache-2.0 | c88a4e33618bc6a79a1ec630dddb0693 | 35.75 | 121 | 0.734694 | 3.640867 | false | false | false | false |
requery/requery | requery-kotlin/src/main/kotlin/io/requery/kotlin/QueryDelegate.kt | 1 | 9387 | /*
* Copyright 2017 requery.io
*
* 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 io.requery.kotlin
import io.requery.meta.EntityModel
import io.requery.query.Condition
import io.requery.query.Expression
import io.requery.query.Return
import io.requery.query.element.*
import io.requery.util.function.Supplier
import java.util.*
import kotlin.reflect.KClass
class ExistsDelegate<E : Any>(element: ExistsElement<E>, query : QueryDelegate<E>)
: Exists<SetGroupByOrderByLimit<E>>, QueryWrapper<E> by query {
private val element: ExistsElement<E> = element
private val query : QueryDelegate<E> = query
override fun exists(query: Return<*>): SetGroupByOrderByLimit<E> {
element.exists(query)
return this.query
}
override fun notExists(query: Return<*>): SetGroupByOrderByLimit<E> {
element.notExists(query)
return this.query
}
}
class HavingDelegate<E : Any>(element: HavingConditionElement<E>, query
: QueryDelegate<E>) : HavingAndOr<E>, QueryWrapper<E> by query {
private var element : HavingConditionElement<E> = element
private var query : QueryDelegate<E> = query
override fun limit(limit: Int): Offset<E> {
query.limit(limit)
return query
}
override fun `as`(alias: String?): Return<E>? {
query.`as`(alias)
return query
}
override fun getAlias(): String? = query.alias
override fun get(): E = query.get()
override fun <V> and(condition: Condition<V, *>): HavingAndOr<E> =
HavingDelegate(element.and(condition) as HavingConditionElement<E>, query)
override fun <V> or(condition: Condition<V, *>): HavingAndOr<E> =
HavingDelegate(element.or(condition) as HavingConditionElement<E>, query)
override fun <V> orderBy(expression: Expression<V>): Limit<E> {
query.orderBy(expression)
return query
}
override fun orderBy(vararg expressions: Expression<*>): Limit<E> {
query.orderBy(*expressions)
return query
}
}
class WhereDelegate<E : Any>(element: WhereConditionElement<E>, query : QueryDelegate<E>)
: WhereAndOr<E>, SetGroupByOrderByLimit<E> by query, QueryWrapper<E> by query {
private var element : WhereConditionElement<E> = element
private var query : QueryDelegate<E> = query
override fun <V> and(condition: Condition<V, *>): WhereAndOr<E> =
WhereDelegate(element.and(condition) as WhereConditionElement<E>, query)
override fun <V> or(condition: Condition<V, *>): WhereAndOr<E> =
WhereDelegate(element.or(condition) as WhereConditionElement<E>, query)
}
class JoinDelegate<E : Any>(element : JoinConditionElement<E>, query: QueryDelegate<E>)
: JoinAndOr<E>, JoinWhereGroupByOrderBy<E> by query, QueryWrapper<E> by query {
private var element : JoinConditionElement<E> = element
private var query : QueryDelegate<E> = query
override fun <V> and(condition: Condition<V, *>): JoinAndOr<E> =
JoinDelegate(element.and(condition) as JoinConditionElement<E>, query)
override fun <V> or(condition: Condition<V, *>): JoinAndOr<E> =
JoinDelegate(element.or(condition) as JoinConditionElement<E>, query)
}
class JoinOnDelegate<E : Any>(element : JoinOnElement<E>, query : QueryDelegate<E>)
: JoinOn<E>, QueryWrapper<E> by query {
private var query : QueryDelegate<E> = query
private var element : JoinOnElement<E> = element
override fun <V> on(field: Condition<V, *>): JoinAndOr<E> {
val join = element.on(field) as JoinConditionElement<E>
return JoinDelegate(join, query)
}
}
class QueryDelegate<E : Any>(element : QueryElement<E>) :
Selectable<E>,
Selection<E>,
DistinctSelection<E>,
Insertion<E>,
InsertInto<E>,
Update<E>,
Deletion<E>,
JoinWhereGroupByOrderBy<E>,
SetGroupByOrderByLimit<E>,
SetHavingOrderByLimit<E>,
OrderByLimit<E>,
Offset<E>,
QueryWrapper<E> {
private var element : QueryElement<E> = element
constructor(type : QueryType, model : EntityModel, operation : QueryOperation<E>)
: this(QueryElement(type, model, operation))
override fun unwrapQuery(): QueryElement<E> = element
override fun select(vararg attributes: Expression<*>): Selection<E> {
element.select(*attributes)
return this
}
override fun union(): Selectable<E> = QueryDelegate(element.union() as QueryElement<E>)
override fun unionAll(): Selectable<E> = QueryDelegate(element.unionAll() as QueryElement<E>)
override fun intersect(): Selectable<E> = QueryDelegate(element.intersect() as QueryElement<E>)
override fun except(): Selectable<E> = QueryDelegate(element.except() as QueryElement<E>)
override fun join(type: KClass<out Any>): JoinOn<E> =
JoinOnDelegate(element.join(type.java) as JoinOnElement<E>, this)
override fun leftJoin(type: KClass<out Any>): JoinOn<E> =
JoinOnDelegate(element.leftJoin(type.java) as JoinOnElement<E>, this)
override fun rightJoin(type: KClass<out Any>): JoinOn<E> =
JoinOnDelegate(element.rightJoin(type.java) as JoinOnElement<E>, this)
override fun <J> join(query: Return<J>): JoinOn<E> =
JoinOnDelegate(element.join(query) as JoinOnElement<E>, this)
override fun <J> leftJoin(query: Return<J>): JoinOn<E> =
JoinOnDelegate(element.leftJoin(query) as JoinOnElement<E>, this)
override fun <J> rightJoin(query: Return<J>): JoinOn<E> =
JoinOnDelegate(element.rightJoin(query) as JoinOnElement<E>, this)
override fun groupBy(vararg expressions: Expression<*>): SetHavingOrderByLimit<E> {
element.groupBy(*expressions)
return this
}
override fun <V> groupBy(expression: Expression<V>): SetHavingOrderByLimit<E> {
element.groupBy(expression)
return this
}
override fun <V> having(condition: Condition<V, *>): HavingAndOr<E> =
HavingDelegate(element.having(condition) as HavingConditionElement<E>, this)
override fun <V> orderBy(expression: Expression<V>): Limit<E> {
element.orderBy(expression)
return this
}
override fun orderBy(vararg expressions: Expression<*>): Limit<E> {
element.orderBy(*expressions)
return this
}
@Suppress("UNCHECKED_CAST")
override fun where(): Exists<SetGroupByOrderByLimit<E>> =
ExistsDelegate(element.where() as ExistsElement<E>, this)
override fun <V> where(condition: Condition<V, *>): WhereAndOr<E> =
WhereDelegate(element.where(condition) as WhereConditionElement<E>, this)
override fun `as`(alias: String?): Return<E>? = element.`as`(alias)
override fun getAlias(): String? = element.alias
override fun distinct(): DistinctSelection<E> {
element.distinct()
return this
}
override fun from(vararg types: KClass<out Any>): JoinWhereGroupByOrderBy<E> {
val javaClasses = Array<Class<*>?>(types.size, {i -> types[i].java })
element.from(*javaClasses)
return this
}
override fun from(vararg types: Class<out Any>): JoinWhereGroupByOrderBy<E> {
element.from(*types)
return this
}
override fun from(vararg subqueries: Supplier<*>): JoinWhereGroupByOrderBy<E> {
val list = ArrayList<QueryDelegate<*>>()
subqueries.forEach { it -> run {
val element = it.get()
if (it is QueryDelegate) {
list.add(element as QueryDelegate<*>)
}
} }
return this
}
override fun get(): E = element.get()
override fun limit(limit: Int): Offset<E> {
element.limit(limit)
return this
}
override fun offset(offset: Int): Return<E> = element.offset(offset)
override fun <V> value(expression: Expression<V>, value: V): Insertion<E> {
element.value(expression, value)
return this
}
override fun <V> set(expression: Expression<V>, value: V): Update<E> {
element.set(expression, value)
return this
}
override fun equals(other: Any?): Boolean {
if (other is QueryDelegate<*>) {
return other.element.equals(element)
}
return false
}
override fun hashCode(): Int = element.hashCode()
@Suppress("UNCHECKED_CAST")
fun <F : E> extend(transform: io.requery.util.function.Function<E, F>): QueryDelegate<F> {
element.extend(transform)
return this as QueryDelegate<F>
}
override fun query(query: Return<*>): Return<E> {
element.query((query as QueryDelegate).element)
return this
}
fun insertColumns(expressions: Array<out QueryableAttribute<*,*>>): InsertInto<E> {
element.insertColumns(expressions)
return this
}
}
| apache-2.0 | 8cc2b1c6db065ddcea7d81b84b592576 | 33.01087 | 99 | 0.663045 | 4.021851 | false | false | false | false |
joan-domingo/Podcasts-RAC1-Android | app/src/main/java/cat/xojan/random1/feature/home/ProgramListAdapter.kt | 1 | 2134 | package cat.xojan.random1.feature.home
import android.support.v4.media.MediaBrowserCompat
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import cat.xojan.random1.R
import cat.xojan.random1.feature.browser.BrowseActivity
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import kotlinx.android.extensions.LayoutContainer
import kotlinx.android.synthetic.main.program_item.*
import java.util.*
class ProgramListAdapter: RecyclerView.Adapter<ProgramListAdapter.MediaItemViewHolder>() {
var programs: List<MediaBrowserCompat.MediaItem> = emptyList()
set(value) {
field = value
notifyDataSetChanged()
}
override fun getItemCount(): Int = programs.size
override fun onBindViewHolder(holder: MediaItemViewHolder, position: Int) {
holder.bind(programs[position])
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MediaItemViewHolder {
val itemView = LayoutInflater.from(parent.context)
.inflate(R.layout.program_item, parent, false)
return MediaItemViewHolder(itemView)
}
class MediaItemViewHolder(override val containerView: View) : RecyclerView
.ViewHolder(containerView), LayoutContainer {
fun bind(item: MediaBrowserCompat.MediaItem) {
itemView.setOnClickListener{
val intent = BrowseActivity.newIntent(itemView.context, item)
itemView.context.startActivity(intent)
}
val description = item.description
programTitle.text = description.title
Glide.with(itemView.context)
.load(description.iconUri.toString() + "?w=" + getWeekOfTheYear())
.apply(RequestOptions()
.placeholder(R.drawable.placeholder))
.into(programImage)
}
private fun getWeekOfTheYear(): Int {
val cal = Calendar.getInstance()
return cal.get(Calendar.WEEK_OF_YEAR)
}
}
} | mit | 9abc33c02d05bf8970d4abcf64b68f9a | 35.810345 | 92 | 0.682755 | 4.928406 | false | false | false | false |
rock3r/detekt | detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/exceptions/ThrowingExceptionInMainSpec.kt | 1 | 3365 | package io.gitlab.arturbosch.detekt.rules.exceptions
import io.gitlab.arturbosch.detekt.test.compileAndLint
import io.gitlab.arturbosch.detekt.test.lint
import org.assertj.core.api.Assertions.assertThat
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
class ThrowingExceptionInMainSpec : Spek({
val subject by memoized { ThrowingExceptionInMain() }
describe("ThrowingExceptionInMain rule") {
it("reports a runnable main function which throws an exception") {
val code = """
fun main(args: Array<String>) { throw IllegalArgumentException() }
fun main() { throw IllegalArgumentException() }
"""
assertThat(subject.compileAndLint(code)).hasSize(2)
}
it("reports runnable main functions with @JvmStatic annotation which throw an exception") {
val code = """
class A {
companion object {
@JvmStatic
fun main(args: Array<String>) { throw IllegalArgumentException() }
}
}
class B {
companion object {
@kotlin.jvm.JvmStatic
fun main() { throw IllegalArgumentException() }
}
}
object O {
@JvmStatic
fun main(args: Array<String>) { throw IllegalArgumentException() }
}
"""
assertThat(subject.compileAndLint(code)).hasSize(3)
}
it("does not report top level main functions with a wrong signature") {
val code = """
private fun main(args: Array<String>) { throw IllegalArgumentException() }
private fun main() { throw IllegalArgumentException() }
fun mai() { throw IllegalArgumentException() }
fun main(args: String) { throw IllegalArgumentException() }
fun main(args: Array<String>, i: Int) { throw IllegalArgumentException() }"""
assertThat(subject.lint(code)).isEmpty()
}
it("does not report top level main functions which throw no exception") {
val code = """
fun main(args: Array<String>) { }
fun main() { }
fun mai() { }
fun main(args: String) { }"""
assertThat(subject.compileAndLint(code)).isEmpty()
}
it("does not report top level main functions with expression body which throw no exception") {
val code = """
fun main(args: Array<String>) = ""
fun main() = Unit
"""
assertThat(subject.compileAndLint(code)).isEmpty()
}
it("does not report main functions with no @JvmStatic annotation inside a class") {
val code = """
class A {
fun main(args: Array<String>) { throw IllegalArgumentException() }
companion object {
fun main(args: Array<String>) { throw IllegalArgumentException() }
}
}
"""
assertThat(subject.compileAndLint(code)).isEmpty()
}
}
})
| apache-2.0 | 9106ca9b16748350d1ea50be32ed7d1d | 38.127907 | 102 | 0.532541 | 5.608333 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/libanki/DB.kt | 1 | 12402 | /****************************************************************************************
* Copyright (c) 2009 Daniel Svärd <[email protected]> *
* Copyright (c) 2009 Nicolas Raoul <[email protected]> *
* Copyright (c) 2009 Andrew <[email protected]> *
* Copyright (c) 2011 Norbert Nagold <[email protected]> *
* Copyright (c) 2018 Mike Hardy <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
*/
package com.ichi2.libanki
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.database.SQLException
import android.database.sqlite.SQLiteDatabase
import androidx.sqlite.db.SupportSQLiteDatabase
import com.ichi2.anki.BuildConfig
import com.ichi2.anki.CollectionHelper
import com.ichi2.anki.CrashReportService.sendExceptionReport
import com.ichi2.anki.dialogs.DatabaseErrorDialog
import com.ichi2.utils.DatabaseChangeDecorator
import com.ichi2.utils.KotlinCleanup
import net.ankiweb.rsdroid.Backend
import net.ankiweb.rsdroid.database.AnkiSupportSQLiteDatabase
import org.intellij.lang.annotations.Language
import timber.log.Timber
import java.lang.Exception
import java.lang.RuntimeException
import java.util.ArrayList
import kotlin.Throws
/**
* Database layer for AnkiDroid. Wraps an SupportSQLiteDatabase (provided by either the Rust backend
* or the Android framework), and provides some helpers on top.
*/
@KotlinCleanup("Improve documentation")
class DB(db: SupportSQLiteDatabase) {
/**
* The collection, which is actually an SQLite database.
*/
val database: SupportSQLiteDatabase = DatabaseChangeDecorator(db)
var mod = false
/**
* The default AnkiDroid SQLite database callback.
*
* IMPORTANT: this disables the default Android behaviour of removing the file if corruption
* is encountered.
*
* We do not handle versioning or connection config using the framework APIs, so those methods
* do nothing in our implementation. However, we on corruption events we want to send messages but
* not delete the database.
*
* Note: this does not apply when using the Rust backend (ie for Collection)
*/
class SupportSQLiteOpenHelperCallback(version: Int) : AnkiSupportSQLiteDatabase.DefaultDbCallback(version) {
/** Send error message when corruption is encountered. We don't call super() as we don't accidentally
* want to opt-in to the standard Android behaviour of removing the corrupted file, but as we're
* inheriting from DefaultDbCallback which does not call super either, it would be technically safe
* if we did so. */
override fun onCorruption(db: SupportSQLiteDatabase) {
Timber.e("The database has been corrupted: %s", db.path)
sendExceptionReport(
RuntimeException("Database corrupted"),
"DB.MyDbErrorHandler.onCorruption",
"Db has been corrupted: " + db.path
)
CollectionHelper.instance.closeCollection(false, "Database corrupted")
DatabaseErrorDialog.databaseCorruptFlag = true
}
}
/**
* Closes a previously opened database connection.
*/
fun close() {
try {
database.close()
Timber.d("Database %s closed = %s", database.path, !database.isOpen)
} catch (e: Exception) {
// The pre-framework requery API ate this exception, but the framework API exposes it.
// We may want to propagate it in the future, but for now maintain the old API and log.
Timber.e(e, "Failed to close database %s", database.path)
}
}
fun commit() {
// SQLiteDatabase db = getDatabase();
// while (db.inTransaction()) {
// db.setTransactionSuccessful();
// db.endTransaction();
// }
// db.beginTransactionNonExclusive();
}
// Allows to avoid using new Object[]
fun query(@Language("SQL") query: String?, vararg selectionArgs: Any): Cursor {
return database.query(query, selectionArgs)
}
/**
* Convenience method for querying the database for a single integer result.
*
* @param query The raw SQL query to use.
* @return The integer result of the query.
*/
fun queryScalar(@Language("SQL") query: String?, vararg selectionArgs: Any): Int {
var cursor: Cursor? = null
val scalar: Int
try {
cursor = database.query(query, selectionArgs)
if (!cursor.moveToNext()) {
return 0
}
scalar = cursor.getInt(0)
} finally {
cursor?.close()
}
return scalar
}
@Throws(SQLException::class)
fun queryString(@Language("SQL") query: String, vararg bindArgs: Any): String {
database.query(query, bindArgs).use { cursor ->
if (!cursor.moveToNext()) {
throw SQLException("No result for query: $query")
}
return cursor.getString(0)
}
}
fun queryLongScalar(@Language("SQL") query: String, vararg bindArgs: Any): Long {
var scalar: Long
database.query(query, bindArgs).use { cursor ->
if (!cursor.moveToNext()) {
return 0
}
scalar = cursor.getLong(0)
}
return scalar
}
/**
* Convenience method for querying the database for an entire column of long.
*
* @param query The SQL query statement.
* @return An ArrayList with the contents of the specified column.
*/
fun queryLongList(@Language("SQL") query: String, vararg bindArgs: Any): ArrayList<Long> {
val results = ArrayList<Long>()
database.query(query, bindArgs).use { cursor ->
while (cursor.moveToNext()) {
results.add(cursor.getLong(0))
}
}
return results
}
/**
* Convenience method for querying the database for an entire column of String.
*
* @param query The SQL query statement.
* @return An ArrayList with the contents of the specified column.
*/
fun queryStringList(@Language("SQL") query: String, vararg bindArgs: Any): ArrayList<String> {
val results = ArrayList<String>()
database.query(query, bindArgs).use { cursor ->
while (cursor.moveToNext()) {
results.add(cursor.getString(0))
}
}
return results
}
fun execute(@Language("SQL") sql: String, vararg `object`: Any?) {
val s = sql.trim { it <= ' ' }.lowercase()
// mark modified?
for (mo in MOD_SQL_STATEMENTS) {
if (s.startsWith(mo)) {
mod = true
break
}
}
database.execSQL(sql, `object`)
}
/**
* WARNING: This is a convenience method that splits SQL scripts into separate queries with semicolons (;)
* as the delimiter. Only use this method on internal functions where we can guarantee that the script does
* not contain any non-statement-terminating semicolons.
*/
@KotlinCleanup("""Use Kotlin string. Change split so that there is no empty string after last ";".""")
fun executeScript(@Language("SQL") sql: String) {
mod = true
@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") val queries = java.lang.String(sql).split(";")
for (query in queries) {
database.execSQL(query)
}
}
/** update must always be called via DB in order to mark the db as changed */
fun update(
table: String,
values: ContentValues,
whereClause: String? = null,
whereArgs: Array<String>? = null
): Int {
mod = true
return database.update(table, SQLiteDatabase.CONFLICT_NONE, values, whereClause, whereArgs)
}
/** insert must always be called via DB in order to mark the db as changed */
fun insert(table: String, values: ContentValues): Long {
mod = true
return database.insert(table, SQLiteDatabase.CONFLICT_NONE, values)
}
fun executeMany(@Language("SQL") sql: String, list: List<Array<out Any?>>) {
mod = true
if (BuildConfig.DEBUG) {
if (list.size <= 1) {
Timber.w(
"Query %s called with a list of at most one element. Usually that's not expected.",
sql
)
}
}
executeInTransaction { executeManyNoTransaction(sql, list) }
}
/** Use this executeMany version with external transaction management */
fun executeManyNoTransaction(@Language("SQL") sql: String, list: List<Array<out Any?>>) {
mod = true
for (o in list) {
database.execSQL(sql, o)
}
}
/**
* @return The full path to this database file.
*/
val path: String
get() = database.path ?: ":memory:"
fun <T> executeInTransaction(r: () -> T): T {
// Ported from code which started the transaction outside the try..finally
database.beginTransaction()
try {
val result = r()
if (database.inTransaction()) {
try {
database.setTransactionSuccessful()
} catch (e: Exception) {
// Unsure if this can happen - copied the structure from endTransaction()
Timber.w(e)
}
} else {
Timber.w("Not in a transaction. Cannot mark transaction successful.")
}
return result
} finally {
safeEndInTransaction(database)
}
}
companion object {
private val MOD_SQL_STATEMENTS = arrayOf("insert", "update", "delete")
/**
* Open a connection using the system framework.
*/
fun withAndroidFramework(context: Context, path: String): DB {
val db = AnkiSupportSQLiteDatabase.withFramework(
context,
path,
SupportSQLiteOpenHelperCallback(1)
)
db.disableWriteAheadLogging()
db.query("PRAGMA synchronous = 2", null)
return DB(db)
}
/**
* Wrap a Rust backend connection (which provides an SQL interface).
* Caller is responsible for opening&closing the database.
*/
fun withRustBackend(backend: Backend): DB {
return DB(AnkiSupportSQLiteDatabase.withRustBackend(backend))
}
fun safeEndInTransaction(database: DB) {
safeEndInTransaction(database.database)
}
fun safeEndInTransaction(database: SupportSQLiteDatabase) {
if (database.inTransaction()) {
try {
database.endTransaction()
} catch (e: Exception) {
// endTransaction throws about invalid transaction even when you check first!
Timber.w(e)
}
} else {
Timber.w("Not in a transaction. Cannot end transaction.")
}
}
}
}
| gpl-3.0 | 3da353b5c6b9b6676c3b27e38a42aae2 | 37.996855 | 112 | 0.580921 | 4.952476 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/anki/dialogs/tags/TagsArrayAdapter.kt | 1 | 18675 | /*
Copyright (c) 2021 Tarek Mohamed Abdalla <[email protected]>
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 3 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ichi2.anki.dialogs.tags
import android.content.res.Resources
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.annotation.VisibleForTesting
import androidx.recyclerview.widget.RecyclerView
import com.ichi2.anki.R
import com.ichi2.annotations.NeedsTest
import com.ichi2.ui.CheckBoxTriStates
import com.ichi2.ui.CheckBoxTriStates.State.*
import com.ichi2.utils.TagsUtil
import com.ichi2.utils.TypedFilter
import java.util.*
/**
* @param tags A reference to the {@link TagsList} passed.
*/
class TagsArrayAdapter(private val tags: TagsList, private val resources: Resources) : RecyclerView.Adapter<TagsArrayAdapter.ViewHolder>(), Filterable {
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
internal lateinit var node: TagTreeNode
internal val mExpandButton: ImageButton = itemView.findViewById(R.id.id_expand_button)
internal val mCheckBoxView: CheckBoxTriStates = itemView.findViewById(R.id.tags_dialog_tag_item_checkbox)
// TextView contains the displayed tag (only the last part), while the full tag is stored in TagTreeNode
internal val mTextView: TextView = itemView.findViewById(R.id.tags_dialog_tag_item_text)
@get:VisibleForTesting(otherwise = VisibleForTesting.NONE)
val text: String
get() = node.tag
@get:VisibleForTesting(otherwise = VisibleForTesting.NONE)
val isChecked: Boolean
get() = mCheckBoxView.isChecked
@get:VisibleForTesting(otherwise = VisibleForTesting.NONE)
val checkboxState: CheckBoxTriStates.State
get() = mCheckBoxView.state
}
/**
* The node class of the tag tree.
* @param tag The full tag that the node represents.
* @param parent The parent of the node (null for the root).
* @param children The children of the node.
* @param level The level of the tag in the tree (-1 for the root).
* @param subtreeSize The size of the subtree if the node is expanded. This exists because
* we want to save the [isExpanded] state of child tags, even if the parent is not expanded.
* When we expand a tag, we do not want to walk the tree to determine how many nodes were added or removed.
* @param isExpanded whether the node is expanded or not
* @param subtreeCheckedCnt The number of checked nodes in the subtree (self included). This exists
* because we want to dynamically turn a checkbox from unchecked into indeterminate if at least one of its
* descendants is checked, or from indeterminate to unchecked if all of its descendants are unchecked.
* @param vh The reference to currently bound [ViewHolder]. A node bound with some [ViewHolder] must have [vh] nonnull.
* @see onBindViewHolder for the binding
*/
@NeedsTest("Make sure that the data structure works properly.")
data class TagTreeNode(
val tag: String,
val parent: TagTreeNode?,
val children: ArrayList<TagTreeNode>,
val level: Int,
var subtreeSize: Int,
var isExpanded: Boolean,
var subtreeCheckedCnt: Int,
var vh: ViewHolder?
) {
/**
* Get or set the checkbox state of the currently bound ViewHolder.
* [vh] must be nonnull.
*/
private var checkBoxState: CheckBoxTriStates.State
get() = vh!!.mCheckBoxView.state
set(state) {
vh!!.mCheckBoxView.state = state
}
/**
* Return the number of visible nodes in the subtree.
* If [isExpanded] is set to false, the subtree is collapsed, only the node itself is visible.
* Otherwise, the subtree is expanded and visible.
*
* @return The number of visible nodes in the subtree.
*/
fun getContributeSize(): Int {
return if (isExpanded) subtreeSize else 1
}
/**
* @return If the node has one or more children.
*/
fun isNotLeaf(): Boolean {
return children.isNotEmpty()
}
/**
* Toggle the expand state of the node, then iterate up to the root to maintain the tree.
* Should never be called on the root node [mTreeRoot].
*/
fun toggleIsExpanded() {
isExpanded = !isExpanded
val delta = if (isExpanded) subtreeSize - 1 else 1 - subtreeSize
for (ancestor in iterateAncestorsOf(this)) {
ancestor.subtreeSize += delta
if (!ancestor.isExpanded) {
break
}
}
}
/**
* Set the cycle style of the node's [vh]'s checkbox.
* For nodes without checked descendants: CHECKED -> UNCHECKED -> CHECKED -> ...
* For nodes with checked descendants: CHECKED -> INDETERMINATE -> CHECKED -> ...
*
* @param tags The [TagsList] that manages tags.
*/
fun updateCheckBoxCycleStyle(tags: TagsList) {
val realSubtreeCnt = subtreeCheckedCnt - if (tags.isChecked(tag)) 1 else 0
val hasDescendantChecked = realSubtreeCnt > 0
vh!!.mCheckBoxView.cycleIndeterminateToChecked = hasDescendantChecked
vh!!.mCheckBoxView.cycleCheckedToIndeterminate = hasDescendantChecked
}
/**
* When the checkbox of the node changes, update [subtreeCheckedCnt]s of itself and its ancestors.
* If the checkbox is INDETERMINATE now, it must be CHECKED before according to the checkbox cycle style.
* @see updateCheckBoxCycleStyle
*
* Update the checkbox to INDETERMINATE if it was UNCHECK and now [subtreeCheckedCnt] > 0.
* Update the checkbox to UNCHECK if it was INDETERMINATE and now [subtreeCheckedCnt] == 0.
*
* @param tags The [TagsList] that manages tags.
*/
fun onCheckStateChanged(tags: TagsList) {
val delta = if (checkBoxState == CHECKED) 1 else -1
fun update(node: TagTreeNode) {
node.subtreeCheckedCnt += delta
if (node.checkBoxState == UNCHECKED && node.subtreeCheckedCnt > 0) {
tags.setIndeterminate(node.tag)
node.checkBoxState = INDETERMINATE
}
if (node.checkBoxState == INDETERMINATE && node.subtreeCheckedCnt == 0) {
tags.uncheck(node.tag)
node.checkBoxState = UNCHECKED
}
node.updateCheckBoxCycleStyle(tags)
}
update(this)
for (ancestor in iterateAncestorsOf(this)) {
// do not perform update on the virtual root
if (ancestor.parent != null) {
update(ancestor)
}
}
}
companion object {
fun iterateAncestorsOf(start: TagTreeNode) = object : Iterator<TagTreeNode> {
var current = start
override fun hasNext(): Boolean = current.parent != null
override fun next(): TagTreeNode {
current = current.parent!!
return current
}
}
}
}
/**
* A subset of all tags in [tags] satisfying the user's search.
* @see getFilter
*/
private val mFilteredList: ArrayList<String>
/**
* The root node of the tag tree.
*/
private lateinit var mTreeRoot: TagTreeNode
/**
* A mapping from tag strings to corresponding nodes.
*/
private val mTagToNode: HashMap<String, TagTreeNode>
/**
* Whether there exists visible nested tag.
* Recalculated everytime [buildTagTree] is called.
*/
private var mHasVisibleNestedTag: Boolean
/**
* A mapping from tag strings to its expand state.
* Used to restore expand states between filtering results.
* Must be updated every time a node's [TagTreeNode.isExpanded] changed.
*/
private val mTagToIsExpanded: HashMap<String, Boolean>
/**
* Long click listener for each tag item. Used to add a subtag for the clicked tag.
* The full tag is passed through View.tag
*/
var tagLongClickListener: View.OnLongClickListener? = null
fun sortData() {
tags.sort()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val v = LayoutInflater.from(parent.context)
.inflate(R.layout.tags_item_list_dialog, parent, false)
val vh = ViewHolder(v.findViewById(R.id.tags_dialog_tag_item))
// clicking the checkbox toggles the tag's check state
vh.mCheckBoxView.setOnClickListener {
val checkBox = vh.mCheckBoxView
when (checkBox.state) {
CHECKED -> tags.check(vh.node.tag, false)
UNCHECKED -> tags.uncheck(vh.node.tag)
INDETERMINATE -> tags.setIndeterminate(vh.node.tag)
}
vh.node.onCheckStateChanged(tags)
}
// clicking other parts toggles the expansion state, or the checkbox (for leaf)
vh.itemView.setOnClickListener {
if (vh.node.isNotLeaf()) {
vh.node.toggleIsExpanded()
mTagToIsExpanded[vh.node.tag] = !mTagToIsExpanded[vh.node.tag]!!
updateExpanderBackgroundImage(vh.mExpandButton, vh.node)
// content of RecyclerView may change due to the expansion / collapse
val deltaSize = vh.node.subtreeSize - 1
if (vh.node.isExpanded) {
notifyItemRangeInserted(vh.layoutPosition + 1, deltaSize)
} else {
notifyItemRangeRemoved(vh.layoutPosition + 1, deltaSize)
}
} else {
// tapping on a leaf node toggles the checkbox
vh.mCheckBoxView.performClick()
}
}
// long clicking a tag opens the add tag dialog with the current tag as the prefix
vh.itemView.setOnLongClickListener(tagLongClickListener)
return vh
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.node = getVisibleTagTreeNode(position)!!
holder.node.vh = holder
holder.itemView.tag = holder.node.tag
if (mHasVisibleNestedTag) {
holder.mExpandButton.visibility = if (holder.node.isNotLeaf()) View.VISIBLE else View.INVISIBLE
updateExpanderBackgroundImage(holder.mExpandButton, holder.node)
// shift according to the level
val lp = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
lp.setMargins(HIERARCHY_SHIFT_BASE * holder.node.level, 0, 0, 0)
holder.mExpandButton.layoutParams = lp
} else {
// do not add padding if there is no visible nested tag
holder.mExpandButton.visibility = View.GONE
}
holder.mExpandButton.contentDescription = resources.getString(R.string.expand_tag, holder.node.tag.replace("::", " "))
holder.mTextView.text = TagsUtil.getTagParts(holder.node.tag).last()
if (tags.isIndeterminate(holder.node.tag)) {
holder.mCheckBoxView.state = INDETERMINATE
} else {
holder.mCheckBoxView.state = if (tags.isChecked(holder.node.tag)) CHECKED else UNCHECKED
}
holder.node.updateCheckBoxCycleStyle(tags)
}
/**
* Find the [TagTreeNode] of the [index]-th visible tag.
* Implemented by walking the tree using [TagTreeNode.subtreeSize].
*
* @param index The index of the node to find.
* @return The corresponding [TagTreeNode]. Null if out-of-bound.
*/
private fun getVisibleTagTreeNode(index: Int): TagTreeNode? {
var remain = index
var node = mTreeRoot
while (remain < node.subtreeSize) {
for (child in node.children) {
if (remain >= child.getContributeSize()) {
remain -= child.getContributeSize()
} else {
if (remain == 0) {
return child
} else {
remain -= 1
node = child
break
}
}
}
}
return null
}
/**
* @return The number of visible tags.
*/
override fun getItemCount(): Int {
return mTreeRoot.subtreeSize
}
/**
* Build the tag tree. The tags have been sorted using the hierarchical comparator
* [TagsUtil.compareTag], which leads to a DFN order. Use a stack to build the tree without
* recursion.
* The initial expand states are inherited through [mTagToIsExpanded].
* A special tag can be set so that the path to it is expanded.
*
* @param expandTarget The target tag to expand. Do nothing if it is empty or not found.
*/
private fun buildTagTree(expandTarget: String) {
// init mapping for newly added tags
mFilteredList.forEach {
if (!mTagToIsExpanded.containsKey(it)) {
mTagToIsExpanded[it] = tags.isChecked(it) || tags.isIndeterminate(it)
}
}
TagsUtil.getTagAncestors(expandTarget).forEach {
if (mTagToIsExpanded.containsKey(it)) {
mTagToIsExpanded[it] = true
}
}
mHasVisibleNestedTag = false
val stack = Stack<TagTreeNode>()
mTreeRoot = TagTreeNode("", null, ArrayList(), -1, 0, true, 0, null)
stack.add(mTreeRoot)
mTagToNode.clear()
fun stackPopAndPushUp() {
val popped = stack.pop()
stack.peek().subtreeSize += popped.getContributeSize()
stack.peek().subtreeCheckedCnt += popped.subtreeCheckedCnt
}
for (tag in mFilteredList) {
// root will never be popped
while (stack.size > 1) {
if (!tag.startsWith(stack.peek().tag + "::")) {
stackPopAndPushUp()
} else {
break
}
}
val parent = stack.peek()
val node = TagTreeNode(tag, parent, ArrayList(), parent.level + 1, 1, mTagToIsExpanded[tag]!!, if (tags.isChecked(tag)) 1 else 0, null)
parent.children.add(node)
mTagToNode[tag] = node
stack.add(node)
if (stack.size > 2) {
mHasVisibleNestedTag = true
}
}
while (stack.size > 1) {
stackPopAndPushUp()
}
}
/**
* Set the background resource of the [ImageButton] according to information of the given [TagTreeNode].
*
* @param button The [ImageButton] to update.
* @param node The corresponding [TagTreeNode].
*/
private fun updateExpanderBackgroundImage(button: ImageButton, node: TagTreeNode) {
// More custom display related to the node can be added here.
// For example, display some icon if the node is a leaf? (assets required)
when (node.isExpanded) {
true -> button.setBackgroundResource(R.drawable.ic_expand_more_black_24dp_xml)
false -> button.setBackgroundResource(R.drawable.ic_baseline_chevron_right_24)
}
}
override fun getFilter(): TagsFilter {
return TagsFilter()
}
/* Custom Filter class - as seen in http://stackoverflow.com/a/29792313/1332026 */
inner class TagsFilter : TypedFilter<String>({ tags.toList() }) {
/**
* A tag may be set so that the path to it is expanded immediately after the filter displays the result.
* When empty, nothing is to be expanded.
* It is cleared every time after the filtered result is calculated.
* @see publishResults
*/
private var mExpandTarget = String()
override fun filterResults(constraint: CharSequence, items: List<String>): List<String> {
val shownTags = TreeSet<String>()
val filterPattern = constraint.toString().lowercase(Locale.getDefault()).trim { it <= ' ' }
val crucialTags = items.filter {
it.lowercase(Locale.getDefault()).contains(filterPattern)
}
shownTags.addAll(crucialTags)
// the ancestors should be displayed as well
for (tag in crucialTags) {
shownTags.addAll(TagsUtil.getTagAncestors(tag))
}
// show tags in the relative order in original list
val res = items.filter { shownTags.contains(it) }
// mark shown tags as expanded, so that they will be expanded next time the tree is built
res.forEach { mTagToIsExpanded[it] = true }
return res
}
override fun publishResults(constraint: CharSequence?, results: List<String>) {
mFilteredList.clear()
mFilteredList.addAll(results)
sortData()
buildTagTree(mExpandTarget)
mExpandTarget = String()
notifyDataSetChanged()
}
/**
* Set the target to expand in the next filtering (optional).
* @see mExpandTarget
*/
fun setExpandTarget(tag: String) {
mExpandTarget = tag
}
}
init {
sortData()
mFilteredList = ArrayList(tags.toList())
mTagToNode = HashMap()
mTagToIsExpanded = HashMap()
// set the initial expand state according to its checked state
tags.forEach { mTagToIsExpanded[it] = tags.isChecked(it) || tags.isIndeterminate(it) }
mHasVisibleNestedTag = false
buildTagTree(String())
}
companion object {
const val HIERARCHY_SHIFT_BASE = 50
}
}
| gpl-3.0 | e5d0148cdb4ab06789ab98a9749fbbd2 | 39.597826 | 152 | 0.61178 | 4.70403 | false | false | false | false |
magnusja/libaums | libaums/src/main/java/me/jahnen/libaums/core/partition/mbr/MasterBootRecord.kt | 2 | 4035 | /*
* (C) Copyright 2014 mjahnen <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package me.jahnen.libaums.core.partition.mbr
import android.util.Log
import me.jahnen.libaums.core.partition.PartitionTable
import me.jahnen.libaums.core.partition.PartitionTableEntry
import me.jahnen.libaums.core.partition.PartitionTypes
import java.io.IOException
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.util.*
/**
* This class represents the Master Boot Record (MBR), which is a partition
* table used by most block devices coming from Windows or Unix.
*
* @author mjahnen
*/
class MasterBootRecord private constructor() : PartitionTable {
private val partitions = ArrayList<PartitionTableEntry>()
override val size: Int
get() = 512
override val partitionTableEntries: List<PartitionTableEntry>
get() = partitions
companion object {
private val partitionTypes = object : HashMap<Int, Int>() {
init {
put(0x0b, PartitionTypes.FAT32)
put(0x0c, PartitionTypes.FAT32)
put(0x1b, PartitionTypes.FAT32)
put(0x1c, PartitionTypes.FAT32)
put(0x01, PartitionTypes.FAT12)
put(0x04, PartitionTypes.FAT16)
put(0x06, PartitionTypes.FAT16)
put(0x0e, PartitionTypes.FAT16)
put(0x83, PartitionTypes.LINUX_EXT)
put(0x07, PartitionTypes.NTFS_EXFAT)
put(0xaf, PartitionTypes.APPLE_HFS_HFS_PLUS)
}
}
private val TAG = MasterBootRecord::class.java.simpleName
private const val TABLE_OFFSET = 446
private const val TABLE_ENTRY_SIZE = 16
/**
* Reads and parses the MBR located in the buffer.
*
* @param buffer
* The data which shall be examined.
* @return A new [.MasterBootRecord] or null if the data does not
* seem to be a MBR.
*/
@Throws(IOException::class)
fun read(buffer: ByteBuffer): MasterBootRecord? {
val result = MasterBootRecord()
buffer.order(ByteOrder.LITTLE_ENDIAN)
if (buffer.limit() < 512) {
throw IOException("Size mismatch!")
}
// test if it is a valid master boot record
if (buffer.get(510) != 0x55.toByte() || buffer.get(511) != 0xaa.toByte()) {
Log.i(TAG, "not a valid mbr partition table!")
return null
}
for (i in 0..3) {
val offset = TABLE_OFFSET + i * TABLE_ENTRY_SIZE
val partitionType = buffer.get(offset + 4)
// unused partition
if (partitionType.toInt() == 0)
continue
if (partitionType.toInt() == 0x05 || partitionType.toInt() == 0x0f) {
Log.w(TAG, "extended partitions are currently unsupported!")
continue
}
var type = partitionTypes[partitionType.toInt() and 0xff]
if (type == null) {
Log.d(TAG, "Unknown partition type$partitionType")
type = PartitionTypes.UNKNOWN
}
val entry = PartitionTableEntry(type,
buffer.getInt(offset + 8), buffer.getInt(offset + 12))
result.partitions.add(entry)
}
return result
}
}
}
| apache-2.0 | f6bcdfe6f66de4a01b98d63e5ae4680e | 32.07377 | 87 | 0.593309 | 4.292553 | false | false | false | false |
pdvrieze/ProcessManager | java-common/src/javaMain/kotlin/net/devrieze/util/StringRep.kt | 1 | 27602 | /*
* Copyright (c) 2018.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
/*
* Created on Jan 9, 2004
*
*/
@file:Suppress("DEPRECATION")
package net.devrieze.util
/**
*
*
* As there is no easy uniform way to access chararrays, stringbuffers and
* strings, this class is a wrapper for any of them.
*
*
*
* Note that the respective functions can return the original data that was
* entered in the wrapper. They do not copy it when not necessary.
*
*
* @author Paul de Vrieze
* @version 1.0 $Revision$
*/
@Deprecated("Stale class that shouldn't be used")
abstract class StringRep : CharSequence {
/**
* A class implementing StringRep for an array of characters.
*
* @author Paul de Vrieze
* @version 1.0 $Revision$
*
* @constructor Create a new CharArrayStringRep based on the given character array.
*
* @param element The character array to be wrapped.
*/
private class CharArrayStringRep constructor(private val element: CharArray) : StringRep() {
override fun get(index: Int): Char {
return element[index]
}
override val length: Int get() = element.size
override fun toCharArray(): CharArray {
return element.clone()
}
override fun toString(): String {
return String(element)
}
override fun toStringBuffer(): StringBuffer {
val result = StringBuffer(element.size)
result.append(element)
return result
}
override fun toStringBuilder(): StringBuilder {
val result = StringBuilder(element.size)
result.append(element)
return result
}
}
/**
* A class that represents a stringrep for a character array that is only
* partly used for the string.
*
* @author Paul de Vrieze
* @version 1.0 $Revision$
*
* @constructor Create a new StringRep based on this character array.
*
* @param begin the index of the first character
* @param end the index of the first character not belonging to the string
* @param element the string to base the rep of.
*/
private class IndexedCharArrayStringRep constructor(private val begin: Int,
private val end: Int,
private val element: CharArray) : StringRep() {
init {
if (end < begin || begin < 0 || end >= element.size) {
throw IndexOutOfBoundsException()
}
}
override fun get(index: Int): Char {
val innerIndex = index + begin
if (innerIndex >= end) {
throw IndexOutOfBoundsException("$innerIndex >= ${end - begin}")
}
return element[innerIndex]
}
override val length: Int get() = end - begin
override fun toCharArray(): CharArray {
return element.sliceArray(begin until end)
}
override fun toString(): String {
return String(element, begin, end - begin)
}
override fun toStringBuffer(): StringBuffer {
val length = end - begin
val result = StringBuffer(length)
result.append(element, begin, length)
return result
}
override fun toStringBuilder(): StringBuilder {
val length = end - begin
val result = StringBuilder(length)
result.append(element, begin, length)
return result
}
}
/**
* @constructor Create a new RepStringRep.
*
* @param begin the start index of the substring
* @param end the end index of the substring
* @param element The string to base this one of
*/
private class RepStringRep constructor(private val begin: Int,
private val end: Int,
private val element: StringRep) : StringRep() {
init {
if (end < begin || begin < 0 || end > element.length) {
throw IndexOutOfBoundsException()
}
}
override fun get(index: Int): Char {
val innerIndex = index + begin
if (innerIndex >= end) {
throw IndexOutOfBoundsException(Integer.toString(index) + " >= " + Integer.toString(end - begin))
}
return element[innerIndex]
}
override fun substring(pStart: Int, pEnd: Int): StringRep {
if (pStart < 0 || pEnd > length) {
throw IndexOutOfBoundsException()
}
val begin = begin + pStart
val end = begin + pEnd - pStart
return createRep(begin, end, element)
}
override val length: Int get() = end - begin
override fun toCharArray(): CharArray {
return element.toCharArray().sliceArray(begin until end)
}
override fun toString(): String {
return String(element.toCharArray(), begin, end - begin)
}
override fun toStringBuffer(): StringBuffer {
val length = end - begin
val foo = StringBuffer(length)
foo.append(element.toCharArray(), begin, length)
return foo
}
override fun toStringBuilder(): StringBuilder {
val length = end - begin
val foo = StringBuilder(length)
foo.append(element.toCharArray(), begin, length)
return foo
}
}
/**
* @constructor Create a new StringBufferStringRep based on this element.
*
* @param element the stringbuffer to base of
*/
private class CharSequenceStringRep constructor(private val element: CharSequence) : StringRep() {
override fun get(index: Int): Char {
return element[index]
}
override val length: Int get() = element.length
override fun toCharArray(): CharArray {
val buffer = CharArray(element.length)
for (i in buffer.indices) {
buffer[i] = element[i]
}
return buffer
}
override fun toString(): String {
return element.toString()
}
override fun toStringBuffer(): StringBuffer {
return element as? StringBuffer ?: StringBuffer(element)
}
override fun toStringBuilder(): StringBuilder {
return element as? StringBuilder ?: StringBuilder(element)
}
}
/**
* @constructor Create a new StringStringRep based on this string.
*
* @param element the string to base the rep on.
*/
private class StringStringRep constructor(private val element: String) : StringRep() {
override fun get(index: Int): Char {
return element[index]
}
override val length: Int get() = element.length
override fun toCharArray(): CharArray {
return element.toCharArray()
}
override fun toString(): String {
return element
}
override fun toStringBuffer(): StringBuffer {
return StringBuffer(element)
}
override fun toStringBuilder(): StringBuilder {
return StringBuilder(element)
}
}
/**
* @constructor Create a new iterator.
*
* @param stringRep The StringRep to iterate over
* @param token The token that splits the elements
* @param quotes `true` if quotes need to be taken into account, `false` if not
*/
private class StringRepIteratorImpl constructor(
private val stringRep: StringRep,
private val token: Char,
private val quotes: Boolean,
private val openQuotes: CharArray,
private val closeQuotes: CharArray) : StringRepIterator {
constructor(stringRep: StringRep, token: Char, quotes: Boolean) :
this(stringRep, token, quotes, charArrayOf(), charArrayOf()) {
if (stringRep.length > pos) {
/* trim on whitespace from left */
var c = stringRep[pos]
while (pos < stringRep.length && (c == ' ' || c == '\n' || c == '\t')) {
pos++
if (pos < stringRep.length) {
c = stringRep[pos]
}
}
}
}
private var last: StringRep? = null
private var pos = 0 /* current position in the stream */
/**
* Create a new iterator.
*
* @param stringRep The StringRep to iterate over
* @param token The token that splits the elements
* @param quotes A string in which quotes are presented pairwise. For
* example at pQuotes[0] the value is '(' and pQuotes[1]==')'
*/
constructor(stringRep: StringRep, token: Char, quotes: CharSequence) :
this(stringRep, token, true,
CharArray(quotes.length / 2) { quotes[it * 2] },
CharArray(quotes.length / 2) { quotes[it * 2 + 1] })
/*
* the check on mLast is necessary to have empty strings not return
* anything
*/
override fun hasNext(): Boolean {
return if (pos == stringRep.length && last != null) {
true
} else pos < stringRep.length
}
/**
* Get the previous element.
*
* @return the previously returned value.
*/
override fun last(): StringRep {
return last!!
}
/**
* Get the next element.
*
* @return the next element to be returned
*/
override fun next(): StringRep {
if (pos == stringRep.length) {
pos++ /* remember to increase, else we get an endless loop */
return createRep("")
}
val newPos: Int = when {
quotes -> nextPosQuoted()
else -> nextPos()
}
var right = newPos - 1
/* trim on right whitespace */
var c = stringRep[right]
while (pos <= right && (c == ' ' || c == '\n' || c == '\t')) {
right--
c = stringRep[right]
}
last = stringRep.substring(pos, right + 1)
pos = newPos + 1 /* increase as at newPos is the token. */
if (pos < stringRep.length) {
/* trim on whitespace from left */
c = stringRep[pos]
while (pos < stringRep.length && (c == ' ' || c == '\n' || c == '\t')) {
pos++
c = stringRep[pos]
}
}
return last!!
}
private fun nextPos(): Int {
for (i in pos until stringRep.length) {
if (stringRep[i] == token) {
return i
}
}
return stringRep.length
}
private fun nextPosQuoted(): Int {
/* TODO refactor this function */
var quote = false
if (openQuotes.isEmpty()) {
var i = pos
while (i < stringRep.length) {
val c = stringRep[i]
if (quote) {
if (c == '\\') {
i++ /* skip next char */
} else if (c == '"') {
quote = false
}
} else if (c == token) {
return i
} else if (c == '"') {
quote = true
}
i++
}
} else {
val stack = IntStack()
var i = pos
while (i < stringRep.length) {
val c = stringRep[i]
if (!stack.isEmpty) {
if (c == '\\') {
i++ /* skip next char */
} else if (c == closeQuotes[stack.peek()]) {
stack.pop()
} else {
for (j in openQuotes.indices) {
if (c == openQuotes[j]) {
stack.push(j)
break
}
}
}
} else if (c == token) {
return i
} else {
for (j in openQuotes.indices) {
if (c == openQuotes[j]) {
stack.push(j)
break
}
}
}
i++
}
if (!stack.isEmpty) {
quote = true
}
}
if (quote) {
throw NumberFormatException("Closing quote missing in a quoted split")
}
return stringRep.length
}
}
/**
* Append the text to the buffer.
*
* @param buffer The buffer to which the text must be appended
* @return the stringbuffer
*/
@Deprecated("Replaced by implementation of CharSequence")
fun bufferAppend(buffer: StringBuffer): StringBuffer {
buffer.append(this)
return buffer
}
/**
* Insert itself into a stringbuffer.
*
* @param index The index of insertion
* @param inBuffer The stringbuffer
* @return the stringbuffer
*/
@Deprecated("Replaced by implementation of CharSequence")
fun bufferInsert(index: Int, inBuffer: StringBuffer): StringBuffer {
inBuffer.insert(index, this)
return inBuffer
}
/**
* append the string to a new rep.
*
* @param rep the to be appended string
* @return the result
*/
fun appendCombine(rep: CharSequence): StringRep {
val b = toStringBuilder()
b.append(rep)
return createRep(b)
}
/**
* Check whether the rep ends with the the character.
*
* @param char the character
* @return `true` if it is the last char
*/
fun endsWith(char: Char): Boolean {
return get(length - 1) == char
}
/**
* Get the index of a character in the buffer.
*
* @param pChar The character to be found
* @param pQuote If `true` take quotes into account
* @return -1 if not found, else the index of the character
*/
fun indexOf(pChar: Char, pQuote: Boolean): Int {
return indexOf(pChar, 0, pQuote)
}
/**
* Get the index of a character in the buffer.
*
* @param pChar The character to be found
* @param pQuotes The quotes to take into account
* @return -1 if not found, else the index of the character
*/
fun indexOf(pChar: Char, pQuotes: CharSequence): Int {
return indexOf(pChar, 0, pQuotes)
}
/**
* Get the index of a character in the buffer. Not that the startindex should
* not be within a quoted area if quotes are taken into account.
*
* @param pChar The character to be found
* @param pStartIndex the index where searching should start
* @param pQuote If `true` take quotes into account
* @return -1 if not found, else the index of the character
* @throws NumberFormatException When quotes in the string are unmatched
*/
fun indexOf(pChar: Char, pStartIndex: Int, pQuote: Boolean): Int {
var quote = false
for (i in pStartIndex until length) {
if (pQuote && get(i) == '"') {
if (quote) {
if (i == 0 || get(i - 1) != '\\') {
quote = false
}
} else {
quote = true
}
} else if (!quote && get(i) == pChar) {
return i
}
}
if (quote) {
throw NumberFormatException("Closing quote missing in a quoted indexOf")
}
return -1
}
/**
* Get the index of a character in the buffer. Not that the startindex should
* not be within a quoted area if quotes are taken into account.
*
* @param char The character to be found
* @param pStartIndex the index where searching should start
* @param pQuotes The quote characters, Alternating the starting quote and the
* closing quote. The opening quotes at the even indices, the closing
* at the odd.
* @return -1 if not found, else the index of the character
* @throws NumberFormatException When quotes are unmatched
*/
fun indexOf(char: Char, pStartIndex: Int, pQuotes: CharSequence?): Int {
/* TODO refactor this function */
var quote = false
if (pQuotes == null) {
var i = pStartIndex
while (i < length) {
val c = get(i)
if (quote) {
if (c == '\\') {
i++ /* skip next char */
} else if (c == '"') {
quote = false
}
} else if (c == char) {
return i
} else if (c == '"') {
quote = true
}
i++
}
} else {
val openQuotes = CharArray(pQuotes.length / 2)
val closeQuotes = CharArray(openQuotes.size)
for (i in openQuotes.indices) {
openQuotes[i] = pQuotes[i * 2]
closeQuotes[i] = pQuotes[i * 2 + 1]
}
val stack = IntStack()
var i = pStartIndex
while (i < length) {
val c = get(i)
if (!stack.isEmpty) {
if (c == '\\') {
i++ /* skip next char */
} else if (c == closeQuotes[stack.peek()]) {
stack.pop()
} else {
for (j in openQuotes.indices) {
if (c == openQuotes[j]) {
stack.push(j)
break
}
}
}
} else if (c == char) {
return i
} else {
for (j in openQuotes.indices) {
if (c == openQuotes[j]) {
stack.push(j)
break
}
}
}
i++
}
if (!stack.isEmpty) {
quote = true
}
}
if (quote) {
throw NumberFormatException("Closing quote missing in a quoted indexOf")
}
return -1
}
/**
* Insert a string into the rep.
*
* @param pIndex the index
* @param pIn the stringrep to be inserted
* @return the resulting rep
*/
fun insertCombine(pIndex: Int, pIn: CharSequence): StringRep {
val b = toStringBuilder()
b.insert(pIndex, pIn)
return createRep(b)
}
/**
* Create a quoted representation of this rep.
*
* @return the new quoted rep
*/
fun quote(): StringRep {
return quote(this)
}
/**
* Create an iterator for splitting a stringrep into substrings separated by
* the token.
*
* @param pToken the token
* @param pQuotes if `true`, double quotes are recognised
* @return the iterator
*/
fun splitOn(pToken: Char, pQuotes: Boolean): StringRepIterator {
return StringRepIteratorImpl(this, pToken, pQuotes)
}
/**
* Create an iterator for splitting a stringrep into substrings separated by
* the token.
*
* @param token the token
* @param quotes if `true`, double quotes are recognised
* @return the iterator
*/
fun splitOn(token: Char, quotes: CharSequence): StringRepIterator {
return StringRepIteratorImpl(this, token, quotes)
}
/**
* Create an iterator for splitting a stringrep into substrings separated by
* the token, however taking quotes into account.
*
* @param pToken the token
* @return the iterator
*/
fun splitOn(pToken: Char): StringRepIterator {
return StringRepIteratorImpl(this, pToken, _DEFAULTQUOTES)
}
/**
* Check whether the rep starts with the the character.
*
* @param pChar the character
* @return `true` if it is the first char
*/
fun startsWith(pChar: Char): Boolean {
return if (length == 0) {
false
} else get(0) == pChar
}
/**
* a chararray representation.
*
* @return a chararray
*/
abstract fun toCharArray(): CharArray
/**
* The stringbuffer representation.
*
* @return the stringbuffer
*/
abstract fun toStringBuffer(): StringBuffer
/**
* The stringbuffer representation.
*
* @return the stringbuffer
*/
abstract fun toStringBuilder(): StringBuilder
/**
* Create a substring representation.
*
* @param pStart The starting character
* @param pEnd The end character (exclusive)
* @return A new rep (note that this can be the same one, but does not need to
* be)
*/
open fun substring(pStart: Int, pEnd: Int): StringRep {
if (pStart < 0 || pEnd > length) {
throw IndexOutOfBoundsException()
}
return RepStringRep(pStart, pEnd, this)
}
/**
* Create a substring representation.
*
* @param pStart The starting character
* @return A new rep (note that this can be the same one, but does not need to
* be)
*/
fun substring(pStart: Int): StringRep {
return substring(pStart, length)
}
/**
* Get a subsequence. This is actually equal to the substring method.
*
*/
override fun subSequence(startIndex: Int, endIndex: Int): CharSequence {
return substring(startIndex, endIndex)
}
/**
* Does the string start with the specified substring.
*
* @param pString The substring
* @return `true` if it starts with it
*/
fun endsWith(pString: CharSequence): Boolean {
if (pString.length > length) {
return false
}
val length = pString.length
val start = length - length
for (i in 0 until length) {
if (get(start + i) != pString[i]) {
return false
}
}
return true
}
/**
* Does the string start with the specified substring.
*
* @param pString The substring
* @return `true` if it starts with it
*/
fun startsWith(pString: CharSequence): Boolean {
if (pString.length > length) {
return false
}
val length = pString.length
for (i in 0 until length) {
if (get(i) != pString[i]) {
return false
}
}
return true
}
/**
* Create a rep without starting and ending whitespace.
*
* @return a new rep
*/
fun trim(): StringRep {
var left = 0
var right = length - 1
var c = get(left)
while (left <= right && (c == ' ' || c == '\n' || c == '\t')) {
left++
c = get(left)
}
if (left == length) {
return createRep("")
}
c = get(right)
while (left <= right && (c == ' ' || c == '\n' || c == '\t')) {
right--
c = get(right)
}
return createRep(left, right + 1, this)
}
/**
* Unquote the string. If it does not start and end with quotes an exception
* will be thrown.
*
* @return An unquoted string
* @throws NumberFormatException When the quotes are unmatched
*/
fun unQuote(): StringRep {
val result = StringBuilder(length)
if (!(startsWith('"') && endsWith('"'))) {
throw NumberFormatException("The element to be unquoted does not start or end with quotes")
}
var index = 1
while (index < length - 1) {
if (get(index) == '\\') {
if (index == length - 1) {
throw NumberFormatException("last quote is escaped")
}
index++
} else if (get(index) == '"') {
throw NumberFormatException("Internal quotes are not allowed unless escaped")
}
result.append(get(index))
index++
}
return createRep(result)
}
companion object {
/** The default quotes that are used. */
val _DEFAULTQUOTES = "\"\"\'\'()[]{}"
/**
* Create a new StringRep.
*
* @param element The string to be encapsulated
* @return a new StringRep
*/
fun createRep(element: String): StringRep {
return StringStringRep(element)
}
/**
* Create a new StringRep.
*
* @param element The string to be encapsulated
* @return a new StringRep
*/
fun createRep(element: CharSequence): StringRep {
return CharSequenceStringRep(element)
}
/**
* Create a new StringRep.
*
* @param element The string to be encapsulated
* @return a new StringRep
*/
fun createRep(element: CharArray): StringRep {
return CharArrayStringRep(element)
}
/**
* Create a new StringRep.
*
* @param pStart The starting index
* @param pEnd The end index
* @param element The string to be encapsulated
* @return a new StringRep
*/
fun createRep(pStart: Int, pEnd: Int, element: CharArray): StringRep {
return IndexedCharArrayStringRep(pStart, pEnd, element)
}
/**
* Create a new StringRep.
*
* @param start The starting index
* @param end The end index
* @param element The string to be encapsulated
* @return a new StringRep
* @throws IndexOutOfBoundsException When the index values are invalid
*/
fun createRep(start: Int, end: Int, element: StringRep): StringRep {
return element.substring(start, end)
}
}
}
| lgpl-3.0 | caa5d26bce7e0cfbdb0b986e6166c7e0 | 28.146779 | 113 | 0.508985 | 4.874956 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/data/visiblequests/VisibleQuestTypeTable.kt | 1 | 620 | package de.westnordost.streetcomplete.data.visiblequests
object VisibleQuestTypeTable {
const val NAME = "quest_visibility"
object Columns {
const val QUEST_PRESET_ID = "quest_preset_id"
const val QUEST_TYPE = "quest_type"
const val VISIBILITY = "visibility"
}
const val CREATE = """
CREATE TABLE $NAME (
${Columns.QUEST_PRESET_ID} INTEGER NOT NULL,
${Columns.QUEST_TYPE} TEXT,
${Columns.VISIBILITY} INTEGER NOT NULL,
CONSTRAINT primary_key PRIMARY KEY (${Columns.QUEST_PRESET_ID}, ${Columns.QUEST_TYPE})
);"""
}
| gpl-3.0 | df0700c7294c8a0a7900a54589ba7943 | 31.631579 | 98 | 0.622581 | 4.305556 | false | false | false | false |
davidwhitman/Tir | GoodreadsApiSdk/src/main/kotlin/com/thunderclouddev/goodreadsapisdk/api/Review.kt | 1 | 2690 | package com.thunderclouddev.goodreadsapisdk.api
import org.simpleframework.xml.Element
/**
* @author David Whitman on 16 Mar, 2017.
*/
@Element(name = "Review")
internal data class Review(
@field:Element(name = "id") var id: Int = 0,
@field:Element(name = "user_id", required = false) var userId: Int = 0,
@field:Element(name = "book_id", required = false) var bookId: Int = 0,
@field:Element(name = "rating", required = false) var rating: Int = 0,
@field:Element(name = "read_status", required = false) var readStatus: String = "",
@field:Element(name = "sell_flag", required = false) var sellFlag: String = "",
@field:Element(name = "review", required = false) var review: String = "",
@field:Element(name = "recommendation", required = false) var recommendation: String = "",
@field:Element(name = "read_at", required = false) var readAt: String = "",
@field:Element(name = "updated_at", required = false) var updatedAt: String = "",
@field:Element(name = "created_at", required = false) var createdAt: String = "",
@field:Element(name = "comments_count", required = false) var commentsCount: Int = 0,
@field:Element(name = "weight", required = false) var weight: Int = 0,
@field:Element(name = "ratings_sum", required = false) var ratingsSum: Int = 0,
@field:Element(name = "ratings_count", required = false) var ratingsCount: Int = 0,
@field:Element(name = "notes", required = false) var notes: String = "",
@field:Element(name = "spoiler_flag", required = false) var spoilerFlag: String = "",
@field:Element(name = "recommender_user_id1", required = false) var recommenderUserId1: Int = 0,
@field:Element(name = "recommender_user_name1", required = false) var recommenderUserName1: Int = 0,
@field:Element(name = "work_id", required = false) var workId: Int = 0,
@field:Element(name = "read_count", required = false) var readCount: String = "",
@field:Element(name = "last_comment_at", required = false) var lastCommentAt: String = "",
@field:Element(name = "started_at", required = false) var startedAt: String = "",
@field:Element(name = "hidden_flag", required = false) var hiddenFlag: String = "",
@field:Element(name = "language_code", required = false) var languageCode: Int = 0,
@field:Element(name = "last_revision_at", required = false) var lastRevisionAt: String = "",
@field:Element(name = "non_friends_rating_count", required = false) var nonFriendsRatingCount: Int = 0,
@field:Element(name = "book", required = false) var book: Book = Book()
) | gpl-3.0 | a22b37001c85584448fe4f1040aa89e4 | 69.815789 | 111 | 0.64052 | 3.674863 | false | false | false | false |
avenwu/filelocker | app/src/main/kotlin/avenwu/net/filelocker/activity/EncodeFileActivity.kt | 1 | 3664 | package avenwu.net.filelocker.activity
import android.content.Intent
import android.net.Uri
import android.os.AsyncTask
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v7.widget.Toolbar
import android.view.View
import android.widget.Button
import android.widget.CheckedTextView
import android.widget.ProgressBar
import android.widget.TextView
import avenwu.net.filelocker.*
import avenwu.net.filelocker.util.*
import java.util.*
import kotlin.text.lastIndexOf
import kotlin.text.substring
import kotlin.text.toLowerCase
/**
* Created by aven on 1/8/16.
*/
class EncodeFileActivity : BaseToolbarActivity() {
var mSrcFileLabel: TextView? = null
var mDesFileLabel: TextView? = null
var mProgressView: ProgressBar? = null
var mButtonConfirm: Button? = null
var mDeleteCheckBox: CheckedTextView? = null
var mTaskList = ArrayList<Any>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.lock_file_edit_layout)
val toolbar = findViewById(R.id.toolbar) as Toolbar
setSupportActionBar(toolbar)
mSrcFileLabel = findViewById(R.id.tv_file_name) as TextView
mDesFileLabel = findViewById(R.id.tv_file_name_encode) as TextView
mProgressView = findViewById(R.id.progressBar) as ProgressBar
mButtonConfirm = findViewById(R.id.btn_translate) as Button
intent.dataString?.let { uri ->
var tmp = getFile(uri)
if (!tmp.exists()) {
alert("File not exist!!($uri)")
return
}
var size = getReadableSize(tmp.length().toDouble())
mSrcFileLabel?.text = tmp.absolutePath + "($size)"
mSrcFileLabel?.setOnClickListener({
var viewFileIntent = Intent(Intent.ACTION_VIEW)
var extension = tmp.absolutePath.substring(tmp.absolutePath.lastIndexOf(".") + 1, tmp.absolutePath.length);
viewFileIntent.setDataAndType(Uri.fromFile(tmp), getNormalMime(extension.toLowerCase()))
startActivity(viewFileIntent)
})
mButtonConfirm?.setOnClickListener({
var tmpSrc = getFile(uri)
var des = getEncodeFile(tmpSrc.name)
mDesFileLabel?.text = des.absolutePath
mTaskList.add(encode(tmpSrc, des, { bytes, percent ->
mProgressView?.progress = percent?.times(100)?.toInt()
}, { result ->
result?.let {
if (result.success) {
mProgressView?.progress = 100
var size = getReadableSize(des.length().toDouble());
mDesFileLabel?.visibility = View.VISIBLE
mDesFileLabel?.text = des.absolutePath + "($size})"
alert("Encode completed!")
} else {
alert("Encode failed!!(${result.msg})")
}
}
}))
})
mDeleteCheckBox = findViewById(R.id.checkbox_delete) as CheckedTextView
mDeleteCheckBox?.setOnClickListener({
mDeleteCheckBox?.toggle()
})
}
}
fun alert(msg: String) {
Snackbar.make(mSrcFileLabel, msg, Snackbar.LENGTH_SHORT).show()
}
override fun onDestroy() {
super.onDestroy()
for (task in mTaskList) {
if (task is AsyncTask<*, *, *>) {
task.cancel(true)
}
}
}
} | apache-2.0 | f929cce96f5ef0afc2c98a7a92cf0821 | 36.783505 | 123 | 0.594705 | 4.746114 | false | false | false | false |
SerCeMan/franky | franky-intellij/src/main/kotlin/me/serce/franky/util/lifetimes.kt | 1 | 1715 | package me.serce.franky.util
import com.intellij.openapi.Disposable
import com.intellij.openapi.util.Disposer
class Lifetime internal constructor(eternal: Boolean = false) {
companion object {
val Eternal: Lifetime = Lifetime(true)
fun create(vararg parents: Lifetime): Lifetime {
val res = Lifetime()
for (parent in parents) {
parent.addNested(res)
}
return res
}
}
val isEternal: Boolean = eternal
@Volatile
var isTerminated: Boolean = false
private set
private val actions = arrayListOf<() -> Unit>()
operator fun plusAssign(action: () -> Unit) = add(action)
fun terminate() {
if (isTerminated) {
throw RuntimeException("Lifetime terminated several times")
}
isTerminated = true;
val actionsCopy = actions
actionsCopy.reversed().forEach {
it()
}
actions.clear()
}
private fun add(action: () -> Unit) {
if (isTerminated) {
throw IllegalStateException("Already terminated")
}
actions.add (action)
}
internal fun addNested(def: Lifetime) {
if (def.isTerminated) {
return
}
val action = { def.terminate() }
add(action)
def.add({ actions.remove(action) })
}
}
fun Lifetime.create(): Lifetime = Lifetime.create(this)
fun Lifetime.toDisposable(): Disposable {
val disposable = Disposer.newDisposable()
this += { Disposer.dispose(disposable) }
Disposer.register(disposable, Disposable {
if (!isTerminated) {
terminate()
}
})
return disposable
}
| apache-2.0 | 7e4527298e3ecc9d41cc68f741756e36 | 24.220588 | 71 | 0.58484 | 4.647696 | false | false | false | false |
andersonlucasg3/SpriteKit-Android | SpriteKitLib/src/main/java/br/com/insanitech/spritekit/actions/SKActionScaleTo.kt | 1 | 2221 | package br.com.insanitech.spritekit.actions
import br.com.insanitech.spritekit.SKEaseCalculations
import br.com.insanitech.spritekit.SKNode
/**
* Created by anderson on 06/01/17.
*/
internal class SKActionScaleTo(private val deltaX: Float, private val deltaY: Float) : SKAction() {
private var startX: Float = 0.toFloat()
private var startY: Float = 0.toFloat()
override fun computeStart(node: SKNode) {
this.startX = node.xScale
this.startY = node.yScale
}
override fun computeAction(node: SKNode, elapsed: Long) {
var newScaleX = node.xScale
var newScaleY = node.yScale
when (this.timingMode) {
SKActionTimingMode.Linear -> {
newScaleX = SKEaseCalculations.linear(elapsed.toFloat(), this.startX, this.deltaX - this.startX, this.duration.toFloat())
newScaleY = SKEaseCalculations.linear(elapsed.toFloat(), this.startY, this.deltaY - this.startY, this.duration.toFloat())
}
SKActionTimingMode.EaseIn -> {
newScaleX = SKEaseCalculations.easeIn(elapsed.toFloat(), this.startX, this.deltaX - this.startX, this.duration.toFloat())
newScaleY = SKEaseCalculations.easeIn(elapsed.toFloat(), this.startY, this.deltaY - this.startY, this.duration.toFloat())
}
SKActionTimingMode.EaseOut -> {
newScaleX = SKEaseCalculations.easeOut(elapsed.toFloat(), this.startX, this.deltaX - this.startX, this.duration.toFloat())
newScaleY = SKEaseCalculations.easeOut(elapsed.toFloat(), this.startY, this.deltaY - this.startY, this.duration.toFloat())
}
SKActionTimingMode.EaseInEaseOut -> {
newScaleX = SKEaseCalculations.easeInOut(elapsed.toFloat(), this.startX, this.deltaX - this.startX, this.duration.toFloat())
newScaleY = SKEaseCalculations.easeInOut(elapsed.toFloat(), this.startY, this.deltaY - this.startY, this.duration.toFloat())
}
}
node.xScale = newScaleX
node.yScale = newScaleY
}
override fun computeFinish(node: SKNode) {
node.xScale = this.deltaX
node.yScale = this.deltaY
}
}
| bsd-3-clause | 834865894b050386119ece1727659a3e | 40.90566 | 140 | 0.65511 | 4.312621 | false | false | false | false |
adityaDave2017/my-vocab | app/src/main/java/com/android/vocab/fragment/dialog/RecyclerViewDialog.kt | 1 | 2653 | package com.android.vocab.fragment.dialog
import android.content.Context
import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import com.android.vocab.R
import com.android.vocab.holder.TextShowHolder
import com.android.vocab.provider.bean.Word
import com.android.vocab.provider.getWords
@Suppress("unused")
class RecyclerViewDialog: DialogFragment() {
private val LOG_TAG: String = RecyclerViewDialog::class.java.simpleName
companion object {
val TYPE_OF_DATA: String = "TYPE_OF_DATA"
}
enum class SupportedTypes {
SYNONYM, ANTONYM
}
interface OnItemSelected {
fun processSelectedItem(type: SupportedTypes, id: Long)
}
var selectedWord: Long = 0L
lateinit var list: List<Word>
lateinit var type: SupportedTypes
override fun onAttach(context: Context?) {
super.onAttach(context)
if (context !is OnItemSelected) {
throw ClassCastException("Must implement OnItemSelect")
}
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
type = SupportedTypes.valueOf(arguments.getString(TYPE_OF_DATA))
dialog.setCanceledOnTouchOutside(false)
val view: View = inflater!!.inflate(R.layout.dialog_recyclerview, container, false)
(view.findViewById(R.id.btnDismiss) as Button).setOnClickListener { dismiss() }
val rv: RecyclerView = view.findViewById(R.id.rvList) as RecyclerView
rv.addItemDecoration(DividerItemDecoration(context, LinearLayoutManager.VERTICAL))
list = getWords(context)
rv.adapter = WordListAdapter()
return view
}
inner class WordListAdapter: RecyclerView.Adapter<TextShowHolder>() {
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): TextShowHolder =
TextShowHolder(LayoutInflater.from(context).inflate(R.layout.text_view_for_display, parent, false))
override fun getItemCount(): Int = list.size
override fun onBindViewHolder(holder: TextShowHolder?, position: Int) {
holder?.textView?.text = list[position].word
holder?.textView?.setOnClickListener {
(context as OnItemSelected).processSelectedItem(type, list[position].wordId)
dismiss()
}
}
}
} | mit | 1c83b26ab350439e7195e0e47f99eae1 | 30.595238 | 116 | 0.710893 | 4.59792 | false | false | false | false |
raatiniemi/worker | app/src/main/java/me/raatiniemi/worker/features/shared/model/LiveData.kt | 1 | 1136 | /*
* Copyright (C) 2018 Tobias Raatiniemi
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 2 of the License.
*
* 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 me.raatiniemi.worker.features.shared.model
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import kotlinx.coroutines.*
fun <T> LiveData<T>.debounce(
duration: Long = 250,
context: CoroutineScope = GlobalScope
) = MediatorLiveData<T>().also { mld ->
var job: Job? = null
mld.addSource(this) {
job?.cancel()
job = context.launch {
delay(duration)
mld.postValue(it)
}
}
}
| gpl-2.0 | c1450ae14923ef521ea9120e249a5bf3 | 28.894737 | 72 | 0.696303 | 4.191882 | false | false | false | false |
Ekito/android-injector | kotlindemoapp/src/main/kotlin/fr/ekito/injector/kotlinapp/di/MyModule.kt | 1 | 1282 | package fr.ekito.injector.kotlinapp.di
import fr.ekito.injector.Module
import fr.ekito.injector.kotlinapp.ws.GitHubService
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
/**
* Created by arnaud on 25/04/2016.
*/
class MyModule : Module() {
override fun load() {
val httpClient = httpClient()
provide(httpClient, OkHttpClient::class.java)
provide(githubWS(httpClient), GitHubService::class.java)
}
private fun httpClient(): OkHttpClient {
val loggingInterceptor = HttpLoggingInterceptor()
loggingInterceptor.level = HttpLoggingInterceptor.Level.BASIC
val httpClient = OkHttpClient.Builder().addInterceptor(loggingInterceptor).build()
return httpClient
}
private fun githubWS(httpClient: OkHttpClient): GitHubService {
val gsonConverterFactory = GsonConverterFactory.create()
val retrofit = Retrofit.Builder()
.baseUrl("https://api.github.com/")
.client(httpClient).addConverterFactory(gsonConverterFactory)
.build()
val service = retrofit.create<GitHubService>(GitHubService::class.java)
return service
}
}
| apache-2.0 | a30e722e59c97a1ca4d05f76e7f73d43 | 31.05 | 90 | 0.709048 | 4.911877 | false | false | false | false |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/inspections/latex/redundancy/LatexMultipleIncludesInspection.kt | 1 | 2705 | package nl.hannahsten.texifyidea.inspections.latex.redundancy
import com.intellij.codeInspection.InspectionManager
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiFile
import nl.hannahsten.texifyidea.inspections.InsightGroup
import nl.hannahsten.texifyidea.inspections.TexifyInspectionBase
import nl.hannahsten.texifyidea.lang.commands.LatexGenericRegularCommand
import nl.hannahsten.texifyidea.lang.magic.MagicCommentScope
import nl.hannahsten.texifyidea.psi.LatexRequiredParam
import nl.hannahsten.texifyidea.util.files.commandsInFile
import nl.hannahsten.texifyidea.util.firstChildOfType
import nl.hannahsten.texifyidea.util.includedPackages
import nl.hannahsten.texifyidea.util.magic.cmd
import nl.hannahsten.texifyidea.util.requiredParameter
import java.util.*
import kotlin.collections.HashSet
/**
* @author Hannah Schellekens
*/
open class LatexMultipleIncludesInspection : TexifyInspectionBase() {
override val inspectionGroup = InsightGroup.LATEX
override val inspectionId = "MultipleIncludes"
override val ignoredSuppressionScopes = EnumSet.of(MagicCommentScope.ENVIRONMENT, MagicCommentScope.MATH_ENVIRONMENT)!!
override val outerSuppressionScopes = EnumSet.of(MagicCommentScope.GROUP)!!
override fun getDisplayName() = "Package has been imported multiple times"
override fun inspectFile(file: PsiFile, manager: InspectionManager, isOntheFly: Boolean): MutableList<ProblemDescriptor> {
val descriptors = descriptorList()
// Find all duplicates.
val packages = file.includedPackages(onlyDirectInclusions = true).map { it.name }
val covered = HashSet<String>()
val duplicates = HashSet<String>()
packages.filterNotTo(duplicates) {
covered.add(it)
}
// Duplicates!
file.commandsInFile().asSequence()
.filter { it.name == LatexGenericRegularCommand.USEPACKAGE.cmd && it.requiredParameter(0) in duplicates }
.forEach {
val parameter = it.firstChildOfType(LatexRequiredParam::class) ?: error("There must be a required parameter.")
descriptors.add(
manager.createProblemDescriptor(
it,
TextRange.from(parameter.textOffset + 1 - it.textOffset, parameter.textLength - 2),
"Package has already been included",
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
isOntheFly
)
)
}
return descriptors
}
} | mit | 2ea4c53eab68e5680d876fdbe7695c57 | 40.630769 | 126 | 0.71793 | 5.162214 | false | false | false | false |
android/android-studio-poet | aspoet/src/main/kotlin/com/google/androidstudiopoet/generators/android_modules/JavaActivityGenerator.kt | 1 | 3885 | /*
Copyright 2021 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.google.androidstudiopoet.generators.android_modules
import com.google.androidstudiopoet.generators.packages.toJavaSpec
import com.google.androidstudiopoet.models.ActivityBlueprint
import com.google.androidstudiopoet.models.ClassBlueprint
import com.google.androidstudiopoet.writers.FileWriter
import com.squareup.javapoet.JavaFile
import com.squareup.javapoet.MethodSpec
import com.squareup.javapoet.TypeSpec
import com.squareup.javapoet.TypeVariableName
import javax.lang.model.element.Modifier
class JavaActivityGenerator(var fileWriter: FileWriter): ActivityGenerator {
override fun generate(blueprint: ActivityBlueprint) {
val onCreateMethodStatements = getOnCreateMethodStatements(blueprint)
val onCreateMethod = getOnCreateMethod(onCreateMethodStatements)
val activityClassBuilder = getClazzSpec(blueprint.className)
.addMethod(onCreateMethod)
blueprint.fields.map {
it.toJavaSpec()
}.forEach {
activityClassBuilder.addField(it)
}
val activityClass = activityClassBuilder
.build()
val javaFile = JavaFile.builder(blueprint.packageName, activityClass).build()
fileWriter.writeToFile(javaFile.toString(), "${blueprint.where}/${blueprint.className}.java")
}
private fun getOnCreateMethodStatements(blueprint: ActivityBlueprint): List<String> {
val classBlueprint = blueprint.classToReferFromActivity
val statements = getMethodStatementFromClassToCall(classBlueprint)?.let { mutableListOf(it) } ?: mutableListOf()
if (blueprint.enableDataBinding) {
statements.addAll(getDataBindingMethodStatements(blueprint.layout.name, blueprint.dataBindingClassName, blueprint.listenerClassesForDataBinding))
} else {
statements.add("setContentView(R.layout.${blueprint.layout.name})")
}
return statements
}
private fun getDataBindingMethodStatements(layout: String, dataBindingClassName: String,
listenerClasses: List<ClassBlueprint>): List<String> {
return listOf("$dataBindingClassName binding = androidx.databinding.DataBindingUtil.setContentView(this, R.layout.$layout)") +
listenerClasses.map { "binding.set${it.className}(new ${it.fullClassName}())" }
}
private fun getMethodStatementFromClassToCall(classBlueprint: ClassBlueprint) =
classBlueprint.getMethodToCallFromOutside()?.let { "new ${it.className}().${it.methodName}()" }
private fun getClazzSpec(activityClassName: String) =
TypeSpec.classBuilder(activityClassName)
.superclass(TypeVariableName.get("android.app.Activity"))
.addModifiers(Modifier.PUBLIC)
private fun getOnCreateMethod(statements: List<String>): MethodSpec {
val builder = MethodSpec.methodBuilder("onCreate")
.addAnnotation(Override::class.java)
.addModifiers(Modifier.PUBLIC)
.returns(Void.TYPE)
.addParameter(TypeVariableName.get("android.os.Bundle"), "savedInstanceState")
.addStatement("super.onCreate(savedInstanceState)")
statements.forEach { builder.addStatement(it) }
return builder.build()
}
}
| apache-2.0 | e0d9ccca8ed9cc91e5f51ad64526d8f4 | 41.692308 | 157 | 0.720206 | 5.098425 | false | false | false | false |
PaulWoitaschek/Voice | search/src/test/kotlin/voice/search/BookFactory.kt | 1 | 1168 | package voice.search
import voice.common.BookId
import voice.data.Book
import voice.data.BookContent
import voice.data.Chapter
import java.time.Instant
import java.util.UUID
fun book(
chapters: List<Chapter> = listOf(chapter(), chapter()),
time: Long = 42,
currentChapter: Chapter.Id = chapters.first().id,
name: String = UUID.randomUUID().toString(),
author: String? = UUID.randomUUID().toString(),
): Book {
return Book(
content = BookContent(
author = author,
name = name,
positionInChapter = time,
playbackSpeed = 1F,
addedAt = Instant.EPOCH,
chapters = chapters.map { it.id },
cover = null,
currentChapter = currentChapter,
isActive = true,
lastPlayedAt = Instant.EPOCH,
skipSilence = false,
id = BookId(UUID.randomUUID().toString()),
gain = 0F,
),
chapters = chapters,
)
}
fun chapter(
duration: Long = 10000,
id: Chapter.Id = Chapter.Id(UUID.randomUUID().toString()),
): Chapter {
return Chapter(
id = id,
name = UUID.randomUUID().toString(),
duration = duration,
fileLastModified = Instant.EPOCH,
markData = emptyList(),
)
}
| gpl-3.0 | f6d8dd4a465b206e2c6ecda2b7bf827c | 23.333333 | 60 | 0.648973 | 3.972789 | false | false | false | false |
FHannes/intellij-community | platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/util.kt | 9 | 2560 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.intellij.build.images
import com.intellij.openapi.util.text.StringUtil
import java.awt.*
import java.io.File
internal val File.children: List<File> get() = if (isDirectory) listFiles().toList() else emptyList()
internal fun isImage(file: File, iconsOnly: Boolean): Boolean {
if (!isImage(file.name)) return false
return !iconsOnly || isIcon(file)
}
internal fun isIcon(file: File): Boolean {
if (!isImage(file.name)) return false
val size = imageSize(file) ?: return false
return size.height == size.width || size.height <= 100 && size.width <= 100
}
private fun isImage(name: String) = name.endsWith(".png") || name.endsWith(".gif")
internal fun imageSize(file: File): Dimension? {
val image = loadImage(file) ?: return null
val width = image.getWidth(null)
val height = image.getHeight(null)
return Dimension(width, height)
}
private fun loadImage(file: File): Image? {
val image = Toolkit.getDefaultToolkit().createImage(file.absolutePath)
if (!waitForImage(image)) return null
return image
}
private fun waitForImage(image: Image?): Boolean {
if (image == null) return false
if (image.getWidth(null) > 0) return true
val mediaTracker = MediaTracker(object : Component() {})
mediaTracker.addImage(image, 1)
mediaTracker.waitForID(1, 5000)
return !mediaTracker.isErrorID(1)
}
internal enum class ImageType(private val suffix: String) {
BASIC(""), RETINA("@2x"), DARCULA("_dark"), RETINA_DARCULA("@2x_dark");
fun getBasicName(name: String): String = StringUtil.trimEnd(name, suffix)
companion object {
fun fromName(name: String): ImageType {
if (name.endsWith(RETINA_DARCULA.suffix)) return RETINA_DARCULA
if (name.endsWith(RETINA.suffix)) return RETINA
if (name.endsWith(DARCULA.suffix)) return DARCULA
return BASIC
}
fun stripSuffix(name: String): String {
val type = fromName(name)
return name.removeSuffix(type.suffix)
}
}
} | apache-2.0 | 60d30df9e625fcad0a367cc7638e3a4a | 32.25974 | 101 | 0.716797 | 3.79822 | false | false | false | false |
ansman/okhttp | okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt | 2 | 13232 | /*
* 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.testing
import android.os.Build
import com.amazon.corretto.crypto.provider.AmazonCorrettoCryptoProvider
import com.amazon.corretto.crypto.provider.SelfTestStatus
import okhttp3.TestUtil
import okhttp3.internal.platform.ConscryptPlatform
import okhttp3.internal.platform.Jdk8WithJettyBootPlatform
import okhttp3.internal.platform.Jdk9Platform
import okhttp3.internal.platform.OpenJSSEPlatform
import okhttp3.internal.platform.Platform
import org.bouncycastle.jce.provider.BouncyCastleProvider
import org.bouncycastle.jsse.provider.BouncyCastleJsseProvider
import org.conscrypt.Conscrypt
import org.hamcrest.BaseMatcher
import org.hamcrest.CoreMatchers.anything
import org.hamcrest.Description
import org.hamcrest.Matcher
import org.hamcrest.StringDescription
import org.hamcrest.TypeSafeMatcher
import org.junit.jupiter.api.Assertions.fail
import org.junit.jupiter.api.Assumptions.assumeFalse
import org.junit.jupiter.api.Assumptions.assumeTrue
import org.junit.jupiter.api.extension.AfterEachCallback
import org.junit.jupiter.api.extension.BeforeEachCallback
import org.junit.jupiter.api.extension.ExtensionContext
import org.junit.jupiter.api.extension.InvocationInterceptor
import org.junit.jupiter.api.extension.ReflectiveInvocationContext
import org.openjsse.net.ssl.OpenJSSE
import org.opentest4j.TestAbortedException
import java.lang.reflect.Method
import java.security.Security
/**
* Marks a test as Platform aware, before the test runs a consistent Platform will be
* established e.g. SecurityProvider for Conscrypt installed.
*
* Also allows a test file to state general platform assumptions, or for individual test.
*/
@Suppress("unused", "MemberVisibilityCanBePrivate")
open class PlatformRule @JvmOverloads constructor(
val requiredPlatformName: String? = null,
val platform: Platform? = null
) : BeforeEachCallback, AfterEachCallback, InvocationInterceptor {
private val versionChecks = mutableListOf<Pair<Matcher<out Any>, Matcher<out Any>>>()
override fun beforeEach(context: ExtensionContext) {
setupPlatform()
}
override fun afterEach(context: ExtensionContext) {
resetPlatform()
}
override fun interceptTestMethod(
invocation: InvocationInterceptor.Invocation<Void>,
invocationContext: ReflectiveInvocationContext<Method>,
extensionContext: ExtensionContext
) {
var failed = false
try {
invocation.proceed()
} catch (e: TestAbortedException) {
throw e
} catch (e: Throwable) {
failed = true
rethrowIfNotExpected(e)
} finally {
resetPlatform()
}
if (!failed) {
failIfExpected()
}
}
fun setupPlatform() {
if (requiredPlatformName != null) {
assumeTrue(getPlatformSystemProperty() == requiredPlatformName)
}
if (platform != null) {
Platform.resetForTests(platform)
} else {
Platform.resetForTests()
}
if (requiredPlatformName != null) {
System.err.println("Running with ${Platform.get().javaClass.simpleName}")
}
}
fun resetPlatform() {
if (platform != null) {
Platform.resetForTests()
}
}
fun expectFailureOnConscryptPlatform() {
expectFailure(platformMatches(CONSCRYPT_PROPERTY))
}
fun expectFailureOnCorrettoPlatform() {
expectFailure(platformMatches(CORRETTO_PROPERTY))
}
fun expectFailureOnOpenJSSEPlatform() {
expectFailure(platformMatches(OPENJSSE_PROPERTY))
}
fun expectFailureFromJdkVersion(majorVersion: Int) {
if (!TestUtil.isGraalVmImage) {
expectFailure(fromMajor(majorVersion))
}
}
fun expectFailureOnJdkVersion(majorVersion: Int) {
if (!TestUtil.isGraalVmImage) {
expectFailure(onMajor(majorVersion))
}
}
private fun expectFailure(
versionMatcher: Matcher<out Any>,
failureMatcher: Matcher<out Any> = anything()
) {
versionChecks.add(Pair(versionMatcher, failureMatcher))
}
fun platformMatches(platform: String): Matcher<Any> = object : BaseMatcher<Any>() {
override fun describeTo(description: Description) {
description.appendText(platform)
}
override fun matches(item: Any?): Boolean {
return getPlatformSystemProperty() == platform
}
}
fun fromMajor(version: Int): Matcher<PlatformVersion> {
return object : TypeSafeMatcher<PlatformVersion>() {
override fun describeTo(description: Description) {
description.appendText("JDK with version from $version")
}
override fun matchesSafely(item: PlatformVersion): Boolean {
return item.majorVersion >= version
}
}
}
fun onMajor(version: Int): Matcher<PlatformVersion> {
return object : TypeSafeMatcher<PlatformVersion>() {
override fun describeTo(description: Description) {
description.appendText("JDK with version $version")
}
override fun matchesSafely(item: PlatformVersion): Boolean {
return item.majorVersion == version
}
}
}
fun rethrowIfNotExpected(e: Throwable) {
versionChecks.forEach { (versionMatcher, failureMatcher) ->
if (versionMatcher.matches(PlatformVersion) && failureMatcher.matches(e)) {
return
}
}
throw e
}
fun failIfExpected() {
versionChecks.forEach { (versionMatcher, failureMatcher) ->
if (versionMatcher.matches(PlatformVersion)) {
val description = StringDescription()
versionMatcher.describeTo(description)
description.appendText(" expected to fail with exception that ")
failureMatcher.describeTo(description)
fail<Any>(description.toString())
}
}
}
fun isConscrypt() = getPlatformSystemProperty() == CONSCRYPT_PROPERTY
fun isJdk9() = getPlatformSystemProperty() == JDK9_PROPERTY
fun isJdk8() = getPlatformSystemProperty() == JDK8_PROPERTY
fun isJdk8Alpn() = getPlatformSystemProperty() == JDK8_ALPN_PROPERTY
fun isBouncyCastle() = getPlatformSystemProperty() == BOUNCYCASTLE_PROPERTY
fun isGraalVMImage() = TestUtil.isGraalVmImage
fun hasHttp2Support() = !isJdk8()
fun assumeConscrypt() {
assumeTrue(getPlatformSystemProperty() == CONSCRYPT_PROPERTY)
}
fun assumeJdk9() {
assumeTrue(getPlatformSystemProperty() == JDK9_PROPERTY)
}
fun assumeOpenJSSE() {
assumeTrue(getPlatformSystemProperty() == OPENJSSE_PROPERTY)
}
fun assumeJdk8() {
assumeTrue(getPlatformSystemProperty() == JDK8_PROPERTY)
}
fun assumeJdk8Alpn() {
assumeTrue(getPlatformSystemProperty() == JDK8_ALPN_PROPERTY)
}
fun assumeCorretto() {
assumeTrue(getPlatformSystemProperty() == CORRETTO_PROPERTY)
}
fun assumeBouncyCastle() {
assumeTrue(getPlatformSystemProperty() == BOUNCYCASTLE_PROPERTY)
}
fun assumeHttp2Support() {
assumeTrue(getPlatformSystemProperty() != JDK8_PROPERTY)
}
fun assumeAndroid() {
assumeTrue(Platform.isAndroid)
}
fun assumeGraalVMImage() {
assumeTrue(isGraalVMImage())
}
fun assumeNotConscrypt() {
assumeTrue(getPlatformSystemProperty() != CONSCRYPT_PROPERTY)
}
fun assumeNotJdk9() {
assumeTrue(getPlatformSystemProperty() != JDK9_PROPERTY)
}
fun assumeNotJdk8() {
assumeTrue(getPlatformSystemProperty() != JDK8_PROPERTY)
}
fun assumeNotJdk8Alpn() {
assumeTrue(getPlatformSystemProperty() != JDK8_ALPN_PROPERTY)
}
fun assumeNotOpenJSSE() {
assumeTrue(getPlatformSystemProperty() != OPENJSSE_PROPERTY)
}
fun assumeNotCorretto() {
assumeTrue(getPlatformSystemProperty() != CORRETTO_PROPERTY)
}
fun assumeNotBouncyCastle() {
// Most failures are with MockWebServer
// org.bouncycastle.tls.TlsFatalAlertReceived: handshake_failure(40)
// at org.bouncycastle.tls.TlsProtocol.handleAlertMessage(TlsProtocol.java:241)
assumeTrue(getPlatformSystemProperty() != BOUNCYCASTLE_PROPERTY)
}
fun assumeNotHttp2Support() {
assumeTrue(getPlatformSystemProperty() == JDK8_PROPERTY)
}
fun assumeJettyBootEnabled() {
assumeTrue(isAlpnBootEnabled())
}
fun assumeNotAndroid() {
assumeFalse(Platform.isAndroid)
}
fun assumeNotGraalVMImage() {
assumeFalse(isGraalVMImage())
}
fun assumeJdkVersion(majorVersion: Int) {
assumeNotAndroid()
assumeNotGraalVMImage()
assumeTrue(PlatformVersion.majorVersion == majorVersion)
}
fun androidSdkVersion(): Int? {
return if (Platform.isAndroid) {
Build.VERSION.SDK_INT
} else {
null
}
}
val isAndroid: Boolean
get() = Platform.Companion.isAndroid
companion object {
const val PROPERTY_NAME = "okhttp.platform"
const val CONSCRYPT_PROPERTY = "conscrypt"
const val CORRETTO_PROPERTY = "corretto"
const val JDK9_PROPERTY = "jdk9"
const val JDK8_ALPN_PROPERTY = "jdk8alpn"
const val JDK8_PROPERTY = "jdk8"
const val OPENJSSE_PROPERTY = "openjsse"
const val BOUNCYCASTLE_PROPERTY = "bouncycastle"
init {
val platformSystemProperty = getPlatformSystemProperty()
if (platformSystemProperty == JDK9_PROPERTY) {
if (System.getProperty("javax.net.debug") == null) {
System.setProperty("javax.net.debug", "")
}
} else if (platformSystemProperty == CONSCRYPT_PROPERTY) {
if (Security.getProviders()[0].name != "Conscrypt") {
if (!Conscrypt.isAvailable()) {
System.err.println("Warning: Conscrypt not available")
}
val provider = Conscrypt.newProviderBuilder()
.provideTrustManager(true)
.build()
Security.insertProviderAt(provider, 1)
}
} else if (platformSystemProperty == JDK8_ALPN_PROPERTY) {
if (!isAlpnBootEnabled()) {
System.err.println("Warning: ALPN Boot not enabled")
}
} else if (platformSystemProperty == JDK8_PROPERTY) {
if (isAlpnBootEnabled()) {
System.err.println("Warning: ALPN Boot enabled unintentionally")
}
} else if (platformSystemProperty == OPENJSSE_PROPERTY && Security.getProviders()[0].name != "OpenJSSE") {
if (!OpenJSSEPlatform.isSupported) {
System.err.println("Warning: OpenJSSE not available")
}
if (System.getProperty("javax.net.debug") == null) {
System.setProperty("javax.net.debug", "")
}
Security.insertProviderAt(OpenJSSE(), 1)
} else if (platformSystemProperty == BOUNCYCASTLE_PROPERTY && Security.getProviders()[0].name != "BC") {
Security.insertProviderAt(BouncyCastleProvider(), 1)
Security.insertProviderAt(BouncyCastleJsseProvider(), 2)
} else if (platformSystemProperty == CORRETTO_PROPERTY) {
AmazonCorrettoCryptoProvider.install()
AmazonCorrettoCryptoProvider.INSTANCE.assertHealthy()
}
Platform.resetForTests()
System.err.println("Running Tests with ${Platform.get().javaClass.simpleName}")
}
@JvmStatic
fun getPlatformSystemProperty(): String {
var property: String? = System.getProperty(PROPERTY_NAME)
if (property == null) {
property = when (Platform.get()) {
is ConscryptPlatform -> CONSCRYPT_PROPERTY
is OpenJSSEPlatform -> OPENJSSE_PROPERTY
is Jdk8WithJettyBootPlatform -> CONSCRYPT_PROPERTY
is Jdk9Platform -> {
if (isCorrettoInstalled) CORRETTO_PROPERTY else JDK9_PROPERTY
}
else -> JDK8_PROPERTY
}
}
return property
}
@JvmStatic
fun conscrypt() = PlatformRule(CONSCRYPT_PROPERTY)
@JvmStatic
fun openjsse() = PlatformRule(OPENJSSE_PROPERTY)
@JvmStatic
fun jdk9() = PlatformRule(JDK9_PROPERTY)
@JvmStatic
fun jdk8() = PlatformRule(JDK8_PROPERTY)
@JvmStatic
fun jdk8alpn() = PlatformRule(JDK8_ALPN_PROPERTY)
@JvmStatic
fun bouncycastle() = PlatformRule(BOUNCYCASTLE_PROPERTY)
@JvmStatic
fun isAlpnBootEnabled(): Boolean = try {
Class.forName("org.eclipse.jetty.alpn.ALPN", true, null)
true
} catch (cnfe: ClassNotFoundException) {
false
}
val isCorrettoSupported: Boolean = try {
// Trigger an early exception over a fatal error, prefer a RuntimeException over Error.
Class.forName("com.amazon.corretto.crypto.provider.AmazonCorrettoCryptoProvider")
AmazonCorrettoCryptoProvider.INSTANCE.loadingError == null &&
AmazonCorrettoCryptoProvider.INSTANCE.runSelfTests() == SelfTestStatus.PASSED
} catch (e: ClassNotFoundException) {
false
}
val isCorrettoInstalled: Boolean =
isCorrettoSupported && Security.getProviders()
.first().name == AmazonCorrettoCryptoProvider.PROVIDER_NAME
}
}
| apache-2.0 | 86b31df8805d88fc964897441a3ac0dd | 29.210046 | 112 | 0.704429 | 4.280815 | false | false | false | false |
tasks/tasks | app/src/test/java/org/tasks/makers/GoogleTaskListMaker.kt | 1 | 874 | package org.tasks.makers
import com.natpryce.makeiteasy.Instantiator
import com.natpryce.makeiteasy.Property
import com.natpryce.makeiteasy.PropertyLookup
import com.natpryce.makeiteasy.PropertyValue
import org.tasks.data.GoogleTaskList
object GoogleTaskListMaker {
val REMOTE_ID: Property<GoogleTaskList, String> = Property.newProperty()
val ACCOUNT: Property<GoogleTaskList, String?> = Property.newProperty()
private val instantiator = Instantiator { lookup: PropertyLookup<GoogleTaskList> ->
val list = GoogleTaskList()
list.remoteId = lookup.valueOf(REMOTE_ID, "1234")
list.account = lookup.valueOf(ACCOUNT, null as String?)
list.setColor(0)
list
}
fun newGoogleTaskList(vararg properties: PropertyValue<in GoogleTaskList?, *>): GoogleTaskList {
return Maker.make(instantiator, *properties)
}
} | gpl-3.0 | 88d675af207bea3bbe7081559a3dfa07 | 35.458333 | 100 | 0.743707 | 4.242718 | false | false | false | false |
meteochu/DecisionKitchen | Android/app/src/main/java/com/decisionkitchen/decisionkitchen/Group.kt | 1 | 1373 | package com.decisionkitchen.decisionkitchen
/**
* Created by kevin on 2017-07-29.
*/
typealias RestaurantID = String;
typealias GroupID = String;
data public class RestaurantOrder(val id: String? = null, val service: String? = null)
data public class Restaurant(val address: String? = null,
val name: String? = null,
val id: RestaurantID? = null,
val order: RestaurantOrder? = null,
val state: String? = null,
val zip: String? = null,
val city: String? = null,
val image: String? = null)
data public class GameMeta(val end: String? = null, val start: String? = null)
data public class Response(val value: ArrayList<ArrayList<Int>>? = null, val location: HashMap<String, Double>? = null)
data public class Game(
val meta: GameMeta? = null,
val rating: HashMap<UserID, Int>? = null,
val responses: HashMap<UserID, Response>? = null,
val result: ArrayList<ArrayList<Any>>? = null)
data public class Group(
val password: String? = null,
val members: ArrayList<UserID>? = null,
val name: String? = null,
val restaurants: HashMap<RestaurantID, Restaurant>? = null,
val id: GroupID? = null,
val games: ArrayList<Game>? = null
) | apache-2.0 | b617ca49a26ee6a599a606b48104440b | 35.157895 | 119 | 0.595047 | 4.173252 | false | false | false | false |
Light-Team/ModPE-IDE-Source | editorkit/src/main/kotlin/com/brackeys/ui/editorkit/model/EditorConfig.kt | 1 | 1331 | /*
* Copyright 2021 Brackeys IDE contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.brackeys.ui.editorkit.model
import android.graphics.Typeface
data class EditorConfig(
// Font
var fontSize: Float = 14f,
var fontType: Typeface = Typeface.MONOSPACE,
// Editor
var wordWrap: Boolean = true,
var codeCompletion: Boolean = true,
var pinchZoom: Boolean = true,
var lineNumbers: Boolean = true,
var highlightCurrentLine: Boolean = true,
var highlightDelimiters: Boolean = true,
// Keyboard
var softKeyboard: Boolean = false,
// Code Style
var autoIndentation: Boolean = true,
var autoCloseBrackets: Boolean = true,
var autoCloseQuotes: Boolean = true,
var useSpacesInsteadOfTabs: Boolean = true,
var tabWidth: Int = 4
) | apache-2.0 | 84adf8643728f09969a551ed94bea937 | 29.272727 | 75 | 0.713749 | 4.225397 | false | false | false | false |
nickthecoder/paratask | paratask-app/src/main/kotlin/uk/co/nickthecoder/paratask/tools/terminal/TerminalTool.kt | 1 | 4646 | /*
ParaTask Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.paratask.tools.terminal
import javafx.scene.input.KeyCode
import javafx.scene.input.KeyEvent
import uk.co.nickthecoder.paratask.TaskDescription
import uk.co.nickthecoder.paratask.parameters.BooleanParameter
import uk.co.nickthecoder.paratask.parameters.FileParameter
import uk.co.nickthecoder.paratask.parameters.MultipleParameter
import uk.co.nickthecoder.paratask.parameters.StringParameter
import uk.co.nickthecoder.paratask.tools.places.DirectoryTool
import uk.co.nickthecoder.paratask.util.process.OSCommand
import uk.co.nickthecoder.paratask.util.process.linuxCurrentDirectory
class TerminalTool() : AbstractTerminalTool(showCommand = true, allowInput = true) {
constructor(command: OSCommand) : this() {
programP.value = command.program
argumentsP.value = command.arguments
directoryP.value = command.directory
}
val programP = StringParameter("program", value = "bash")
val argumentsP = MultipleParameter("arguments") { StringParameter("", required = false) }
val directoryP = FileParameter("directory", expectFile = false, required = false)
val titleP = StringParameter(name = "title", value = "Terminal")
val closeWhenFinishedP = BooleanParameter("closeWhenFinished", value = false)
override val taskD = TaskDescription("terminal", description = "A simple terminal emulator")
.addParameters(programP, argumentsP, directoryP, titleP, closeWhenFinishedP)
override fun run() {
shortTitle = titleP.value
longTitle = "${titleP.value} ${programP.value} ${argumentsP.value.joinToString(separator = " ")}"
super.run()
}
override fun finished() {
if (closeWhenFinishedP.value == true) {
toolPane?.halfTab?.close()
}
}
fun input(value: Boolean): TerminalTool {
allowInput = value
return this
}
override fun createCommand(): OSCommand {
val command = OSCommand(programP.value)
argumentsP.value.forEach { arg ->
command.addArgument(arg)
}
command.directory = directoryP.value
return command
}
/**
* Splits the view, so that there's a DirectoryTool on the right.
* If there is ALREADY a directory tool on the right, then update it's directory to match the terminal's current working directory
* This only works on Linux, as it uses /proc/
*/
fun syncDirectoryTool() {
val directory = terminalResults?.process?.linuxCurrentDirectory()
directory ?: return
val otherHalf = toolPane?.halfTab?.otherHalf()
if (otherHalf == null) {
val tool = DirectoryTool()
tool.directoriesP.value = listOf(directory)
toolPane?.halfTab?.projectTab?.split(tool)
} else {
updateSyncedDirectoryTool()
}
}
private fun updateSyncedDirectoryTool() {
val otherHalf = toolPane?.halfTab?.otherHalf()
if (otherHalf != null) {
val otherTool = otherHalf.toolPane.tool
if (otherTool is DirectoryTool) {
val oldValue = otherTool.directoriesP.value
if (otherTool.directoriesP.innerParameters.isEmpty()) {
otherTool.directoriesP.addValue(directory)
} else {
otherTool.directoriesP.innerParameters[0].value = directory
}
if (oldValue != otherTool.directoriesP.value) {
otherTool.toolPane?.skipFocus = true
otherTool.toolPane?.parametersPane?.run()
}
}
}
}
override fun createTerminalResults(): TerminalResults {
val results = super.createTerminalResults()
results.node.addEventFilter(KeyEvent.KEY_RELEASED) { event ->
if (event.code == KeyCode.ENTER) {
updateSyncedDirectoryTool()
}
}
return results
}
}
| gpl-3.0 | b86aa09a7254400722f0635596d632cf | 35.015504 | 134 | 0.669608 | 4.59545 | false | false | false | false |
aglne/mycollab | mycollab-services/src/main/java/com/mycollab/module/file/service/impl/AccountLogoServiceImpl.kt | 3 | 3575 | /**
* Copyright © MyCollab
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mycollab.module.file.service.impl
import com.mycollab.core.MyCollabException
import com.mycollab.core.utils.ImageUtil
import com.mycollab.module.ecm.domain.Content
import com.mycollab.module.ecm.service.ResourceService
import com.mycollab.module.file.PathUtils
import com.mycollab.module.file.service.AccountLogoService
import com.mycollab.module.user.service.BillingAccountService
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import java.awt.image.BufferedImage
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.util.*
import javax.imageio.ImageIO
/**
* @author MyCollab Ltd.
* @since 4.1
*/
@Service
class AccountLogoServiceImpl(private val resourceService: ResourceService,
private val billingAccountService: BillingAccountService) : AccountLogoService {
override fun upload(uploadedUser: String, logo: BufferedImage, sAccountId: Int): String {
val account = billingAccountService.getAccountById(sAccountId) ?: throw MyCollabException("There's no account associated with provided id $sAccountId")
// Construct new logoid
val newLogoId = UUID.randomUUID().toString()
SUPPORT_SIZES.forEach { uploadLogoToStorage(uploadedUser, logo, newLogoId, it, sAccountId) }
// account old logo
if (account.logopath != null) {
SUPPORT_SIZES.forEach {
try {
resourceService.removeResource(PathUtils.buildLogoPath(sAccountId, account.logopath, it),
uploadedUser, true, sAccountId)
} catch (e: Exception) {
LOG.error("Error while delete old logo", e)
}
}
}
// save logo id
account.logopath = newLogoId
billingAccountService.updateSelectiveWithSession(account, uploadedUser)
return newLogoId
}
private fun uploadLogoToStorage(uploadedUser: String, image: BufferedImage, logoId: String, width: Int, sAccountId: Int?) {
val scaleImage = ImageUtil.scaleImage(image, width.toFloat() / image.width)
val outStream = ByteArrayOutputStream()
try {
ImageIO.write(scaleImage, "png", outStream)
} catch (e: IOException) {
throw MyCollabException("Error while write image to stream", e)
}
val logoContent = Content()
logoContent.path = PathUtils.buildLogoPath(sAccountId, logoId, width)
logoContent.name = "${logoId}_$width"
resourceService.saveContent(logoContent, uploadedUser, ByteArrayInputStream(outStream.toByteArray()), null)
}
companion object {
private val LOG = LoggerFactory.getLogger(AccountLogoServiceImpl::class.java)
private val SUPPORT_SIZES = intArrayOf(150, 100, 64)
}
} | agpl-3.0 | f00adad5c7e180ae728e7103bd4d3fbc | 39.168539 | 159 | 0.704533 | 4.570332 | false | false | false | false |
softelnet/sponge | sponge-kotlin/src/test/kotlin/examples/UnorderedRules.kt | 1 | 4226 | /*
* Sponge Knowledge Base
* Using unordered rules
*/
package org.openksavi.sponge.kotlin.examples
import org.openksavi.sponge.core.library.Deduplication
import org.openksavi.sponge.event.Event
import org.openksavi.sponge.examples.SameSourceJavaUnorderedRule
import org.openksavi.sponge.kotlin.KFilter
import org.openksavi.sponge.kotlin.KKnowledgeBase
import org.openksavi.sponge.kotlin.KRule
import org.openksavi.sponge.kotlin.KTrigger
import org.openksavi.sponge.rule.Rule
import java.time.Duration
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
class UnorderedRules : KKnowledgeBase() {
override fun onInit() {
// Variables for assertions only
sponge.setVariable("hardwareFailureJavaCount", AtomicInteger(0))
sponge.setVariable("hardwareFailureScriptCount", AtomicInteger(0))
sponge.setVariable("sameSourceFirstFireCount", AtomicInteger(0))
}
class FirstRule : KRule() {
override fun onConfigure() {
withEvents("filesystemFailure", "diskFailure").withOrdered(false)
withAllConditions(
{ rule: Rule, event: Event -> rule.firstEvent.get<Any?>("source") == event.get<Any?>("source") },
{ rule: Rule, event: Event -> Duration.between(rule.firstEvent.time, event.time).seconds <= 2 }
)
withDuration(Duration.ofSeconds(5))
}
override fun onRun(event: Event?) {
logger.debug("Running rule for events: {}", eventSequence)
sponge.getVariable<AtomicInteger>("sameSourceFirstFireCount").incrementAndGet()
sponge.event("alarm").set("source", firstEvent.get("source")).send()
}
}
class SameSourceAllRule : KRule() {
override fun onConfigure() {
withEvents("filesystemFailure e1", "diskFailure e2 :all").withOrdered(false)
withCondition("e1", this::severityCondition)
withConditions("e2", this::severityCondition, this::diskFailureSourceCondition)
withDuration(Duration.ofSeconds(5))
}
override fun onRun(event: Event?) {
logger.info("Monitoring log [{}]: Critical failure in {}! Events: {}", event?.time, event?.get("source"),
eventSequence)
sponge.getVariable<AtomicInteger>("hardwareFailureScriptCount").incrementAndGet()
}
fun severityCondition(event: Event) = event.get<Int>("severity") > 5
fun diskFailureSourceCondition(event: Event): Boolean {
// Both events have to have the same source
return event.get<String>("source") == this.firstEvent.get<String>("source") &&
Duration.between(this.firstEvent.time, event.time).seconds <= 4
}
}
class AlarmFilter : KFilter() {
val deduplication = Deduplication("source")
override fun onConfigure() {
withEvent("alarm")
}
override fun onInit() {
deduplication.cacheBuilder.expireAfterWrite(2, TimeUnit.SECONDS)
}
override fun onAccept(event: Event) = deduplication.onAccept(event)
}
class Alarm : KTrigger() {
override fun onConfigure() {
withEvent("alarm")
}
override fun onRun(event: Event) = logger.debug("Received alarm from {}", event.get<String>("source"))
}
override fun onLoad() = sponge.enableJava(SameSourceJavaUnorderedRule::class.java)
override fun onStartup() {
sponge.event("diskFailure").set("severity", 10).set("source", "server1").send()
sponge.event("diskFailure").set("severity", 10).set("source", "server2").send()
sponge.event("diskFailure").set("severity", 8).set("source", "server1").send()
sponge.event("diskFailure").set("severity", 8).set("source", "server1").send()
sponge.event("filesystemFailure").set("severity", 8).set("source", "server1").send()
sponge.event("filesystemFailure").set("severity", 6).set("source", "server1").send()
sponge.event("diskFailure").set("severity", 6).set("source", "server1").send()
}
}
| apache-2.0 | e5dfcef5b394d0d558a2baa7a61dd7e5 | 40.686869 | 117 | 0.636536 | 4.411273 | false | false | false | false |
nextcloud/android | app/src/androidTest/java/com/owncloud/android/ui/fragment/AvatarIT.kt | 1 | 6595 | /*
* Nextcloud Android client application
*
* @author Tobias Kaminsky
* Copyright (C) 2020 Tobias Kaminsky
* Copyright (C) 2020 Nextcloud GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.owncloud.android.ui.fragment
import android.graphics.BitmapFactory
import androidx.test.espresso.intent.rule.IntentsTestRule
import androidx.test.internal.runner.junit4.statement.UiThreadStatement.runOnUiThread
import com.nextcloud.client.TestActivity
import com.owncloud.android.AbstractIT
import com.owncloud.android.R
import com.owncloud.android.lib.resources.users.StatusType
import com.owncloud.android.ui.TextDrawable
import com.owncloud.android.utils.BitmapUtils
import com.owncloud.android.utils.DisplayUtils
import com.owncloud.android.utils.ScreenshotTest
import org.junit.Rule
import org.junit.Test
class AvatarIT : AbstractIT() {
@get:Rule
val testActivityRule = IntentsTestRule(TestActivity::class.java, true, false)
@Test
@ScreenshotTest
fun showAvatars() {
val avatarRadius = targetContext.resources.getDimension(R.dimen.list_item_avatar_icon_radius)
val width = DisplayUtils.convertDpToPixel(2 * avatarRadius, targetContext)
val sut = testActivityRule.launchActivity(null)
val fragment = AvatarTestFragment()
sut.addFragment(fragment)
runOnUiThread {
fragment.addAvatar("Admin", avatarRadius, width, targetContext)
fragment.addAvatar("Test Server Admin", avatarRadius, width, targetContext)
fragment.addAvatar("Cormier Paulette", avatarRadius, width, targetContext)
fragment.addAvatar("winston brent", avatarRadius, width, targetContext)
fragment.addAvatar("Baker James Lorena", avatarRadius, width, targetContext)
fragment.addAvatar("Baker James Lorena", avatarRadius, width, targetContext)
fragment.addAvatar("[email protected]", avatarRadius, width, targetContext)
}
shortSleep()
waitForIdleSync()
screenshot(sut)
}
@Test
@ScreenshotTest
fun showAvatarsWithStatus() {
val avatarRadius = targetContext.resources.getDimension(R.dimen.list_item_avatar_icon_radius)
val width = DisplayUtils.convertDpToPixel(2 * avatarRadius, targetContext)
val sut = testActivityRule.launchActivity(null)
val fragment = AvatarTestFragment()
val paulette = BitmapFactory.decodeFile(getFile("paulette.jpg").absolutePath)
val christine = BitmapFactory.decodeFile(getFile("christine.jpg").absolutePath)
val textBitmap = BitmapUtils.drawableToBitmap(TextDrawable.createNamedAvatar("Admin", avatarRadius))
sut.addFragment(fragment)
runOnUiThread {
fragment.addBitmap(
BitmapUtils.createAvatarWithStatus(paulette, StatusType.ONLINE, "😘", targetContext),
width * 2,
1,
targetContext
)
fragment.addBitmap(
BitmapUtils.createAvatarWithStatus(christine, StatusType.ONLINE, "☁️", targetContext),
width * 2,
1,
targetContext
)
fragment.addBitmap(
BitmapUtils.createAvatarWithStatus(christine, StatusType.ONLINE, "🌴️", targetContext),
width * 2,
1,
targetContext
)
fragment.addBitmap(
BitmapUtils.createAvatarWithStatus(christine, StatusType.ONLINE, "", targetContext),
width * 2,
1,
targetContext
)
fragment.addBitmap(
BitmapUtils.createAvatarWithStatus(paulette, StatusType.DND, "", targetContext),
width * 2,
1,
targetContext
)
fragment.addBitmap(
BitmapUtils.createAvatarWithStatus(christine, StatusType.AWAY, "", targetContext),
width * 2,
1,
targetContext
)
fragment.addBitmap(
BitmapUtils.createAvatarWithStatus(paulette, StatusType.OFFLINE, "", targetContext),
width * 2,
1,
targetContext
)
fragment.addBitmap(
BitmapUtils.createAvatarWithStatus(textBitmap, StatusType.ONLINE, "😘", targetContext),
width,
2,
targetContext
)
fragment.addBitmap(
BitmapUtils.createAvatarWithStatus(textBitmap, StatusType.ONLINE, "☁️", targetContext),
width,
2,
targetContext
)
fragment.addBitmap(
BitmapUtils.createAvatarWithStatus(textBitmap, StatusType.ONLINE, "🌴️", targetContext),
width,
2,
targetContext
)
fragment.addBitmap(
BitmapUtils.createAvatarWithStatus(textBitmap, StatusType.ONLINE, "", targetContext),
width,
2,
targetContext
)
fragment.addBitmap(
BitmapUtils.createAvatarWithStatus(textBitmap, StatusType.DND, "", targetContext),
width,
2,
targetContext
)
fragment.addBitmap(
BitmapUtils.createAvatarWithStatus(textBitmap, StatusType.AWAY, "", targetContext),
width,
2,
targetContext
)
fragment.addBitmap(
BitmapUtils.createAvatarWithStatus(textBitmap, StatusType.OFFLINE, "", targetContext),
width,
2,
targetContext
)
}
shortSleep()
waitForIdleSync()
screenshot(sut)
}
}
| gpl-2.0 | 0c2f6357bd4b7b83b7c1b73fbce4f49b | 34.518919 | 108 | 0.614214 | 5.035249 | false | true | false | false |
nextcloud/android | app/src/androidTest/java/com/owncloud/android/providers/DocumentsProviderUtils.kt | 1 | 8905 | package com.owncloud.android.providers
import android.content.Context
import android.database.ContentObserver
import android.database.Cursor
import android.net.Uri
import android.provider.DocumentsContract.Document.COLUMN_DOCUMENT_ID
import android.provider.DocumentsContract.Document.COLUMN_MIME_TYPE
import android.provider.DocumentsContract.Document.MIME_TYPE_DIR
import android.provider.DocumentsContract.EXTRA_LOADING
import android.provider.DocumentsContract.buildChildDocumentsUriUsingTree
import android.provider.DocumentsContract.buildDocumentUriUsingTree
import android.provider.DocumentsContract.buildTreeDocumentUri
import android.provider.DocumentsContract.getDocumentId
import androidx.annotation.VisibleForTesting
import androidx.documentfile.provider.DocumentFile
import com.owncloud.android.datamodel.FileDataStorageManager
import com.owncloud.android.datamodel.OCFile
import com.owncloud.android.lib.common.OwnCloudClient
import com.owncloud.android.lib.common.utils.Log_OC
import com.owncloud.android.lib.resources.files.ExistenceCheckRemoteOperation
import com.owncloud.android.providers.DocumentsStorageProvider.DOCUMENTID_SEPARATOR
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeout
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertTrue
import java.io.IOException
import java.io.InputStream
import kotlin.coroutines.resume
// Uploads can sometimes take a bit of time, so 15sec is still considered recent enough
private const val RECENT_MILLISECONDS = 15_000
object DocumentsProviderUtils {
internal fun DocumentFile.getOCFile(storageManager: FileDataStorageManager): OCFile? {
val id = getDocumentId(uri)
val separated: List<String> = id.split(DOCUMENTID_SEPARATOR.toRegex())
return storageManager.getFileById(separated[1].toLong())
}
internal fun DocumentFile.assertRegularFile(
name: String? = null,
size: Long? = null,
mimeType: String? = null,
parent: DocumentFile? = null
) {
name?.let { assertEquals(it, this.name) }
assertTrue(exists())
assertTrue(isFile)
assertFalse(isDirectory)
assertFalse(isVirtual)
size?.let { assertEquals(it, length()) }
mimeType?.let { assertEquals(it, type) }
parent?.let { assertEquals(it.uri.toString(), parentFile!!.uri.toString()) }
}
internal fun DocumentFile.assertRegularFolder(name: String? = null, parent: DocumentFile? = null) {
name?.let { assertEquals(it, this.name) }
assertTrue(exists())
assertFalse(isFile)
assertTrue(isDirectory)
assertFalse(isVirtual)
parent?.let { assertEquals(it.uri.toString(), parentFile!!.uri.toString()) }
}
internal fun DocumentFile.assertRecentlyModified() {
val diff = System.currentTimeMillis() - lastModified()
assertTrue("File $name older than expected: $diff", diff < RECENT_MILLISECONDS)
}
internal fun assertExistsOnServer(client: OwnCloudClient, remotePath: String, shouldExist: Boolean) {
val result = ExistenceCheckRemoteOperation(remotePath, !shouldExist).execute(client)
assertTrue("$result", result.isSuccess)
}
internal fun assertListFilesEquals(expected: Collection<DocumentFile>, actual: Collection<DocumentFile>) {
// assertEquals(
// "Actual: ${actual.map { it.name.toString() }}",
// expected.map { it.uri.toString() }.apply { sorted() },
// actual.map { it.uri.toString() }.apply { sorted() },
// )
// FIXME replace with commented out stronger assertion above
// when parallel [UploadFileOperation]s don't bring back deleted files
val expectedSet = HashSet<String>(expected.map { it.uri.toString() })
val actualSet = HashSet<String>(actual.map { it.uri.toString() })
assertTrue(actualSet.containsAll(expectedSet))
actualSet.removeAll(expectedSet)
actualSet.forEach {
Log_OC.e("TEST", "Error: Found unexpected file: $it")
}
}
internal fun assertReadEquals(data: ByteArray, inputStream: InputStream?) {
assertNotNull(inputStream)
inputStream!!.use {
assertArrayEquals(data, it.readBytes())
}
}
/**
* Same as [DocumentFile.findFile] only that it re-queries when the first result was stale.
*
* Most documents providers including Nextcloud are listing the full directory content
* when querying for a specific file in a directory,
* so there is no point in trying to optimize the query by not listing all children.
*/
suspend fun DocumentFile.findFileBlocking(context: Context, displayName: String): DocumentFile? {
val files = listFilesBlocking(context)
for (doc in files) {
if (displayName == doc.name) return doc
}
return null
}
/**
* Works like [DocumentFile.listFiles] except that it waits until the DocumentProvider has a result.
* This prevents getting an empty list even though there are children to be listed.
*/
suspend fun DocumentFile.listFilesBlocking(context: Context) = withContext(Dispatchers.IO) {
val resolver = context.contentResolver
val childrenUri = buildChildDocumentsUriUsingTree(uri, getDocumentId(uri))
val projection = arrayOf(COLUMN_DOCUMENT_ID, COLUMN_MIME_TYPE)
val result = ArrayList<DocumentFile>()
try {
getLoadedCursor {
resolver.query(childrenUri, projection, null, null, null)
}
} catch (e: TimeoutCancellationException) {
throw IOException(e)
}.use { cursor ->
while (cursor.moveToNext()) {
val documentId = cursor.getString(0)
val isDirectory = cursor.getString(1) == MIME_TYPE_DIR
val file = if (isDirectory) {
val treeUri = buildTreeDocumentUri(uri.authority, documentId)
DocumentFile.fromTreeUri(context, treeUri)!!
} else {
val documentUri = buildDocumentUriUsingTree(uri, documentId)
DocumentFile.fromSingleUri(context, documentUri)!!
}
result.add(file)
}
}
result
}
/**
* Returns a cursor for the given query while ensuring that the cursor was loaded.
*
* When the SAF backend is a cloud storage provider (e.g. Nextcloud),
* it can happen that the query returns an outdated (e.g. empty) cursor
* which will only be updated in response to this query.
*
* See: https://commonsware.com/blog/2019/12/14/scoped-storage-stories-listfiles-woe.html
*
* This method uses a [suspendCancellableCoroutine] to wait for the result of a [ContentObserver]
* registered on the cursor in case the cursor is still loading ([EXTRA_LOADING]).
* If the cursor is not loading, it will be returned right away.
*
* @param timeout an optional time-out in milliseconds
* @throws TimeoutCancellationException if there was no result before the time-out
* @throws IOException if the query returns null
*/
@Suppress("EXPERIMENTAL_API_USAGE")
@VisibleForTesting
internal suspend fun getLoadedCursor(timeout: Long = 15_000, query: () -> Cursor?) =
withTimeout(timeout) {
suspendCancellableCoroutine<Cursor> { cont ->
val cursor = query() ?: throw IOException("Initial query returned no results")
cont.invokeOnCancellation { cursor.close() }
val loading = cursor.extras.getBoolean(EXTRA_LOADING, false)
if (loading) {
Log_OC.e("TEST", "Cursor was loading, wait for update...")
cursor.registerContentObserver(
object : ContentObserver(null) {
override fun onChange(selfChange: Boolean, uri: Uri?) {
cursor.close()
val newCursor = query()
if (newCursor == null) {
cont.cancel(IOException("Re-query returned no results"))
} else {
cont.resume(newCursor)
}
}
}
)
} else {
// not loading, return cursor right away
cont.resume(cursor)
}
}
}
}
| gpl-2.0 | bd0a3afa93ec59148011ece776321a44 | 43.303483 | 110 | 0.655474 | 4.914459 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.