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
google/intellij-community
platform/build-scripts/src/org/jetbrains/intellij/build/impl/MacDistributionBuilder.kt
1
23109
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("BlockingMethodInNonBlockingContext") package org.jetbrains.intellij.build.impl import com.intellij.diagnostic.telemetry.use import com.intellij.diagnostic.telemetry.useWithScope2 import com.intellij.openapi.util.SystemInfoRt import com.intellij.openapi.util.io.FileUtilRt import com.intellij.util.SystemProperties import io.opentelemetry.api.common.AttributeKey import io.opentelemetry.api.trace.Span import kotlinx.collections.immutable.persistentListOf import kotlinx.coroutines.* import org.apache.commons.compress.archivers.zip.ZipArchiveEntry import org.jetbrains.intellij.build.* import org.jetbrains.intellij.build.TraceManager.spanBuilder import org.jetbrains.intellij.build.impl.productInfo.ProductInfoLaunchData import org.jetbrains.intellij.build.impl.productInfo.checkInArchive import org.jetbrains.intellij.build.impl.productInfo.generateMultiPlatformProductJson import org.jetbrains.intellij.build.io.copyDir import org.jetbrains.intellij.build.io.copyFile import org.jetbrains.intellij.build.io.substituteTemplatePlaceholders import org.jetbrains.intellij.build.io.writeNewFile import org.jetbrains.intellij.build.tasks.NoDuplicateZipArchiveOutputStream import org.jetbrains.intellij.build.tasks.dir import org.jetbrains.intellij.build.tasks.entry import org.jetbrains.intellij.build.tasks.executableFileUnixMode import java.io.File import java.nio.file.Files import java.nio.file.Path import java.nio.file.attribute.PosixFilePermission import java.time.LocalDate import java.util.function.BiConsumer import java.util.zip.Deflater import kotlin.io.path.nameWithoutExtension class MacDistributionBuilder(override val context: BuildContext, private val customizer: MacDistributionCustomizer, private val ideaProperties: Path?) : OsSpecificDistributionBuilder { private val targetIcnsFileName: String = "${context.productProperties.baseFileName}.icns" override val targetOs: OsFamily get() = OsFamily.MACOS private fun getDocTypes(): String { val associations = mutableListOf<String>() if (customizer.associateIpr) { val association = """<dict> <key>CFBundleTypeExtensions</key> <array> <string>ipr</string> </array> <key>CFBundleTypeIconFile</key> <string>${targetIcnsFileName}</string> <key>CFBundleTypeName</key> <string>${context.applicationInfo.productName} Project File</string> <key>CFBundleTypeRole</key> <string>Editor</string> </dict>""" associations.add(association) } for (fileAssociation in customizer.fileAssociations) { val iconPath = fileAssociation.iconPath val association = """<dict> <key>CFBundleTypeExtensions</key> <array> <string>${fileAssociation.extension}</string> </array> <key>CFBundleTypeIconFile</key> <string>${if (iconPath.isEmpty()) targetIcnsFileName else File(iconPath).name}</string> <key>CFBundleTypeRole</key> <string>Editor</string> </dict>""" associations.add(association) } return associations.joinToString(separator = "\n ") + customizer.additionalDocTypes } override suspend fun copyFilesForOsDistribution(targetPath: Path, arch: JvmArchitecture) { withContext(Dispatchers.IO) { doCopyExtraFiles(macDistDir = targetPath, arch = arch, copyDistFiles = true) } } private suspend fun doCopyExtraFiles(macDistDir: Path, arch: JvmArchitecture?, copyDistFiles: Boolean) { @Suppress("SpellCheckingInspection") val platformProperties = mutableListOf( "\n#---------------------------------------------------------------------", "# macOS-specific system properties", "#---------------------------------------------------------------------", "com.apple.mrj.application.live-resize=false", "apple.laf.useScreenMenuBar=true", "jbScreenMenuBar.enabled=true", "apple.awt.fileDialogForDirectories=true", "apple.awt.graphics.UseQuartz=true", "apple.awt.fullscreencapturealldisplays=false" ) customizer.getCustomIdeaProperties(context.applicationInfo).forEach(BiConsumer { k, v -> platformProperties.add("$k=$v") }) layoutMacApp(ideaProperties!!, platformProperties, getDocTypes(), macDistDir, context) unpackPty4jNative(context, macDistDir, "darwin") generateBuildTxt(context, macDistDir.resolve("Resources")) if (copyDistFiles) { copyDistFiles(context, macDistDir) } customizer.copyAdditionalFiles(context, macDistDir.toString()) if (arch != null) { customizer.copyAdditionalFiles(context, macDistDir, arch) } generateUnixScripts(context, emptyList(), macDistDir.resolve("bin"), OsFamily.MACOS) } override suspend fun buildArtifacts(osAndArchSpecificDistPath: Path, arch: JvmArchitecture) { withContext(Dispatchers.IO) { doCopyExtraFiles(macDistDir = osAndArchSpecificDistPath, arch = arch, copyDistFiles = false) } context.executeStep(spanBuilder("build macOS artifacts").setAttribute("arch", arch.name), BuildOptions.MAC_ARTIFACTS_STEP) { val baseName = context.productProperties.getBaseArtifactName(context.applicationInfo, context.buildNumber) val publishSit = context.publishSitArchive val publishZipOnly = !publishSit && context.options.buildStepsToSkip.contains(BuildOptions.MAC_DMG_STEP) val binariesToSign = customizer.getBinariesToSign(context, arch) if (!binariesToSign.isEmpty()) { context.executeStep(spanBuilder("sign binaries for macOS distribution") .setAttribute("arch", arch.name), BuildOptions.MAC_SIGN_STEP) { context.signFiles(binariesToSign.map(osAndArchSpecificDistPath::resolve), mapOf( "mac_codesign_options" to "runtime", "mac_codesign_force" to "true", "mac_codesign_deep" to "true", )) } } val macZip = (if (publishZipOnly) context.paths.artifactDir else context.paths.tempDir).resolve("$baseName.mac.${arch.name}.zip") val macZipWithoutRuntime = macZip.resolveSibling(macZip.nameWithoutExtension + "-no-jdk.zip") val zipRoot = getMacZipRoot(customizer, context) val runtimeDist = context.bundledRuntime.extract(BundledRuntimeImpl.getProductPrefix(context), OsFamily.MACOS, arch) val directories = listOf(context.paths.distAllDir, osAndArchSpecificDistPath, runtimeDist) val extraFiles = context.getDistFiles() val compressionLevel = if (publishSit || publishZipOnly) Deflater.DEFAULT_COMPRESSION else Deflater.BEST_SPEED if (context.options.buildMacArtifactsWithRuntime) { buildMacZip( targetFile = macZip, zipRoot = zipRoot, productJson = generateMacProductJson(builtinModule = context.builtinModule, context = context, javaExecutablePath = "../jbr/Contents/Home/bin/java"), directories = directories, extraFiles = extraFiles, executableFilePatterns = generateExecutableFilesPatterns(true), compressionLevel = compressionLevel ) } if (context.options.buildMacArtifactsWithoutRuntime) { buildMacZip( targetFile = macZipWithoutRuntime, zipRoot = zipRoot, productJson = generateMacProductJson(builtinModule = context.builtinModule, context = context, javaExecutablePath = null), directories = directories.filterNot { it == runtimeDist }, extraFiles = extraFiles, executableFilePatterns = generateExecutableFilesPatterns(false), compressionLevel = compressionLevel ) } if (publishZipOnly) { Span.current().addEvent("skip DMG and SIT artifacts producing") if (context.options.buildMacArtifactsWithRuntime) { context.notifyArtifactBuilt(macZip) } if (context.options.buildMacArtifactsWithoutRuntime) { context.notifyArtifactBuilt(macZipWithoutRuntime) } } else { buildAndSignDmgFromZip(macZip = macZip, macZipWithoutRuntime = macZipWithoutRuntime, arch = arch, builtinModule = context.builtinModule) } } } suspend fun buildAndSignDmgFromZip(macZip: Path, macZipWithoutRuntime: Path?, arch: JvmArchitecture, builtinModule: BuiltinModulesFileData?) { buildForArch(builtinModule = builtinModule, arch = arch, macZip = macZip, macZipWithoutRuntime = macZipWithoutRuntime, customizer = customizer, context = context) } private fun layoutMacApp(ideaPropertiesFile: Path, platformProperties: List<String>, docTypes: String?, macDistDir: Path, context: BuildContext) { val macCustomizer = customizer copyDirWithFileFilter(context.paths.communityHomeDir.communityRoot.resolve("bin/mac"), macDistDir.resolve("bin"), customizer.binFilesFilter) copyDir(context.paths.communityHomeDir.communityRoot.resolve("platform/build-scripts/resources/mac/Contents"), macDistDir) val executable = context.productProperties.baseFileName Files.move(macDistDir.resolve("MacOS/executable"), macDistDir.resolve("MacOS/$executable")) //noinspection SpellCheckingInspection val icnsPath = Path.of((if (context.applicationInfo.isEAP) customizer.icnsPathForEAP else null) ?: customizer.icnsPath) val resourcesDistDir = macDistDir.resolve("Resources") copyFile(icnsPath, resourcesDistDir.resolve(targetIcnsFileName)) for (fileAssociation in customizer.fileAssociations) { if (!fileAssociation.iconPath.isEmpty()) { val source = Path.of(fileAssociation.iconPath) val dest = resourcesDistDir.resolve(source.fileName) Files.deleteIfExists(dest) copyFile(source, dest) } } val fullName = context.applicationInfo.productName //todo[nik] improve val minor = context.applicationInfo.minorVersion val isNotRelease = context.applicationInfo.isEAP && !minor.contains("RC") && !minor.contains("Beta") val version = if (isNotRelease) "EAP ${context.fullBuildNumber}" else "${context.applicationInfo.majorVersion}.${minor}" val isEap = if (isNotRelease) "-EAP" else "" val properties = Files.readAllLines(ideaPropertiesFile) properties.addAll(platformProperties) Files.write(macDistDir.resolve("bin/idea.properties"), properties) val bootClassPath = context.xBootClassPathJarNames.joinToString(separator = ":") { "\$APP_PACKAGE/Contents/lib/$it" } val classPath = context.bootClassPathJarNames.joinToString(separator = ":") { "\$APP_PACKAGE/Contents/lib/$it" } val fileVmOptions = VmOptionsGenerator.computeVmOptions(context.applicationInfo.isEAP, context.productProperties).toMutableList() val additionalJvmArgs = context.getAdditionalJvmArguments(OsFamily.MACOS).toMutableList() if (!bootClassPath.isEmpty()) { //noinspection SpellCheckingInspection additionalJvmArgs.add("-Xbootclasspath/a:$bootClassPath") } val predicate: (String) -> Boolean = { it.startsWith("-D") } val launcherProperties = additionalJvmArgs.filter(predicate) val launcherVmOptions = additionalJvmArgs.filterNot(predicate) fileVmOptions.add("-XX:ErrorFile=\$USER_HOME/java_error_in_${executable}_%p.log") fileVmOptions.add("-XX:HeapDumpPath=\$USER_HOME/java_error_in_${executable}.hprof") VmOptionsGenerator.writeVmOptions(macDistDir.resolve("bin/${executable}.vmoptions"), fileVmOptions, "\n") val urlSchemes = macCustomizer.urlSchemes val urlSchemesString = if (urlSchemes.isEmpty()) { "" } else { """ <key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleTypeRole</key> <string>Editor</string> <key>CFBundleURLName</key> <string>Stacktrace</string> <key>CFBundleURLSchemes</key> <array> ${urlSchemes.joinToString(separator = "\n") { " <string>$it</string>" }} </array> </dict> </array> """ } val todayYear = LocalDate.now().year.toString() //noinspection SpellCheckingInspection substituteTemplatePlaceholders( inputFile = macDistDir.resolve("Info.plist"), outputFile = macDistDir.resolve("Info.plist"), placeholder = "@@", values = listOf( Pair("build", context.fullBuildNumber), Pair("doc_types", docTypes ?: ""), Pair("executable", executable), Pair("icns", targetIcnsFileName), Pair("bundle_name", fullName), Pair("product_state", isEap), Pair("bundle_identifier", macCustomizer.bundleIdentifier), Pair("year", todayYear), Pair("version", version), Pair("vm_options", optionsToXml(launcherVmOptions)), Pair("vm_properties", propertiesToXml(launcherProperties, mapOf("idea.executable" to context.productProperties.baseFileName))), Pair("class_path", classPath), Pair("main_class_name", context.productProperties.mainClassName.replace('.', '/')), Pair("url_schemes", urlSchemesString), Pair("architectures", "<key>LSArchitecturePriority</key>\n <array>\n" + macCustomizer.architectures.joinToString(separator = "\n") { " <string>$it</string>\n" } + " </array>"), Pair("min_osx", macCustomizer.minOSXVersion), ) ) val distBinDir = macDistDir.resolve("bin") Files.createDirectories(distBinDir) val sourceScriptDir = context.paths.communityHomeDir.communityRoot.resolve("platform/build-scripts/resources/mac/scripts") Files.newDirectoryStream(sourceScriptDir).use { stream -> val inspectCommandName = context.productProperties.inspectCommandName for (file in stream) { if (file.toString().endsWith(".sh")) { var fileName = file.fileName.toString() if (fileName == "inspect.sh" && inspectCommandName != "inspect") { fileName = "${inspectCommandName}.sh" } val sourceFileLf = Files.createTempFile(context.paths.tempDir, file.fileName.toString(), "") try { // Until CR (\r) will be removed from the repository checkout, we need to filter it out from Unix-style scripts // https://youtrack.jetbrains.com/issue/IJI-526/Force-git-to-use-LF-line-endings-in-working-copy-of-via-gitattri Files.writeString(sourceFileLf, Files.readString(file).replace("\r", "")) val target = distBinDir.resolve(fileName) substituteTemplatePlaceholders( sourceFileLf, target, "@@", listOf( Pair("product_full", fullName), Pair("script_name", executable), Pair("inspectCommandName", inspectCommandName), ), false, ) } finally { Files.delete(sourceFileLf) } } } } } override fun generateExecutableFilesPatterns(includeRuntime: Boolean): List<String> { var executableFilePatterns = persistentListOf( "bin/*.sh", "bin/*.py", "bin/fsnotifier", "bin/printenv", "bin/restarter", "bin/repair", "MacOS/*" ) if (includeRuntime) { executableFilePatterns = executableFilePatterns.addAll(context.bundledRuntime.executableFilesPatterns(OsFamily.MACOS)) } return executableFilePatterns.addAll(customizer.extraExecutables) } private suspend fun buildForArch(builtinModule: BuiltinModulesFileData?, arch: JvmArchitecture, macZip: Path, macZipWithoutRuntime: Path?, customizer: MacDistributionCustomizer, context: BuildContext) { spanBuilder("build macOS artifacts for specific arch").setAttribute("arch", arch.name).useWithScope2 { val notarize = SystemProperties.getBooleanProperty("intellij.build.mac.notarize", true) withContext(Dispatchers.IO) { buildForArch(builtinModule, arch, macZip, macZipWithoutRuntime, notarize, customizer, context) Files.deleteIfExists(macZip) } } } private suspend fun buildForArch(builtinModule: BuiltinModulesFileData?, arch: JvmArchitecture, macZip: Path, macZipWithoutRuntime: Path?, notarize: Boolean, customizer: MacDistributionCustomizer, context: BuildContext) { val suffix = if (arch == JvmArchitecture.x64) "" else "-${arch.fileSuffix}" val archStr = arch.name coroutineScope { if (context.options.buildMacArtifactsWithRuntime) { createSkippableJob( spanBuilder("build DMG with Runtime").setAttribute("arch", archStr), "${BuildOptions.MAC_ARTIFACTS_STEP}_jre_$archStr", context ) { signAndBuildDmg(builder = this@MacDistributionBuilder, builtinModule = builtinModule, context = context, customizer = customizer, macHostProperties = context.proprietaryBuildTools.macHostProperties, macZip = macZip, isRuntimeBundled = true, suffix = suffix, arch = arch, notarize = notarize) } } if (context.options.buildMacArtifactsWithoutRuntime) { requireNotNull(macZipWithoutRuntime) createSkippableJob( spanBuilder("build DMG without Runtime").setAttribute("arch", archStr), "${BuildOptions.MAC_ARTIFACTS_STEP}_no_jre_$archStr", context ) { signAndBuildDmg(builder = this@MacDistributionBuilder, builtinModule = builtinModule, context = context, customizer = customizer, macHostProperties = context.proprietaryBuildTools.macHostProperties, macZip = macZipWithoutRuntime, isRuntimeBundled = false, suffix = "-no-jdk$suffix", arch = arch, notarize = notarize) } } } } } private fun optionsToXml(options: List<String>): String { val buff = StringBuilder() for (it in options) { buff.append(" <string>").append(it).append("</string>\n") } return buff.toString().trim() } private fun propertiesToXml(properties: List<String>, moreProperties: Map<String, String>): String { val buff = StringBuilder() for (it in properties) { val p = it.indexOf('=') buff.append(" <key>").append(it.substring(2, p)).append("</key>\n") buff.append(" <string>").append(it.substring(p + 1)).append("</string>\n") } moreProperties.forEach { (key, value) -> buff.append(" <key>").append(key).append("</key>\n") buff.append(" <string>").append(value).append("</string>\n") } return buff.toString().trim() } internal fun getMacZipRoot(customizer: MacDistributionCustomizer, context: BuildContext): String = "${customizer.getRootDirectoryName(context.applicationInfo, context.buildNumber)}/Contents" internal fun generateMacProductJson(builtinModule: BuiltinModulesFileData?, context: BuildContext, javaExecutablePath: String?): String { val executable = context.productProperties.baseFileName return generateMultiPlatformProductJson( relativePathToBin = "../bin", builtinModules = builtinModule, launch = listOf( ProductInfoLaunchData( os = OsFamily.MACOS.osName, launcherPath = "../MacOS/${executable}", javaExecutablePath = javaExecutablePath, vmOptionsFilePath = "../bin/${executable}.vmoptions", startupWmClass = null, bootClassPathJarNames = context.bootClassPathJarNames, additionalJvmArguments = context.getAdditionalJvmArguments(OsFamily.MACOS) ) ), context = context ) } private fun MacDistributionBuilder.buildMacZip(targetFile: Path, zipRoot: String, productJson: String, directories: List<Path>, extraFiles: Collection<Map.Entry<Path, String>>, executableFilePatterns: List<String>, compressionLevel: Int) { spanBuilder("build zip archive for macOS") .setAttribute("file", targetFile.toString()) .setAttribute("zipRoot", zipRoot) .setAttribute(AttributeKey.stringArrayKey("executableFilePatterns"), executableFilePatterns) .use { for (dir in directories) { updateExecutablePermissions(dir, executableFilePatterns) } val entryCustomizer: (ZipArchiveEntry, Path, String) -> Unit = { entry, file, _ -> if (SystemInfoRt.isUnix && PosixFilePermission.OWNER_EXECUTE in Files.getPosixFilePermissions(file)) { entry.unixMode = executableFileUnixMode } } writeNewFile(targetFile) { targetFileChannel -> NoDuplicateZipArchiveOutputStream(targetFileChannel).use { zipOutStream -> zipOutStream.setLevel(compressionLevel) zipOutStream.entry("$zipRoot/Resources/product-info.json", productJson.encodeToByteArray()) val fileFilter: (Path, String) -> Boolean = { sourceFile, relativePath -> if (relativePath.endsWith(".txt") && !relativePath.contains('/')) { zipOutStream.entry("$zipRoot/Resources/${relativePath}", sourceFile) false } else { true } } for (dir in directories) { zipOutStream.dir(dir, "$zipRoot/", fileFilter = fileFilter, entryCustomizer = entryCustomizer) } for ((file, relativePath) in extraFiles) { zipOutStream.entry("$zipRoot/${FileUtilRt.toSystemIndependentName(relativePath)}${if (relativePath.isEmpty()) "" else "/"}${file.fileName}", file) } } } checkInArchive(archiveFile = targetFile, pathInArchive = "$zipRoot/Resources", context = context) } }
apache-2.0
edc30d0f997b202292f81093fdce9c73
43.698259
158
0.644338
5.197706
false
false
false
false
aquatir/remember_java_api
code-sample-kotlin/code-sample-kotlin-basics/src/main/kotlin/codesample/kotlin/sandbox/basics/HelloKotlin.kt
1
4092
package codesample.kotlin.sandbox.basics fun sum(a: Int, b: Int): Int { return a + b } fun printText(a: String) { println("You string is: $a") } fun getNullString(): String? { return null } fun printNotNullString(a: String) { println(a) } fun main(args: Array<String>) { println("Hello, Kotlin!") println(sum(5, 1)) printText("Hello, world!") val c: Int val a = 5 // Read-only variable c = a println(c) val text = "This is Kotlin" println("text: ${text.replace("is", "was")}") fun maxOfTwo(a: Int, b: Int): Int = if (a > b) a else b println("Max of 5 and 10 is: " + maxOfTwo(5, 10)) var nullStr = getNullString() println("$nullStr bla-bla-bla") if (nullStr != null) { // This will be smart-casted into from String? to String printNotNullString(nullStr) } // We can define function like this fun printTextt(text: String) = println(text) // Or with body fun printTexttWithBody(text: String) = println(text) printTextt("text") printTexttWithBody("textt") fun strLength(something: Any): Int { if (something is String) { // We can use .length on Any argument, because is gets smart-casted to String return something.length } return 0 } println("\n****** WHEN ******* ") fun describe(obj: Any): String = when (obj) { 1 -> "One" "Hello" -> "Greeting" is Long -> "Long" !is String -> "Not a string" else -> "Unknown" } println(describe(1)) println(describe("Hello")) println(describe(30L)) println(describe(323.12)) println(describe("Str")) val b = 3 when (b) { 1, 2 -> println("a is either 1 or 2") else -> { println("a in neither 1 nor 2") } } println("\n****** RANGES ******* ") for (x in 0..5) if (x !in 2..3) println(x) val y = 50 if (y in 44..56) println("y is in 44-56 range") for (x in 5 downTo 0 step 2) println(x) println("\n****** COLLECTIONS AND LAMBDAS ******* ") val fruits = listOf("apple", "mango", "avocado", "banana", "apple", null, null) fruits .map { it.toString() } // null will be "null" .filter { it.startsWith("a") } // and they will be filtered out .sortedBy { it } .distinctBy { it } .map { it.toUpperCase() } .forEach { println(it) } for ((index, value) in fruits.withIndex()) { println("intex: $index value: $value") } println("\n****** DESTRUCTURING DECLARATION ******* ") data class Student(val a: String, val b: Int, val c: String) { var name: String = this.a var age: Int = this.b val subject: String = this.c } val student = Student("Ivan", 4, "Biology") val (param1, param2, param3) = student println("Name $param1, age: $param2, subject: $param3") fun returnArrayOfInt(): Array<Int> { return arrayOf(1, 2, 3) } val (value1, value2, value3) = returnArrayOfInt() println("value1: $value1, value2: $value2, value3: $value3") // Kotlin provides multi-line strings with 3 " characters """ |Tell me and I forget. |Teach me and I remember. |Involve me and I learn. |(Benjamin Franklin) """.trimMargin("|").also { println(it) } // We can use labels! label@ for (i in 0..100) { for (j in 3..100) { println("value: $j") if (j == 5) { println("breaking inner AND outer loops together") break@label } } } var aa = 1 var bb = 2 println("a: $aa b: $bb") // This works because the expression inside {} only changes global bb value. The inner bb value is staying // the same, thus also will return bb value which was passed to function initially. // Protip: do not make it your interview question... aa = bb.also { bb = aa } println("a: $aa b: $bb") }
mit
6a7aeb683de842795ed35102ca938f5d
24.265432
110
0.546676
3.608466
false
false
false
false
exercism/xkotlin
exercises/practice/resistor-color-trio/.meta/src/reference/kotlin/ResistorColorTrio.kt
1
507
import kotlin.math.log10 import kotlin.math.pow object ResistorColorTrio { fun text(vararg input: Color): String { val duoValue = 10 * input[0].ordinal + input[1].ordinal val trioValue = duoValue * 10.0.pow(input[2].ordinal) val thousandPowers = (log10(trioValue) / 3).toInt() val resultValue = (trioValue / 1000.0.pow(thousandPowers)).toInt() val resultUnit = Unit.values()[thousandPowers].name.lowercase() return "$resultValue $resultUnit" } }
mit
91242082c06fb734932b057e14599ed2
28.823529
74
0.658777
3.44898
false
false
false
false
lomza/screenlookcount
app/src/main/java/com/totemsoft/screenlookcount/utils/C.kt
1
514
package com.totemsoft.screenlookcount.utils /** * Object for holding app's constants. * * @author Antonina */ internal object C { const val TAG = "SLC" const val DIALOG_TAG_STAT = "statistics_dialog" const val DIALOG_TAG_STAT_CAT = "statistics_category_dialog" const val FRAGMENT_TAG_MAIN = "main_fragment" const val FRAGMENT_TAG_ABOUT = "about_fragment" const val BUNDLE_ARG_SCREEN_LOOK = "arg_screen_look_count" const val BUNDLE_ARG_SCREEN_UNLOCK = "arg_screen_unlock_count" }
gpl-3.0
f09f4ef99079076449b3cc1da307cd9f
27.555556
66
0.70428
3.403974
false
false
false
false
jdbi/jdbi
kotlin-sqlobject/src/main/kotlin/org/jdbi/v3/sqlobject/kotlin/KotlinDefaultMethodHandlerFactory.kt
2
2650
/* * 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.jdbi.v3.sqlobject.kotlin import org.jdbi.v3.core.kotlin.isKotlinClass import org.jdbi.v3.sqlobject.Handler import org.jdbi.v3.sqlobject.HandlerFactory import java.lang.reflect.InvocationTargetException import java.lang.reflect.Method import java.util.Collections import java.util.Optional import java.util.WeakHashMap class KotlinDefaultMethodHandlerFactory : HandlerFactory { private val implsClassCache = Collections.synchronizedMap(WeakHashMap<Class<*>, Map<MethodKey, Method>>()) override fun buildHandler(sqlObjectType: Class<*>, method: Method): Optional<Handler> { val implementation = getImplementation(sqlObjectType, method) ?: return Optional.empty() return Optional.of( Handler { t, a, _ -> @Suppress("SwallowedException") try { @Suppress("SpreadOperator") implementation.invoke(null, t, *a) } catch (e: InvocationTargetException) { throw e.targetException } } ) } fun getImplementation(type: Class<*>, method: Method): Method? { if (!type.isKotlinClass()) return null val implMethods: Map<MethodKey, Method> = implsClassCache.computeIfAbsent(type) { findImplClass(it)?.methods?.associateBy { MethodKey(it.name, it.parameters.map { p -> p.type }, it.returnType) } ?: emptyMap() }!! return findImplMethod(type, method, implMethods) } private fun findImplMethod(type: Class<*>, method: Method, implMethods: Map<MethodKey, Method>): Method? { // default method is generated as static method that takes target interface as first parameter val paramTypes = listOf(type) + method.parameters.map { it.type } return implMethods[MethodKey(method.name, paramTypes, method.returnType)] } private fun findImplClass(type: Class<*>): Class<*>? = type.classes.find { it.simpleName == "DefaultImpls" } } data class MethodKey(val name: String, val paramTypes: List<Class<*>>, val returnType: Class<*>)
apache-2.0
632c51f177f0b3a8809e199975fedd9e
39.769231
138
0.68566
4.446309
false
false
false
false
leafclick/intellij-community
platform/configuration-store-impl/src/StoreReloadManagerImpl.kt
1
13194
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.configurationStore import com.intellij.configurationStore.schemeManager.SchemeChangeApplicator import com.intellij.configurationStore.schemeManager.SchemeChangeEvent import com.intellij.ide.impl.ProjectUtil import com.intellij.openapi.Disposable import com.intellij.openapi.application.AppUIExecutor import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ApplicationNamesInfo import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.ex.ApplicationManagerEx import com.intellij.openapi.application.impl.ApplicationInfoImpl import com.intellij.openapi.components.ComponentManager import com.intellij.openapi.components.StateStorage import com.intellij.openapi.components.impl.stores.IComponentStore import com.intellij.openapi.components.impl.stores.IProjectStore import com.intellij.openapi.components.stateStore import com.intellij.openapi.diagnostic.debug import com.intellij.openapi.diagnostic.runAndLogException import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectBundle import com.intellij.openapi.project.ProjectReloadState import com.intellij.openapi.project.ex.ProjectManagerEx import com.intellij.openapi.project.processOpenedProjects import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.Key import com.intellij.openapi.util.Ref import com.intellij.openapi.util.UserDataHolderEx import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManagerListener import com.intellij.ui.AppUIUtil import com.intellij.util.ExceptionUtil import com.intellij.util.SingleAlarm import gnu.trove.THashSet import kotlinx.coroutines.withContext import org.jetbrains.annotations.ApiStatus import java.util.* import java.util.concurrent.atomic.AtomicInteger import java.util.concurrent.atomic.AtomicReference import kotlin.collections.LinkedHashSet private val CHANGED_FILES_KEY = Key<LinkedHashMap<ComponentStoreImpl, LinkedHashSet<StateStorage>>>("CHANGED_FILES_KEY") private val CHANGED_SCHEMES_KEY = Key<LinkedHashMap<SchemeChangeApplicator, LinkedHashSet<SchemeChangeEvent>>>("CHANGED_SCHEMES_KEY") /** * This service is temporary allowed to be overriden to support reloading of new project model entities. It should be removed after merging * new project model modules to community project. */ @ApiStatus.Internal open class StoreReloadManagerImpl : StoreReloadManager, Disposable { private val reloadBlockCount = AtomicInteger() private val blockStackTrace = AtomicReference<Throwable?>() private val changedApplicationFiles = LinkedHashSet<StateStorage>() private val changedFilesAlarm = SingleAlarm(Runnable { if (isReloadBlocked() || !tryToReloadApplication()) { return@Runnable } val projectsToReload = THashSet<Project>() processOpenedProjects { project -> val changedSchemes = CHANGED_SCHEMES_KEY.getAndClear(project as UserDataHolderEx) val changedStorages = CHANGED_FILES_KEY.getAndClear(project as UserDataHolderEx) if ((changedSchemes == null || changedSchemes.isEmpty()) && (changedStorages == null || changedStorages.isEmpty()) && !mayHaveAdditionalConfigurations(project)) { return@processOpenedProjects } runBatchUpdate(project.messageBus) { // reload schemes first because project file can refer to scheme (e.g. inspection profile) if (changedSchemes != null) { for ((tracker, files) in changedSchemes) { LOG.runAndLogException { tracker.reload(files) } } } if (changedStorages != null) { for ((store, storages) in changedStorages) { if ((store.storageManager as? StateStorageManagerImpl)?.componentManager?.isDisposed == true) { continue } @Suppress("UNCHECKED_CAST") if (reloadStore(storages, store) == ReloadComponentStoreStatus.RESTART_AGREED) { projectsToReload.add(project) } } } reloadAdditionalConfigurations(project) } } for (project in projectsToReload) { doReloadProject(project) } }, delay = 300, parentDisposable = this) protected open fun reloadAdditionalConfigurations(project: Project) { } protected open fun mayHaveAdditionalConfigurations(project: Project): Boolean = false internal class MyVirtualFileManagerListener : VirtualFileManagerListener { private val manager = StoreReloadManager.getInstance() override fun beforeRefreshStart(asynchronous: Boolean) { manager.blockReloadingProjectOnExternalChanges() } override fun afterRefreshFinish(asynchronous: Boolean) { manager.unblockReloadingProjectOnExternalChanges() } } override fun isReloadBlocked(): Boolean { val count = reloadBlockCount.get() LOG.debug { "[RELOAD] myReloadBlockCount = $count" } return count > 0 } override fun saveChangedProjectFile(file: VirtualFile, project: Project) { val storageManager = (project.stateStore as ComponentStoreImpl).storageManager as? StateStorageManagerImpl ?: return storageManager.getCachedFileStorages(listOf(storageManager.collapseMacros(file.path))).firstOrNull()?.let { // if empty, so, storage is not yet loaded, so, we don't have to reload storageFilesChanged(mapOf(project to listOf(it))) } } override fun blockReloadingProjectOnExternalChanges() { if (reloadBlockCount.getAndIncrement() == 0 && !ApplicationInfoImpl.isInStressTest()) { blockStackTrace.set(Throwable()) } } override fun unblockReloadingProjectOnExternalChanges() { val counter = reloadBlockCount.get() if (counter <= 0) { LOG.error("Block counter $counter must be > 0, first block stack trace: ${blockStackTrace.get()?.let { ExceptionUtil.getThrowableText(it) }}") } if (reloadBlockCount.decrementAndGet() != 0) { return } blockStackTrace.set(null) changedFilesAlarm.request() } /** * Internal use only. Force reload changed project files. Must be called before save otherwise saving maybe not performed (because storage saving is disabled). */ override fun flushChangedProjectFileAlarm() { changedFilesAlarm.drainRequestsInTest() } override suspend fun reloadChangedStorageFiles() { val unfinishedRequest = changedFilesAlarm.getUnfinishedRequest() ?: return withContext(storeEdtCoroutineDispatcher) { unfinishedRequest.run() // just to be sure changedFilesAlarm.getUnfinishedRequest()?.run() } } override fun reloadProject(project: Project) { CHANGED_FILES_KEY.set(project, null) doReloadProject(project) } override fun storageFilesChanged(componentManagerToStorages: Map<ComponentManager, Collection<StateStorage>>) { if (componentManagerToStorages.isEmpty()) { return } if (LOG.isDebugEnabled) { LOG.debug("[RELOAD] registering to reload: ${componentManagerToStorages.map { "${it.key}: ${it.value.joinToString()}" }.joinToString("\n")}", Exception()) } for ((componentManager, storages) in componentManagerToStorages) { val project: Project? = when (componentManager) { is Project -> componentManager is Module -> componentManager.project else -> null } if (project == null) { val changes = changedApplicationFiles synchronized(changes) { changes.addAll(storages) } } else { val changes = CHANGED_FILES_KEY.get(project) ?: (project as UserDataHolderEx).putUserDataIfAbsent(CHANGED_FILES_KEY, linkedMapOf()) synchronized(changes) { changes.getOrPut(componentManager.stateStore as ComponentStoreImpl) { LinkedHashSet() }.addAll(storages) } } for (storage in storages) { if (storage is StateStorageBase<*>) { storage.disableSaving() } } } scheduleProcessingChangedFiles() } internal fun registerChangedSchemes(events: List<SchemeChangeEvent>, schemeFileTracker: SchemeChangeApplicator, project: Project) { if (LOG.isDebugEnabled) { LOG.debug("[RELOAD] Registering schemes to reload: $events", Exception()) } val changes = CHANGED_SCHEMES_KEY.get(project) ?: (project as UserDataHolderEx).putUserDataIfAbsent(CHANGED_SCHEMES_KEY, linkedMapOf()) synchronized(changes) { changes.getOrPut(schemeFileTracker) { LinkedHashSet() }.addAll(events) } scheduleProcessingChangedFiles() } override fun scheduleProcessingChangedFiles() { if (!isReloadBlocked()) { changedFilesAlarm.cancelAndRequest() } } private fun tryToReloadApplication(): Boolean { if (ApplicationManager.getApplication().isDisposed) { return false } if (changedApplicationFiles.isEmpty()) { return true } val changes = LinkedHashSet(changedApplicationFiles) changedApplicationFiles.clear() return reloadAppStore(changes) } override fun dispose() { } } fun reloadAppStore(changes: Set<StateStorage>): Boolean { val status = reloadStore(changes, ApplicationManager.getApplication().stateStore as ComponentStoreImpl) if (status == ReloadComponentStoreStatus.RESTART_AGREED) { ApplicationManagerEx.getApplicationEx().restart(true) return false } else { return status == ReloadComponentStoreStatus.SUCCESS || status == ReloadComponentStoreStatus.RESTART_CANCELLED } } internal fun reloadStore(changedStorages: Set<StateStorage>, store: ComponentStoreImpl): ReloadComponentStoreStatus { val notReloadableComponents: Collection<String>? var willBeReloaded = false try { try { notReloadableComponents = store.reload(changedStorages) } catch (e: Throwable) { LOG.warn(e) AppUIUtil.invokeOnEdt { Messages.showWarningDialog(ProjectBundle.message("project.reload.failed", e.message), ProjectBundle.message("project.reload.failed.title")) } return ReloadComponentStoreStatus.ERROR } if (notReloadableComponents == null || notReloadableComponents.isEmpty()) { return ReloadComponentStoreStatus.SUCCESS } willBeReloaded = askToRestart(store, notReloadableComponents, changedStorages, store.project == null) return if (willBeReloaded) ReloadComponentStoreStatus.RESTART_AGREED else ReloadComponentStoreStatus.RESTART_CANCELLED } finally { if (!willBeReloaded) { for (storage in changedStorages) { if (storage is StateStorageBase<*>) { storage.enableSaving() } } } } } // used in settings repository plugin fun askToRestart(store: IComponentStore, notReloadableComponents: Collection<String>, changedStorages: Set<StateStorage>?, isApp: Boolean): Boolean { val message = StringBuilder() val storeName = if (store is IProjectStore) "Project '${store.projectName}'" else "Application" message.append(storeName).append(' ') message.append("components were changed externally and cannot be reloaded:\n\n") var count = 0 for (component in notReloadableComponents) { if (count == 10) { message.append('\n').append("and ").append(notReloadableComponents.size - count).append(" more").append('\n') } else { message.append(component).append('\n') count++ } } message.append("\nWould you like to ") if (isApp) { message.append(if (ApplicationManager.getApplication().isRestartCapable) "restart" else "shutdown").append(' ') message.append(ApplicationNamesInfo.getInstance().productName).append('?') } else { message.append("reload project?") } if (Messages.showYesNoDialog(message.toString(), "$storeName Files Changed", Messages.getQuestionIcon()) == Messages.YES) { if (changedStorages != null) { for (storage in changedStorages) { if (storage is StateStorageBase<*>) { storage.disableSaving() } } } return true } return false } internal enum class ReloadComponentStoreStatus { RESTART_AGREED, RESTART_CANCELLED, ERROR, SUCCESS } private fun <T : Any> Key<T>.getAndClear(holder: UserDataHolderEx): T? { val value = holder.getUserData(this) ?: return null holder.replace(this, value, null) return value } private fun doReloadProject(project: Project) { val projectRef = Ref.create(project) ProjectReloadState.getInstance(project).onBeforeAutomaticProjectReload() AppUIExecutor.onWriteThread(ModalityState.NON_MODAL).later().submit { LOG.debug("Reloading project.") val project1 = projectRef.get() // Let it go projectRef.set(null) if (project1.isDisposed) { return@submit } // must compute here, before project dispose val presentableUrl = project1.presentableUrl if (!ProjectManagerEx.getInstanceEx().closeAndDispose(project1)) { return@submit } ProjectUtil.openProject(Objects.requireNonNull<String>(presentableUrl), null, true) } }
apache-2.0
7f0b8a6bf1efa3470b8b359eec98a457
34.758808
161
0.728589
4.992054
false
false
false
false
mtransitapps/mtransit-for-android
src/main/java/org/mtransit/android/ui/MTViewModelWithLocation.kt
1
820
package org.mtransit.android.ui import android.location.Location import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import org.mtransit.android.commons.LocationUtils import org.mtransit.android.commons.MTLog abstract class MTViewModelWithLocation : ViewModel(), MTLog.Loggable { private val _deviceLocation = MutableLiveData<Location?>() val deviceLocation: LiveData<Location?> = _deviceLocation fun onDeviceLocationChanged(newDeviceLocation: Location?) { newDeviceLocation?.let { val currentDeviceLocation = _deviceLocation.value if (currentDeviceLocation == null || LocationUtils.isMoreRelevant(logTag, currentDeviceLocation, it)) { _deviceLocation.value = it } } } }
apache-2.0
a76c36a4042cdb8073bb5688b1743c34
33.208333
115
0.740244
5
false
false
false
false
leafclick/intellij-community
platform/configuration-store-impl/src/StorageVirtualFileTracker.kt
1
4823
// 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.configurationStore import com.intellij.openapi.components.ComponentManager import com.intellij.openapi.components.StateStorage import com.intellij.openapi.components.impl.stores.FileStorageCoreUtil import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.openapi.vfs.newvfs.BulkFileListener import com.intellij.openapi.vfs.newvfs.events.* import com.intellij.util.containers.ContainerUtil import com.intellij.util.messages.MessageBus import java.nio.file.Paths import java.util.concurrent.ConcurrentMap import java.util.concurrent.atomic.AtomicBoolean class StorageVirtualFileTracker(private val messageBus: MessageBus) { private val filePathToStorage: ConcurrentMap<String, TrackedStorage> = ContainerUtil.newConcurrentMap() @Volatile private var hasDirectoryBasedStorages = false private val vfsListenerAdded = AtomicBoolean() interface TrackedStorage : StateStorage { val storageManager: StateStorageManagerImpl } fun put(path: String, storage: TrackedStorage) { filePathToStorage.put(path, storage) if (storage is DirectoryBasedStorage) { hasDirectoryBasedStorages = true } if (vfsListenerAdded.compareAndSet(false, true)) { addVfsChangesListener() } } fun remove(path: String) { filePathToStorage.remove(path) } fun remove(processor: (TrackedStorage) -> Boolean) { val iterator = filePathToStorage.values.iterator() for (storage in iterator) { if (processor(storage)) { iterator.remove() } } } private fun addVfsChangesListener() { messageBus.connect().subscribe(VirtualFileManager.VFS_CHANGES, object : BulkFileListener { override fun after(events: MutableList<out VFileEvent>) { var storageEvents: LinkedHashMap<ComponentManager, LinkedHashSet<StateStorage>>? = null eventLoop@ for (event in events) { var storage: StateStorage? if (event is VFilePropertyChangeEvent && VirtualFile.PROP_NAME == event.propertyName) { val oldPath = event.oldPath storage = filePathToStorage.remove(oldPath) if (storage != null) { filePathToStorage.put(event.path, storage) if (storage is FileBasedStorage) { storage.setFile(null, Paths.get(event.path)) } // we don't support DirectoryBasedStorage renaming // StoragePathMacros.MODULE_FILE -> old path, we must update value storage.storageManager.pathRenamed(oldPath, event.path, event) } } else { val path = event.path storage = filePathToStorage.get(path) // we don't care about parent directory create (because it doesn't affect anything) and move (because it is not supported case), // but we should detect deletion - but again, it is not supported case. So, we don't check if some of registered storages located inside changed directory. // but if we have DirectoryBasedStorage, we check - if file located inside it if (storage == null && hasDirectoryBasedStorages && path.endsWith(FileStorageCoreUtil.DEFAULT_EXT, ignoreCase = true)) { storage = filePathToStorage.get(VfsUtil.getParentDir(path)) } } if (storage == null) { continue } when (event) { is VFileMoveEvent -> { if (storage is FileBasedStorage) { storage.setFile(null, Paths.get(event.path)) } } is VFileCreateEvent -> { if (storage is FileBasedStorage && event.requestor !is SaveSession) { storage.setFile(event.file, null) } } is VFileDeleteEvent -> { if (storage is FileBasedStorage) { storage.setFile(null, null) } else { (storage as DirectoryBasedStorage).setVirtualDir(null) } } is VFileCopyEvent -> continue@eventLoop } if (isFireStorageFileChangedEvent(event)) { val componentManager = storage.storageManager.componentManager!! if (storageEvents == null) { storageEvents = LinkedHashMap() } storageEvents.getOrPut(componentManager) { LinkedHashSet() }.add(storage) } } if (storageEvents != null) { StoreReloadManager.getInstance().storageFilesChanged(storageEvents) } } }) } }
apache-2.0
0e01860cc1ff7c24ad3414d8d23b9482
37.285714
167
0.651254
5.202805
false
false
false
false
zdary/intellij-community
java/java-tests/testSrc/com/intellij/util/indexing/IndexDiagnosticTest.kt
2
5700
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.util.indexing import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import com.fasterxml.jackson.module.kotlin.readValue import com.fasterxml.jackson.module.kotlin.registerKotlinModule import com.intellij.idea.TestFor import com.intellij.openapi.application.PathManager import com.intellij.openapi.project.getProjectCachePath import com.intellij.testFramework.fixtures.JavaCodeInsightFixtureTestCase import com.intellij.util.indexing.diagnostic.IndexDiagnosticDumper import com.intellij.util.indexing.diagnostic.dto.* import com.intellij.util.indexing.diagnostic.dump.paths.PortableFilePath import org.junit.Assert import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import java.time.ZonedDateTime import kotlin.streams.toList /** * Tests for [IndexDiagnosticDumper]. */ class IndexDiagnosticTest : JavaCodeInsightFixtureTestCase() { private var previousLogDir: Path? = null override fun setUp() { previousLogDir = System.getProperty(PathManager.PROPERTY_LOG_PATH)?.let { Paths.get(it) } val tempLogDir = createTempDir().toPath() System.setProperty(PathManager.PROPERTY_LOG_PATH, tempLogDir.toAbsolutePath().toString()) IndexDiagnosticDumper.shouldDumpInUnitTestMode = true super.setUp() } override fun tearDown() { super.tearDown() IndexDiagnosticDumper.shouldDumpInUnitTestMode = false if (previousLogDir == null) { System.clearProperty(PathManager.PROPERTY_LOG_PATH) } else { System.setProperty(PathManager.PROPERTY_LOG_PATH, previousLogDir!!.toAbsolutePath().toString()) } } @TestFor(issues = ["IDEA-252012"]) fun `test index diagnostics are laid out per project`() { myFixture.addFileToProject("A.java", "class A { void m() { } }") val indexingDiagnosticDir = IndexDiagnosticDumper.indexingDiagnosticDir val allDirs = Files.list(indexingDiagnosticDir).use { it.toList() } val projectDir = myFixture.project.getProjectCachePath(IndexDiagnosticDumper.indexingDiagnosticDir) assertEquals(listOf(projectDir), allDirs) /* for (dir in allDirs) { val files = Files.list(dir).use { it.toList() } val jsonFiles = files.filter { it.extension == "json" } val htmlFiles = files.filter { it.extension == "html" } assertTrue(files.isNotEmpty()) assertEquals(files.joinToString { it.toString() }, files.size, jsonFiles.size + htmlFiles.size) assertEquals(files.joinToString { it.toString() }, jsonFiles.map { it.nameWithoutExtension }.toSet(), htmlFiles.map { it.nameWithoutExtension }.toSet()) } */ } fun `test index diagnostics json can be deserialized`() { val indexDiagnostic = JsonIndexDiagnostic( JsonIndexDiagnosticAppInfo.create(), JsonRuntimeInfo.create(), JsonProjectIndexingHistory( projectName = "projectName", times = JsonProjectIndexingHistoryTimes( JsonDuration(123), JsonDuration(456), JsonDuration(789), JsonDuration(234), JsonDuration(345), JsonDateTime(ZonedDateTime.now()), JsonDateTime(ZonedDateTime.now()), JsonDuration(333), false ), totalStatsPerFileType = listOf( JsonProjectIndexingHistory.JsonStatsPerFileType( "java", JsonPercentages(30, 100), JsonPercentages(40, 100), 22, JsonFileSize(333), JsonProcessingSpeed(444, 555), listOf( JsonProjectIndexingHistory.JsonStatsPerFileType.JsonBiggestFileTypeContributor( "providerName", 444, JsonFileSize(555), JsonPercentages(8, 10) ) ) ) ), totalStatsPerIndexer = listOf( JsonProjectIndexingHistory.JsonStatsPerIndexer( "IdIndex", JsonPercentages(5, 10), 444, 555, JsonFileSize(123), JsonProcessingSpeed(111, 222), JsonProjectIndexingHistory.JsonStatsPerIndexer.JsonSnapshotInputMappingStats(33, 44, 55) ) ), scanningStatistics = listOf( JsonScanningStatistics( "providerName", 333, 11, 55, 33, JsonDuration(123), JsonDuration(456), JsonDuration(789), JsonDuration(222), scannedFiles = listOf( JsonScanningStatistics.JsonScannedFile( path = PortableFilePath.RelativePath (PortableFilePath.ProjectRoot, "src/a.java"), isUpToDate = true, wasFullyIndexedByInfrastructureExtension = false ) ) ) ), fileProviderStatistics = listOf( JsonFileProviderIndexStatistics( "providerName", 444, 33, JsonDuration(123), 1, listOf( JsonFileProviderIndexStatistics.JsonIndexedFile( path = PortableFilePath.RelativePath(PortableFilePath.ProjectRoot, "src/a.java"), wasFullyIndexedByExtensions = true ) ) ) ) ) ) val mapper = jacksonObjectMapper().registerKotlinModule() println(mapper.writeValueAsString(indexDiagnostic)) val deserialized = mapper.readValue<JsonIndexDiagnostic>(mapper.writeValueAsString(indexDiagnostic)) Assert.assertEquals(indexDiagnostic, deserialized) } }
apache-2.0
9531f68eba59b306b9e0e7c498995723
35.312102
158
0.654912
5.080214
false
true
false
false
zdary/intellij-community
platform/platform-impl/src/com/intellij/ide/actions/HideSideWindowsAction.kt
4
1655
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.actions import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAware import com.intellij.openapi.wm.ToolWindowManager import com.intellij.openapi.wm.ex.ToolWindowManagerEx import com.intellij.openapi.wm.impl.ToolWindowEventSource import com.intellij.openapi.wm.impl.ToolWindowManagerImpl internal class HideSideWindowsAction : AnAction(), DumbAware { override fun actionPerformed(e: AnActionEvent) { val project = e.project ?: return val toolWindowManager = ToolWindowManagerEx.getInstanceEx(project) as ToolWindowManagerImpl val id = toolWindowManager.activeToolWindowId ?: toolWindowManager.lastActiveToolWindowId ?: return if (HideToolWindowAction.shouldBeHiddenByShortCut(toolWindowManager, id)) { toolWindowManager.hideToolWindow(id, true, true, ToolWindowEventSource.HideSideWindowsAction) } } override fun update(event: AnActionEvent) { val presentation = event.presentation val project = event.project if (project == null) { presentation.isEnabled = false return } val toolWindowManager = ToolWindowManager.getInstance(project) var id = toolWindowManager.activeToolWindowId if (id != null) { presentation.isEnabled = true return } id = toolWindowManager.lastActiveToolWindowId presentation.isEnabled = id != null && HideToolWindowAction.shouldBeHiddenByShortCut(toolWindowManager, id) } }
apache-2.0
3482fc40eb1d5e2c816b3f146f6b7f2a
40.4
140
0.779456
4.89645
false
false
false
false
aconsuegra/algorithms-playground
src/main/kotlin/me/consuegra/algorithms/KUrlify.kt
1
730
package me.consuegra.algorithms /** * Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient * space at the end to hold the additional characters, and that you are given the "true" length of the string. */ class KUrlify { fun replaceSpaces(input: CharArray, length: Int): CharArray { val output = CharArray(input.size) var i = input.size - 1 for (j in length - 1 downTo 0) { if (input[j] != ' ') { output[i] = input[j] i-- } else { output[i--] = '0' output[i--] = '2' output[i--] = '%' } } return output } }
mit
5788cfeaae98b301c0b67bf48e8c2afc
28.2
110
0.516438
4.078212
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/stdlib/collections/GroupingTest/foldWithComputedInitialValue.kt
2
1153
import kotlin.test.* data class Collector<out K, V>(val key: K, val values: MutableList<V> = mutableListOf<V>()) fun box() { fun <K> Collector<K, String>.accumulateIfEven(e: String) = apply { if (e.length % 2 == 0) values.add(e) } fun <K, V> Collector<K, V>.toPair() = key to values as List<V> val elements = listOf("foo", "bar", "flea", "zoo", "biscuit") val result = elements.groupingBy { it.first() } .fold({ k, e -> Collector<Char, String>(k) }, { k, acc, e -> acc.accumulateIfEven(e) }) val ordered = result.values.sortedBy { it.key }.map { it.toPair() } assertEquals(listOf('b' to emptyList(), 'f' to listOf("flea"), 'z' to emptyList()), ordered) val moreElements = listOf("fire", "zero") val result2 = moreElements.groupingBy { it.first() } .foldTo(HashMap(result), { k, e -> error("should not be called for $k") }, { k, acc, e -> acc.accumulateIfEven(e) }) val ordered2 = result2.values.sortedBy { it.key }.map { it.toPair() } assertEquals(listOf('b' to emptyList(), 'f' to listOf("flea", "fire"), 'z' to listOf("zero")), ordered2) }
apache-2.0
21db01e77f96848d9fc28ddd48c8f609
45.12
109
0.5915
3.313218
false
false
false
false
muhrifqii/Maos
app/src/main/java/io/github/muhrifqii/maos/libs/ActivityViewModel.kt
1
3169
/* * Copyright 2017 Muhammad Rifqi Fatchurrahman Putra Danar * * 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.github.muhrifqii.maos.libs import android.content.Intent import android.os.Bundle import android.support.annotation.CallSuper import com.trello.rxlifecycle2.android.ActivityEvent import io.github.muhrifqii.maos.ui.data.MaosActivityResult import io.reactivex.Observable import io.reactivex.disposables.CompositeDisposable import io.reactivex.subjects.PublishSubject import timber.log.Timber /** * Created on : 23/01/17 * Author : muhrifqii * Name : Muhammad Rifqi Fatchurrahman Putra Danar * Github : https://github.com/muhrifqii * LinkedIn : https://linkedin.com/in/muhrifqii */ open class ActivityViewModel<TheView>(params: ViewModelParams) // enables reflection on subclass where TheView : LifecycleActivityType { private val viewChange: PublishSubject<LifecycleActivityType> = PublishSubject.create() private val view: Observable<TheView> = viewChange.filter { it !is EmptyLifecycleActivityType }.map { it as TheView } private val activityResult: PublishSubject<MaosActivityResult> = PublishSubject.create() private val intent: PublishSubject<Intent> = PublishSubject.create() protected val disposables: CompositeDisposable = CompositeDisposable() fun setActivityResult(activityResult: MaosActivityResult) = this.activityResult.onNext(activityResult) fun setIntent(intent: Intent) = this.intent.onNext(intent) protected fun getActivityResult() = activityResult.hide() protected fun getIntent() = intent.hide() /** * lifecycle start, but viewmodel should not be started yet */ @CallSuper open fun onCreate(savedInstanceState: Bundle?) { Timber.d("onCreate %s", this.toString()) val x = EmptyLifecycleActivityType() viewChange.onNext(x) } /** * begin to change the view */ @CallSuper open fun <TheView : LifecycleActivityType> onTakeView(view: TheView) { Timber.d("onTakeView %s in %s", this.toString(), view.toString()) viewChange.onNext(view) } /** * stop the view with an empty type of view */ @CallSuper open fun onDropView() { Timber.d("onDropView %s", this.toString()) val x = EmptyLifecycleActivityType() viewChange.onNext(x) } @CallSuper open fun onDestroy() { Timber.d("onDestroy %s", this.toString()) disposables.clear() viewChange.onComplete() } /** * All observables in a view model must compose `bindToLifecycle()` before calling * `subscribe`. */ fun <T> bindToLifecycle() = ViewModelLifecycleTransformer<T>(view) }
apache-2.0
451832a9ccf48bfc1dd0732991b67be8
33.075269
96
0.728305
4.294038
false
false
false
false
android/storage-samples
ScopedStorage/app/src/main/java/com/samples/storage/scopedstorage/common/FileUtils.kt
1
1635
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.samples.storage.scopedstorage.common import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.io.InputStream import java.security.MessageDigest /** * Number of bytes to read at a time from an open stream */ private const val FILE_BUFFER_SIZE_BYTES = 1024 object FileUtils { suspend fun getInputStreamChecksum(inputStream: InputStream): String { return withContext(Dispatchers.IO) { inputStream.use { stream -> val messageDigest = MessageDigest.getInstance("SHA-256") val buffer = ByteArray(FILE_BUFFER_SIZE_BYTES) var bytesRead = stream.read(buffer) while (bytesRead > 0) { messageDigest.update(buffer, 0, bytesRead) bytesRead = stream.read(buffer) } val hashResult = messageDigest.digest() return@withContext hashResult.joinToString("") { "%02x".format(it) } } } } }
apache-2.0
3b7e2f7334654b132e6b88211806ea09
33.808511
84
0.669725
4.65812
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/jvm-debugger/coroutines/src/org/jetbrains/kotlin/idea/debugger/coroutine/proxy/CoroutineNoLibraryProxy.kt
5
4316
// 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.coroutine.proxy import com.intellij.openapi.util.registry.Registry import com.sun.jdi.Field import com.sun.jdi.ObjectReference import org.jetbrains.kotlin.idea.debugger.coroutine.data.CompleteCoroutineInfoData import org.jetbrains.kotlin.idea.debugger.coroutine.proxy.mirror.CancellableContinuationImpl import org.jetbrains.kotlin.idea.debugger.coroutine.util.findCancellableContinuationImplReferenceType import org.jetbrains.kotlin.idea.debugger.coroutine.util.findCoroutineMetadataType import org.jetbrains.kotlin.idea.debugger.coroutine.util.findDispatchedContinuationReferenceType import org.jetbrains.kotlin.idea.debugger.coroutine.util.logger import org.jetbrains.kotlin.idea.debugger.evaluate.DefaultExecutionContext class CoroutineNoLibraryProxy(private val executionContext: DefaultExecutionContext) : CoroutineInfoProvider { companion object { private val log by logger } private val debugMetadataKtType = executionContext.findCoroutineMetadataType() private val holder = ContinuationHolder.instance(executionContext) override fun dumpCoroutinesInfo(): List<CompleteCoroutineInfoData> { val vm = executionContext.vm val resultList = mutableListOf<CompleteCoroutineInfoData>() if (vm.virtualMachine.canGetInstanceInfo()) { when (coroutineSwitch()) { "DISPATCHED_CONTINUATION" -> dispatchedContinuation(resultList) "CANCELLABLE_CONTINUATION" -> cancellableContinuation(resultList) else -> dispatchedContinuation(resultList) } } else log.warn("Remote JVM doesn't support canGetInstanceInfo capability (perhaps JDK-8197943).") return resultList } private fun cancellableContinuation(resultList: MutableList<CompleteCoroutineInfoData>): Boolean { val dcClassTypeList = executionContext.findCancellableContinuationImplReferenceType() if (dcClassTypeList?.size == 1) { val dcClassType = dcClassTypeList.first() val cci = CancellableContinuationImpl(executionContext) val continuationList = dcClassType.instances(maxCoroutines()) for (cancellableContinuation in continuationList) { val coroutineInfo = extractCancellableContinuation(cancellableContinuation, cci) ?: continue resultList.add(coroutineInfo) } } return false } private fun extractCancellableContinuation( dispatchedContinuation: ObjectReference, ccMirrorProvider: CancellableContinuationImpl ): CompleteCoroutineInfoData? { val mirror = ccMirrorProvider.mirror(dispatchedContinuation, executionContext) ?: return null val continuation = mirror.delegate?.continuation ?: return null return holder.extractCoroutineInfoData(continuation) } private fun dispatchedContinuation(resultList: MutableList<CompleteCoroutineInfoData>): Boolean { val dcClassTypeList = executionContext.findDispatchedContinuationReferenceType() if (dcClassTypeList?.size == 1) { val dcClassType = dcClassTypeList.first() val continuationField = dcClassType.fieldByName("continuation") ?: return true val continuationList = dcClassType.instances(maxCoroutines()) for (dispatchedContinuation in continuationList) { val coroutineInfo = extractDispatchedContinuation(dispatchedContinuation, continuationField) ?: continue resultList.add(coroutineInfo) } } return false } private fun extractDispatchedContinuation(dispatchedContinuation: ObjectReference, continuation: Field): CompleteCoroutineInfoData? { debugMetadataKtType ?: return null val initialContinuation = dispatchedContinuation.getValue(continuation) as ObjectReference return holder.extractCoroutineInfoData(initialContinuation) } } fun maxCoroutines() = Registry.intValue("kotlin.debugger.coroutines.max", 1000).toLong() fun coroutineSwitch() = Registry.stringValue("kotlin.debugger.coroutines.switch")
apache-2.0
dac6380eafed00c8c2337f307606432a
49.776471
158
0.745366
5.519182
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeVariableMutabilityFix.kt
1
6976
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.DiagnosticFactory1 import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.quickfix.createFromUsage.createCallable.CreatePropertyDelegateAccessorsActionFactory import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils import org.jetbrains.kotlin.util.OperatorNameConventions class ChangeVariableMutabilityFix( element: KtValVarKeywordOwner, private val makeVar: Boolean, @Nls private val actionText: String? = null, private val deleteInitializer: Boolean = false ) : KotlinQuickFixAction<KtValVarKeywordOwner>(element) { override fun getText() = actionText ?: ((if (makeVar) KotlinBundle.message("change.to.var") else KotlinBundle.message("change.to.val")) + if (deleteInitializer) KotlinBundle.message("and.delete.initializer") else "") override fun getFamilyName(): String = text override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean { val element = element ?: return false val valOrVar = element.valOrVarKeyword?.node?.elementType ?: return false return (valOrVar == KtTokens.VAR_KEYWORD) != makeVar } override fun invoke(project: Project, editor: Editor?, file: KtFile) { val element = element ?: return val factory = KtPsiFactory(project) val newKeyword = if (makeVar) factory.createVarKeyword() else factory.createValKeyword() element.valOrVarKeyword!!.replace(newKeyword) if (deleteInitializer) { (element as? KtProperty)?.initializer = null } if (makeVar) { (element as? KtModifierListOwner)?.removeModifier(KtTokens.CONST_KEYWORD) } } companion object { val VAL_WITH_SETTER_FACTORY: KotlinSingleIntentionActionFactory = object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction { val accessor = diagnostic.psiElement as KtPropertyAccessor return ChangeVariableMutabilityFix(accessor.property, true) } } class ReassignmentActionFactory(val factory: DiagnosticFactory1<*, DeclarationDescriptor>) : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val propertyDescriptor = factory.cast(diagnostic).a val declaration = DescriptorToSourceUtils.descriptorToDeclaration(propertyDescriptor) as? KtValVarKeywordOwner ?: return null return ChangeVariableMutabilityFix(declaration, true) } } val VAL_REASSIGNMENT_FACTORY = ReassignmentActionFactory(Errors.VAL_REASSIGNMENT) val CAPTURED_VAL_INITIALIZATION_FACTORY = ReassignmentActionFactory(Errors.CAPTURED_VAL_INITIALIZATION) val CAPTURED_MEMBER_VAL_INITIALIZATION_FACTORY = ReassignmentActionFactory(Errors.CAPTURED_MEMBER_VAL_INITIALIZATION) val VAR_OVERRIDDEN_BY_VAL_FACTORY: KotlinSingleIntentionActionFactory = object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val element = diagnostic.psiElement return when (element) { is KtProperty, is KtParameter -> ChangeVariableMutabilityFix(element as KtValVarKeywordOwner, true) else -> null } } } val VAR_ANNOTATION_PARAMETER_FACTORY: KotlinSingleIntentionActionFactory = object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction { val element = diagnostic.psiElement as KtParameter return ChangeVariableMutabilityFix(element, false) } } val LATEINIT_VAL_FACTORY = object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val lateinitElement = Errors.INAPPLICABLE_LATEINIT_MODIFIER.cast(diagnostic).psiElement val property = lateinitElement.getStrictParentOfType<KtProperty>() ?: return null if (property.valOrVarKeyword.text != "val") return null return ChangeVariableMutabilityFix(property, makeVar = true) } } val CONST_VAL_FACTORY = object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val (modifier, element) = Errors.WRONG_MODIFIER_TARGET.cast(diagnostic).run { a to psiElement } if (modifier != KtTokens.CONST_KEYWORD) return null val property = element.getStrictParentOfType<KtProperty>() ?: return null return ChangeVariableMutabilityFix(property, makeVar = false) } } val DELEGATED_PROPERTY_VAL_FACTORY = object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val element = Errors.DELEGATE_SPECIAL_FUNCTION_MISSING.cast(diagnostic).psiElement val property = element.getStrictParentOfType<KtProperty>() ?: return null val info = CreatePropertyDelegateAccessorsActionFactory.extractFixData(property, diagnostic).singleOrNull() ?: return null if (info.name != OperatorNameConventions.SET_VALUE.asString()) return null return ChangeVariableMutabilityFix(property, makeVar = false, actionText = KotlinBundle.message("change.to.val")) } } val MUST_BE_INITIALIZED_FACTORY = object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val property = Errors.MUST_BE_INITIALIZED.cast(diagnostic).psiElement as? KtProperty ?: return null val getter = property.getter ?: return null if (!getter.hasBody()) return null if (getter.hasBlockBody() && property.typeReference == null) return null return ChangeVariableMutabilityFix(property, makeVar = false) } } } }
apache-2.0
3967f686685adcfe4716787be59d9370
52.251908
158
0.696818
5.549722
false
false
false
false
kickstarter/android-oss
app/src/main/java/com/kickstarter/models/ErroredBacking.kt
1
2509
package com.kickstarter.models import android.os.Parcelable import kotlinx.parcelize.Parcelize import org.joda.time.DateTime @Parcelize class ErroredBacking private constructor( private val project: Project ) : Parcelable { fun project() = this.project @Parcelize data class Builder( private var project: Project = Project.builder().build() ) : Parcelable { fun project(project: Project) = apply { this.project = project } fun build() = ErroredBacking( project = project ) } fun toBuilder() = Builder( project = project ) override fun equals(other: Any?): Boolean { var equals = super.equals(other) if (other is ErroredBacking) { equals = project() == other.project() } return equals } companion object { fun builder(): Builder = Builder() } @Parcelize class Project private constructor( private val finalCollectionDate: DateTime, private val name: String, private val slug: String, ) : Parcelable { fun finalCollectionDate() = this.finalCollectionDate fun name() = this.name fun slug() = this.slug @Parcelize data class Builder( private var finalCollectionDate: DateTime = DateTime.now(), private var name: String = "", private var slug: String = "" ) : Parcelable { fun finalCollectionDate(finalCollectionDate: DateTime?) = apply { this.finalCollectionDate = finalCollectionDate ?: DateTime.now() } fun name(name: String?) = apply { this.name = name ?: "" } fun slug(slug: String?) = apply { this.slug = slug ?: "" } fun build() = Project( finalCollectionDate = finalCollectionDate, name = name, slug = slug ) } fun toBuilder() = Builder( finalCollectionDate = finalCollectionDate, name = name, slug = slug ) override fun equals(other: Any?): Boolean { var equals = super.equals(other) if (other is Project) { equals = finalCollectionDate() == other.finalCollectionDate() && name() == other.name() && slug() == other.slug() } return equals } companion object { fun builder(): Builder = Builder() } } }
apache-2.0
e4fd92869bec6844afa2f9de5ac654d2
27.83908
144
0.557593
4.881323
false
false
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/inventory/items/ItemRecyclerFragment.kt
1
10916
package com.habitrpg.android.habitica.ui.fragments.inventory.items import android.graphics.drawable.BitmapDrawable import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.Window import android.widget.Button import android.widget.TextView import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.components.UserComponent import com.habitrpg.android.habitica.data.InventoryRepository import com.habitrpg.android.habitica.data.UserRepository import com.habitrpg.android.habitica.extensions.subscribeWithErrorHandler import com.habitrpg.android.habitica.helpers.MainNavigationController import com.habitrpg.android.habitica.helpers.RxErrorHandler import com.habitrpg.android.habitica.models.inventory.* import com.habitrpg.android.habitica.models.user.OwnedPet import com.habitrpg.android.habitica.models.user.User import com.habitrpg.android.habitica.ui.activities.MainActivity import com.habitrpg.android.habitica.ui.adapter.inventory.ItemRecyclerAdapter import com.habitrpg.android.habitica.ui.fragments.BaseFragment import com.habitrpg.android.habitica.ui.helpers.* import com.habitrpg.android.habitica.ui.views.HabiticaSnackbar import com.habitrpg.android.habitica.ui.views.HabiticaSnackbar.Companion.showSnackbar import io.reactivex.functions.Consumer import javax.inject.Inject class ItemRecyclerFragment : BaseFragment() { @Inject lateinit var inventoryRepository: InventoryRepository @Inject lateinit var userRepository: UserRepository val recyclerView: RecyclerViewEmptySupport? by bindView(R.id.recyclerView) val emptyView: View? by bindView(R.id.emptyView) private val emptyTextView: TextView? by bindView(R.id.empty_text_view) val titleView: TextView? by bindView(R.id.titleTextView) private val footerView: TextView? by bindView(R.id.footerTextView) private val openMarketButton: Button? by bindView(R.id.openMarketButton) private val openEmptyMarketButton: Button? by bindView(R.id.openEmptyMarketButton) var adapter: ItemRecyclerAdapter? = null var itemType: String? = null var itemTypeText: String? = null var isHatching: Boolean = false var isFeeding: Boolean = false private var hatchingItem: Item? = null var feedingPet: Pet? = null var user: User? = null internal var layoutManager: androidx.recyclerview.widget.LinearLayoutManager? = null override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { super.onCreateView(inflater, container, savedInstanceState) return inflater.inflate(R.layout.fragment_items, container, false) } override fun onDestroy() { inventoryRepository.close() super.onDestroy() } override fun injectFragment(component: UserComponent) { component.inject(this) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) resetViews() recyclerView?.setEmptyView(emptyView) emptyTextView?.text = getString(R.string.empty_items, itemTypeText) val context = activity layoutManager = androidx.recyclerview.widget.LinearLayoutManager(context) recyclerView?.layoutManager = layoutManager adapter = recyclerView?.adapter as? ItemRecyclerAdapter if (adapter == null) { context?.let { adapter = ItemRecyclerAdapter(null, true, context) adapter?.isHatching = this.isHatching adapter?.isFeeding = this.isFeeding adapter?.fragment = this } if (this.hatchingItem != null) { adapter?.hatchingItem = this.hatchingItem } if (this.feedingPet != null) { adapter?.feedingPet = this.feedingPet } recyclerView?.adapter = adapter adapter?.let { adapter -> compositeSubscription.add(adapter.getSellItemFlowable() .flatMap { item -> inventoryRepository.sellItem(user, item) } .subscribe(Consumer { }, RxErrorHandler.handleEmptyError())) compositeSubscription.add(adapter.getQuestInvitationFlowable() .flatMap { quest -> inventoryRepository.inviteToQuest(quest) } .subscribe(Consumer { MainNavigationController.navigate(R.id.partyFragment) }, RxErrorHandler.handleEmptyError())) compositeSubscription.add(adapter.getOpenMysteryItemFlowable() .flatMap { inventoryRepository.openMysteryItem(user) } .doOnNext { val activity = activity as? MainActivity if (activity != null) { DataBindingUtils.loadImage("shop_${it.key}") {image -> showSnackbar(activity.snackbarContainer, BitmapDrawable(context?.resources, image), null, getString(R.string.mystery_item_received, it.text), HabiticaSnackbar.SnackbarDisplayType.NORMAL) } } } .flatMap { userRepository.retrieveUser(false) } .subscribe(Consumer { }, RxErrorHandler.handleEmptyError())) compositeSubscription.add(adapter.startHatchingEvents.subscribeWithErrorHandler(Consumer { showHatchingDialog(it) })) compositeSubscription.add(adapter.hatchPetEvents.subscribeWithErrorHandler(Consumer { hatchPet(it.first, it.second) })) } } activity?.let { recyclerView?.addItemDecoration(androidx.recyclerview.widget.DividerItemDecoration(it, androidx.recyclerview.widget.DividerItemDecoration.VERTICAL)) } recyclerView?.itemAnimator = SafeDefaultItemAnimator() if (savedInstanceState != null) { this.itemType = savedInstanceState.getString(ITEM_TYPE_KEY, "") } when { this.isHatching -> { dialog?.requestWindowFeature(Window.FEATURE_NO_TITLE) this.titleView?.text = getString(R.string.hatch_with, this.hatchingItem?.text) this.titleView?.visibility = View.VISIBLE this.footerView?.text = getString(R.string.hatching_market_info) this.footerView?.visibility = View.VISIBLE this.openMarketButton?.visibility = View.VISIBLE } this.isFeeding -> { dialog?.requestWindowFeature(Window.FEATURE_NO_TITLE) this.titleView?.text = getString(R.string.dialog_feeding, this.feedingPet?.text) this.titleView?.visibility = View.VISIBLE this.footerView?.text = getString(R.string.feeding_market_info) this.footerView?.visibility = View.VISIBLE this.openMarketButton?.visibility = View.VISIBLE } else -> { this.titleView?.visibility = View.GONE this.footerView?.visibility = View.GONE this.openMarketButton?.visibility = View.GONE } } openMarketButton?.setOnClickListener { dismiss() openMarket() } openEmptyMarketButton?.setOnClickListener { openMarket() } this.loadItems() } private fun showHatchingDialog(item: Item) { val fragment = ItemRecyclerFragment() if (item is Egg) { fragment.itemType = "hatchingPotions" fragment.hatchingItem = item } else { fragment.itemType = "eggs" fragment.hatchingItem = item } fragment.isHatching = true fragment.isFeeding = false fragmentManager?.let { fragment.show(it, "hatchingDialog") } } override fun onResume() { if ((this.isHatching || this.isFeeding) && dialog?.window != null) { val params = dialog?.window?.attributes params?.width = ViewGroup.LayoutParams.MATCH_PARENT params?.verticalMargin = 60f dialog?.window?.attributes = params } super.onResume() } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putString(ITEM_TYPE_KEY, this.itemType) } private fun hatchPet(potion: HatchingPotion, egg: Egg) { dismiss() (activity as? MainActivity)?.hatchPet(potion, egg) } private fun loadItems() { val itemClass: Class<out Item> = when (itemType) { "eggs" -> Egg::class.java "hatchingPotions" -> HatchingPotion::class.java "food" -> Food::class.java "quests" -> QuestContent::class.java "special" -> SpecialItem::class.java else -> Egg::class.java } itemType?.let { type -> compositeSubscription.add(inventoryRepository.getOwnedItems(type) .doOnNext { items -> if (items.size > 0) { adapter?.updateData(items) } } .map { items -> items.mapNotNull { it.key } } .flatMap { inventoryRepository.getItems(itemClass, it.toTypedArray(), user) } .map { val itemMap = mutableMapOf<String, Item>() for (item in it) { itemMap[item.key] = item } itemMap } .subscribe(Consumer { items -> adapter?.items = items }, RxErrorHandler.handleEmptyError())) } compositeSubscription.add(inventoryRepository.getPets().subscribe(Consumer { adapter?.setExistingPets(it) }, RxErrorHandler.handleEmptyError())) compositeSubscription.add(inventoryRepository.getOwnedPets().firstElement() .map { ownedMounts -> val mountMap = mutableMapOf<String, OwnedPet>() ownedMounts.forEach { mountMap[it.key ?: ""] = it } return@map mountMap } .subscribe(Consumer { adapter?.setOwnedPets(it) }, RxErrorHandler.handleEmptyError())) } private fun openMarket() { MainNavigationController.navigate(R.id.shopsFragment) } companion object { private const val ITEM_TYPE_KEY = "CLASS_TYPE_KEY" } }
gpl-3.0
c6f6c94b9d601cfd033373466c542837
42.194332
222
0.615793
5.330078
false
false
false
false
jotomo/AndroidAPS
omnipod/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/ui/wizard/deactivation/fragment/DeactivatePodActionFragment.kt
1
2931
package info.nightscout.androidaps.plugins.pump.omnipod.ui.wizard.deactivation.fragment import android.os.Bundle import android.view.View import androidx.annotation.IdRes import androidx.annotation.StringRes import androidx.appcompat.app.AlertDialog import androidx.fragment.app.viewModels import androidx.lifecycle.ViewModelProvider import androidx.navigation.fragment.findNavController import info.nightscout.androidaps.plugins.pump.omnipod.R import info.nightscout.androidaps.plugins.pump.omnipod.dagger.OmnipodPluginQualifier import info.nightscout.androidaps.plugins.pump.omnipod.manager.AapsOmnipodManager import info.nightscout.androidaps.plugins.pump.omnipod.ui.wizard.common.fragment.ActionFragmentBase import info.nightscout.androidaps.plugins.pump.omnipod.ui.wizard.deactivation.viewmodel.DeactivatePodActionViewModel import info.nightscout.androidaps.utils.extensions.toVisibility import kotlinx.android.synthetic.main.omnipod_wizard_action_page_fragment.* import javax.inject.Inject class DeactivatePodActionFragment : ActionFragmentBase() { @Inject @OmnipodPluginQualifier lateinit var viewModelFactory: ViewModelProvider.Factory @Inject lateinit var aapsOmnipodManager: AapsOmnipodManager override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val vm: DeactivatePodActionViewModel by viewModels { viewModelFactory } this.viewModel = vm } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) omnipod_wizard_button_discard_pod.setOnClickListener { context?.let { AlertDialog.Builder(it) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle(getString(R.string.omnipod_pod_deactivation_wizard_discard_pod)) .setMessage(getString(R.string.omnipod_pod_deactivation_wizard_discard_pod_confirmation)) .setPositiveButton(getString(R.string.omnipod_yes)) { _, _ -> aapsOmnipodManager.discardPodState() findNavController().navigate(R.id.action_deactivatePodActionFragment_to_podDiscardedInfoFragment) } .setNegativeButton(getString(R.string.omnipod_no), null) .show() } } } override fun onActionFailure() { omnipod_wizard_button_discard_pod.visibility = (!isActionExecuting()).toVisibility() } @StringRes override fun getTitleId(): Int = R.string.omnipod_pod_deactivation_wizard_deactivating_pod_title @StringRes override fun getTextId(): Int = R.string.omnipod_pod_deactivation_wizard_deactivating_pod_text @IdRes override fun getNextPageActionId(): Int = R.id.action_deactivatePodActionFragment_to_podDeactivatedInfoFragment override fun getIndex(): Int = 2 }
agpl-3.0
385c2093cf696ef9b6784be8917bbb17
42.117647
121
0.737632
4.659777
false
false
false
false
tensorflow/examples
lite/examples/pose_estimation/android/app/src/main/java/org/tensorflow/lite/examples/poseestimation/data/TorsoAndBodyDistance.kt
1
897
/* Copyright 2021 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.poseestimation.data data class TorsoAndBodyDistance( val maxTorsoYDistance: Float, val maxTorsoXDistance: Float, val maxBodyYDistance: Float, val maxBodyXDistance: Float )
apache-2.0
690a2e89b8b2cd9ddfbca3ec43c034b7
36.375
78
0.716834
4.485
false
false
false
false
leafclick/intellij-community
python/tools/src/com/jetbrains/python/tools/PyTypeShedBuiltinsSplitter.kt
1
5679
// 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.tools import com.intellij.util.io.copy import com.intellij.util.io.delete import com.jetbrains.python.psi.PyIndentUtil import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths /** * `typeshed` has one file for Python 2 and Python 3 builtins where differences are guarded with `if sys.version_info` checks. * PyCharm does not support such checks at the moment so we have to split this file and * put builtins into the corresponding `typeshed` directories. */ fun splitBuiltins(typeshed: Path) { val typeshedStdlib: Path = typeshed.resolve("stdlib").abs().normalize() val originalBuiltins: Path = typeshedStdlib.resolve(Paths.get("2and3/builtins.pyi")) extractPython2Builtins(typeshedStdlib, originalBuiltins) extractPython3Builtins(typeshedStdlib, originalBuiltins) originalBuiltins.delete() println("Removed: ${originalBuiltins.abs()}") } private fun extractPython2Builtins(typeshedStdlib: Path, originalBuiltins: Path) { val python2Builtins = typeshedStdlib.resolve(Paths.get("2/__builtin__.pyi")) extractBuiltins(originalBuiltins, python2Builtins, true) println("Created: ${python2Builtins.abs()}") val python2BuiltinsMirror = typeshedStdlib.resolve(Paths.get("2/builtins.pyi")) python2Builtins.copy(python2BuiltinsMirror) println("Copied: ${python2Builtins.abs()} to ${python2BuiltinsMirror.abs()}") } private fun extractPython3Builtins(typeshedStdlib: Path, originalBuiltins: Path) { val python3Builtins = typeshedStdlib.resolve(Paths.get("3/builtins.pyi")) extractBuiltins(originalBuiltins, python3Builtins, false) println("Created: ${python3Builtins.abs()}") } private fun extractBuiltins(originalBuiltins: Path, targetBuiltins: Path, py2: Boolean) { Files.newBufferedWriter(targetBuiltins).use { writer -> var state: ReadingState = DefaultReading(py2) Files .lines(originalBuiltins) .forEach { val (updatedLine, updatedState) = state.processLine(it) updatedLine?.let { writer.write(it) writer.newLine() } state = updatedState } } } private interface ReadingState { fun processLine(line: String): Pair<String?, ReadingState> } private class DefaultReading(private val py2: Boolean) : ReadingState { override fun processLine(line: String): Pair<String?, ReadingState> = processLine(line, this) fun processLine(line: String, currentState: ReadingState): Pair<String?, ReadingState> { val indent = PyIndentUtil.getLineIndentSize(line) return when { disabledBlockStarted(line, indent, py2) -> null to ReadingConditionallyDisabledBlock(indent, py2) enabledBlockStarted(line, indent, py2) -> null to ReadingConditionallyEnabledBlock(indent, py2) line.startsWith("else:", indent) -> when (currentState) { is ReadingConditionallyEnabledBlock -> null to ReadingConditionallyDisabledBlock(indent, py2) is ReadingConditionallyDisabledBlock -> null to ReadingConditionallyEnabledBlock(indent, py2) else -> line to currentState } else -> line to this } } private fun disabledBlockStarted(line: String, indent: Int, py2: Boolean): Boolean { if (py2) { if (line.startsWith("if sys.version_info > (3,", indent)) return true if (line.startsWith("if sys.version_info >= (3,", indent)) return true if (line.startsWith("elif sys.version_info > (3,", indent)) return true if (line.startsWith("elif sys.version_info >= (3,", indent)) return true } else { if (line.startsWith("if sys.version_info < (3,)", indent)) return true if (line.startsWith("if sys.version_info <= (3,)", indent)) return true if (line.startsWith("elif sys.version_info < (3,)", indent)) return true if (line.startsWith("elif sys.version_info <= (3,)", indent)) return true } return false } private fun enabledBlockStarted(line: String, indent: Int, py2: Boolean): Boolean { if (py2) { if (line.startsWith("if sys.version_info < (3,)", indent)) return true if (line.startsWith("elif sys.version_info < (3,)", indent)) return true } else { if (line.startsWith("if sys.version_info > (3,)", indent)) return true if (line.startsWith("if sys.version_info >= (3,)", indent)) return true if (line.startsWith("elif sys.version_info > (3,)", indent)) return true if (line.startsWith("elif sys.version_info >= (3,)", indent)) return true } return false } } private class ReadingConditionallyDisabledBlock(private val guardIndent: Int, private val py2: Boolean) : ReadingState { override fun processLine(line: String): Pair<String?, ReadingState> { return when { line.isBlank() -> line to this PyIndentUtil.getLineIndentSize(line) <= guardIndent -> DefaultReading(py2).processLine(line, this) else -> null to this } } } private class ReadingConditionallyEnabledBlock(private val guardIndent: Int, private val py2: Boolean) : ReadingState { private var indentDifference: Int = 0 override fun processLine(line: String): Pair<String?, ReadingState> { val currentIndent = PyIndentUtil.getLineIndentSize(line) return when { line.isBlank() -> line to this currentIndent <= guardIndent -> DefaultReading(py2).processLine(line, this) else -> { if (indentDifference == 0) indentDifference = currentIndent - guardIndent line.substring(indentDifference) to this } } } } private fun Path.abs() = toAbsolutePath()
apache-2.0
88d52de8e6dcb356d09a5b81c7a075e9
36.86
140
0.709104
3.999296
false
false
false
false
siosio/intellij-community
platform/statistics/src/com/intellij/internal/statistic/eventLog/StatisticsEventLogProviderUtil.kt
1
2749
// 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.internal.statistic.eventLog import com.intellij.internal.statistic.eventLog.StatisticsEventLoggerProvider.Companion.EP_NAME import com.intellij.internal.statistic.utils.PluginType import com.intellij.internal.statistic.utils.StatisticsRecorderUtil import com.intellij.internal.statistic.utils.getPluginInfo import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.text.StringUtil import com.intellij.util.PlatformUtils import com.intellij.util.containers.ContainerUtil object StatisticsEventLogProviderUtil { private val LOG = Logger.getInstance(StatisticsEventLogProviderUtil::class.java) @JvmStatic fun getEventLogProviders(): List<StatisticsEventLoggerProvider> { val providers = EP_NAME.extensionsIfPointIsRegistered if (providers.isEmpty()) { return emptyList() } val isJetBrainsProduct = isJetBrainsProduct() return ContainerUtil.filter(providers) { isProviderApplicable(isJetBrainsProduct, it.recorderId, it) }.distinctBy { it.recorderId } } @JvmStatic fun getEventLogProvider(recorderId: String): StatisticsEventLoggerProvider { if (ApplicationManager.getApplication().extensionArea.hasExtensionPoint(EP_NAME.name)) { val isJetBrainsProduct = isJetBrainsProduct() val provider = EP_NAME.findFirstSafe { isProviderApplicable(isJetBrainsProduct, recorderId, it) } provider?.let { if (LOG.isTraceEnabled) { LOG.trace("Use event log provider '${provider.javaClass.simpleName}' for recorder-id=${recorderId}") } return it } } LOG.warn("Cannot find event log provider with recorder-id=${recorderId}") return EmptyStatisticsEventLoggerProvider(recorderId) } private fun isJetBrainsProduct(): Boolean { val appInfo = ApplicationInfo.getInstance() if (appInfo == null || StringUtil.isEmpty(appInfo.shortCompanyName)) { return true } return PlatformUtils.isJetBrainsProduct() } private fun isProviderApplicable(isJetBrainsProduct: Boolean, recorderId: String, extension: StatisticsEventLoggerProvider): Boolean { if (recorderId == extension.recorderId) { if (!isJetBrainsProduct || !StatisticsRecorderUtil.isBuildInRecorder(recorderId)) { return true } val pluginInfo = getPluginInfo(extension::class.java) return pluginInfo.type == PluginType.PLATFORM || pluginInfo.type == PluginType.FROM_SOURCES || pluginInfo.isAllowedToInjectIntoFUS() } return false } }
apache-2.0
3c27225d744fbdd1d87eda1f5b829744
43.354839
140
0.767188
5.053309
false
false
false
false
siosio/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinTopLevelExtensionsByReceiverTypeIndex.kt
2
1725
// 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.stubindex class KotlinTopLevelExtensionsByReceiverTypeIndex private constructor() : KotlinExtensionsByReceiverTypeIndex() { override fun getKey() = KEY override fun getVersion(): Int = super.getVersion() + 1 companion object { private val KEY = KotlinIndexUtil.createIndexKey(KotlinTopLevelExtensionsByReceiverTypeIndex::class.java) val INSTANCE: KotlinTopLevelExtensionsByReceiverTypeIndex = KotlinTopLevelExtensionsByReceiverTypeIndex() @Deprecated( "Use instance method in 'KotlinExtensionsByReceiverTypeIndex' instead of the static one", ReplaceWith("KotlinTopLevelExtensionsByReceiverTypeIndex.INSTANCE.buildKey(receiverTypeName, callableName)") ) fun buildKey(receiverTypeName: String, callableName: String): String = INSTANCE.buildKey(receiverTypeName, callableName) @Deprecated( "Use instance method in 'KotlinExtensionsByReceiverTypeIndex' instead of the static one", ReplaceWith("KotlinTopLevelExtensionsByReceiverTypeIndex.INSTANCE.receiverTypeNameFromKey(key)") ) fun receiverTypeNameFromKey(key: String): String = INSTANCE.receiverTypeNameFromKey(key) @Deprecated( "Use instance method in 'KotlinExtensionsByReceiverTypeIndex' instead of the static one", ReplaceWith("KotlinTopLevelExtensionsByReceiverTypeIndex.INSTANCE.callableNameFromKey(key)") ) fun callableNameFromKey(key: String): String = INSTANCE.callableNameFromKey(key) } }
apache-2.0
688fb4939ef269dc165683b45840c561
51.272727
158
0.751304
5.827703
false
false
false
false
siosio/intellij-community
plugins/kotlin/core/src/org/jetbrains/kotlin/idea/core/script/ucache/SdkId.kt
1
1292
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.core.script.ucache import com.intellij.openapi.util.io.FileUtil import java.io.File /** * Safe key for locating sdk in intellij project jdk table * * null means default sdk */ class SdkId private constructor(val homeDirectory: String?) { companion object { val default = SdkId(null as String?) operator fun invoke(homeDirectory: File?): SdkId { if (homeDirectory == null) return default val canonicalPath = FileUtil.toSystemIndependentName(homeDirectory.canonicalPath) return SdkId(canonicalPath) } operator fun invoke(homeDirectory: String?): SdkId { if (homeDirectory == null) return default return invoke(File(homeDirectory)) } } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as SdkId if (homeDirectory != other.homeDirectory) return false return true } override fun hashCode(): Int { return homeDirectory?.hashCode() ?: 0 } }
apache-2.0
77bcb163ec45fe1d7e71d371e8307ccb
29.069767
158
0.660991
4.66426
false
false
false
false
BijoySingh/Quick-Note-Android
base/src/main/java/com/maubis/scarlet/base/core/note/NoteImage.kt
1
4298
package com.maubis.scarlet.base.core.note import android.content.Context import android.view.View import android.widget.ImageView import com.github.bijoysingh.starter.util.RandomHelper import com.maubis.scarlet.base.config.ApplicationBase import com.maubis.scarlet.base.core.format.Format import com.maubis.scarlet.base.core.format.FormatBuilder import com.maubis.scarlet.base.core.format.FormatType import com.maubis.scarlet.base.database.room.note.Note import com.maubis.scarlet.base.support.utils.maybeThrow import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import java.io.File interface ImageLoadCallback { fun onSuccess() fun onError() } class NoteImage(context: Context) { val rootFolder = File(context.filesDir, "images") fun renameOrCopy(note: Note, imageFile: File): File { val targetFile = getFile(note.uuid, RandomHelper.getRandom() + ".jpg") targetFile.mkdirs() deleteIfExist(targetFile) val renamed = imageFile.renameTo(targetFile) if (!renamed) { imageFile.copyTo(targetFile, true) } return targetFile } fun getFile(noteUUID: String, imageFormat: Format): File { if (imageFormat.formatType != FormatType.IMAGE) { maybeThrow("Format should be an Image") } return getFile(noteUUID, imageFormat.text) } fun getFile(noteUUID: String, formatFileName: String): File { return File(rootFolder, noteUUID + File.separator + formatFileName) } fun deleteAllFiles(note: Note) { for (format in FormatBuilder().getFormats(note.description)) { if (format.formatType === FormatType.IMAGE) { val file = getFile(note.uuid, format) deleteIfExist(file) } } } fun loadPersistentFileToImageView(image: ImageView, file: File, callback: ImageLoadCallback? = null) { GlobalScope.launch { if (!file.exists()) { GlobalScope.launch(Dispatchers.Main) { image.visibility = View.GONE callback?.onError() } return@launch } val bitmap = ApplicationBase.sAppImageCache.loadFromCache(file) if (bitmap === null) { deleteIfExist(file) GlobalScope.launch(Dispatchers.Main) { image.visibility = View.GONE callback?.onError() } return@launch } GlobalScope.launch(Dispatchers.Main) { image.visibility = View.VISIBLE image.setImageBitmap(bitmap) } } } fun loadThumbnailFileToImageView( noteUUID: String, imageUuid: String, image: ImageView, callback: ImageLoadCallback? = null) { GlobalScope.launch { val thumbnailFile = ApplicationBase.sAppImageCache.thumbnailFile(noteUUID, imageUuid) val persistentFile = ApplicationBase.sAppImageCache.persistentFile(noteUUID, imageUuid) if (!persistentFile.exists()) { GlobalScope.launch(Dispatchers.Main) { image.visibility = View.GONE callback?.onError() } return@launch } if (thumbnailFile.exists()) { val bitmap = ApplicationBase.sAppImageCache.loadFromCache(thumbnailFile) if (bitmap === null) { deleteIfExist(thumbnailFile) GlobalScope.launch(Dispatchers.Main) { image.visibility = View.GONE callback?.onError() } return@launch } GlobalScope.launch(Dispatchers.Main) { image.visibility = View.VISIBLE image.setImageBitmap(bitmap) } return@launch } val persistentBitmap = ApplicationBase.sAppImageCache.loadFromCache(persistentFile) if (persistentBitmap === null) { deleteIfExist(persistentFile) GlobalScope.launch(Dispatchers.Main) { image.visibility = View.GONE callback?.onError() } return@launch } val compressedBitmap = ApplicationBase.sAppImageCache.saveThumbnail(thumbnailFile, persistentBitmap) GlobalScope.launch(Dispatchers.Main) { image.visibility = View.VISIBLE image.setImageBitmap(compressedBitmap) } } } companion object { fun deleteIfExist(file: File): Boolean { return when { file.exists() -> file.delete() else -> false } } } }
gpl-3.0
1abd8622449f1f93e5d4c0b533e7c706
28.244898
106
0.67101
4.449275
false
false
false
false
jwren/intellij-community
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/core/AbstractNameSuggester.kt
1
7236
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.core import org.jetbrains.kotlin.lexer.KotlinLexer import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.isIdentifier import org.jetbrains.kotlin.util.capitalizeDecapitalize.capitalizeAsciiOnly import org.jetbrains.kotlin.util.capitalizeDecapitalize.decapitalizeAsciiOnly import org.jetbrains.kotlin.util.capitalizeDecapitalize.decapitalizeSmart abstract class AbstractNameSuggester { fun suggestNamesByFqName( fqName: FqName, ignoreCompanion: Boolean = true, validator: (String) -> Boolean = { true }, defaultName: () -> String? = { null } ): Collection<String> { val result = LinkedHashSet<String>() var name = "" fqName.asString().split('.').asReversed().forEach { if (ignoreCompanion && it == "Companion") return@forEach name = name.withPrefix(it) result.addName(name, validator) } if (result.isEmpty()) { result.addName(defaultName(), validator) } return result } /** * Validates name, and slightly improves it by adding number to name in case of conflicts * @param name to check it in scope * @return name or nameI, where I is number */ fun suggestNameByName(name: String, validator: (String) -> Boolean): String { if (validator(name)) return name var i = 1 while (i <= MAX_NUMBER_OF_SUGGESTED_NAME_CHECKS && !validator(name + i)) { ++i } return name + i } fun suggestNamesForTypeParameters(count: Int, validator: (String) -> Boolean): List<String> { val result = ArrayList<String>() for (i in 0 until count) { result.add(suggestNameByMultipleNames(COMMON_TYPE_PARAMETER_NAMES, validator)) } return result } fun suggestTypeAliasNameByPsi(typeElement: KtTypeElement, validator: (String) -> Boolean): String { fun KtTypeElement.render(): String { return when (this) { is KtNullableType -> "Nullable${innerType?.render() ?: ""}" is KtFunctionType -> { val arguments = listOfNotNull(receiverTypeReference) + parameters.mapNotNull { it.typeReference } val argText = arguments.joinToString(separator = "") { it.typeElement?.render() ?: "" } val returnText = returnTypeReference?.typeElement?.render() ?: "Unit" "${argText}To$returnText" } is KtUserType -> { val argText = typeArguments.joinToString(separator = "") { it.typeReference?.typeElement?.render() ?: "" } "$argText${referenceExpression?.text ?: ""}" } else -> text.capitalizeAsciiOnly() } } return suggestNameByName(typeElement.render(), validator) } /** * Validates name using set of variants which are tried in succession (and extended with suffixes if necessary) * For example, when given sequence of a, b, c possible names are tried out in the following order: a, b, c, a1, b1, c1, a2, b2, c2, ... * @param names to check it in scope * @return name or nameI, where name is one of variants and I is a number */ fun suggestNameByMultipleNames(names: Collection<String>, validator: (String) -> Boolean): String { var i = 0 while (true) { for (name in names) { val candidate = if (i > 0) name + i else name if (validator(candidate)) return candidate } i++ } } fun getCamelNames(name: String, validator: (String) -> Boolean, startLowerCase: Boolean): List<String> { val result = ArrayList<String>() result.addCamelNames(name, validator, startLowerCase) return result } protected fun MutableCollection<String>.addCamelNames(name: String, validator: (String) -> Boolean, startLowerCase: Boolean = true) { if (name === "" || !name.unquote().isIdentifier()) return var s = extractIdentifiers(name) for (prefix in ACCESSOR_PREFIXES) { if (!s.startsWith(prefix)) continue val len = prefix.length if (len < s.length && Character.isUpperCase(s[len])) { s = s.substring(len) break } } var upperCaseLetterBefore = false for (i in s.indices) { val c = s[i] val upperCaseLetter = Character.isUpperCase(c) if (i == 0) { addName(if (startLowerCase) s.decapitalizeSmart() else s, validator) } else { if (upperCaseLetter && !upperCaseLetterBefore) { val substring = s.substring(i) addName(if (startLowerCase) substring.decapitalizeSmart() else substring, validator) } } upperCaseLetterBefore = upperCaseLetter } } private fun extractIdentifiers(s: String): String { return buildString { val lexer = KotlinLexer() lexer.start(s) while (lexer.tokenType != null) { if (lexer.tokenType == KtTokens.IDENTIFIER) { append(lexer.tokenText) } lexer.advance() } } } protected fun MutableCollection<String>.addNamesByExpressionPSI(expression: KtExpression?, validator: (String) -> Boolean) { if (expression == null) return when (val deparenthesized = KtPsiUtil.safeDeparenthesize(expression)) { is KtSimpleNameExpression -> addCamelNames(deparenthesized.getReferencedName(), validator) is KtQualifiedExpression -> addNamesByExpressionPSI(deparenthesized.selectorExpression, validator) is KtCallExpression -> addNamesByExpressionPSI(deparenthesized.calleeExpression, validator) is KtPostfixExpression -> addNamesByExpressionPSI(deparenthesized.baseExpression, validator) } } protected fun MutableCollection<String>.addName(name: String?, validator: (String) -> Boolean) { if (name == null) return val correctedName = when { name.isIdentifier() -> name name == "class" -> "clazz" else -> return } add(suggestNameByName(correctedName, validator)) } private fun String.withPrefix(prefix: String): String { if (isEmpty()) return prefix val c = this[0] return (if (c in 'a'..'z') prefix.decapitalizeAsciiOnly() else prefix.capitalizeAsciiOnly()) + capitalizeAsciiOnly() } companion object { private const val MAX_NUMBER_OF_SUGGESTED_NAME_CHECKS = 1000 private val COMMON_TYPE_PARAMETER_NAMES = listOf("T", "U", "V", "W", "X", "Y", "Z") private val ACCESSOR_PREFIXES = arrayOf("get", "is", "set") } }
apache-2.0
5c951d513b860e411251f27a2dc54703
38.546448
158
0.605169
4.698701
false
false
false
false
androidx/androidx
compose/ui/ui-unit/src/commonMain/kotlin/androidx/compose/ui/unit/IntOffset.kt
3
5269
/* * 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( "NOTHING_TO_INLINE", "", "EXPERIMENTAL_FEATURE_WARNING" ) package androidx.compose.ui.unit import androidx.compose.runtime.Immutable import androidx.compose.runtime.Stable import androidx.compose.ui.geometry.Offset import androidx.compose.ui.util.lerp import androidx.compose.ui.util.packInts import androidx.compose.ui.util.unpackInt1 import androidx.compose.ui.util.unpackInt2 import kotlin.math.roundToInt /** * Constructs a [IntOffset] from [x] and [y] position [Int] values. */ @Stable fun IntOffset(x: Int, y: Int): IntOffset = IntOffset(packInts(x, y)) /** * A two-dimensional position using [Int] pixels for units */ @Immutable @kotlin.jvm.JvmInline value class IntOffset internal constructor(@PublishedApi internal val packedValue: Long) { /** * The horizontal aspect of the position in [Int] pixels. */ @Stable val x: Int get() = unpackInt1(packedValue) /** * The vertical aspect of the position in [Int] pixels. */ @Stable val y: Int get() = unpackInt2(packedValue) @Stable operator fun component1(): Int = x @Stable operator fun component2(): Int = y /** * Returns a copy of this IntOffset instance optionally overriding the * x or y parameter */ fun copy(x: Int = this.x, y: Int = this.y) = IntOffset(x, y) /** * Subtract a [IntOffset] from another one. */ @Stable inline operator fun minus(other: IntOffset) = IntOffset(x - other.x, y - other.y) /** * Add a [IntOffset] to another one. */ @Stable inline operator fun plus(other: IntOffset) = IntOffset(x + other.x, y + other.y) /** * Returns a new [IntOffset] representing the negation of this point. */ @Stable inline operator fun unaryMinus() = IntOffset(-x, -y) /** * Multiplication operator. * * Returns an IntOffset whose coordinates are the coordinates of the * left-hand-side operand (an IntOffset) multiplied by the scalar * right-hand-side operand (a Float). The result is rounded to the nearest integer. */ @Stable operator fun times(operand: Float): IntOffset = IntOffset( (x * operand).roundToInt(), (y * operand).roundToInt() ) /** * Division operator. * * Returns an IntOffset whose coordinates are the coordinates of the * left-hand-side operand (an IntOffset) divided by the scalar right-hand-side * operand (a Float). The result is rounded to the nearest integer. */ @Stable operator fun div(operand: Float): IntOffset = IntOffset( (x / operand).roundToInt(), (y / operand).roundToInt() ) /** * Modulo (remainder) operator. * * Returns an IntOffset whose coordinates are the remainder of dividing the * coordinates of the left-hand-side operand (an IntOffset) by the scalar * right-hand-side operand (an Int). */ @Stable operator fun rem(operand: Int) = IntOffset(x % operand, y % operand) @Stable override fun toString(): String = "($x, $y)" companion object { val Zero = IntOffset(0, 0) } } /** * Linearly interpolate between two [IntOffset]s. * * The [fraction] argument represents position on the timeline, with 0.0 meaning * that the interpolation has not started, returning [start] (or something * equivalent to [start]), 1.0 meaning that the interpolation has finished, * returning [stop] (or something equivalent to [stop]), and values in between * meaning that the interpolation is at the relevant point on the timeline * between [start] and [stop]. The interpolation can be extrapolated beyond 0.0 and * 1.0, so negative values and values greater than 1.0 are valid. */ @Stable fun lerp(start: IntOffset, stop: IntOffset, fraction: Float): IntOffset = IntOffset(lerp(start.x, stop.x, fraction), lerp(start.y, stop.y, fraction)) /** * Converts the [IntOffset] to an [Offset]. */ @Stable inline fun IntOffset.toOffset() = Offset(x.toFloat(), y.toFloat()) @Stable operator fun Offset.plus(offset: IntOffset): Offset = Offset(x + offset.x, y + offset.y) @Stable operator fun Offset.minus(offset: IntOffset): Offset = Offset(x - offset.x, y - offset.y) @Stable operator fun IntOffset.plus(offset: Offset): Offset = Offset(x + offset.x, y + offset.y) @Stable operator fun IntOffset.minus(offset: Offset): Offset = Offset(x - offset.x, y - offset.y) /** * Round a [Offset] down to the nearest [Int] coordinates. */ @Stable inline fun Offset.round(): IntOffset = IntOffset(x.roundToInt(), y.roundToInt())
apache-2.0
6d48ee8ed29f072cadc55c05cd010dab
28.441341
90
0.672613
3.940912
false
false
false
false
androidx/androidx
glance/glance-wear-tiles/src/androidMain/kotlin/androidx/glance/wear/tiles/Border.kt
3
2177
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.glance.wear.tiles import android.content.res.Resources import androidx.annotation.DimenRes import androidx.annotation.RestrictTo import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.glance.GlanceModifier import androidx.glance.unit.ColorProvider /** * Apply a border around an element, border width is provided in Dp * * @param width The width of the border, in DP * @param color The color of the border */ public fun GlanceModifier.border( width: Dp, color: ColorProvider ): GlanceModifier = this.then( BorderModifier(BorderDimension(dp = width), color) ) /** * Apply a border around an element, border width is provided with dimension resource * * @param width The width of the border, value provided by a dimension resource * @param color The color of the border */ public fun GlanceModifier.border( @DimenRes width: Int, color: ColorProvider ): GlanceModifier = this.then( BorderModifier(BorderDimension(resourceId = width), color) ) /** @suppress */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public data class BorderModifier( public val width: BorderDimension, public val color: ColorProvider ) : GlanceModifier.Element /** @suppress */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public data class BorderDimension( public val dp: Dp = 0.dp, @DimenRes public val resourceId: Int = 0 ) { fun toDp(resources: Resources): Dp = if (resourceId == 0) dp else (resources.getDimension(resourceId) / resources.displayMetrics.density).dp }
apache-2.0
e6719c22ab59a1bbdb92fc7ab93fb835
30.550725
85
0.744143
4.13093
false
false
false
false
androidx/androidx
benchmark/benchmark-common/src/main/java/androidx/benchmark/DeviceInfo.kt
3
5264
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.benchmark import android.content.Intent import android.content.IntentFilter import android.os.BatteryManager import android.os.Build import androidx.annotation.RestrictTo import androidx.test.platform.app.InstrumentationRegistry import java.io.File @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) object DeviceInfo { val isEmulator = Build.FINGERPRINT.startsWith("generic") || Build.FINGERPRINT.startsWith("unknown") || Build.FINGERPRINT.contains("emulator") || Build.MODEL.contains("google_sdk") || Build.MODEL.contains("Emulator") || Build.MODEL.contains("Android SDK built for x86") || Build.MANUFACTURER.contains("Genymotion") || Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic") || "google_sdk" == Build.PRODUCT val isEngBuild = Build.FINGERPRINT.contains(":eng/") val isRooted = arrayOf( "/system/app/Superuser.apk", "/sbin/su", "/system/bin/su", "/system/xbin/su", "/data/local/xbin/su", "/data/local/bin/su", "/system/sd/xbin/su", "/system/bin/failsafe/su", "/data/local/su", "/su/bin/su" ).any { File(it).exists() } /** * Battery percentage required to avoid low battery warning. * * This number is supposed to be a conservative cutoff for when low-battery-triggered power * savings modes (such as disabling cores) may be enabled. It's possible that * [BatteryManager.EXTRA_BATTERY_LOW] is a better source of truth for this, but we want to be * conservative in case the device loses power slowly while benchmarks run. */ const val MINIMUM_BATTERY_PERCENT = 25 val initialBatteryPercent: Int /** * String summarizing device hardware and software, for bug reporting purposes. */ val deviceSummaryString: String /** * General errors about device configuration, applicable to all types of benchmark. * * These errors indicate no performance tests should be performed on this device, in it's * current conditions. */ val errors: List<ConfigurationError> init { val context = InstrumentationRegistry.getInstrumentation().targetContext val filter = IntentFilter(Intent.ACTION_BATTERY_CHANGED) initialBatteryPercent = context.registerReceiver(null, filter)?.run { val level = getIntExtra(BatteryManager.EXTRA_LEVEL, 100) val scale = getIntExtra(BatteryManager.EXTRA_SCALE, 100) level * 100 / scale } ?: 100 deviceSummaryString = "DeviceInfo(Brand=${Build.BRAND}" + ", Model=${Build.MODEL}" + ", SDK=${Build.VERSION.SDK_INT}" + ", BuildFp=${Build.FINGERPRINT})" errors = listOfNotNull( conditionalError( hasError = isEngBuild, id = "ENG-BUILD", summary = "Running on Eng Build", message = """ Benchmark is running on device flashed with a '-eng' build. Eng builds of the platform drastically reduce performance to enable testing changes quickly. For this reason they should not be used for benchmarking. Use a '-user' or '-userdebug' system image. """.trimIndent() ), conditionalError( hasError = isEmulator, id = "EMULATOR", summary = "Running on Emulator", message = """ Benchmark is running on an emulator, which is not representative of real user devices. Use a physical device to benchmark. Emulator benchmark improvements might not carry over to a real user's experience (or even regress real device performance). """.trimIndent() ), conditionalError( hasError = initialBatteryPercent < MINIMUM_BATTERY_PERCENT, id = "LOW-BATTERY", summary = "Device has low battery ($initialBatteryPercent)", message = """ When battery is low, devices will often reduce performance (e.g. disabling big cores) to save remaining battery. This occurs even when they are plugged in. Wait for your battery to charge to at least $MINIMUM_BATTERY_PERCENT%. Currently at $initialBatteryPercent%. """.trimIndent() ) ) } }
apache-2.0
721bbdba654c15b05bff8d1d76affc9b
39.19084
98
0.615691
4.883117
false
false
false
false
siosio/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/inspections/AbstractKotlinInspection.kt
1
2383
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.* import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.PsiNamedElement import com.intellij.psi.util.parents import org.jetbrains.kotlin.asJava.unwrapped import org.jetbrains.kotlin.psi.KtNamedDeclaration import org.jetbrains.kotlin.psi.KtPropertyAccessor import org.jetbrains.kotlin.psi.KtValVarKeywordOwner abstract class AbstractKotlinInspection : LocalInspectionTool() { fun ProblemsHolder.registerProblemWithoutOfflineInformation( element: PsiElement, description: String, isOnTheFly: Boolean, highlightType: ProblemHighlightType, vararg fixes: LocalQuickFix ) { registerProblemWithoutOfflineInformation(element, description, isOnTheFly, highlightType, null, *fixes) } fun ProblemsHolder.registerProblemWithoutOfflineInformation( element: PsiElement, description: String, isOnTheFly: Boolean, highlightType: ProblemHighlightType, range: TextRange?, vararg fixes: LocalQuickFix ) { if (!isOnTheFly && highlightType == ProblemHighlightType.INFORMATION) return val problemDescriptor = manager.createProblemDescriptor(element, range, description, highlightType, isOnTheFly, *fixes) registerProblem(problemDescriptor) } } @Suppress("unused") fun Array<ProblemDescriptor>.registerWithElementsUnwrapped( holder: ProblemsHolder, isOnTheFly: Boolean, quickFixSubstitutor: ((LocalQuickFix, PsiElement) -> LocalQuickFix?)? = null ) { forEach { problem -> @Suppress("UNCHECKED_CAST") val originalFixes = problem.fixes as? Array<LocalQuickFix> ?: LocalQuickFix.EMPTY_ARRAY val newElement = problem.psiElement.unwrapped ?: return@forEach val newFixes = quickFixSubstitutor?.let { subst -> originalFixes.mapNotNull { subst(it, newElement) }.toTypedArray() } ?: originalFixes val descriptor = holder.manager.createProblemDescriptor(newElement, problem.descriptionTemplate, isOnTheFly, newFixes, problem.highlightType) holder.registerProblem(descriptor) } }
apache-2.0
60c2ead74feb527b2b2bb1f9c3ebff99
40.807018
158
0.741502
5.203057
false
false
false
false
jwren/intellij-community
platform/execution-impl/src/com/intellij/execution/runToolbar/RunToolbarMainSlotActive.kt
2
5974
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.execution.runToolbar import com.intellij.execution.runToolbar.RunToolbarProcessStartedAction.Companion.PROP_ACTIVE_ENVIRONMENT import com.intellij.execution.runToolbar.components.MouseListenerHelper import com.intellij.execution.runToolbar.components.TrimmedMiddleLabel import com.intellij.icons.AllIcons import com.intellij.idea.ActionsBundle import com.intellij.openapi.actionSystem.ActionToolbar import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.Presentation import com.intellij.openapi.actionSystem.impl.segmentedActionBar.SegmentedCustomAction import com.intellij.openapi.actionSystem.impl.segmentedActionBar.SegmentedCustomPanel import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.Key import com.intellij.util.ui.JBDimension import com.intellij.util.ui.UIUtil import net.miginfocom.swing.MigLayout import java.awt.* import java.beans.PropertyChangeEvent import javax.swing.Icon import javax.swing.JLabel import javax.swing.JPanel import javax.swing.UIManager class RunToolbarMainSlotActive : SegmentedCustomAction(), RTBarAction { companion object { private val LOG = Logger.getInstance(RunToolbarMainSlotActive::class.java) val ARROW_DATA = Key<Icon?>("ARROW_DATA") } override fun actionPerformed(e: AnActionEvent) { } override fun checkMainSlotVisibility(state: RunToolbarMainSlotState): Boolean { return state == RunToolbarMainSlotState.PROCESS } override fun update(e: AnActionEvent) { RunToolbarProcessStartedAction.updatePresentation(e) if (!RunToolbarProcess.isExperimentalUpdatingEnabled) { e.mainState()?.let { e.presentation.isEnabledAndVisible = e.presentation.isEnabledAndVisible && checkMainSlotVisibility(it) } } val a = JPanel() MigLayout("ins 0, fill, gap 0", "[200]") a.add(JLabel(), "pushx") e.presentation.description = e.runToolbarData()?.let { RunToolbarData.prepareDescription(e.presentation.text, ActionsBundle.message("action.RunToolbarShowHidePopupAction.click.to.show.popup.text")) } e.presentation.putClientProperty(ARROW_DATA, e.arrowIcon()) traceLog(LOG, e) } override fun createCustomComponent(presentation: Presentation, place: String): SegmentedCustomPanel { return RunToolbarMainSlotActive(presentation) } private class RunToolbarMainSlotActive(presentation: Presentation) : SegmentedCustomPanel(presentation), PopupControllerComponent { private val arrow = JLabel() private val dragArea = DraggablePane() private val setting = object : TrimmedMiddleLabel() { override fun getFont(): Font { return UIUtil.getToolbarFont() } override fun getForeground(): Color { return UIUtil.getLabelForeground() } } private val process = object : JLabel() { override fun getFont(): Font { return UIUtil.getToolbarFont() } override fun getForeground(): Color { return UIUtil.getLabelInfoForeground() } } init { layout = MigLayout("ins 0 0 0 3, fill, ay center, gap 0") val pane = JPanel().apply { layout = MigLayout("ins 0, fill, novisualpadding, ay center, gap 0", "[pref!][min!]3[shp 1, push]3[]push") add(JPanel().apply { isOpaque = false add(arrow) val d = preferredSize d.width = FixWidthSegmentedActionToolbarComponent.ARROW_WIDTH preferredSize = d }) add(JPanel().apply { preferredSize = JBDimension(1, 12) minimumSize = JBDimension(1, 12) background = UIManager.getColor("Separator.separatorColor") }) add(setting, "wmin 10") add(process, "wmin 0") isOpaque = false } add(dragArea, "pos 0 0") add(pane, "growx") MouseListenerHelper.addListener(pane, { doClick() }, { doShiftClick() }, { doRightClick() }) } fun doRightClick() { RunToolbarRunConfigurationsAction.doRightClick(ActionToolbar.getDataContextFor(this)) } private fun doClick() { val list = mutableListOf<PopupControllerComponentListener>() list.addAll(listeners) list.forEach { it.actionPerformedHandler() } } private fun doShiftClick() { ActionToolbar.getDataContextFor(this).editConfiguration() } private val listeners = mutableListOf<PopupControllerComponentListener>() override fun addListener(listener: PopupControllerComponentListener) { listeners.add(listener) } override fun removeListener(listener: PopupControllerComponentListener) { listeners.remove(listener) } override fun updateIconImmediately(isOpened: Boolean) { arrow.icon = if (isOpened) AllIcons.Toolbar.Collapse else AllIcons.Toolbar.Expand } override fun presentationChanged(event: PropertyChangeEvent) { updateArrow() updateEnvironment() setting.icon = presentation.icon setting.text = presentation.text toolTipText = presentation.description } private fun updateEnvironment() { presentation.getClientProperty(PROP_ACTIVE_ENVIRONMENT)?.let { env -> env.getRunToolbarProcess()?.let { background = it.pillColor process.text = if (env.isProcessTerminating()) ActionsBundle.message("action.RunToolbarRemoveSlotAction.terminating") else it.name } } ?: kotlin.run { isOpaque = false } } private fun updateArrow() { arrow.icon = presentation.getClientProperty(ARROW_DATA) } override fun getPreferredSize(): Dimension { val d = super.getPreferredSize() d.width = FixWidthSegmentedActionToolbarComponent.CONFIG_WITH_ARROW_WIDTH return d } } }
apache-2.0
7e538e097a673a8bf3c91fd0aa3c600d
32.757062
158
0.709407
4.790698
false
false
false
false
jwren/intellij-community
plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenDependencyAnalyzerContributor.kt
1
5190
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.idea.maven.project import com.intellij.openapi.Disposable import com.intellij.openapi.externalSystem.dependency.analyzer.* import com.intellij.openapi.externalSystem.util.ExternalSystemBundle.message import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.Pair import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.LocalFileSystem import org.jetbrains.idea.maven.model.MavenArtifactNode import org.jetbrains.idea.maven.model.MavenArtifactState import org.jetbrains.idea.maven.model.MavenConstants import org.jetbrains.idea.maven.model.MavenId import org.jetbrains.idea.maven.server.NativeMavenProjectHolder import com.intellij.openapi.externalSystem.dependency.analyzer.DependencyAnalyzerDependency as Dependency class MavenDependencyAnalyzerContributor(private val project: Project) : DependencyAnalyzerContributor { override fun whenDataChanged(listener: () -> Unit, parentDisposable: Disposable) { val projectsManager = MavenProjectsManager.getInstance(project) projectsManager.addProjectsTreeListener(object : MavenProjectsTree.Listener { override fun projectResolved(projectWithChanges: Pair<MavenProject, MavenProjectChanges>, nativeMavenProject: NativeMavenProjectHolder?) { listener() } }, parentDisposable) } override fun getProjects(): List<DependencyAnalyzerProject> { return MavenProjectsManager.getInstance(project) .projects .map { DAProject(it.path, it.displayName) } } override fun getDependencyScopes(externalProjectPath: String): List<Dependency.Scope> { return listOf(scope(MavenConstants.SCOPE_COMPILE), scope(MavenConstants.SCOPE_PROVIDED), scope(MavenConstants.SCOPE_RUNTIME), scope(MavenConstants.SCOPE_SYSTEM), scope(MavenConstants.SCOPE_IMPORT), scope(MavenConstants.SCOPE_TEST)) } override fun getDependencies(externalProjectPath: String): List<Dependency> { return LocalFileSystem.getInstance().findFileByPath(externalProjectPath) ?.let { MavenProjectsManager.getInstance(project).findProject(it) } ?.let { createDependencyList(it) } ?: emptyList() } private fun createDependencyList(mavenProject: MavenProject): List<Dependency> { val root = DAModule(mavenProject.displayName) val mavenId = mavenProject.mavenId root.putUserData(MAVEN_ARTIFACT_ID, MavenId(mavenId.groupId, mavenId.artifactId, mavenId.version)) val rootDependency = DADependency(root, scope(MavenConstants.SCOPE_COMPILE), null, emptyList()) val result = mutableListOf<Dependency>() collectDependency(mavenProject.dependencyTree, rootDependency, result) return result } private fun collectDependency(nodes: List<MavenArtifactNode>, parentDependency: Dependency, result: MutableList<Dependency>) { for (mavenArtifactNode in nodes) { val dependency = DADependency( getDependencyData(mavenArtifactNode), scope(mavenArtifactNode.originalScope ?: MavenConstants.SCOPE_COMPILE), parentDependency, getStatus(mavenArtifactNode)) result.add(dependency) if (mavenArtifactNode.dependencies != null) { collectDependency(mavenArtifactNode.dependencies, dependency, result) } } } private fun getDependencyData(mavenArtifactNode: MavenArtifactNode): Dependency.Data { val mavenProject = MavenProjectsManager.getInstance(project).findProject(mavenArtifactNode.artifact) val daArtifact = DAArtifact( mavenArtifactNode.artifact.groupId, mavenArtifactNode.artifact.artifactId, mavenArtifactNode.artifact.version ) if (mavenProject != null) { val daModule = DAModule(mavenProject.displayName) daModule.putUserData(MAVEN_ARTIFACT_ID, MavenId(daArtifact.groupId, daArtifact.artifactId, daArtifact.version)) return daModule } return daArtifact } private fun getStatus(mavenArtifactNode: MavenArtifactNode): List<Dependency.Status> { val status = mutableListOf<Dependency.Status>() if (mavenArtifactNode.getState() == MavenArtifactState.CONFLICT) { status.add(DAOmitted) mavenArtifactNode.relatedArtifact?.version?.also { val message = message("external.system.dependency.analyzer.warning.version.conflict", it) status.add(DAWarning(message)) } } else if (mavenArtifactNode.getState() == MavenArtifactState.DUPLICATE) { status.add(DAOmitted) } if (!mavenArtifactNode.artifact.isResolvedArtifact) { status.add(DAWarning(message("external.system.dependency.analyzer.warning.unresolved"))) } return status } companion object { fun scope(name: @NlsSafe String) = DAScope(name, StringUtil.toTitleCase(name)) val MAVEN_ARTIFACT_ID = Key.create<MavenId>("MavenDependencyAnalyzerContributor.MavenId") } }
apache-2.0
7befee2c58d40bd979cb7c827e949adf
44.13913
120
0.742582
4.80111
false
false
false
false
GunoH/intellij-community
plugins/kotlin/code-insight/postfix-templates-k1/src/org/jetbrains/kotlin/idea/codeInsight/postfix/stringBasedPostfixTemplates.kt
1
5991
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.codeInsight.postfix import com.intellij.codeInsight.template.Template import com.intellij.codeInsight.template.impl.ConstantNode import com.intellij.codeInsight.template.impl.MacroCallNode import com.intellij.codeInsight.template.postfix.templates.PostfixTemplateExpressionSelector import com.intellij.codeInsight.template.postfix.templates.PostfixTemplateProvider import com.intellij.codeInsight.template.postfix.templates.StringBasedPostfixTemplate import com.intellij.psi.PsiElement import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.core.IterableTypesDetection import org.jetbrains.kotlin.idea.liveTemplates.k1.macro.Fe10SuggestVariableNameMacro import org.jetbrains.kotlin.idea.resolve.ideService import org.jetbrains.kotlin.idea.util.getResolutionScope import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtReturnExpression import org.jetbrains.kotlin.psi.KtThrowExpression import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.typeUtil.isBoolean internal abstract class ConstantStringBasedPostfixTemplate( name: String, desc: String, private val template: String, selector: PostfixTemplateExpressionSelector, provider: PostfixTemplateProvider ) : StringBasedPostfixTemplate(name, desc, selector, provider) { override fun getTemplateString(element: PsiElement) = template override fun getElementToRemove(expr: PsiElement?) = expr } internal abstract class KtWrapWithCallPostfixTemplate(private val functionName: String, provider: PostfixTemplateProvider) : ConstantStringBasedPostfixTemplate( functionName, "$functionName(expr)", "$functionName(\$expr$)\$END$", createExpressionSelectorWithComplexFilter { expression, _ -> expression !is KtReturnExpression }, provider ) internal class KtWrapWithListOfPostfixTemplate(provider: PostfixTemplateProvider) : KtWrapWithCallPostfixTemplate("listOf", provider) internal class KtWrapWithSetOfPostfixTemplate(provider: PostfixTemplateProvider) : KtWrapWithCallPostfixTemplate("setOf", provider) internal class KtWrapWithArrayOfPostfixTemplate(provider: PostfixTemplateProvider) : KtWrapWithCallPostfixTemplate("arrayOf", provider) internal class KtWrapWithSequenceOfPostfixTemplate(provider: PostfixTemplateProvider) : KtWrapWithCallPostfixTemplate("sequenceOf", provider) internal class KtForEachPostfixTemplate( name: String, provider: PostfixTemplateProvider ) : ConstantStringBasedPostfixTemplate( name, "for (item in expr)", "for (\$name$ in \$expr$) {\n \$END$\n}", createExpressionSelectorWithComplexFilter(statementsOnly = true, predicate = KtExpression::hasIterableType), provider ) { override fun setVariables(template: Template, element: PsiElement) { val name = MacroCallNode(Fe10SuggestVariableNameMacro()) template.addVariable("name", name, ConstantNode("item"), true) } } private fun KtExpression.hasIterableType(bindingContext: BindingContext): Boolean { val resolutionFacade = getResolutionFacade() val type = getType(bindingContext) ?: return false val scope = getResolutionScope(bindingContext, resolutionFacade) val detector = resolutionFacade.ideService<IterableTypesDetection>().createDetector(scope) return detector.isIterable(type) } internal class KtAssertPostfixTemplate(provider: PostfixTemplateProvider) : ConstantStringBasedPostfixTemplate( "assert", "assert(expr) { \"\" }", "assert(\$expr$) { \"\$END$\" }", createExpressionSelector(statementsOnly = true, typePredicate = KotlinType::isBoolean), provider ) internal class KtParenthesizedPostfixTemplate(provider: PostfixTemplateProvider) : ConstantStringBasedPostfixTemplate( "par", "(expr)", "(\$expr$)\$END$", createExpressionSelector(), provider ) internal class KtSoutPostfixTemplate(provider: PostfixTemplateProvider) : ConstantStringBasedPostfixTemplate( "sout", "println(expr)", "println(\$expr$)\$END$", createExpressionSelector(statementsOnly = true), provider ) internal class KtReturnPostfixTemplate(provider: PostfixTemplateProvider) : ConstantStringBasedPostfixTemplate( "return", "return expr", "return \$expr$\$END$", createExpressionSelector(statementsOnly = true), provider ) internal class KtWhilePostfixTemplate(provider: PostfixTemplateProvider) : ConstantStringBasedPostfixTemplate( "while", "while (expr) {}", "while (\$expr$) {\n\$END$\n}", createExpressionSelector(statementsOnly = true, typePredicate = KotlinType::isBoolean), provider ) internal class KtSpreadPostfixTemplate(provider: PostfixTemplateProvider) : ConstantStringBasedPostfixTemplate( "spread", "*expr", "*\$expr$\$END$", createExpressionSelector(typePredicate = { KotlinBuiltIns.isArray(it) || KotlinBuiltIns.isPrimitiveArray(it) }), provider ) internal class KtArgumentPostfixTemplate(provider: PostfixTemplateProvider) : ConstantStringBasedPostfixTemplate( "arg", "functionCall(expr)", "\$call$(\$expr$\$END$)", createExpressionSelectorWithComplexFilter { expression, _ -> expression !is KtReturnExpression && expression !is KtThrowExpression }, provider ) { override fun setVariables(template: Template, element: PsiElement) { template.addVariable("call", "", "", true) } } internal class KtWithPostfixTemplate(provider: PostfixTemplateProvider) : ConstantStringBasedPostfixTemplate( "with", "with(expr) {}", "with(\$expr$) {\n\$END$\n}", createExpressionSelector(), provider )
apache-2.0
57475dd55f18c3a11cb55995595a438c
41.489362
158
0.777333
4.947151
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/uast/uast-kotlin/tests/testData/TypeAliasConstructorReference.kt
10
110
class A(param: String) typealias AA = A typealias AAA = AA val a = AA("10") val b = A("10") val c = AAA("10")
apache-2.0
f350f916e7b823c50f0de61033d5e5ca
14.857143
22
0.609091
2.619048
false
false
false
false
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/ide/ui/html/LafCssProvider.kt
1
4345
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.ui.html import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.openapi.editor.colors.EditorFontType import com.intellij.ui.ColorUtil import com.intellij.ui.JBColor import com.intellij.ui.scale.JBUIScale internal object LafCssProvider { private val PX_SIZE_REGEX = Regex("""(\d+)px""") private val LAF_COLOR_REGEX = Regex("""LAF_COLOR\((.+)\)""") private const val EDITOR_FONT_FAMILY_STUB = """___EDITOR_FONT___""" private const val EDITOR_FOREGROUND_STUB = """___EDITOR_FOREGROUND___""" private const val EDITOR_BACKGROUND_STUB = """___EDITOR_BACKGROUND___""" /** * Get custom css styles and overrides for default swing CSS */ fun getCssForCurrentLaf(): String { return (defaultOverridesCss + customCss) .replace(PX_SIZE_REGEX) { val pxSize = it.groupValues[1].toInt() JBUIScale.scale(pxSize).toString() + "px" } .replace(LAF_COLOR_REGEX) { val colorCode = it.groupValues[1].removeSurrounding("\"") ColorUtil.toHtmlColor(JBColor.namedColor(colorCode)) } } /** * Get custom editor styles */ fun getCssForCurrentEditorScheme(): String { val editorColorsScheme = EditorColorsManager.getInstance().globalScheme return editorCss .replace(EDITOR_FONT_FAMILY_STUB, editorColorsScheme.getFont(EditorFontType.PLAIN).family) .replace(EDITOR_FOREGROUND_STUB, ColorUtil.toHtmlColor(editorColorsScheme.defaultForeground)) .replace(EDITOR_BACKGROUND_STUB, ColorUtil.toHtmlColor(editorColorsScheme.defaultBackground)) } @Suppress("CssInvalidFunction") //language=CSS private val defaultOverridesCss = """ body { color: LAF_COLOR("Label.foreground"); } small { font-size: small; } p { margin-top: 15px; } h1, h2, h3, h4, h5, h6 { margin: 10px 0; } a { color: LAF_COLOR("Link.activeForeground"); text-decoration: none; } address { color: LAF_COLOR("Link.activeForeground"); text-decoration: none; } code { font-size: medium; } blockquote { margin: 5px 0; } table { border: none; } td { border: none; padding: 3px; } th { border: none; padding: 3px; } pre { margin: 5px 0; } menu { margin-top: 10px; margin-bottom: 10px; margin-left-ltr: 40px; margin-right-rtl: 40px; } dir { margin-top: 10px; margin-bottom: 10px; margin-left-ltr: 40px; margin-right-rtl: 40px; } dd { margin-left-ltr: 40px; margin-right-rtl: 40px; } dl { margin: 10px 0; } ol { margin-top: 10px; margin-bottom: 10px; margin-left-ltr: 22px; margin-right-rtl: 22px; } ul { margin-top: 10px; margin-bottom: 10px; margin-left-ltr: 12px; margin-right-rtl: 12px; -bullet-gap: 10px; } ul li p { margin-top: 0; } ul li ul { margin-left-ltr: 25px; margin-right-rtl: 25px; } ul li ul li ul { margin-left-ltr: 25px; margin-right-rtl: 25px; } ul li menu { margin-left-ltr: 25px; margin-right-rtl: 25px; } """.trimIndent() //language=CSS private val editorCss = """ code { font-family: ${EDITOR_FONT_FAMILY_STUB}; } pre { font-family: ${EDITOR_FONT_FAMILY_STUB}; } .editor-color { color: ${EDITOR_FOREGROUND_STUB}; } .editor-background { background-color: ${EDITOR_BACKGROUND_STUB}; } """.trimIndent() @Suppress("CssInvalidFunction") //language=CSS private val customCss = """ blockquote p { border-left: 2px solid LAF_COLOR("Component.borderColor"); padding-left: 10px; } """.trimIndent() }
apache-2.0
33808b47ba56002f1a5c45aa01969f63
22.365591
120
0.555351
3.893369
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/NestedLambdaShadowedImplicitParameterInspection.kt
1
5386
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.* import com.intellij.openapi.project.Project import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElementVisitor import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.inspections.collections.isCalling import org.jetbrains.kotlin.idea.intentions.ReplaceItWithExplicitFunctionLiteralParamIntention import org.jetbrains.kotlin.idea.intentions.callExpression import org.jetbrains.kotlin.idea.refactoring.rename.KotlinVariableInplaceRenameHandler import org.jetbrains.kotlin.idea.util.safeAnalyzeNonSourceRootCode import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall class NestedLambdaShadowedImplicitParameterInspection : AbstractKotlinInspection() { companion object { val scopeFunctions = listOf( "kotlin.also", "kotlin.let", "kotlin.takeIf", "kotlin.takeUnless" ).map { FqName(it) } } override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return lambdaExpressionVisitor(fun(lambda: KtLambdaExpression) { if (lambda.valueParameters.isNotEmpty()) return if (lambda.getStrictParentOfType<KtLambdaExpression>() == null) return val context = lambda.safeAnalyzeNonSourceRootCode() val implicitParameter = lambda.getImplicitParameter(context) ?: return if (lambda.getParentImplicitParameterLambda(context) == null) return val qualifiedExpression = lambda.getStrictParentOfType<KtQualifiedExpression>() if (qualifiedExpression != null) { val receiver = qualifiedExpression.receiverExpression val call = qualifiedExpression.callExpression if (receiver.text == "it" && call?.isCalling(scopeFunctions, context) == true) return } val containingFile = lambda.containingFile lambda.forEachDescendantOfType<KtNameReferenceExpression> { if (it.isImplicitParameterReference(lambda, implicitParameter, context)) { holder.registerProblem( it, KotlinBundle.message("implicit.parameter.it.of.enclosing.lambda.is.shadowed"), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, AddExplicitParameterToOuterLambdaFix(), IntentionWrapper(ReplaceItWithExplicitFunctionLiteralParamIntention()) ) } } }) } private class AddExplicitParameterToOuterLambdaFix : LocalQuickFix { override fun getName() = KotlinBundle.message("add.explicit.parameter.to.outer.lambda.fix.text") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val implicitParameterReference = descriptor.psiElement as? KtNameReferenceExpression ?: return val lambda = implicitParameterReference.getStrictParentOfType<KtLambdaExpression>() ?: return val parentLambda = lambda.getParentImplicitParameterLambda() ?: return val parameter = parentLambda.functionLiteral.getOrCreateParameterList().addParameterBefore( KtPsiFactory(project).createLambdaParameterList("it").parameters.first(), null ) val editor = parentLambda.findExistingEditor() ?: return PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.document) editor.caretModel.moveToOffset(parameter.startOffset) KotlinVariableInplaceRenameHandler().doRename(parameter, editor, null) } } } private fun KtLambdaExpression.getImplicitParameter(context: BindingContext): ValueParameterDescriptor? { return context[BindingContext.FUNCTION, functionLiteral]?.valueParameters?.singleOrNull() } private fun KtLambdaExpression.getParentImplicitParameterLambda(context: BindingContext = this.analyze()): KtLambdaExpression? { return getParentOfTypesAndPredicate(true, KtLambdaExpression::class.java) { lambda -> if (lambda.valueParameters.isNotEmpty()) return@getParentOfTypesAndPredicate false val implicitParameter = lambda.getImplicitParameter(context) ?: return@getParentOfTypesAndPredicate false lambda.anyDescendantOfType<KtNameReferenceExpression> { it.isImplicitParameterReference(lambda, implicitParameter, context) } } } private fun KtNameReferenceExpression.isImplicitParameterReference( lambda: KtLambdaExpression, implicitParameter: ValueParameterDescriptor, context: BindingContext ): Boolean { return text == "it" && getStrictParentOfType<KtLambdaExpression>() == lambda && getResolvedCall(context)?.resultingDescriptor == implicitParameter }
apache-2.0
8796a3674eecf6df4f3efc467b732239
49.820755
158
0.726142
5.723698
false
false
false
false
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateInfoPanel.kt
9
6053
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.updateSettings.impl import com.intellij.ide.IdeBundle import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.application.ApplicationNamesInfo import com.intellij.openapi.application.IdeUrlTrackingParametersProvider import com.intellij.openapi.application.PathManager import com.intellij.openapi.options.ShowSettingsUtil import com.intellij.openapi.ui.VerticalFlowLayout import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.SystemInfo import com.intellij.ui.BrowserHyperlinkListener import com.intellij.ui.JBColor import com.intellij.ui.ScrollPaneFactory import com.intellij.ui.SimpleTextAttributes import com.intellij.ui.components.ActionLink import com.intellij.ui.components.JBLabel import com.intellij.util.FontUtil import com.intellij.util.ui.JBUI import com.intellij.util.ui.StartupUiUtil import com.intellij.util.ui.UIUtil import java.awt.BorderLayout import java.awt.Dimension import java.awt.FlowLayout import java.awt.Font import java.io.File import javax.swing.JEditorPane import javax.swing.JPanel import javax.swing.event.HyperlinkEvent import kotlin.math.max import kotlin.math.min internal object UpdateInfoPanel { private const val DEFAULT_MIN_HEIGHT = 300 private const val DEFAULT_MAX_HEIGHT = 600 private const val DEFAULT_WIDTH = 700 private val DIVIDER_COLOR = JBColor(0xd9d9d9, 0x515151) private val PATCH_SIZE_RANGE: Regex = "from \\d+ to (\\d+)".toRegex() private val REPORTING_LISTENER = object : BrowserHyperlinkListener() { override fun hyperlinkActivated(e: HyperlinkEvent) { UpdateInfoStatsCollector.click(e.description) super.hyperlinkActivated(e) } } @JvmStatic fun create(newBuild: BuildInfo, patches: UpdateChain?, testPatch: File?, writeProtected: Boolean, @NlsContexts.Label licenseInfo: String?, licenseWarn: Boolean, enableLink: Boolean, updatedChannel: UpdateChannel): JPanel { val appInfo = ApplicationInfo.getInstance() val appNames = ApplicationNamesInfo.getInstance() val textPane = JEditorPane("text/html", "") textPane.border = JBUI.Borders.empty(10, 16) textPane.isEditable = false textPane.caretPosition = 0 textPane.text = textPaneContent(newBuild, updatedChannel, appNames) textPane.addHyperlinkListener(REPORTING_LISTENER) val scrollPane = ScrollPaneFactory.createScrollPane(textPane, true) scrollPane.border = JBUI.Borders.customLine(DIVIDER_COLOR, 0, 0, 1, 0) scrollPane.preferredSize = Dimension( min(scrollPane.preferredSize.width, DEFAULT_WIDTH), scrollPane.preferredSize.height.coerceIn(DEFAULT_MIN_HEIGHT, DEFAULT_MAX_HEIGHT)) val infoPanel = JPanel(VerticalFlowLayout(0, 10)) infoPanel.border = JBUI.Borders.empty(8, 16) if (licenseInfo != null) { val label = JBLabel(licenseInfo) label.foreground = if (licenseWarn) JBColor.RED else null label.font = smallFont(label.font) infoPanel.add(label) } if (writeProtected) { val label = JBLabel(IdeBundle.message("updates.write.protected", appNames.productName, PathManager.getHomePath())) label.foreground = JBColor.RED label.font = smallFont(label.font) infoPanel.add(label) } val infoRow = JPanel(FlowLayout(FlowLayout.LEFT, 0, 0)) val infoLabel = JBLabel() infoLabel.foreground = SimpleTextAttributes.GRAY_ITALIC_ATTRIBUTES.fgColor infoLabel.font = smallFont(infoLabel.font) infoLabel.text = infoLabelText(newBuild, patches, testPatch, appInfo) infoRow.add(infoLabel) if (enableLink) { val link = ActionLink(IdeBundle.message("updates.configure.updates.label")) { ShowSettingsUtil.getInstance().editConfigurable(infoRow, UpdateSettingsConfigurable(false)) } link.border = JBUI.Borders.empty(0, 4, 0, 0) link.font = smallFont(link.font) infoRow.add(link) } infoPanel.add(infoRow) val panel = JPanel(BorderLayout()) panel.add(scrollPane, BorderLayout.CENTER) panel.add(infoPanel, BorderLayout.SOUTH) return panel } @NlsSafe private fun textPaneContent(newBuild: BuildInfo, updatedChannel: UpdateChannel, appNames: ApplicationNamesInfo): String { val style = UIUtil.getCssFontDeclaration(StartupUiUtil.getLabelFont()) val message = newBuild.message val content = when { message.isNotBlank() -> message else -> IdeBundle.message("updates.new.version.available", appNames.fullProductName, downloadUrl(newBuild, updatedChannel)) } return """<html><head>${style}</head><body>${content}</body></html>""" } @NlsContexts.DetailedDescription private fun infoLabelText(newBuild: BuildInfo, patches: UpdateChain?, testPatch: File?, appInfo: ApplicationInfo): String { val patchSize = when { testPatch != null -> max(testPatch.length() shr 20, 1).toString() patches != null && !patches.size.isNullOrBlank() -> { val match = PATCH_SIZE_RANGE.matchEntire(patches.size) if (match != null) match.groupValues[1] else patches.size } else -> null } return when { patchSize != null -> IdeBundle.message("updates.from.to.size", appInfo.fullVersion, newBuild.version, newBuild.number, patchSize) else -> IdeBundle.message("updates.from.to", appInfo.fullVersion, newBuild.version, newBuild.number) } } private fun smallFont(font: Font): Font = when { SystemInfo.isMac -> FontUtil.minusOne(font) SystemInfo.isLinux -> FontUtil.minusOne(FontUtil.minusOne(font)) else -> font } @JvmStatic fun downloadUrl(newBuild: BuildInfo, updatedChannel: UpdateChannel): String = IdeUrlTrackingParametersProvider.getInstance().augmentUrl( newBuild.downloadUrl ?: newBuild.blogPost ?: updatedChannel.url ?: "https://www.jetbrains.com") }
apache-2.0
ef22f20078c175df57c229f63c59b60b
38.822368
135
0.735833
4.262676
false
false
false
false
extendedmind/extendedmind
ui/android/app/src/main/java/org/extendedmind/android/ui/theme/Theme.kt
1
891
package org.extendedmind.android.ui.theme import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material.MaterialTheme import androidx.compose.material.darkColors import androidx.compose.material.lightColors import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.Color private val LightThemeColors = lightColors( onPrimary = Color.White, onSecondary = Color.White, onBackground = Color.Black, ) private val DarkThemeColors = darkColors( onPrimary = Color.Black, onSecondary = Color.Black, onBackground = Color.White, ) @Composable fun ExtendedMindTheme ( darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit ) { MaterialTheme( colors = if (darkTheme) DarkThemeColors else LightThemeColors, typography = ExtendedMindTypography, content = content ) }
agpl-3.0
733e35094060e882341216bc7515cd37
28.7
70
0.756453
4.592784
false
false
false
false
Tolriq/yatse-customcommandsplugin-api
sample/src/main/java/tv/yatse/plugin/customcommands/sample/CCPluginActivity.kt
1
1895
/* * Copyright 2015 Tolriq / Genimee. * 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 tv.yatse.plugin.customcommands.sample import android.os.Bundle import android.view.View import android.widget.TextView import tv.yatse.plugin.customcommands.api.CustomCommandsActivity class CCPluginActivity : CustomCommandsActivity() { private lateinit var mViewTitle: TextView private lateinit var mViewParam1: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_custom_commands) mViewTitle = findViewById(R.id.custom_command_title) mViewParam1 = findViewById(R.id.custom_command_param1) if (isEditing) { mViewTitle.text = pluginCustomCommand.title mViewParam1.text = pluginCustomCommand.param1 } findViewById<View>(R.id.btn_save).setOnClickListener { cancelAndFinish() } findViewById<View>(R.id.btn_save).setOnClickListener { pluginCustomCommand = pluginCustomCommand.copy( // Custom command source field must always equals to plugin uniqueId !! source = getString(R.string.plugin_unique_id), title = mViewTitle.text.toString(), param1 = mViewParam1.text.toString() ) saveAndFinish() } } }
apache-2.0
2a87e04d6621e53878c80a7e0abe1033
39.340426
87
0.699208
4.396752
false
false
false
false
BenWoodworth/FastCraft
fastcraft-bukkit/bukkit-1.7/src/main/kotlin/net/benwoodworth/fastcraft/bukkit/command/FcCommandSource_Bukkit_1_7.kt
1
2435
package net.benwoodworth.fastcraft.bukkit.command import net.benwoodworth.fastcraft.bukkit.player.FcPlayer_Bukkit import net.benwoodworth.fastcraft.bukkit.player.bukkit import net.benwoodworth.fastcraft.bukkit.player.getPlayer import net.benwoodworth.fastcraft.bukkit.server.permission import net.benwoodworth.fastcraft.platform.command.FcCommandSource import net.benwoodworth.fastcraft.platform.player.FcPlayer import net.benwoodworth.fastcraft.platform.server.FcPermission import net.benwoodworth.fastcraft.platform.text.FcText import net.benwoodworth.fastcraft.platform.text.FcTextConverter import org.bukkit.command.CommandSender import org.bukkit.command.ConsoleCommandSender import org.bukkit.entity.Player import java.util.* import javax.inject.Inject import javax.inject.Singleton class FcCommandSource_Bukkit_1_7( override val commandSender: CommandSender, override val player: FcPlayer?, private val fcTextConverter: FcTextConverter, fcPlayerOperations: FcPlayer.Operations, ) : FcCommandSource_Bukkit, FcPlayer_Bukkit.Operations by fcPlayerOperations.bukkit { override val isConsole: Boolean get() = commandSender is ConsoleCommandSender override fun hasPermission(permission: FcPermission): Boolean { return commandSender.hasPermission(permission.permission) } override val locale: Locale get() = player?.locale ?: Locale.ENGLISH // TODO Don't default to English override fun sendMessage(message: FcText) { if (player != null) { player.sendMessage(message) } else { commandSender.sendMessage(fcTextConverter.toLegacy(message, Locale.ENGLISH)) } } @Singleton class Factory @Inject constructor( private val fcPlayerProvider: FcPlayer.Provider, private val fcTextConverter: FcTextConverter, private val fcPlayerOperations: FcPlayer.Operations, ) : FcCommandSource_Bukkit.Factory { override fun create(commandSender: CommandSender): FcCommandSource { return FcCommandSource_Bukkit_1_7( commandSender = commandSender, player = when (commandSender) { is Player -> fcPlayerProvider.getPlayer(commandSender) else -> null }, fcTextConverter = fcTextConverter, fcPlayerOperations = fcPlayerOperations, ) } } }
gpl-3.0
f226f4f601e75bd77b02e5d3fcff8965
37.650794
88
0.724846
4.802761
false
false
false
false
ThiagoGarciaAlves/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/impl/LineStatusTrackerManager.kt
1
27953
/* * 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.openapi.vcs.impl import com.google.common.collect.HashMultiset import com.google.common.collect.Multiset import com.intellij.openapi.Disposable import com.intellij.openapi.application.Application import com.intellij.openapi.application.ApplicationAdapter import com.intellij.openapi.application.ModalityState import com.intellij.openapi.components.ProjectComponent import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.EditorFactory import com.intellij.openapi.editor.event.DocumentEvent import com.intellij.openapi.editor.event.DocumentListener import com.intellij.openapi.editor.event.EditorFactoryAdapter import com.intellij.openapi.editor.event.EditorFactoryEvent import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.project.Project import com.intellij.openapi.roots.impl.DirectoryIndex import com.intellij.openapi.startup.StartupManager import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.io.FileUtilRt import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vcs.* import com.intellij.openapi.vcs.changes.* import com.intellij.openapi.vcs.ex.LineStatusTracker import com.intellij.openapi.vcs.ex.PartialLocalLineStatusTracker import com.intellij.openapi.vcs.ex.SimpleLocalLineStatusTracker import com.intellij.openapi.vcs.history.VcsRevisionNumber import com.intellij.openapi.vfs.* import com.intellij.testFramework.LightVirtualFile import com.intellij.ui.GuiUtils import com.intellij.util.concurrency.AppExecutorUtil import com.intellij.util.containers.HashMap import com.intellij.vcsUtil.VcsUtil import org.jetbrains.annotations.CalledInAny import org.jetbrains.annotations.CalledInAwt import org.jetbrains.annotations.NonNls import java.nio.charset.Charset import java.util.* class LineStatusTrackerManager( private val project: Project, private val application: Application, private val statusProvider: VcsBaseContentProvider, private val changeListManager: ChangeListManagerImpl, private val fileDocumentManager: FileDocumentManager, @Suppress("UNUSED_PARAMETER") makeSureIndexIsInitializedFirst: DirectoryIndex ) : ProjectComponent, LineStatusTrackerManagerI { private val LOCK = Any() private val disposable: Disposable = Disposer.newDisposable() private var isDisposed = false private val trackers = HashMap<Document, TrackerData>() private val forcedDocuments = HashMap<Document, Multiset<Any>>() private val partialChangeListsEnabled = Registry.`is`("vcs.enable.partial.changelists") private val documentsInDefaultChangeList = HashSet<Document>() private val loader: SingleThreadLoader<RefreshRequest, RefreshData> = MyBaseRevisionLoader() companion object { private val LOG = Logger.getInstance(LineStatusTrackerManager::class.java) @JvmStatic fun getInstance(project: Project): LineStatusTrackerManagerI { return project.getComponent(LineStatusTrackerManagerI::class.java) } } override fun initComponent() { StartupManager.getInstance(project).registerPreStartupActivity { if (isDisposed) return@registerPreStartupActivity application.addApplicationListener(MyApplicationListener(), disposable) val busConnection = project.messageBus.connect(disposable) busConnection.subscribe(LineStatusTrackerSettingListener.TOPIC, MyLineStatusTrackerSettingListener()) val fsManager = FileStatusManager.getInstance(project) fsManager.addFileStatusListener(MyFileStatusListener(), disposable) val editorFactory = EditorFactory.getInstance() editorFactory.addEditorFactoryListener(MyEditorFactoryListener(), disposable) if (partialChangeListsEnabled) editorFactory.eventMulticaster.addDocumentListener(MyDocumentListener(), disposable) changeListManager.addChangeListListener(MyChangeListListener()) val virtualFileManager = VirtualFileManager.getInstance() virtualFileManager.addVirtualFileListener(MyVirtualFileListener(), disposable) } } override fun disposeComponent() { isDisposed = true Disposer.dispose(disposable) synchronized(LOCK) { for ((document, multiset) in forcedDocuments) { for (requester in multiset.elementSet()) { warn("Tracker for is being held on dispose by $requester", document) } } forcedDocuments.clear() for (data in trackers.values) { unregisterTrackerInCLM(data.tracker) data.tracker.release() } trackers.clear() loader.clear() } } @NonNls override fun getComponentName(): String { return "LineStatusTrackerManager" } override fun getLineStatusTracker(document: Document): LineStatusTracker<*>? { synchronized(LOCK) { return trackers[document]?.tracker } } override fun getLineStatusTracker(file: VirtualFile): LineStatusTracker<*>? { val document = fileDocumentManager.getCachedDocument(file) ?: return null return getLineStatusTracker(document) } @CalledInAwt override fun requestTrackerFor(document: Document, requester: Any) { synchronized(LOCK) { val multiset = forcedDocuments.computeIfAbsent(document) { HashMultiset.create<Any>() } multiset.add(requester) if (trackers[document] == null) { val virtualFile = fileDocumentManager.getFile(document) ?: return installTracker(virtualFile, document) } } } @CalledInAwt override fun releaseTrackerFor(document: Document, requester: Any) { synchronized(LOCK) { val multiset = forcedDocuments[document] if (multiset == null || !multiset.contains(requester)) { warn("Tracker release underflow by $requester", document) return } multiset.remove(requester) if (multiset.isEmpty()) { forcedDocuments.remove(document) checkIfTrackerCanBeReleased(document) } } } override fun invokeAfterUpdate(task: Runnable) { loader.addAfterUpdateRunnable(task) } @CalledInAwt private fun checkIfTrackerCanBeReleased(document: Document) { synchronized(LOCK) { val data = trackers[document] ?: return if (forcedDocuments.containsKey(document)) return if (data.tracker is PartialLocalLineStatusTracker) { val hasPartialChanges = data.tracker.getAffectedChangeListsIds().size > 1 val isLoading = loader.hasRequest(RefreshRequest(document)) if (hasPartialChanges || isLoading) return } releaseTracker(document) } } @CalledInAwt private fun onEverythingChanged() { synchronized(LOCK) { if (isDisposed) return log("onEverythingChanged", null) val files = HashSet<VirtualFile>() for (data in trackers.values) { files.add(data.tracker.virtualFile) } for (document in forcedDocuments.keys) { val file = fileDocumentManager.getFile(document) if (file != null) files.add(file) } for (file in files) { onFileChanged(file) } } } @CalledInAwt private fun onFileChanged(virtualFile: VirtualFile) { val document = fileDocumentManager.getCachedDocument(virtualFile) ?: return synchronized(LOCK) { if (isDisposed) return log("onFileChanged", virtualFile) val tracker = trackers[document]?.tracker if (tracker == null) { if (forcedDocuments.containsKey(document)) { installTracker(virtualFile, document) } } else { val isPartialTrackerExpected = canCreatePartialTrackerFor(virtualFile) val isPartialTracker = tracker is PartialLocalLineStatusTracker if (isPartialTrackerExpected == isPartialTracker) { refreshTracker(tracker) } else { releaseTracker(document) installTracker(virtualFile, document) } } } } private fun registerTrackerInCLM(tracker: LineStatusTracker<*>) { if (tracker is PartialLocalLineStatusTracker) { val filePath = VcsUtil.getFilePath(tracker.virtualFile) changeListManager.registerChangeTracker(filePath, tracker) } } private fun unregisterTrackerInCLM(tracker: LineStatusTracker<*>) { if (tracker is PartialLocalLineStatusTracker) { val filePath = VcsUtil.getFilePath(tracker.virtualFile) changeListManager.unregisterChangeTracker(filePath, tracker) } } private fun reregisterTrackerInCLM(tracker: LineStatusTracker<*>, oldPath: FilePath, newPath: FilePath) { if (tracker is PartialLocalLineStatusTracker) { changeListManager.unregisterChangeTracker(oldPath, tracker) changeListManager.registerChangeTracker(newPath, tracker) } } private fun canGetBaseRevisionFor(virtualFile: VirtualFile?): Boolean { if (isDisposed) return false if (virtualFile == null || virtualFile is LightVirtualFile || !virtualFile.isValid) return false if (virtualFile.fileType.isBinary || FileUtilRt.isTooLarge(virtualFile.length)) return false if (!statusProvider.isSupported(virtualFile)) return false val status = FileStatusManager.getInstance(project).getStatus(virtualFile) if (status == FileStatus.ADDED || status == FileStatus.DELETED || status == FileStatus.UNKNOWN || status == FileStatus.IGNORED) { return false } return true } private fun canCreatePartialTrackerFor(virtualFile: VirtualFile): Boolean { if (!arePartialChangelistsEnabled(virtualFile)) return false val status = FileStatusManager.getInstance(project).getStatus(virtualFile) if (status != FileStatus.MODIFIED && status != FileStatus.NOT_CHANGED) return false val change = ChangeListManager.getInstance(project).getChange(virtualFile) return change != null && change.javaClass == Change::class.java && change.type == Change.Type.MODIFICATION && change.afterRevision is CurrentContentRevision } override fun arePartialChangelistsEnabled(virtualFile: VirtualFile): Boolean { if (!partialChangeListsEnabled) return false if (getTrackingMode() == LineStatusTracker.Mode.SILENT) return false val vcs = VcsUtil.getVcsFor(project, virtualFile) return vcs != null && vcs.arePartialChangelistsSupported() } @CalledInAwt private fun installTracker(virtualFile: VirtualFile, document: Document) { if (!canGetBaseRevisionFor(virtualFile)) return val changelistId = changeListManager.getChangeList(virtualFile)?.id installTracker(virtualFile, document, changelistId, emptyList()) } @CalledInAwt private fun installTracker(virtualFile: VirtualFile, document: Document, oldChangesChangelistId: String?, events: List<DocumentEvent>) { synchronized(LOCK) { if (isDisposed) return if (trackers[document] != null) return val tracker = if (canCreatePartialTrackerFor(virtualFile)) { PartialLocalLineStatusTracker.createTracker(project, document, virtualFile, getTrackingMode(), events) } else { SimpleLocalLineStatusTracker.createTracker(project, document, virtualFile, getTrackingMode()) } trackers.put(document, TrackerData(tracker)) registerTrackerInCLM(tracker) refreshTracker(tracker, oldChangesChangelistId) log("Tracker installed", virtualFile) } } @CalledInAwt private fun releaseTracker(document: Document) { synchronized(LOCK) { if (isDisposed) return val data = trackers.remove(document) ?: return unregisterTrackerInCLM(data.tracker) data.tracker.release() log("Tracker released", data.tracker.virtualFile) } } private fun getTrackingMode(): LineStatusTracker.Mode { val settings = VcsApplicationSettings.getInstance() if (!settings.SHOW_LST_GUTTER_MARKERS) return LineStatusTracker.Mode.SILENT if (settings.SHOW_WHITESPACES_IN_LST) return LineStatusTracker.Mode.SMART return LineStatusTracker.Mode.DEFAULT } @CalledInAwt private fun refreshTracker(tracker: LineStatusTracker<*>, changelistId: String? = null) { synchronized(LOCK) { if (isDisposed) return loader.scheduleRefresh(RefreshRequest(tracker.document, changelistId)) log("Refresh queued", tracker.virtualFile) } } private inner class MyBaseRevisionLoader() : SingleThreadLoader<RefreshRequest, RefreshData>(project) { override fun loadRequest(request: RefreshRequest): Result<RefreshData> { if (isDisposed) return Result.Canceled() val document = request.document val virtualFile = fileDocumentManager.getFile(document) log("Loading started", virtualFile) if (virtualFile == null || !virtualFile.isValid) { log("Loading error: virtual file is not valid", virtualFile) return Result.Error() } if (!canGetBaseRevisionFor(virtualFile)) { log("Loading error: cant get base revision", virtualFile) return Result.Error() } val baseContent = statusProvider.getBaseRevision(virtualFile) if (baseContent == null) { log("Loading error: base revision not found", virtualFile) return Result.Error() } val newContentInfo = ContentInfo(baseContent.revisionNumber, virtualFile.charset) synchronized(LOCK) { val data = trackers[document] if (data == null) { log("Loading cancelled: tracker not found", virtualFile) return Result.Canceled() } if (!shouldBeUpdated(data.contentInfo, newContentInfo)) { log("Loading cancelled: no need to update", virtualFile) return Result.Canceled() } } val lastUpToDateContent = baseContent.loadContent() if (lastUpToDateContent == null) { log("Loading error: provider failure", virtualFile) return Result.Error() } val converted = StringUtil.convertLineSeparators(lastUpToDateContent) log("Loading successful", virtualFile) return Result.Success(RefreshData(converted, newContentInfo)) } override fun handleResult(request: RefreshRequest, result: Result<RefreshData>) { val document = request.document when (result) { is Result.Canceled -> { } is Result.Error -> { edt { synchronized(LOCK) { val data = trackers[document] ?: return@edt data.tracker.dropBaseRevision() data.contentInfo = null checkIfTrackerCanBeReleased(document) } } } is Result.Success -> { edt { val virtualFile = fileDocumentManager.getFile(document)!! val refreshData = result.data synchronized(LOCK) { val data = trackers[document] if (data == null) { log("Loading finished: tracker already released", virtualFile) return@edt } if (!shouldBeUpdated(data.contentInfo, refreshData.info)) { log("Loading finished: no need to update", virtualFile) return@edt } data.contentInfo = refreshData.info if (data.tracker is PartialLocalLineStatusTracker) { val changelist = request.changelistId ?: changeListManager.getChangeList(virtualFile)?.id data.tracker.setBaseRevision(refreshData.text, changelist) } else { data.tracker.setBaseRevision(refreshData.text) } log("Loading finished: success", virtualFile) } } } } } } private inner class MyFileStatusListener : FileStatusListener { override fun fileStatusesChanged() { onEverythingChanged() } override fun fileStatusChanged(virtualFile: VirtualFile) { onFileChanged(virtualFile) } } private inner class MyEditorFactoryListener : EditorFactoryAdapter() { override fun editorCreated(event: EditorFactoryEvent) { val editor = event.editor if (isTrackedEditor(editor)) { requestTrackerFor(editor.document, editor) } } override fun editorReleased(event: EditorFactoryEvent) { val editor = event.editor if (isTrackedEditor(editor)) { releaseTrackerFor(editor.document, editor) } } private fun isTrackedEditor(editor: Editor): Boolean { return editor.project == null || editor.project == project } } private inner class MyVirtualFileListener : VirtualFileListener { override fun beforePropertyChange(event: VirtualFilePropertyEvent) { if (VirtualFile.PROP_ENCODING == event.propertyName) { onFileChanged(event.file) } if (VirtualFile.PROP_NAME == event.propertyName) { val file = event.file val parent = event.parent if (parent != null) { handleFileMovement(file) { Pair(VcsUtil.getFilePath(parent, event.oldValue as String), VcsUtil.getFilePath(parent, event.newValue as String)) } } } } override fun beforeFileMovement(event: VirtualFileMoveEvent) { val file = event.file handleFileMovement(file) { Pair(VcsUtil.getFilePath(event.oldParent, file.name), VcsUtil.getFilePath(event.newParent, file.name)) } } private fun handleFileMovement(file: VirtualFile, getPaths: () -> Pair<FilePath, FilePath>) { if (!partialChangeListsEnabled) return synchronized(LOCK) { val tracker = getLineStatusTracker(file) if (tracker != null) { val (oldPath, newPath) = getPaths() reregisterTrackerInCLM(tracker, oldPath, newPath) } } } } private inner class MyDocumentListener : DocumentListener { override fun documentChanged(event: DocumentEvent) { val document = event.document if (documentsInDefaultChangeList.contains(document)) return val virtualFile = fileDocumentManager.getFile(document) ?: return if (getLineStatusTracker(document) != null) return if (!canCreatePartialTrackerFor(virtualFile)) return val changeList = changeListManager.getChangeList(virtualFile) if (changeList != null && !changeList.isDefault) { installTracker(virtualFile, document, changeList.id, listOf(event)) return } documentsInDefaultChangeList.add(document) } } private inner class MyApplicationListener : ApplicationAdapter() { override fun afterWriteActionFinished(action: Any) { documentsInDefaultChangeList.clear() synchronized(LOCK) { val documents = trackers.values.map { it.tracker.document } for (document in documents) { checkIfTrackerCanBeReleased(document) } } } } private inner class MyLineStatusTrackerSettingListener : LineStatusTrackerSettingListener { override fun settingsUpdated() { synchronized(LOCK) { val mode = getTrackingMode() for (data in trackers.values) { val tracker = data.tracker val document = tracker.document val virtualFile = tracker.virtualFile if (tracker.mode == mode) continue val isPartialTrackerExpected = canCreatePartialTrackerFor(virtualFile) val isPartialTracker = tracker is PartialLocalLineStatusTracker if (isPartialTrackerExpected == isPartialTracker) { tracker.mode = mode } else { releaseTracker(document) installTracker(virtualFile, document) } } } } } private inner class MyChangeListListener : ChangeListAdapter() { override fun defaultListChanged(oldDefaultList: ChangeList?, newDefaultList: ChangeList?) { edt { EditorFactory.getInstance().allEditors .filterIsInstance(EditorEx::class.java) .forEach { it.gutterComponentEx.repaint() } } } } private fun shouldBeUpdated(oldInfo: ContentInfo?, newInfo: ContentInfo): Boolean { if (oldInfo == null) return true if (oldInfo.revision == newInfo.revision && oldInfo.revision != VcsRevisionNumber.NULL) { return oldInfo.charset != newInfo.charset } return true } private class TrackerData(val tracker: LineStatusTracker<*>, var contentInfo: ContentInfo? = null) private class ContentInfo(val revision: VcsRevisionNumber, val charset: Charset) private class RefreshRequest(val document: Document, val changelistId: String? = null) { override fun equals(other: Any?): Boolean = other is RefreshRequest && document == other.document override fun hashCode(): Int = document.hashCode() } private class RefreshData(val text: String, val info: ContentInfo) private fun edt(task: () -> Unit) { GuiUtils.invokeLaterIfNeeded(task, ModalityState.any()) } private fun log(message: String, file: VirtualFile?) { if (LOG.isDebugEnabled) { if (file != null) { LOG.debug(message + "; file: " + file.path) } else { LOG.debug(message) } } } private fun warn(message: String, document: Document?) { val file = document?.let { fileDocumentManager.getFile(it) } warn(message, file) } private fun warn(message: String, file: VirtualFile?) { if (file != null) { LOG.warn(message + "; file: " + file.path) } else { LOG.warn(message) } } @CalledInAwt internal fun collectPartiallyChangedFilesStates(): List<PartialLocalLineStatusTracker.State> { val result = mutableListOf<PartialLocalLineStatusTracker.State>() synchronized(LOCK) { for (data in trackers.values) { val tracker = data.tracker if (tracker is PartialLocalLineStatusTracker) { val hasPartialChanges = tracker.affectedChangeListsIds.size > 1 if (hasPartialChanges) { result.add(tracker.storeTrackerState()) } } } } return result } @CalledInAwt internal fun restoreTrackersForPartiallyChangedFiles(trackerStates: List<PartialLocalLineStatusTracker.State>) { synchronized(LOCK) { for (state in trackerStates) { val virtualFile = state.virtualFile val document = fileDocumentManager.getDocument(virtualFile) ?: continue if (!canCreatePartialTrackerFor(virtualFile)) continue val tracker = PartialLocalLineStatusTracker.createTracker(project, document, virtualFile, getTrackingMode(), state) val oldTracker = trackers.put(document, TrackerData(tracker)) if (oldTracker != null) { unregisterTrackerInCLM(oldTracker.tracker) oldTracker.tracker.release() } registerTrackerInCLM(tracker) refreshTracker(tracker) log("Tracker restored from config", virtualFile) } } } } /** * Single threaded queue with the following properties: * - Ignores duplicated requests (the first queued is used). * - Allows to check whether request is scheduled or is waiting for completion. * - Notifies callbacks when queue is exhausted. */ abstract private class SingleThreadLoader<Request, T>(private val project: Project) { private val LOG = Logger.getInstance(SingleThreadLoader::class.java) private val LOCK: Any = Any() private val executor = AppExecutorUtil.createBoundedScheduledExecutorService("LineStatusTrackerManager pool", 1) private val taskQueue = ArrayDeque<Request>() private val waitingForRefresh = HashSet<Request>() private val callbacksWaitingUpdateCompletion = ArrayList<Runnable>() private var isScheduled: Boolean = false protected abstract fun loadRequest(request: Request): Result<T> protected abstract fun handleResult(request: Request, result: Result<T>) @CalledInAwt fun scheduleRefresh(request: Request) { if (isDisposed()) return synchronized(LOCK) { if (taskQueue.contains(request)) return taskQueue.add(request) schedule() } } @CalledInAwt fun clear() { val callbacks = mutableListOf<Runnable>() synchronized(LOCK) { taskQueue.clear() waitingForRefresh.clear() callbacks += callbacksWaitingUpdateCompletion callbacksWaitingUpdateCompletion.clear() } executeCallbacks(callbacksWaitingUpdateCompletion) } @CalledInAwt fun hasRequest(request: Request): Boolean { synchronized(LOCK) { for (refreshData in taskQueue) { if (refreshData == request) return true } for (refreshData in waitingForRefresh) { if (refreshData == request) return true } } return false } @CalledInAny fun addAfterUpdateRunnable(task: Runnable) { val updateScheduled = putRunnableIfUpdateScheduled(task) if (updateScheduled) return edt { if (!putRunnableIfUpdateScheduled(task)) { task.run() } } } private fun putRunnableIfUpdateScheduled(task: Runnable): Boolean { synchronized(LOCK) { if (taskQueue.isEmpty() && waitingForRefresh.isEmpty()) return false callbacksWaitingUpdateCompletion.add(task) return true } } private fun schedule() { if (isDisposed()) return synchronized(LOCK) { if (isScheduled) return if (taskQueue.isEmpty()) return isScheduled = true executor.execute { handleRequests() } } } private fun handleRequests() { while (true) { val request = synchronized(LOCK) { val request = taskQueue.poll() if (isDisposed() || request == null) { isScheduled = false return } waitingForRefresh.add(request) return@synchronized request } handleSingleRequest(request) } } private fun handleSingleRequest(request: Request) { val result: Result<T> = try { loadRequest(request) } catch (e: Throwable) { LOG.error(e) Result.Error() } edt { handleResult(request, result) notifyTrackerRefreshed(request) } } @CalledInAwt private fun notifyTrackerRefreshed(request: Request) { if (isDisposed()) return val callbacks = mutableListOf<Runnable>() synchronized(LOCK) { waitingForRefresh.remove(request) if (taskQueue.isEmpty() && waitingForRefresh.isEmpty()) { callbacks += callbacksWaitingUpdateCompletion callbacksWaitingUpdateCompletion.clear() } } executeCallbacks(callbacks) } @CalledInAwt private fun executeCallbacks(callbacks: List<Runnable>) { for (callback in callbacks) { try { callback.run() } catch (e: Throwable) { LOG.error(e) } } } private fun isDisposed() = project.isDisposed private fun edt(task: () -> Unit) { GuiUtils.invokeLaterIfNeeded(task, ModalityState.any()) } } private sealed class Result<T> { class Success<T>(val data: T) : Result<T>() class Canceled<T> : Result<T>() class Error<T> : Result<T>() }
apache-2.0
aee586a8269367790acaf98436f4d1d0
30.55079
123
0.688549
5.193794
false
false
false
false
shabtaisharon/ds3_java_browser
dsb-gui/src/main/java/com/spectralogic/dsbrowser/gui/services/jobService/data/PutJobData.kt
1
7069
/* * *************************************************************************** * Copyright 2014-2018 Spectra Logic Corporation. 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. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file 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.spectralogic.dsbrowser.gui.services.jobService.data import com.spectralogic.ds3client.Ds3Client import com.spectralogic.ds3client.commands.spectrads3.GetActiveJobSpectraS3Request import com.spectralogic.ds3client.commands.spectrads3.GetJobSpectraS3Request import com.spectralogic.ds3client.helpers.Ds3ClientHelpers import com.spectralogic.ds3client.helpers.FileObjectPutter import com.spectralogic.ds3client.helpers.options.WriteJobOptions import com.spectralogic.ds3client.models.JobStatus import com.spectralogic.ds3client.models.Priority import com.spectralogic.ds3client.models.bulk.Ds3Object import com.spectralogic.ds3client.utils.Guard import com.spectralogic.dsbrowser.api.services.logging.LoggingService import com.spectralogic.dsbrowser.gui.services.jobService.JobTaskElement import com.spectralogic.dsbrowser.gui.services.jobService.util.EmptyChannelBuilder import com.spectralogic.dsbrowser.gui.util.DateTimeUtils import com.spectralogic.dsbrowser.gui.util.ParseJobInterruptionMap import javafx.beans.property.BooleanProperty import java.nio.file.Files import java.nio.file.Path import java.time.Instant import java.util.* import java.util.function.Supplier import java.util.stream.Stream data class PutJobData(private val items: List<Pair<String, Path>>, private val targetDir: String, override val bucket: String, private val jobTaskElement: JobTaskElement) : JobData { override fun runningTitle(): String { val transferringPut = jobTaskElement.resourceBundle.getString("transferringPut") val jobId = job?.jobId val startedAt = jobTaskElement.resourceBundle.getString("startedAt") val started = jobTaskElement.dateTimeUtils.format(getStartTime()) return "$transferringPut $jobId $startedAt $started" } override var jobId: UUID? = null public override var cancelled: Supplier<Boolean>? = null override fun client(): Ds3Client = jobTaskElement.client override public var lastFile = "" override fun internationalize(labelName: String): String = jobTaskElement.resourceBundle.getString(labelName) override fun modifyJob(job: Ds3ClientHelpers.Job) { job.withMaxParallelRequests(jobTaskElement.settingsStore.processSettings.maximumNumberOfParallelThreads) } override var job: Ds3ClientHelpers.Job? = null get() { if (field == null) { field = if (writeJobOptions() == null) { Ds3ClientHelpers.wrap(jobTaskElement.client).startWriteJob(bucket, buildDs3Objects()) } else { Ds3ClientHelpers.wrap(jobTaskElement.client).startWriteJob(bucket, buildDs3Objects(), writeJobOptions()) } } jobId = field?.jobId return field!! } set(value) { if (value != null) { field = value } } override var prefixMap: MutableMap<String, Path> = mutableMapOf() override fun showCachedJobProperty(): BooleanProperty = jobTaskElement.settingsStore.showCachedJobSettings.showCachedJobEnableProperty() override fun loggingService(): LoggingService = jobTaskElement.loggingService override fun targetPath(): String = targetDir override fun dateTimeUtils(): DateTimeUtils = jobTaskElement.dateTimeUtils private var startTime: Instant = Instant.now() public override fun getStartTime(): Instant = startTime public override fun setStartTime(): Instant { startTime = Instant.now() return startTime } override fun getObjectChannelBuilder(prefix: String): Ds3ClientHelpers.ObjectChannelBuilder = EmptyChannelBuilder(FileObjectPutter(prefixMap.get(prefix)!!.parent), prefixMap.get(prefix)!!) private fun buildDs3Objects(): List<Ds3Object> = items.flatMap({ dataToDs3Objects(it) }).distinct() private fun dataToDs3Objects(item: Pair<String, Path>): Iterable<Ds3Object> { val localDelim = item.second.fileSystem.separator val parent = item.second.parent val paths = Files.walk(item.second).use { stream: Stream<Path> -> stream.iterator().asSequence() .takeWhile { !cancelled!!.get() } .filter { !(Files.isDirectory(it) && Files.list(it).use { f -> f.findAny().isPresent }) } .map { Ds3Object(if (Files.isDirectory(it)) { targetDir + parent.relativize(it).toString().replace(localDelim, "/") + "/" } else { targetDir + parent.relativize(it).toString().replace(localDelim, "/") } , if (Files.isDirectory(it)) 0L else Files.size(it)) } .toList() } paths.forEach { prefixMap.put(it.name, item.second) } return paths } override fun jobSize() = jobTaskElement.client.getActiveJobSpectraS3(GetActiveJobSpectraS3Request(job!!.jobId)).activeJobResult.originalSizeInBytes override fun shouldRestoreFileAttributes() = jobTaskElement.settingsStore.filePropertiesSettings.isFilePropertiesEnabled override fun isCompleted() = jobTaskElement.client.getJobSpectraS3(GetJobSpectraS3Request(job!!.jobId)).masterObjectListResult.status == JobStatus.COMPLETED override fun removeJob() { ParseJobInterruptionMap.removeJobIdFromFile(jobTaskElement.jobInterruptionStore, job!!.jobId.toString(), jobTaskElement.client.connectionDetails.endpoint) } override fun saveJob(jobSize: Long) { ParseJobInterruptionMap.saveValuesToFiles(jobTaskElement.jobInterruptionStore, prefixMap, mapOf(), jobTaskElement.client.connectionDetails.endpoint, job!!.jobId, jobSize, targetPath(), jobTaskElement.dateTimeUtils, "PUT", bucket) } private fun writeJobOptions(): WriteJobOptions? { val writeJobOptions = WriteJobOptions.create() val priority = jobTaskElement.savedJobPrioritiesStore.jobSettings.putJobPriority return if (Guard.isStringNullOrEmpty(priority) || priority.equals("Data Policy Default (no change)")) { null } else { writeJobOptions.withPriority(Priority.valueOf(priority)) } } }
apache-2.0
16ce819fa9b17fac8e7ea3af0af76fd2
48.788732
237
0.688641
4.782815
false
false
false
false
hazuki0x0/YuzuBrowser
module/download/src/main/java/jp/hazuki/yuzubrowser/download/service/DownloadService.kt
1
19215
/* * Copyright (C) 2017-2021 Hazuki * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jp.hazuki.yuzubrowser.download.service import android.annotation.SuppressLint import android.app.NotificationManager import android.app.PendingIntent import android.app.Service import android.content.* import android.net.Uri import android.os.* import android.provider.MediaStore import androidx.annotation.StringRes import androidx.core.app.NotificationCompat import androidx.documentfile.provider.DocumentFile import dagger.hilt.android.AndroidEntryPoint import jp.hazuki.yuzubrowser.core.utility.extensions.resolvePath import jp.hazuki.yuzubrowser.core.utility.log.ErrorReport import jp.hazuki.yuzubrowser.core.utility.log.Logger import jp.hazuki.yuzubrowser.core.utility.storage.toDocumentFile import jp.hazuki.yuzubrowser.download.* import jp.hazuki.yuzubrowser.download.core.data.DownloadFile import jp.hazuki.yuzubrowser.download.core.data.DownloadFileInfo import jp.hazuki.yuzubrowser.download.core.data.DownloadRequest import jp.hazuki.yuzubrowser.download.core.data.MetaData import jp.hazuki.yuzubrowser.download.core.downloader.Downloader import jp.hazuki.yuzubrowser.download.core.utils.getNotificationString import jp.hazuki.yuzubrowser.download.core.utils.registerMediaScanner import jp.hazuki.yuzubrowser.download.repository.DownloadsDao import jp.hazuki.yuzubrowser.download.service.connection.ServiceClient import jp.hazuki.yuzubrowser.download.service.connection.ServiceCommand import jp.hazuki.yuzubrowser.download.service.connection.ServiceSocket import jp.hazuki.yuzubrowser.download.ui.DownloadListActivity import jp.hazuki.yuzubrowser.ui.extensions.intentFor import jp.hazuki.yuzubrowser.ui.widget.longToast import jp.hazuki.yuzubrowser.ui.widget.toast import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import okhttp3.OkHttpClient import javax.inject.Inject @AndroidEntryPoint class DownloadService : Service(), ServiceClient.ServiceClientListener { private lateinit var handler: Handler private lateinit var powerManager: PowerManager private lateinit var notificationManager: NotificationManager private lateinit var messenger: Messenger private val threadList = mutableListOf<DownloadThread>() private val observers = mutableListOf<Messenger>() @Inject lateinit var okHttpClient: OkHttpClient @Inject lateinit var downloadsDao: DownloadsDao override fun onCreate() { super.onCreate() handler = Handler(Looper.getMainLooper()) powerManager = getSystemService(Context.POWER_SERVICE) as PowerManager notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager messenger = Messenger(ServiceClient(this)) val notify = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_DOWNLOAD_SERVICE) .setContentTitle(getText(R.string.download_service)) .setSmallIcon(R.drawable.ic_yuzubrowser_white) .setPriority(NotificationCompat.PRIORITY_MIN) .build() GlobalScope.launch(Dispatchers.IO) { downloadsDao.cleanUp() } val filter = IntentFilter(INTENT_ACTION_CANCEL_DOWNLOAD) filter.addAction(INTENT_ACTION_PAUSE_DOWNLOAD) registerReceiver(notificationControl, filter) startForeground(Int.MIN_VALUE, notify) } override fun onDestroy() { synchronized(threadList) { threadList.forEach { it.abort() } } unregisterReceiver(notificationControl) stopForeground(true) } override fun onBind(intent: Intent?): IBinder = messenger.binder override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { if (intent == null) { stopSelf() return START_NOT_STICKY } GlobalScope.launch(Dispatchers.IO) { var thread: DownloadThread? = null when (intent.action) { INTENT_ACTION_START_DOWNLOAD -> { val root = intent.getParcelableExtra<Uri>(INTENT_EXTRA_DOWNLOAD_ROOT_URI)!! .toDocumentFile(this@DownloadService) val file = intent.getParcelableExtra<DownloadFile>(INTENT_EXTRA_DOWNLOAD_REQUEST) val metadata = intent.getParcelableExtra<MetaData?>(INTENT_EXTRA_DOWNLOAD_METADATA) if (file != null) { thread = FirstDownloadThread(root, file, metadata) } } INTENT_ACTION_RESTART_DOWNLOAD -> { val id = intent.getLongExtra(INTENT_EXTRA_DOWNLOAD_ID, -1) val info = downloadsDao[id] val root = info.root.toDocumentFile(this@DownloadService) thread = ReDownloadThread(root, info, DownloadRequest(null, null, null)) } } if (thread != null) { synchronized(threadList) { threadList.add(thread) } thread.start() } else { stopSelf() } } return START_NOT_STICKY } override fun registerObserver(messenger: Messenger) { observers.add(messenger) } override fun unregisterObserver(messenger: Messenger) { observers.remove(messenger) } override fun update(msg: Message) { val it = observers.iterator() while (it.hasNext()) { try { it.next().send(Message.obtain(msg)) } catch (e: RemoteException) { ErrorReport.printAndWriteLog(e) it.remove() } } } override fun getDownloadInfo(messenger: Messenger) { val list = synchronized(threadList) { threadList.map { it.info } } val it = observers.iterator() while (it.hasNext()) { try { it.next().send(Message.obtain(null, ServiceSocket.GET_DOWNLOAD_INFO, list)) } catch (e: RemoteException) { ErrorReport.printAndWriteLog(e) it.remove() } } } override fun cancelDownload(id: Long) { synchronized(threadList) { threadList.firstOrNull { id == it.info.id }?.cancel() } } override fun pauseDownload(id: Long) { synchronized(threadList) { threadList.firstOrNull { id == it.info.id }?.pause() } } private val notificationControl = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent?) { if (intent == null) return val id = intent.getLongExtra(INTENT_EXTRA_DOWNLOAD_ID, -1) if (id >= 0) { when (intent.action) { INTENT_ACTION_CANCEL_DOWNLOAD -> cancelDownload(id) INTENT_ACTION_PAUSE_DOWNLOAD -> pauseDownload(id) } } } } private inner class FirstDownloadThread( private val root: DocumentFile, private val file: DownloadFile, private val metadata: MetaData?, ) : DownloadThread(root, file.request) { override val info: DownloadFileInfo by lazy { DownloadFileInfo(root.uri, file, metadata ?: MetaData(this@DownloadService, okHttpClient, root, file.url, file.request, file.name)) } } private inner class ReDownloadThread( root: DocumentFile, override val info: DownloadFileInfo, request: DownloadRequest, ) : DownloadThread(root, request) private abstract inner class DownloadThread( private var root: DocumentFile, private val request: DownloadRequest, ) : Thread(), Downloader.DownloadListener { abstract val info: DownloadFileInfo private val notification = NotificationCompat.Builder(this@DownloadService, NOTIFICATION_CHANNEL_DOWNLOAD_NOTIFY) private val bigTextStyle = NotificationCompat.BigTextStyle() private var downloader: Downloader? = null private var isActionAdded = false private var isAbort = false @SuppressLint("WakelockTimeout") override fun run() { if (isAbort) return val wakelock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "DownloadThread:wakelock") prepareThread(wakelock) if (checkValidRootDir(info.root)) { if (!root.exists()) { failedCheckFolder(info, R.string.download_failed_root_not_exists) endThreaded(wakelock) return } else if (!root.canWrite()) { failedCheckFolder(info, R.string.download_failed_root_not_writable) endThreaded(wakelock) return } } else { request.isScopedStorageMode = true info.resumable = false val values = ContentValues().apply { put(MediaStore.Downloads.DISPLAY_NAME, info.name) put(MediaStore.Downloads.MIME_TYPE, info.mimeType) put(MediaStore.Downloads.IS_PENDING, 1) put(MediaStore.Downloads.IS_DOWNLOAD, 1) } val collection = MediaStore.Downloads.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY) val itemUri = contentResolver.insert(collection, values) if (itemUri == null) { failedCheckFolder(info, R.string.failed) endThreaded(wakelock) return } info.root = itemUri root = itemUri.toDocumentFile(this@DownloadService) } if (info.id == 0L) { info.id = downloadsDao.insert(info) } else { info.state = DownloadFileInfo.STATE_DOWNLOADING downloadsDao.update(info) } val downloader = Downloader.getDownloader(this@DownloadService, okHttpClient, info, request) this.downloader = downloader downloader.downloadListener = this downloader.download() endThreaded(wakelock) } fun cancel() = downloader?.cancel() fun pause() = downloader?.pause() fun abort() { downloader?.abort() isAbort = true } override fun onStartDownload(info: DownloadFileInfo) { downloadsDao.update(info) notification.run { setSmallIcon(android.R.drawable.stat_sys_download) setOngoing(false) setContentTitle(info.name) setWhen(info.startTime) setProgress(0, 0, true) setContentIntent(PendingIntent.getActivity(applicationContext, 0, intentFor<DownloadListActivity>(), 0)) notificationManager.notify(info.id.toInt(), build()) } updateInfo(ServiceSocket.UPDATE, info) } override fun onFileDownloaded(info: DownloadFileInfo, downloadedFile: DocumentFile) { if (info.size < 0) { info.size = info.currentSize } downloadsDao.update(info) if (request.isScopedStorageMode) { val values = ContentValues().apply { put(MediaStore.Downloads.IS_PENDING, 0) } // Workaround for samsung device in Android 11 try { contentResolver.update(info.root, values, null, null) } catch (e: IllegalStateException) { if (Build.MANUFACTURER != "samsung") throw e } } else { root.findFile(info.name)?.uri?.resolvePath(this@DownloadService) ?.let { registerMediaScanner(it) } } NotificationCompat.Builder(this@DownloadService, NOTIFICATION_CHANNEL_DOWNLOAD_NOTIFY).run { setOngoing(false) setContentTitle(info.name) setWhen(System.currentTimeMillis()) setProgress(0, 0, false) setAutoCancel(true) setContentText(getText(R.string.download_success)) setSmallIcon(android.R.drawable.stat_sys_download_done) setContentIntent(PendingIntent.getActivity(applicationContext, 0, info.createFileOpenIntent(this@DownloadService, downloadedFile), 0)) notificationManager.notify(info.id.toInt(), build()) } updateInfo(ServiceSocket.UPDATE, info) } override fun onFileDownloadFailed(info: DownloadFileInfo, cause: String?) { if (request.isScopedStorageMode) { val file = root if (file.exists()) { contentResolver.delete(file.uri, null, null) } } downloadsDao.update(info) if (cause != null) { handler.post { longToast(cause) } Logger.d("download error", cause) } NotificationCompat.Builder(this@DownloadService, NOTIFICATION_CHANNEL_DOWNLOAD_NOTIFY).run { setOngoing(false) setContentTitle(info.name) setWhen(System.currentTimeMillis()) setProgress(0, 0, false) setAutoCancel(true) setContentText(getText(R.string.download_fail)) setSmallIcon(android.R.drawable.stat_sys_warning) setContentIntent(PendingIntent.getActivity(applicationContext, 0, intentFor<DownloadListActivity>(), 0)) notificationManager.notify(info.id.toInt(), build()) } updateInfo(ServiceSocket.UPDATE, info) } override fun onFileDownloadAbort(info: DownloadFileInfo) { downloadsDao.update(info) if (info.state == DownloadFileInfo.STATE_PAUSED) { NotificationCompat.Builder(this@DownloadService, NOTIFICATION_CHANNEL_DOWNLOAD_NOTIFY).run { setOngoing(false) setContentTitle(info.name) setWhen(System.currentTimeMillis()) setAutoCancel(true) setContentText(getText(R.string.download_paused)) setSmallIcon(R.drawable.ic_pause_white_24dp) setContentIntent(PendingIntent.getActivity(applicationContext, 0, intentFor<DownloadListActivity>(), 0)) val resume = Intent(this@DownloadService, DownloadService::class.java).apply { action = INTENT_ACTION_RESTART_DOWNLOAD putExtra(INTENT_EXTRA_DOWNLOAD_ID, info.id) } addAction(R.drawable.ic_start_white_24dp, getText(R.string.resume_download), PendingIntent.getService(this@DownloadService, info.id.toInt(), resume, 0)) notificationManager.notify(info.id.toInt(), build()) } } else { notificationManager.cancel(info.id.toInt()) } updateInfo(ServiceSocket.UPDATE, info) } override fun onFileDownloading(info: DownloadFileInfo, progress: Long) { notification.run { setAction(info) if (info.size <= 0) { setProgress(0, 0, true) } else { setProgress(1000, (progress * 1000 / info.size).toInt(), false) } setStyle(bigTextStyle.bigText(info.getNotificationString(applicationContext))) notificationManager.notify(info.id.toInt(), build()) } updateInfo(ServiceSocket.UPDATE, info) } private fun setAction(info: DownloadFileInfo) { if (!isActionAdded) { isActionAdded = true notification.run { if (info.resumable) { val pause = Intent(INTENT_ACTION_PAUSE_DOWNLOAD).apply { putExtra(INTENT_EXTRA_DOWNLOAD_ID, info.id) } addAction(R.drawable.ic_pause_white_24dp, getText(R.string.pause_download), PendingIntent.getBroadcast(this@DownloadService, info.id.toInt(), pause, PendingIntent.FLAG_UPDATE_CURRENT)) } val cancel = Intent(INTENT_ACTION_CANCEL_DOWNLOAD).apply { putExtra(INTENT_EXTRA_DOWNLOAD_ID, info.id) } addAction(R.drawable.ic_cancel_white_24dp, getText(android.R.string.cancel), PendingIntent.getBroadcast(this@DownloadService, info.id.toInt(), cancel, PendingIntent.FLAG_UPDATE_CURRENT)) } } } private fun updateInfo(@ServiceCommand command: Int, info: DownloadFileInfo) { try { messenger.send(Message.obtain(null, command, info)) } catch (e: RemoteException) { ErrorReport.printAndWriteLog(e) } } @SuppressLint("WakelockTimeout") private fun prepareThread(wakeLock: PowerManager.WakeLock) { wakeLock.acquire() } private fun endThreaded(wakeLock: PowerManager.WakeLock) { wakeLock.release() synchronized(threadList) { threadList.remove(this) if (threadList.isEmpty()) { stopSelf() } } } private fun failedCheckFolder(info: DownloadFileInfo, @StringRes message: Int) { info.state = DownloadFileInfo.STATE_UNKNOWN_ERROR downloadsDao.updateWithEmptyRoot(info) handler.post { toast(message) } NotificationCompat.Builder(this@DownloadService, NOTIFICATION_CHANNEL_DOWNLOAD_NOTIFY).run { setOngoing(false) setContentTitle(info.name) setWhen(System.currentTimeMillis()) setProgress(0, 0, false) setAutoCancel(true) setContentText(getText(message)) setSmallIcon(android.R.drawable.stat_sys_warning) setContentIntent(PendingIntent.getActivity(applicationContext, 0, intentFor<DownloadListActivity>(), 0)) notificationManager.notify(info.id.toInt(), build()) } updateInfo(ServiceSocket.UPDATE, info) } } }
apache-2.0
61d05de944b61025404f3001d88299ed
39.03125
150
0.605829
5.133583
false
false
false
false
JetBrains/teamcity-azure-plugin
plugin-azure-server/src/main/kotlin/jetbrains/buildServer/clouds/azure/arm/throttler/AzureThrottlerCacheableTaskImpl.kt
1
3113
/* * Copyright 2000-2021 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 jetbrains.buildServer.clouds.azure.arm.throttler import com.google.common.cache.CacheBuilder import com.microsoft.azure.management.Azure import jetbrains.buildServer.serverSide.TeamCityProperties import rx.Single import java.time.Clock import java.time.LocalDateTime import java.time.ZoneOffset import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicLong import java.util.concurrent.atomic.AtomicReference abstract class AzureThrottlerCacheableTaskBaseImpl<P, T> : AzureThrottlerTaskBaseImpl<Azure, P, T>(), AzureThrottlerCacheableTask<Azure, P, T> { private val myTimeoutInSeconds = AtomicLong(60) private val myCache = createCache() override fun getFromCache(parameter: P): T? { return myCache.getIfPresent(parameter)?.value } override fun invalidateCache() { myCache.invalidateAll() } override fun setCacheTimeout(timeoutInSeconds: Long) { myTimeoutInSeconds.set(timeoutInSeconds) } override fun create(api: Azure, parameter: P): Single<T> { return createQuery(api, parameter) .doOnSuccess { myCache.put(parameter, CacheValue(it, LocalDateTime.now(Clock.systemUTC()))) } } override fun needCacheUpdate(parameter: P): Boolean { val lastUpdatedDateTime = myCache.getIfPresent(parameter)?.lastUpdatedDateTime return lastUpdatedDateTime == null || lastUpdatedDateTime.plusSeconds(myTimeoutInSeconds.get()) < LocalDateTime.now(Clock.systemUTC()) } override fun checkThrottleTime(parameter: P): Boolean { val lastUpdatedDateTime = myCache.getIfPresent(parameter)?.lastUpdatedDateTime return lastUpdatedDateTime != null && lastUpdatedDateTime.plusSeconds(getTaskThrottleTime()) < LocalDateTime.now(Clock.systemUTC()) } override fun areParametersEqual(parameter: P, other: P): Boolean { return parameter == other } private fun getTaskThrottleTime(): Long { return TeamCityProperties.getLong(TEAMCITY_CLOUDS_AZURE_THROTTLER_TASK_THROTTLE_TIMEOUT_SEC, 5) } protected abstract fun createQuery(api: Azure, parameter: P): Single<T> data class CacheValue<T>(val value: T, val lastUpdatedDateTime : LocalDateTime) private fun createCache() = CacheBuilder .newBuilder() .expireAfterWrite(TeamCityProperties.getLong(TEAMCITY_CLOUDS_AZURE_THROTTLER_TASK_CACHE_TIMEOUT_SEC, 32 * 60), TimeUnit.SECONDS) .build<P, CacheValue<T>>() }
apache-2.0
77ba58892bdce386840d263354044fe0
38.405063
144
0.730485
4.505065
false
false
false
false
hazuki0x0/YuzuBrowser
module/ui/src/main/java/jp/hazuki/yuzubrowser/ui/widget/RootLayout.kt
1
1909
/* * Copyright (C) 2017-2019 Hazuki * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jp.hazuki.yuzubrowser.ui.widget import android.app.Activity import android.content.Context import android.graphics.Color import android.util.AttributeSet import androidx.annotation.AttrRes import androidx.coordinatorlayout.widget.CoordinatorLayout import jp.hazuki.yuzubrowser.core.utility.extensions.getResColor import jp.hazuki.yuzubrowser.core.utility.extensions.isImeShown import jp.hazuki.yuzubrowser.ui.R class RootLayout @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr: Int = 0 ) : CoordinatorLayout(context, attrs, defStyleAttr) { private var isWhiteMode = false private var onImeShownListener: ((Boolean) -> Unit)? = null override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { onImeShownListener?.invoke((context as Activity).isImeShown()) super.onMeasure(widthMeasureSpec, heightMeasureSpec) } fun setOnImeShownListener(l: (visible: Boolean) -> Unit) { onImeShownListener = l } fun setWhiteBackgroundMode(whiteMode: Boolean) { isWhiteMode = whiteMode if (whiteMode) { setBackgroundColor(Color.WHITE) } else { setBackgroundColor(context.getResColor(R.color.browserBackground)) } } }
apache-2.0
d251df779f8d38910c3003630a8b7652
32.491228
78
0.730225
4.328798
false
false
false
false
BlueBoxWare/LibGDXPlugin
src/main/kotlin/com/gmail/blueboxware/libgdxplugin/filetypes/skin/references/SkinJavaClassReference.kt
1
1712
package com.gmail.blueboxware.libgdxplugin.filetypes.skin.references import com.gmail.blueboxware.libgdxplugin.filetypes.skin.psi.SkinClassName import com.gmail.blueboxware.libgdxplugin.utils.DollarClassName import com.gmail.blueboxware.libgdxplugin.utils.collectTagsFromAnnotations import com.intellij.psi.PsiClass import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementResolveResult /* * Copyright 2017 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. */ class SkinJavaClassReference(element: SkinClassName) : SkinReference<SkinClassName>(element) { override fun multiResolve(incompleteCode: Boolean) = element.multiResolve().map(::PsiElementResolveResult).toTypedArray() override fun handleElementRename(newElementName: String): PsiElement = element override fun bindToElement(target: PsiElement): PsiElement { if (target is PsiClass) { if (element.project.collectTagsFromAnnotations().none { it.first == element.value.plainName }) { element.stringLiteral.value = DollarClassName(target).dollarName } } else { super.bindToElement(target) } return element } }
apache-2.0
9425891d819f4e5e8d12f5ddc505ed89
37.909091
108
0.747664
4.602151
false
false
false
false
STMicroelectronics-CentralLabs/BlueSTSDK_Android
BlueSTSDK/src/main/java/com/st/BlueSTSDK/Features/FeatureQVAR.kt
1
6120
package com.st.BlueSTSDK.Features import com.st.BlueSTSDK.Feature import com.st.BlueSTSDK.Node import com.st.BlueSTSDK.Utils.NumberConversion class FeatureQVAR constructor(n: Node) : Feature(FEATURE_NAME_QVAR, n, arrayOf(QVAR_FIELD, FLAG_FIELD, DQVAR_FIELD, PARAM_FIELD,NUM_FIELD)) { //TimeStamp (2); Qvar (4); Flag (1) ,dQvar (4);Parameter (4); override fun extractData(timestamp: Long, data: ByteArray, dataOffset: Int): ExtractResult { //val temp: Array<Field> = arrayOf(QVAR_FIELD, FLAG_FIELD, DQVAR_FIELD, PARAM_FIELD) //mDataDesc = temp val numberOfFields = when(data.size - dataOffset){ 4-> 1 5-> 2 9 -> 3 13 -> 4 else -> { 0 } } if(numberOfFields!=0) { //We allocate always 4 results... this is a tmp workaround for plot Demo // if we want to avoid to display all the Feature elements val results = arrayOfNulls<Number>(5) //val results = arrayOfNulls<Number>(4) var numBytes = 4; results[0] = NumberConversion.LittleEndian.bytesToInt32(data, dataOffset) if (numberOfFields > 1) { //Read the Flag Value results[1] = data[dataOffset + 4]; numBytes += 1 if (numberOfFields > 2) { //Read the DQVAR value numBytes += 4 results[2] = NumberConversion.LittleEndian.bytesToInt32(data, dataOffset + 5) if (numberOfFields == 4) { //Read the PARAM Value numBytes += 4 results[3] = NumberConversion.LittleEndian.bytesToUInt32(data, dataOffset + 9) } } } //Filling the empty Fields // this is a tmp workaround for plot Demo // if we want to avoid to display all the Feature elements if(numberOfFields!=4) { for (i in numberOfFields..3) { results[i] = 0 } } results[4]= numberOfFields; return ExtractResult(Sample(timestamp, results, fieldsDesc), numBytes) } return ExtractResult(null, 0) } companion object { private const val FEATURE_NAME_QVAR = "Electric Charge Variation" private const val FEATURE_DATA_NAME_QVAR = "QVAR" private const val FEATURE_UNIT_QVAR = "LSB" private val DATA_MAX_QVAR_DQVAR_: Number = Int.MAX_VALUE private val DATA_MIN_QVAR_DQVAR: Number = Int.MIN_VALUE private const val FEATURE_DATA_NAME_FLAG = "Flag" private const val FEATURE_UNIT_FLAG = "NotDefined" private val DATA_MAX_FLAG: Number = 255 private val DATA_MIN_FLAG: Number = 0 private const val FEATURE_DATA_NAME_DQVAR = "DQVAR" private const val FEATURE_UNIT_DQVAR = "LSB" private const val FEATURE_DATA_NAME_PARAM = "Parameter" private const val FEATURE_UNIT_PARAM = "NotDefined" private val DATA_MAX_PARAM: Number = 1L shl 32 - 1 private val DATA_MIN_PARAM: Number = 0 private val QVAR_FIELD = Field(FEATURE_DATA_NAME_QVAR, FEATURE_UNIT_QVAR, Field.Type.Int32, DATA_MAX_QVAR_DQVAR_, DATA_MIN_QVAR_DQVAR,true) private val FLAG_FIELD = Field(FEATURE_DATA_NAME_FLAG, FEATURE_UNIT_FLAG, Field.Type.UInt8, DATA_MAX_FLAG, DATA_MIN_FLAG,false) private val DQVAR_FIELD = Field(FEATURE_DATA_NAME_DQVAR, FEATURE_UNIT_DQVAR, Field.Type.Int32, DATA_MAX_QVAR_DQVAR_, DATA_MIN_QVAR_DQVAR,true) private val PARAM_FIELD = Field(FEATURE_DATA_NAME_PARAM, FEATURE_UNIT_PARAM, Field.Type.UInt32, DATA_MAX_PARAM, DATA_MIN_PARAM,false) private val NUM_FIELD = Field("Num Fields", "#", Field.Type.UInt8, 4, 0,false) /** * Return the QVAR * @param sample data sample * @return */ fun getQVARValue(sample: Sample?): Long? { if (sample != null) { if (sample.data.isNotEmpty()) if(sample.data[0]!=null) return sample.data[0].toLong() } return null } /** * Return the Flag * @param sample data sample * @return */ fun getFlagValue(sample: Sample?): Byte? { if (sample != null) { if (sample.data.isNotEmpty()) if (sample.data.size>=2) if(sample.data[1]!=null) return sample.data[1].toByte() } return null } /** * Return the DQVAR * @param sample data sample * @return */ fun getDQVARValue(sample: Sample?): Long? { if (sample != null) { if (sample.data.isNotEmpty()) if (sample.data.size>=3) if(sample.data[2]!=null) return sample.data[2].toLong() } return null } /** * Return the PARAM * @param sample data sample * @return */ fun getParamValue(sample: Sample?): Long? { if (sample != null) { if (sample.data.isNotEmpty()) if (sample.data.size==4) if(sample.data[3]!=null) return sample.data[3].toLong() } return null } /** * Return the Number of fields * @param sample data sample * @return */ fun getNumFields(sample: Sample?): Int { if (sample != null) { if (sample.data.isNotEmpty()) if (sample.data.size==5) if(sample.data[4]!=null) return sample.data[4].toInt() } return 0 } } }
bsd-3-clause
e1c8819becf091f67824f023dad2b45c
34.795322
150
0.515686
4.255911
false
false
false
false
hwki/SimpleBitcoinWidget
bitcoin/src/main/java/com/brentpanther/bitcoinwidget/ui/home/HomeScreen.kt
1
6489
package com.brentpanther.bitcoinwidget.ui.home import android.app.PendingIntent import android.appwidget.AppWidgetManager import android.content.ComponentName import android.content.Context import android.content.Intent import android.os.Build import androidx.annotation.RequiresApi import androidx.compose.animation.* import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.tween import androidx.compose.foundation.layout.* import androidx.compose.material.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.rotate import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.NavController import com.brentpanther.bitcoinwidget.R import com.brentpanther.bitcoinwidget.ValueWidgetProvider import com.brentpanther.bitcoinwidget.WidgetProvider import com.brentpanther.bitcoinwidget.ui.MainActivity @Composable fun HomeScreen(navController: NavController, viewModel: ManageWidgetsViewModel = viewModel()) { var index by remember { mutableStateOf(0) } val context = LocalContext.current val supportsPin = remember { Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && AppWidgetManager.getInstance(context).isRequestPinAppWidgetSupported } Scaffold( topBar = { TopAppBar( title = { Text(stringResource(R.string.app_name)) } ) }, bottomBar = { BottomNavigation { BottomNavigationItem( selected = index == 0, label = { Text(stringResource(R.string.nav_title_manage_widgets)) }, icon = { Icon(painterResource(id = R.drawable.ic_outline_widgets_24), null) }, onClick = { index = 0 } ) BottomNavigationItem( selected = index == 1, label = { Text(stringResource(R.string.nav_title_settings)) }, icon = { Icon(painterResource(id = R.drawable.ic_outline_settings_24), null) }, onClick = { index = 1 } ) } }, floatingActionButton = { if (index == 0 && supportsPin) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { PinWidgetFAB() } } }, ) { paddingValues -> Box(Modifier.padding(paddingValues)) { when (index) { 0 -> WidgetList(navController, supportsPin, viewModel) 1 -> GlobalSettings(viewModel) } } } } @RequiresApi(Build.VERSION_CODES.O) private fun <T : WidgetProvider> pinWidget(context: Context, className: Class<T>) { val myProvider = ComponentName(context, className) val intent = Intent(context.applicationContext, MainActivity::class.java) val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE } else { PendingIntent.FLAG_UPDATE_CURRENT } val pendingIntent = PendingIntent.getActivity(context.applicationContext, 123, intent, flags) AppWidgetManager.getInstance(context).requestPinAppWidget(myProvider, null, pendingIntent) } @RequiresApi(Build.VERSION_CODES.O) @OptIn(ExperimentalAnimationApi::class) @Composable fun PinWidgetFAB() { var expanded by remember { mutableStateOf(false) } val context = LocalContext.current Column( horizontalAlignment = Alignment.End, verticalArrangement = Arrangement.spacedBy(16.dp) ) { AnimatedVisibility( visible = expanded, enter = fadeIn(tween()), exit = fadeOut(tween()), ) { Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { Card( elevation = 2.dp, ) { Text( stringResource(R.string.widget_value_name), Modifier.padding(horizontal = 8.dp, vertical = 4.dp) ) } FloatingActionButton( onClick = { expanded = false pinWidget(context, ValueWidgetProvider::class.java) }, modifier = Modifier .padding(4.dp) .size(46.dp) .animateEnterExit(enter = scaleIn(), exit = scaleOut()) ) { Icon(painterResource(R.drawable.ic_outline_attach_money_24), stringResource(R.string.add_value_widget)) } } } AnimatedVisibility( visible = expanded, enter = fadeIn(tween()), exit = fadeOut(tween()) ) { Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { Card( elevation = 2.dp, ) { Text( stringResource(R.string.widget_price_name), Modifier.padding(horizontal = 8.dp, vertical = 4.dp) ) } FloatingActionButton( onClick = { expanded = false pinWidget(context, WidgetProvider::class.java) }, modifier = Modifier .padding(4.dp) .size(46.dp) .animateEnterExit(enter = scaleIn(), exit = scaleOut()) ) { Icon(painterResource(R.drawable.ic_bitcoin), stringResource(R.string.add_price_widget)) } } } val rotationAngle by animateFloatAsState( targetValue = if (expanded) 90f else 0f ) FloatingActionButton( onClick = { expanded = !expanded }, modifier = Modifier.rotate(rotationAngle) ) { Icon(painterResource(R.drawable.ic_outline_add_24), stringResource(R.string.add_widget)) } } }
mit
999f54cb6e1e42173e0ae212240b54e2
38.090361
123
0.57975
4.995381
false
false
false
false
tonyofrancis/Fetch
fetch2core/src/main/java/com/tonyodev/fetch2core/FetchCoreUtils.kt
1
13194
@file:JvmName("FetchCoreUtils") package com.tonyodev.fetch2core import android.annotation.SuppressLint import android.content.Context import android.net.Uri import java.io.* import java.math.BigInteger import java.net.CookieManager import java.net.CookiePolicy import java.net.HttpURLConnection import java.security.DigestInputStream import java.security.MessageDigest import java.util.concurrent.TimeUnit import kotlin.math.abs import kotlin.math.ceil const val GET_REQUEST_METHOD = "GET" const val HEAD_REQUEST_METHOD = "HEAD" internal const val HEADER_ACCEPT_RANGE = "Accept-Ranges" internal const val HEADER_ACCEPT_RANGE_LEGACY = "accept-ranges" internal const val HEADER_ACCEPT_RANGE_COMPAT = "AcceptRanges" internal const val HEADER_CONTENT_LENGTH = "content-length" internal const val HEADER_CONTENT_LENGTH_LEGACY = "Content-Length" internal const val HEADER_CONTENT_LENGTH_COMPAT = "ContentLength" internal const val HEADER_TRANSFER_ENCODING = "Transfer-Encoding" internal const val HEADER_TRANSFER_LEGACY = "transfer-encoding" internal const val HEADER_TRANSFER_ENCODING_COMPAT = "TransferEncoding" internal const val HEADER_CONTENT_RANGE = "Content-Range" internal const val HEADER_CONTENT_RANGE_LEGACY = "content-range" internal const val HEADER_CONTENT_RANGE_COMPAT = "ContentRange" fun calculateProgress(downloaded: Long, total: Long): Int { return when { total < 1 -> -1 downloaded < 1 -> 0 downloaded >= total -> 100 else -> ((downloaded.toDouble() / total.toDouble()) * 100).toInt() } } fun calculateEstimatedTimeRemainingInMilliseconds(downloadedBytes: Long, totalBytes: Long, downloadedBytesPerSecond: Long): Long { return when { totalBytes < 1 -> -1 downloadedBytes < 1 -> -1 downloadedBytesPerSecond < 1 -> -1 else -> { val seconds = (totalBytes - downloadedBytes).toDouble() / downloadedBytesPerSecond.toDouble() return abs(ceil(seconds)).toLong() * 1000 } } } fun hasIntervalTimeElapsed(nanoStartTime: Long, nanoStopTime: Long, progressIntervalMilliseconds: Long): Boolean { return TimeUnit.NANOSECONDS .toMillis(nanoStopTime - nanoStartTime) >= progressIntervalMilliseconds } fun getUniqueId(url: String, file: String): Int { return (url.hashCode() * 31) + file.hashCode() } fun getIncrementedFileIfOriginalExists(originalPath: String): File { var file = File(originalPath) var counter = 0 if (file.exists()) { val parentPath = "${file.parent}/" val extension = file.extension val fileName: String = file.nameWithoutExtension while (file.exists()) { ++counter val newFileName = "$fileName ($counter)" file = File("$parentPath$newFileName.$extension") } } createFile(file) return file } fun createFile(file: File) { if (!file.exists()) { if (file.parentFile != null && !file.parentFile.exists()) { if (file.parentFile.mkdirs()) { if (!file.createNewFile()) throw FileNotFoundException("$file $FILE_NOT_FOUND") } else { throw FileNotFoundException("$file $FILE_NOT_FOUND") } } else { if (!file.createNewFile()) throw FileNotFoundException("$file $FILE_NOT_FOUND") } } } fun getFileTempDir(context: Context): String { return "${context.filesDir.absoluteFile}/_fetchData/temp" } fun getFile(filePath: String): File { val file = File(filePath) if (!file.exists()) { if (file.parentFile != null && !file.parentFile.exists()) { if (file.parentFile.mkdirs()) { file.createNewFile() } } else { file.createNewFile() } } return file } fun writeLongToFile(filePath: String, data: Long) { val file = getFile(filePath) if (file.exists()) { val randomAccessFile = RandomAccessFile(file, "rw") try { randomAccessFile.seek(0) randomAccessFile.setLength(0) randomAccessFile.writeLong(data) } catch (e: Exception) { } finally { try { randomAccessFile.close() } catch (e: Exception) { } } } } fun getLongDataFromFile(filePath: String): Long? { val file = getFile(filePath) var data: Long? = null if (file.exists()) { val randomAccessFile = RandomAccessFile(file, "r") try { data = randomAccessFile.readLong() } catch (e: Exception) { } finally { try { randomAccessFile.close() } catch (e: Exception) { } } } return data } //eg: fetchlocal://192.168.0.1:80/45 //eg: fetchlocal://192.168.0.1:80/file.txt fun isFetchFileServerUrl(url: String): Boolean { return try { url.startsWith("fetchlocal://") && getFetchFileServerHostAddress(url).isNotEmpty() && getFetchFileServerPort(url) > -1 } catch (e: Exception) { false } } fun getFetchFileServerPort(url: String): Int { val colonIndex = url.lastIndexOf(":") val modifiedUrl = url.substring(colonIndex + 1, url.length) val firstSeparatorIndex = modifiedUrl.indexOf("/") return if (firstSeparatorIndex == -1) { modifiedUrl.toInt() } else { modifiedUrl.substring(0, firstSeparatorIndex).toInt() } } fun getFetchFileServerHostAddress(url: String): String { val firstIndexOfDoubleSep = url.indexOf("//") val colonIndex = url.lastIndexOf(":") return url.substring(firstIndexOfDoubleSep + 2, colonIndex) } fun getFileResourceIdFromUrl(url: String): String { return Uri.parse(url).lastPathSegment ?: "-1" } //eg: bytes=10- fun getRangeForFetchFileServerRequest(range: String): Pair<Long, Long> { val firstIndex = range.lastIndexOf("=") val lastIndex = range.lastIndexOf("-") val start = range.substring(firstIndex + 1, lastIndex).toLong() val end = try { range.substring(lastIndex + 1, range.length).toLong() } catch (e: Exception) { -1L } return Pair(start, end) } @Suppress("ControlFlowWithEmptyBody") fun getMd5String(bytes: ByteArray, start: Int = 0, length: Int = bytes.size): String { return try { val buffer = ByteArray(kotlin.io.DEFAULT_BUFFER_SIZE) val md = MessageDigest.getInstance("MD5") val inputStream = DigestInputStream(ByteArrayInputStream(bytes, start, length), md) inputStream.use { dis -> while (dis.read(buffer) != -1); } var md5: String = BigInteger(1, md.digest()).toString(16) while (md5.length < 32) { md5 = "0$md5" } md5 } catch (e: Exception) { "" } } @Suppress("ControlFlowWithEmptyBody") fun getFileMd5String(file: String): String? { val contentFile = File(file) return try { val buffer = ByteArray(kotlin.io.DEFAULT_BUFFER_SIZE) val md = MessageDigest.getInstance("MD5") val inputStream = DigestInputStream(FileInputStream(contentFile), md) inputStream.use { dis -> while (dis.read(buffer) != -1); } var md5: String = BigInteger(1, md.digest()).toString(16) while (md5.length < 32) { md5 = "0$md5" } md5 } catch (e: Exception) { null } } fun isParallelDownloadingSupported(code: Int, headers: Map<String, List<String>>): Boolean { return acceptRanges(code, headers) } fun getRequestSupportedFileDownloaderTypes( request: Downloader.ServerRequest, downloader: Downloader<*, *> ): Set<Downloader.FileDownloaderType> { val fileDownloaderTypeSet = mutableSetOf(Downloader.FileDownloaderType.SEQUENTIAL) return try { val response = downloader.execute(request, getSimpleInterruptMonitor()) if (response != null) { if (isParallelDownloadingSupported(response.code, response.responseHeaders)) { fileDownloaderTypeSet.add(Downloader.FileDownloaderType.PARALLEL) } downloader.disconnect(response) } fileDownloaderTypeSet } catch (e: Exception) { fileDownloaderTypeSet } } @SuppressLint("DefaultLocale") fun acceptRanges( code: Int, headers: Map<String, List<String>> ): Boolean { val acceptRangeValue = getHeaderValue( headers, HEADER_ACCEPT_RANGE, HEADER_ACCEPT_RANGE_LEGACY, HEADER_ACCEPT_RANGE_COMPAT ) val transferValue = getHeaderValue( headers, HEADER_TRANSFER_ENCODING, HEADER_TRANSFER_LEGACY, HEADER_TRANSFER_ENCODING_COMPAT ) val contentLength = getContentLengthFromHeader(headers, -1L) val acceptsRanges = code == HttpURLConnection.HTTP_PARTIAL || acceptRangeValue == "bytes" return (contentLength > -1L && acceptsRanges) || (contentLength > -1L && transferValue?.toLowerCase() != "chunked") } fun getContentLengthFromHeader(headers: Map<String, List<String>>, defaultValue: Long): Long { val contentRange = getHeaderValue( headers, HEADER_CONTENT_RANGE, HEADER_CONTENT_RANGE_LEGACY, HEADER_CONTENT_RANGE_COMPAT ) val lastIndexOf = contentRange?.lastIndexOf("/") var contentLength = -1L if (lastIndexOf != null && lastIndexOf != -1 && lastIndexOf < contentRange.length) { contentLength = contentRange.substring(lastIndexOf + 1).toLongOrNull() ?: -1L } if (contentLength == -1L) { contentLength = getHeaderValue( headers, HEADER_CONTENT_LENGTH, HEADER_CONTENT_LENGTH_LEGACY, HEADER_CONTENT_LENGTH_COMPAT )?.toLongOrNull() ?: defaultValue } return contentLength } fun getHeaderValue( headers: Map<String, List<String>>, vararg keys: String ): String? { for (key in keys) { val value = headers[key]?.firstOrNull() if (!value.isNullOrBlank()) { return value } } return null } fun getRequestContentLength(request: Downloader.ServerRequest, downloader: Downloader<*, *>): Long { return try { val response = downloader.execute(request, getSimpleInterruptMonitor()) val headers = response?.responseHeaders ?: emptyMap() val contentLength = getContentLengthFromHeader(headers, -1L) if (response != null) { downloader.disconnect(response) } contentLength } catch (e: Exception) { -1L } } fun isUriPath(path: String): Boolean = path.takeIf { it.isNotEmpty() } ?.let { it.startsWith("content://") || it.startsWith("file://") } ?: false fun getFileUri(path: String): Uri { return when { isUriPath(path) -> Uri.parse(path) else -> Uri.fromFile(File(path)) } } fun deleteFile(file: File): Boolean { return if (file.exists() && file.canWrite()) file.delete() else false } fun renameFile(oldFile: File, newFile: File): Boolean { return oldFile.renameTo(newFile) } fun copyDownloadResponseNoStream(response: Downloader.Response): Downloader.Response { return Downloader.Response(response.code, response.isSuccessful, response.contentLength, null, response.request, response.hash, response.responseHeaders, response.acceptsRanges, response.errorResponse) } fun getDefaultCookieManager(): CookieManager { val cookieManager = CookieManager() cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL) return cookieManager } fun hasAllowedTimeExpired(timeStartedMillis: Long, timeStopMillis: Long, allowedTimeMillis: Long): Boolean { return timeStopMillis - timeStartedMillis >= allowedTimeMillis } fun getRefererFromUrl(url: String): String { return try { val uri = Uri.parse(url) "${uri.scheme}://${uri.authority}" } catch (e: Exception) { "https://google.com" } } fun copyStreamToString(inputStream: InputStream?, closeStream: Boolean = true): String? { return if (inputStream == null) { return null } else { var bufferedReader: BufferedReader? = null try { bufferedReader = BufferedReader(InputStreamReader(inputStream)) val stringBuilder = StringBuilder() var line: String? = bufferedReader.readLine() while (line != null) { stringBuilder.append(line) .append('\n') line = bufferedReader.readLine() } stringBuilder.toString() } catch (e: Exception) { null } finally { if (closeStream) { try { bufferedReader?.close() } catch (e: Exception) { } } } } } fun getSimpleInterruptMonitor() = object : InterruptMonitor { override val isInterrupted: Boolean get() = false }
apache-2.0
c6d971c632a124cf86b75f4a8d3dcc92
30.491647
119
0.625663
4.371769
false
false
false
false
hwki/SimpleBitcoinWidget
bitcoin/src/main/java/com/brentpanther/bitcoinwidget/Coin.kt
1
9761
package com.brentpanther.bitcoinwidget import android.os.Build import android.os.Parcelable import com.brentpanther.bitcoinwidget.R.drawable.* import com.brentpanther.bitcoinwidget.Theme.SOLID import com.brentpanther.bitcoinwidget.Theme.TRANSPARENT import kotlinx.parcelize.Parcelize import java.util.* @Parcelize enum class Coin(val coinName: String, val coinGeckoId: String, private vararg val themes: IconTheme) : Parcelable { CUSTOM("Custom", "", IconTheme(SOLID, ic_placeholder)), ONE_INCH("1inch", "1inch", IconTheme(SOLID, ic_1inch)), AAVE("Aave", "aave", IconTheme(SOLID, ic_aave)), ADA("Cardano", "cardano", IconTheme(SOLID, ic_ada)), ALGO("Algorand", "algorand", IconTheme(SOLID, ic_algo, ic_algo_white)), APE("ApeCoin", "apecoin", IconTheme(SOLID, ic_ape)), ARRR("Pirate Chain", "pirate-chain", IconTheme(SOLID, ic_arrr)), ATOM("Cosmos", "cosmos", IconTheme(SOLID, ic_atom)), AVA("Travala.com", "concierge-io", IconTheme(SOLID, ic_ava)), AVAX("Avalanche","avalanche-2", IconTheme(SOLID, ic_avax, ic_avax_dark)), AXS("Axie Infinity", "axie-infinity", IconTheme(SOLID, ic_axs)), BAL("Balancer", "balancer", IconTheme(SOLID, ic_bal)), BAND("Band Protocol", "band-protocol", IconTheme(SOLID, ic_band_color)), BAT("Basic Attention Token", "basic-attention-token", IconTheme(SOLID, ic_bat)), BCD("Bitcoin Diamond", "bitcoin-diamond", IconTheme(SOLID, ic_bcd, ic_bcd_white)), BCH("Bitcoin Cash", "bitcoin-cash", IconTheme(SOLID, ic_bch, ic_bch_dark)) { override fun getUnits() = listOf(CoinUnit("BCH", 1.0), CoinUnit("mBCH", .001), CoinUnit("μBCH", .000001)) }, BNB("Binance Coin", "binancecoin", IconTheme(SOLID, ic_bnb)), BEST("Bitpanda Ecosystem Token", "bitpanda-ecosystem-token", IconTheme(SOLID, ic_best)), BNT("Bancor Network Token", "bancor", IconTheme(SOLID, ic_bnt)), BSV("Bitcoin SV", "bitcoin-cash-sv", IconTheme(SOLID, ic_bsv, ic_bsv_dark)), BTC("Bitcoin", "bitcoin", IconTheme(SOLID, ic_btc, ic_btc_dark)) { override fun getUnits() = listOf(CoinUnit("BTC", 1.0), CoinUnit("mBTC", .001), CoinUnit("Bit", .000001), CoinUnit("Sat", .00000001)) }, BTG("Bitcoin Gold", "bitcoin-gold", IconTheme(SOLID, ic_btg, ic_btg_dark)), BTM("Bytom", "bytom", IconTheme(SOLID, ic_btm, ic_btm_gray)), BTT("BitTorrent", "bittorrent", IconTheme(SOLID, ic_btt)), CEL("Celsius", "celsius-degree-token", IconTheme(SOLID, ic_cel)), CHZ("Chiliz", "chiliz",IconTheme(SOLID, ic_chz)), COMP("Compound", "compound-coin", IconTheme(SOLID, ic_comp_black, ic_comp_white)), CRO("Crypto.com Coin", "crypto-com-chain", IconTheme(SOLID, ic_cro, ic_cro_white)), CRV("Curve DAO Token", "curve-dao-token", IconTheme(SOLID, ic_crv)), CUBE("Somnium Space CUBEs", "somnium-space-cubes", IconTheme(SOLID, ic_cube_black, ic_cube_white)), DAI("Dai", "dai", IconTheme(SOLID, ic_dai_color)), DASH("Dash", "dash", IconTheme(SOLID, ic_dash, ic_dash_dark)), DCR("Decred", "decred", IconTheme(SOLID, ic_dcr)), DOGE("Dogecoin", "dogecoin", IconTheme(SOLID, ic_doge)), DOT("Polkadot", "polkadot", IconTheme(SOLID, ic_dot_black, ic_dot_white)), EGLD("Elrond", "elrond-erd-2", IconTheme(SOLID, ic_egld_dark, ic_egld_white)), ENJ("Enjin Coin", "enjincoin", IconTheme(SOLID, ic_enj)), EOS("EOS", "eos", IconTheme(SOLID, ic_eos_black, ic_eos_white), IconTheme(TRANSPARENT, ic_eos_white)), ETC("Ethereum Classic", "ethereum-classic", IconTheme(SOLID, ic_etc)), ETH("Ethereum", "ethereum", IconTheme(SOLID, ic_eth)), FIL("Filecoin", "filecoin", IconTheme(SOLID, ic_fil)), FIRO("Firo", "zcoin", IconTheme(SOLID, ic_firo, ic_firo_dark)), FTM("Fantom", "fantom", IconTheme(SOLID, ic_ftm)), FTT("FTX Token", "ftx-token", IconTheme(SOLID, ic_ftt)), GALA("Gala", "gala", IconTheme(SOLID, ic_gala, ic_gala_white)), GNO("Gnosis", "gnosis", IconTheme(SOLID, ic_gno_color)), GNT("Golem", "golem", IconTheme(SOLID, ic_gnt_blue)), GRIN("Grin", "grin", IconTheme(SOLID, ic_grin_color_black)), GRT("The Graph", "the-graph", IconTheme(SOLID, ic_grt)), HBAR("Hedera Hashgraph", "hedera-hashgraph", IconTheme(SOLID, ic_hbar, ic_hbar_white)), HNS("Handshake", "handshake", IconTheme(SOLID, ic_hns, ic_hns_dark)), HT("Huobi Token", "huobi-token", IconTheme(SOLID, ic_ht)), ICX("Icon", "icon", IconTheme(SOLID, ic_icx)), IOTA("Iota", "iota", IconTheme(SOLID, ic_iota, ic_iota_white)), KAVA("Kava", "kava", IconTheme(SOLID, ic_kava)), KMD("Komodo", "komodo", IconTheme(SOLID, ic_kmd)), KNC("Kyber Network", "kyber-network", IconTheme(SOLID, ic_knc_color)), KSM("Kusama", "kusama", IconTheme(SOLID, ic_ksm_black, ic_ksm_white)), LEO("LEO Token", "leo-token", IconTheme(SOLID, ic_leo)), LINK("ChainLink", "chainlink", IconTheme(SOLID, ic_link)), LRC("Loopring", "loopring", IconTheme(SOLID, ic_lrc)), LSK("Lisk", "lisk", IconTheme(SOLID, ic_lsk)), LTC("Litecoin", "litecoin", IconTheme(SOLID, ic_ltc)) { override fun getUnits() = listOf(CoinUnit("LTC", 1.0), CoinUnit("mŁ", .001), CoinUnit("μŁ", .0000001)) }, LTO("LTO Network", "lto-network", IconTheme(SOLID, ic_lto)), LUNA("Terra", "terra-luna-2", IconTheme(SOLID, ic_luna)), LUNC("Terra Luna Classic", "terra-luna", IconTheme(SOLID, ic_lunc)), MANA("Decentraland", "decentraland", IconTheme(SOLID, ic_mana)), MATIC("Polygon", "matic-network", IconTheme(SOLID, ic_matic)), MCO("MCO", "monaco", IconTheme(SOLID, ic_mco, ic_mco_white)), MKR("Maker", "maker", IconTheme(SOLID, ic_mkr)), MLN("Melon", "melon", IconTheme(SOLID, ic_mln)), NANO("Nano", "nano", IconTheme(SOLID, ic_nano)), NEAR("Near", "near", IconTheme(SOLID, ic_near_black, ic_near_white)), NEO("NEO", "neo", IconTheme(SOLID, ic_neo)), NRG("Energi", "energi", IconTheme(SOLID, ic_nrg)), OKB("OKB", "okb", IconTheme(SOLID, ic_okb)), OMG("OMG", "omisego", IconTheme(SOLID, ic_omg)), ONT("Ontology", "ontology", IconTheme(SOLID, ic_ont)), PAX("Paxos Standard", "paxos-standard", IconTheme(SOLID, ic_pax)), PAXG("PAX Gold", "pax-gold", IconTheme(SOLID, ic_paxg_color)), POWR("Power Ledger", "power-ledger", IconTheme(SOLID, ic_powr_color)), PPC("Peercoin", "peercoin", IconTheme(SOLID, ic_ppc)), QTUM("Qtum", "qtum", IconTheme(SOLID, ic_qtum)), RDD("Reddcoin", "reddcoin", IconTheme(SOLID, ic_rdd)), REN("REN", "republic-protocol", IconTheme(SOLID, ic_ren)), REP("Augur", "augur", IconTheme(SOLID, ic_rep)), RUNE("THORChain", "thorchain", IconTheme(SOLID, ic_rune)), RVN("Ravencoin", "ravencoin", IconTheme(SOLID, ic_rvn)), SAND("The Sandbox", "the-sandbox", IconTheme(SOLID, ic_sand)), SHIB("Shiba Inu", "shiba-inu", IconTheme(SOLID, ic_shib)), SNX("Synthetix Network Token", "havven", IconTheme(SOLID, ic_snx)), SOL("Solana", "solana", IconTheme(SOLID, ic_sol)), STORJ("Storj", "storj", IconTheme(SOLID, ic_storj)), SUSHI("Sushi", "sushi", IconTheme(SOLID, ic_sushi)), THETA("Theta Network", "theta-token", IconTheme(SOLID, ic_theta)), TRX("Tron", "tron", IconTheme(SOLID, ic_trx)), UMA("UMA", "uma", IconTheme(SOLID, ic_uma)), UNI("Uniswap", "uniswap", IconTheme(SOLID, ic_uni)), VET("VeChain", "vechain", IconTheme(SOLID, ic_vet)), VTC("Vertcoin", "vertcoin", IconTheme(SOLID, ic_vtc)), WAVES("Waves", "waves", IconTheme(SOLID, ic_waves)), WBTC("Wrapped Bitcoin", "wrapped-bitcoin", IconTheme(SOLID, ic_wbtc)), XAUT("Tether Gold", "tether-gold", IconTheme(SOLID, ic_xaut_color)), XEM("NEM", "nem", IconTheme(SOLID, ic_xem, ic_xem_dark_gray)), XLM("Stellar", "stellar", IconTheme(SOLID, ic_xlm, ic_xlm_white)), XMR("Monero", "monero", IconTheme(SOLID, ic_xmr), IconTheme(TRANSPARENT, ic_xmr, dark = ic_xmr_dark)), XRP("Ripple", "ripple", IconTheme(SOLID, ic_xrp_black, ic_xrp_white), IconTheme(TRANSPARENT, ic_xrp_white)), XTZ("Tezos", "tezos", IconTheme(SOLID, ic_xtz)), XVG("Verge", "verge", IconTheme(SOLID, ic_xvg)), XYM("Symbol", "symbol", IconTheme(SOLID, ic_xym)), YFI("yearn.finance", "yearn-finance", IconTheme(SOLID, ic_yfi)), ZEC("Zcash", "zcash", IconTheme(SOLID, ic_zec, ic_zec_dark), IconTheme(TRANSPARENT, ic_zec)), ZIL("Zilliqa", "zilliqa", IconTheme(SOLID, ic_zil)), ZRX("0x", "0x", IconTheme(SOLID, ic_zrx_black, ic_zrx_white)); open fun getUnits() = emptyList<CoinUnit>() fun getUnitAmount(text: String) = getUnits().firstOrNull { it.text == text }?.amount ?: 1.0 fun getIcon(theme: Theme, dark: Boolean): Int { val iconTheme = themes.firstOrNull { it.theme == theme } ?: themes.first() return if (dark) iconTheme.dark else iconTheme.light } fun getSymbol() = if (this == ONE_INCH) "1INCH" else name companion object { internal var COIN_NAMES: SortedSet<String> = values().map { it.name }.toSortedSet(String.CASE_INSENSITIVE_ORDER) fun getByName(name: String): Coin? { if (name == "1INCH") return ONE_INCH return Coin.runCatching { valueOf(name) }.getOrNull() } fun getVirtualCurrencyFormat(currency: String, hideSymbol: Boolean): String { if (hideSymbol) { return "#,###" } return when (currency) { "BTC" -> // bitcoin symbol added in Oreo if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) "₿ #,###" else "Ƀ #,###" "LTC" -> "Ł #,###" "DOGE" -> "Ð #,###" else -> "#,### $currency" } } } } @Parcelize class CoinUnit(val text: String, val amount: Double) : Parcelable
mit
f5ea041730cfad9ea14652dac6c53da8
54.409091
120
0.636792
2.916268
false
false
false
false
wakim/esl-pod-client
app/src/main/java/br/com/wakim/eslpodclient/data/interactor/PodcastDbInteractor.kt
2
8258
package br.com.wakim.eslpodclient.data.interactor import android.database.sqlite.SQLiteDatabase import br.com.wakim.eslpodclient.Application import br.com.wakim.eslpodclient.data.db.DatabaseOpenHelper import br.com.wakim.eslpodclient.data.db.database import br.com.wakim.eslpodclient.data.model.* import br.com.wakim.eslpodclient.util.extensions.LongAnyParser import br.com.wakim.eslpodclient.util.extensions.toContentValues import org.jetbrains.anko.db.* import org.threeten.bp.ZonedDateTime class PodcastDbInteractor(private val app: Application) { fun insertPodcast(podcastItem: PodcastItem) { insertPodcasts(arrayListOf(podcastItem)) } fun insertPodcasts(podcasts: List<PodcastItem>) { app.database .use { podcasts.asSequence().forEach { podcastItem -> with (podcastItem) { insertWithOnConflict( DatabaseOpenHelper.PODCASTS_TABLE_NAME, null, arrayOf( "remote_id" to remoteId, "title" to title, "mp3_url" to mp3Url, "blurb" to blurb, "date" to date?.toEpochDay(), "tags" to tags, "type" to type ).toContentValues(), SQLiteDatabase.CONFLICT_IGNORE) } } } } fun getPodcasts(page: Int, limit: Int): List<PodcastItem> = app.database .use { select(DatabaseOpenHelper.PODCASTS_TABLE_NAME) .columns( "remote_id", "title", "mp3_url", "blurb", "date", "tags", "type" ) .orderBy("_id", SqlOrderDirection.ASC) .limit(page * limit, limit) .exec { parseList(PodcastItemRowParser()) } } fun insertLastSeekPos(remoteId: Long, seekPos: Int): Boolean = app.database .use { update(DatabaseOpenHelper.PODCASTS_TABLE_NAME, "last_seek_pos" to seekPos) .where("remote_id = {remoteId}", "remoteId" to remoteId) .exec() > 0 } fun getLastSeekPos(remoteId: Long): Any? = app.database .use { select(DatabaseOpenHelper.PODCASTS_TABLE_NAME) .column("last_seek_pos") .where("remote_id = {remoteId}", "remoteId" to remoteId) .exec { parseOpt(LongAnyParser()) } } fun getPodcastDetail(podcastItem: PodcastItem): PodcastItemDetail? = app.database .use { select(DatabaseOpenHelper.PODCASTS_TABLE_NAME) .columns("remote_id", "title", "script", "type", "slow_index", "explanation_index", "normal_index") .where("remote_id = {remoteId} AND script IS NOT NULL", "remoteId" to podcastItem.remoteId) .exec { parseOpt(PodcastItemDetailRowParser()) } } fun insertPodcastDetail(podcastItemDetail: PodcastItemDetail): Boolean = app.database .use { with (podcastItemDetail) { update( DatabaseOpenHelper.PODCASTS_TABLE_NAME, arrayOf( "script" to script, "slow_index" to podcastItemDetail.seekPos?.slow, "explanation_index" to podcastItemDetail.seekPos?.explanation, "normal_index" to podcastItemDetail.seekPos?.normal ).toContentValues(), "remote_id = ?", arrayOf(remoteId.toString()) ) > 0 } } fun addFavorite(podcastItem: PodcastItem): Boolean = app.database .use { val favoritedDate = ZonedDateTime.now().toEpochSecond() with (podcastItem) { update(DatabaseOpenHelper.PODCASTS_TABLE_NAME, "favorited_date" to favoritedDate) .where("remote_id = {remoteId}", "remoteId" to remoteId) .exec() > 0 } } fun removeFavorite(podcastItem: PodcastItem): Boolean = app.database .use { update(DatabaseOpenHelper.PODCASTS_TABLE_NAME, arrayOf("favorited_date" to null).toContentValues(), "remote_id = ?", arrayOf(podcastItem.remoteId.toString()) ) > 0 } fun getFavorites(page: Int, limit: Int): List<PodcastItem> = app.database .use { select(DatabaseOpenHelper.PODCASTS_TABLE_NAME) .columns( "remote_id", "title", "mp3_url", "blurb", "date", "tags", "type" ) .where("favorited_date IS NOT NULL") .orderBy("date", SqlOrderDirection.DESC) .limit(page * limit, limit) .exec { parseList(PodcastItemRowParser()) } } fun getDownloaded(page: Int, limit: Int): List<PodcastItem> = app.database .use { select("${DatabaseOpenHelper.PODCASTS_TABLE_NAME} p") .columns( "remote_id", "title", "mp3_url", "blurb", "date", "tags", "type" ) .where("EXISTS (SELECT 1 FROM ${DatabaseOpenHelper.DOWNLOADS_TABLE_NAME} d WHERE d.remote_id = p.remote_id AND d.status = ${DownloadStatus.DOWNLOADED})") .orderBy("date", SqlOrderDirection.DESC) .limit(page * limit, limit) .exec { parseList(PodcastItemRowParser()) } } fun clearPodcasts() { app.database.use { delete(DatabaseOpenHelper.PODCASTS_TABLE_NAME) } } }
apache-2.0
39b9ae03ab9bda3d2c3aabfb02a0d286
45.139665
185
0.378421
6.548771
false
false
false
false
googlemaps/android-maps-rx
places-rx/src/main/java/com/google/maps/android/rx/places/PlacesClientFetchPlaceSingle.kt
1
1777
package com.google.maps.android.rx.places import com.google.android.libraries.places.api.model.Place import com.google.android.libraries.places.api.net.FetchPlaceRequest import com.google.android.libraries.places.api.net.FetchPlaceResponse import com.google.android.libraries.places.api.net.PlacesClient import com.google.maps.android.rx.places.internal.MainThreadTaskSingle import com.google.maps.android.rx.places.internal.TaskCompletionListener import io.reactivex.rxjava3.core.Single /** * Fetches a [Place] and emits the result in a [Single]. * * @param placeId the ID of the place to be requested * @param placeFields the fields of the place to be requested * @param actions additional actions to apply to the [FetchPlaceRequest.Builder] * @return a [Single] emitting the response */ public fun PlacesClient.fetchPlace( placeId: String, placeFields: List<Place.Field>, actions: FetchPlaceRequest.Builder.() -> Unit = {} ): Single<FetchPlaceResponse> = PlacesClientFetchPlaceSingle( placesClient = this, placeId = placeId, placeFields = placeFields, actions = actions ) private class PlacesClientFetchPlaceSingle( private val placesClient: PlacesClient, private val placeId: String, private val placeFields: List<Place.Field>, private val actions: FetchPlaceRequest.Builder.() -> Unit ) : MainThreadTaskSingle<FetchPlaceResponse>() { override fun invokeRequest(listener: TaskCompletionListener<FetchPlaceResponse>) { val request = FetchPlaceRequest.builder(placeId, placeFields) .apply(actions) .setCancellationToken(listener.cancellationTokenSource.token) .build() placesClient.fetchPlace(request).addOnCompleteListener(listener) } }
apache-2.0
6913b9af331abf1b80f0c8e3610d30c5
39.409091
86
0.752392
4.171362
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/magic/DisableBoostExecutor.kt
1
1358
package net.perfectdreams.loritta.morenitta.commands.vanilla.magic import net.perfectdreams.loritta.morenitta.utils.NitroBoostUtils import net.perfectdreams.loritta.morenitta.api.commands.CommandContext import net.perfectdreams.loritta.morenitta.messages.LorittaReply import net.perfectdreams.loritta.morenitta.platform.discord.legacy.commands.DiscordCommandContext import net.perfectdreams.loritta.morenitta.platform.discord.legacy.entities.jda.JDAUser object DisableBoostExecutor : LoriToolsCommand.LoriToolsExecutor { override val args = "donation boost disable <user>" override fun executes(): suspend CommandContext.() -> Boolean = task@{ if (this.args.getOrNull(0) != "donation") return@task false if (this.args.getOrNull(1) != "boost") return@task false if (this.args.getOrNull(2) != "disable") return@task false val context = this.checkType<DiscordCommandContext>(this) val user = context.user(3) ?: run { context.sendMessage("Usuário inexistente!") return@task true } user as JDAUser val member = context.discordMessage.guild.getMember(user.handle) ?: run { context.sendMessage("Usuário não está na guild atual!") return@task true } NitroBoostUtils.onBoostDeactivate(loritta, member) context.reply( LorittaReply( "Vantagens de Booster Desativadas!" ) ) return@task true } }
agpl-3.0
b5e6901c5175a3658bccf2e2a9d9ce12
31.261905
97
0.765879
3.679348
false
false
false
false
Haldir65/AndroidRepo
otherprojects/_008_textview/app/src/main/java/com/me/harris/textviewtest/MainActivity.kt
1
4344
package com.me.harris.textviewtest import android.app.Activity import android.content.Intent import android.graphics.Rect import android.os.Bundle import android.support.v4.view.PagerAdapter import android.support.v7.app.AppCompatActivity import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.View import com.me.harris.textviewtest.clippath.CustomDrawingActivity import com.me.harris.textviewtest.config.UpdatingConfigActivity import com.me.harris.textviewtest.constraint.ConstraintActivity import com.me.harris.textviewtest.coordinated.CoordinateActivity import com.me.harris.textviewtest.edittextpassword.EditTextActivity import com.me.harris.textviewtest.flowable.FlowableMainActivity import com.me.harris.textviewtest.interfaces.ItemClickListener import com.me.harris.textviewtest.jsonfast.FastJsonDemoActivity import com.me.harris.textviewtest.linebreak.TextLineBreakActivity import com.me.harris.textviewtest.mail.SendMailActivity import com.me.harris.textviewtest.progressbarstuyle.ProgressBarStyleActivity import com.me.harris.textviewtest.round_img.RoundBgActivity import com.me.harris.textviewtest.shadow_layer_list.ShadowLayerListActivity import com.me.harris.textviewtest.strikeThrough.StrikeThroughActivity import com.me.harris.textviewtest.ui.CustomAdapter import com.me.harris.textviewtest.ui._001_retrofit.RetrofitSampleActivity import com.me.harris.textviewtest.ui._002_bitmap.BitmapActivity import com.me.harris.textviewtest.ui._003_transform.GlideTransformActivity import com.me.harris.textviewtest.view_pager.PagerActivity import kotlinx.android.synthetic.main.activity_recycler_view.* class MainActivity :AppCompatActivity(), ItemClickListener { lateinit var mAdapter: CustomAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_recycler_view) initAdapter() } private fun initAdapter() { val userList = mutableListOf<Triple<String,Int,Class<out Activity>>>( Triple("RoundedBg",17,RoundBgActivity::class.java), Triple("BitmapSample",1, BitmapActivity::class.java), Triple("Retrofit",2,RetrofitSampleActivity::class.java), Triple("RoundCorner",3,GlideTransformActivity::class.java), Triple("Constraint",4,ConstraintActivity::class.java), Triple("Flowable",5,FlowableMainActivity::class.java), Triple("ClipPath",6,CustomDrawingActivity::class.java), Triple("Coordinate",7,CoordinateActivity::class.java), Triple("ClipPath",8,CustomDrawingActivity::class.java), Triple("Locale",9,UpdatingConfigActivity::class.java), Triple("Mail",10,SendMailActivity::class.java), Triple("pager",11,PagerActivity::class.java), Triple("EditText",12,EditTextActivity::class.java), Triple("progressbar",13,ProgressBarStyleActivity::class.java), Triple("shadow",14,ShadowLayerListActivity::class.java), Triple("Strike",15,StrikeThroughActivity::class.java), Triple("LineBreak",16,TextLineBreakActivity::class.java), Triple("JSOSON",17,FastJsonDemoActivity::class.java) ).apply { // this.addAll(this) // this.addAll(this) // this.addAll(this) // this.addAll(this) // this.addAll(this) } mAdapter = CustomAdapter(userList,this) recyclerView1.adapter = mAdapter recyclerView1.layoutManager = LinearLayoutManager(this) recyclerView1.addItemDecoration(object : RecyclerView.ItemDecoration(){ override fun getItemOffsets(outRect: Rect?, view: View?, parent: RecyclerView?, state: RecyclerView.State?) { super.getItemOffsets(outRect, view, parent, state) outRect?.set(12,5,12,5) } }) } override fun onItemClick(position: Int, view: View) { val target = mAdapter.userList[position].third val intent = Intent(this,target) startActivity(intent) // Toast.makeText(this,"点击了 $position 以及View的id 是 ${view.id}",Toast.LENGTH_SHORT).show() } }
apache-2.0
4a68afef42fc018b0ed7f38153261248
46.076087
121
0.7194
4.34739
false
true
false
false
luoyuan800/NeverEnd
dataModel/src/cn/luo/yuan/maze/model/goods/types/HalfSafe.kt
1
2037
package cn.luo.yuan.maze.model.goods.types import cn.luo.yuan.maze.listener.LostListener import cn.luo.yuan.maze.model.HarmAble import cn.luo.yuan.maze.model.Hero import cn.luo.yuan.maze.model.NameObject import cn.luo.yuan.maze.model.goods.Goods import cn.luo.yuan.maze.model.goods.GoodsProperties import cn.luo.yuan.maze.model.skill.SkillParameter import cn.luo.yuan.maze.service.BattleMessage import cn.luo.yuan.maze.service.InfoControlInterface import cn.luo.yuan.maze.service.ListenerService import cn.luo.yuan.maze.utils.Field import cn.luo.yuan.maze.utils.Field.Companion.SERVER_VERSION import cn.luo.yuan.maze.utils.StringUtils /** * Created by gluo on 5/5/2017. */ class HalfSafe() : Goods(){ companion object { private const val serialVersionUID: Long = Field.SERVER_VERSION } override fun canLocalSell(): Boolean { return true } override fun load(properties: GoodsProperties) { ListenerService.registerListener(HalfSafeListener) } override var price = 500000L override var desc = "拥有这个物品可以在被击败时只掉到当前层数的一半,你和你宠物半血复活。" override var name = "折扣"; override fun use(properties: GoodsProperties): Boolean { if (super.use(properties)) { properties.hero.hp = properties.hero.maxHp/2 for (pet in properties.hero.pets) { pet.hp = pet.maxHp/2 } return true } else { return false } } val HalfSafeListener = object : LostListener { override fun lost(loser: Hero, winner: HarmAble, context: InfoControlInterface) { val p = GoodsProperties(loser); if(use(p)){ val maze = context.maze maze.level /= 2 context.addMessage("${loser.displayName}使用了 $name 掉到${maze.level/2}后复活了!") } } override fun getKey(): String? { return "HalfSafe"; } } }
bsd-3-clause
1c4671cb553fd19442c1af4dbb86c46b
29.40625
90
0.65347
3.669811
false
false
false
false
ngageoint/mage-android
mage/src/main/java/mil/nga/giat/mage/login/idp/IdpLoginFragment.kt
1
3476
package mil.nga.giat.mage.login.idp import android.app.Activity import android.content.Intent import android.content.SharedPreferences import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import dagger.hilt.android.AndroidEntryPoint import mil.nga.giat.mage.R import mil.nga.giat.mage.databinding.FragmentAuthenticationIdpBinding import mil.nga.giat.mage.login.LoginViewModel import mil.nga.giat.mage.login.idp.IdpLoginActivity.Companion.EXTRA_IDP_TOKEN import org.json.JSONObject import javax.inject.Inject @AndroidEntryPoint class IdpLoginFragment : Fragment() { companion object { private const val EXTRA_IDP_RESULT = 100 private const val EXTRA_IDP_STRATEGY = "EXTRA_IDP_STRATEGY" private const val EXTRA_IDP_STRATEGY_NAME = "EXTRA_IDP_STRATEGY_NAME" fun newInstance(strategyName: String, strategy: JSONObject): IdpLoginFragment { return IdpLoginFragment().apply { arguments = Bundle().apply { putString(EXTRA_IDP_STRATEGY, strategy.toString()) putString(EXTRA_IDP_STRATEGY_NAME, strategyName) } } } } private lateinit var binding: FragmentAuthenticationIdpBinding private lateinit var viewModel: LoginViewModel @Inject protected lateinit var preferences: SharedPreferences private lateinit var strategy: JSONObject private lateinit var strategyName: String override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) require(arguments?.getString(EXTRA_IDP_STRATEGY) != null) {"EXTRA_IDP_STRATEGY is required to launch IdpLoginFragment"} require(arguments?.getString(EXTRA_IDP_STRATEGY_NAME) != null) {"EXTRA_IDP_STRATEGY_NAME is required to launch IdpLoginFragment"} strategy = JSONObject(requireArguments().getString(EXTRA_IDP_STRATEGY)!!) strategyName = requireArguments().getString(EXTRA_IDP_STRATEGY_NAME)!! } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) viewModel = activity?.run { ViewModelProvider(this).get(LoginViewModel::class.java) } ?: throw Exception("Invalid Activity") } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { binding = FragmentAuthenticationIdpBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.authenticationButton.bind(strategy) binding.authenticationButton.setOnClickListener { idpLogin() } } private fun idpLogin() { val serverUrl = preferences.getString(getString(R.string.serverURLKey), getString(R.string.serverURLDefaultValue))!! val intent = IdpLoginActivity.intent(context, serverUrl, strategyName) startActivityForResult(intent, EXTRA_IDP_RESULT) } override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?) { if (requestCode == EXTRA_IDP_RESULT && resultCode == Activity.RESULT_OK) { val token = intent?.getStringExtra(EXTRA_IDP_TOKEN) authorize(token) } } private fun authorize(token: String?) { viewModel.authorize(strategyName, token ?: "") } }
apache-2.0
d5d91aa182e976c5347c89952ca78d26
35.989362
135
0.739931
4.543791
false
false
false
false
jiangkang/KTools
buildSrc/src/main/kotlin/Versions.kt
1
175
const val vCompileSdkVersion = 30 const val vBuildToolsVersion = "30.0.2" const val vNdkVersion = "21.3.6528147" const val vMinSdkVersion = 26 const val vTargetSdkVersion = 30
mit
5de929e0c6d0f9624dbe234bbacec3c4
34.2
39
0.788571
3.301887
false
false
false
false
wireapp/wire-android
app/src/main/kotlin/com/waz/zclient/feature/backup/conversations/ConversationRolesBackupDataSource.kt
1
1494
package com.waz.zclient.feature.backup.conversations import com.waz.zclient.core.extension.empty import com.waz.zclient.feature.backup.BackUpDataMapper import com.waz.zclient.feature.backup.BackUpDataSource import com.waz.zclient.feature.backup.BackUpIOHandler import com.waz.zclient.storage.db.conversations.ConversationRoleActionEntity import kotlinx.serialization.Serializable import java.io.File @Serializable data class ConversationRoleActionBackUpModel( val label: String = String.empty(), val action: String = String.empty(), val convId: String = String.empty() ) class ConversationRoleBackupMapper : BackUpDataMapper<ConversationRoleActionBackUpModel, ConversationRoleActionEntity> { override fun fromEntity(entity: ConversationRoleActionEntity) = ConversationRoleActionBackUpModel(label = entity.label, action = entity.action, convId = entity.convId) override fun toEntity(model: ConversationRoleActionBackUpModel) = ConversationRoleActionEntity(label = model.label, action = model.action, convId = model.convId) } class ConversationRolesBackupDataSource( override val databaseLocalDataSource: BackUpIOHandler<ConversationRoleActionEntity, Unit>, override val backUpLocalDataSource: BackUpIOHandler<ConversationRoleActionBackUpModel, File>, override val mapper: BackUpDataMapper<ConversationRoleActionBackUpModel, ConversationRoleActionEntity> ) : BackUpDataSource<ConversationRoleActionBackUpModel, ConversationRoleActionEntity>()
gpl-3.0
557d0f076aa4752af51bac3dc1847963
48.8
120
0.828648
4.834951
false
false
false
false
macrat/RuuMusic
app/src/main/java/jp/blanktar/ruumusic/util/RuuClient.kt
1
3965
package jp.blanktar.ruumusic.util import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.os.Build import jp.blanktar.ruumusic.service.RuuService class RuuClient(val context: Context) { @JvmField var status = PlayingStatus() private val receiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { when (intent.action) { RuuService.ACTION_STATUS -> onReceiveStatus(intent) RuuService.ACTION_EQUALIZER_INFO -> eventListener?.onEqualizerInfo(EqualizerInfo(intent)) RuuService.ACTION_FAILED_PLAY -> { onReceiveStatus(intent) eventListener?.onFailedPlay(intent.getStringExtra("path")!!) } RuuService.ACTION_NOT_FOUND -> eventListener?.onMusicNotFound(intent.getStringExtra("path")!!) } } } fun release() { eventListener = null } private fun intent(action: String) = Intent(context, RuuService::class.java).setAction(action) private fun send(i: Intent) = if (Build.VERSION.SDK_INT >= 26) context.startForegroundService(i) else context.startService(i) var eventListener: EventListener? = null set(listener) { if (listener != null && field == null) { val intentFilter = IntentFilter() intentFilter.addAction(RuuService.ACTION_STATUS) intentFilter.addAction(RuuService.ACTION_EQUALIZER_INFO) intentFilter.addAction(RuuService.ACTION_FAILED_PLAY) intentFilter.addAction(RuuService.ACTION_NOT_FOUND) try { context.unregisterReceiver(receiver) } catch (e: IllegalArgumentException) { } context.registerReceiver(receiver, intentFilter) } if (listener == null && field != null) { context.unregisterReceiver(receiver) } field = listener } fun play() { send(intent(RuuService.ACTION_PLAY)) } fun play(file: RuuFile) { send(intent(RuuService.ACTION_PLAY).putExtra("path", file.fullPath)) } fun playRecursive(dir: RuuDirectory) { send(intent(RuuService.ACTION_PLAY_RECURSIVE).putExtra("path", dir.fullPath)) } fun playSearch(dir: RuuDirectory, query: String) { send(intent(RuuService.ACTION_PLAY_SEARCH) .putExtra("path", dir.fullPath) .putExtra("query", query)) } fun pause() { send(intent(RuuService.ACTION_PAUSE)) } fun pauseTransient() { send(intent(RuuService.ACTION_PAUSE_TRANSIENT)) } fun playPause() { send(intent(RuuService.ACTION_PLAY_PAUSE)) } fun seek(newtime: Int) { send(intent(RuuService.ACTION_SEEK).putExtra("newtime", newtime)) } fun next() { send(intent(RuuService.ACTION_NEXT)) } fun prev() { send(intent(RuuService.ACTION_PREV)) } fun repeat(mode: RepeatModeType) { send(intent(RuuService.ACTION_REPEAT).putExtra("mode", mode.name)) } fun shuffle(enabled: Boolean) { send(intent(RuuService.ACTION_SHUFFLE).putExtra("mode", enabled)) } fun ping() { context.startService(intent(RuuService.ACTION_PING)) } fun requestEqualizerInfo() { send(intent(RuuService.ACTION_REQUEST_EQUALIZER_INFO)) } fun onReceiveStatus(intent: Intent) { status = PlayingStatus(context, intent) eventListener?.onUpdatedStatus(status) } open class EventListener { open fun onUpdatedStatus(status: PlayingStatus) {} open fun onEqualizerInfo(info: EqualizerInfo) {} open fun onFailedPlay(path: String) {} open fun onMusicNotFound(path: String) {} } }
mit
91d05b68e343a01c02a60858cb297e44
30.220472
129
0.620933
4.300434
false
false
false
false
cyq7on/DataStructureAndAlgorithm
Project/Practice/src/com/cyq7on/leetcode/linklist/kotlin/MergeKSortedLists.kt
1
479
package com.cyq7on.leetcode.linklist.kotlin class MergeKSortedLists { fun mergeKLists(lists: Array<ListNode>): ListNode { return lists[0] } } fun main() { val mergeKSortedLists = MergeKSortedLists() val listNode1 = ListNode(intArrayOf(1, 4, 5)) val listNode2 = ListNode(intArrayOf(1, 3, 4)) val listNode3 = ListNode(intArrayOf(2, 6)) val lists = arrayOf(listNode1, listNode2, listNode3) println(mergeKSortedLists.mergeKLists(lists)) }
apache-2.0
10300d97de5dbc219d627613aad91d3d
25.611111
56
0.701461
3.421429
false
false
false
false
moezbhatti/qksms
presentation/src/main/java/com/moez/QKSMS/feature/settings/swipe/SwipeActionsPresenter.kt
3
3289
/* * 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.feature.settings.swipe import android.content.Context import androidx.annotation.DrawableRes import com.moez.QKSMS.R import com.moez.QKSMS.common.base.QkPresenter import com.moez.QKSMS.util.Preferences import com.uber.autodispose.android.lifecycle.scope import com.uber.autodispose.autoDisposable import io.reactivex.rxkotlin.plusAssign import io.reactivex.rxkotlin.withLatestFrom import javax.inject.Inject class SwipeActionsPresenter @Inject constructor( context: Context, private val prefs: Preferences ) : QkPresenter<SwipeActionsView, SwipeActionsState>(SwipeActionsState()) { init { val actionLabels = context.resources.getStringArray(R.array.settings_swipe_actions) disposables += prefs.swipeRight.asObservable() .subscribe { action -> newState { copy(rightLabel = actionLabels[action], rightIcon = iconForAction(action)) } } disposables += prefs.swipeLeft.asObservable() .subscribe { action -> newState { copy(leftLabel = actionLabels[action], leftIcon = iconForAction(action)) } } } override fun bindIntents(view: SwipeActionsView) { super.bindIntents(view) view.actionClicks() .map { action -> when (action) { SwipeActionsView.Action.RIGHT -> prefs.swipeRight.get() SwipeActionsView.Action.LEFT -> prefs.swipeLeft.get() } } .autoDisposable(view.scope()) .subscribe(view::showSwipeActions) view.actionSelected() .withLatestFrom(view.actionClicks()) { actionId, action -> when (action) { SwipeActionsView.Action.RIGHT -> prefs.swipeRight.set(actionId) SwipeActionsView.Action.LEFT -> prefs.swipeLeft.set(actionId) } } .autoDisposable(view.scope()) .subscribe() } @DrawableRes private fun iconForAction(action: Int) = when (action) { Preferences.SWIPE_ACTION_ARCHIVE -> R.drawable.ic_archive_white_24dp Preferences.SWIPE_ACTION_DELETE -> R.drawable.ic_delete_white_24dp Preferences.SWIPE_ACTION_BLOCK -> R.drawable.ic_block_white_24dp Preferences.SWIPE_ACTION_CALL -> R.drawable.ic_call_white_24dp Preferences.SWIPE_ACTION_READ -> R.drawable.ic_check_white_24dp Preferences.SWIPE_ACTION_UNREAD -> R.drawable.ic_markunread_black_24dp else -> 0 } }
gpl-3.0
20d026cb1b3837f71751b2997b0e9b2c
39.121951
128
0.664336
4.37367
false
false
false
false
talhacohen/android
app/src/main/java/com/etesync/syncadapter/AccountUpdateService.kt
1
3712
/* * Copyright © 2013 – 2016 Ricki Hirner (bitfire web engineering). * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html */ package com.etesync.syncadapter import android.accounts.AccountManager import android.annotation.SuppressLint import android.app.Service import android.content.Intent import android.os.Binder import android.os.IBinder import at.bitfire.vcard4android.ContactsStorageException import com.etesync.syncadapter.model.ServiceEntity import com.etesync.syncadapter.resource.LocalAddressBook import java.lang.ref.WeakReference import java.util.* import java.util.logging.Level class AccountUpdateService : Service() { private val binder = InfoBinder() private val runningRefresh = HashSet<Long>() private val refreshingStatusListeners = LinkedList<WeakReference<RefreshingStatusListener>>() override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { if (intent != null) { val action = intent.action when (action) { ACTION_ACCOUNTS_UPDATED -> cleanupAccounts() } } return Service.START_NOT_STICKY } /* BOUND SERVICE PART for communicating with the activities */ override fun onBind(intent: Intent): IBinder? { return binder } interface RefreshingStatusListener { fun onDavRefreshStatusChanged(id: Long, refreshing: Boolean) } inner class InfoBinder : Binder() { fun isRefreshing(id: Long): Boolean { return runningRefresh.contains(id) } fun addRefreshingStatusListener(listener: RefreshingStatusListener, callImmediate: Boolean) { refreshingStatusListeners.add(WeakReference(listener)) if (callImmediate) for (id in runningRefresh) listener.onDavRefreshStatusChanged(id, true) } fun removeRefreshingStatusListener(listener: RefreshingStatusListener) { val iterator = refreshingStatusListeners.iterator() while (iterator.hasNext()) { val item = iterator.next().get() if (listener == item) iterator.remove() } } } /* ACTION RUNNABLES which actually do the work */ @SuppressLint("MissingPermission") internal fun cleanupAccounts() { App.log.info("Cleaning up orphaned accounts") val accountNames = LinkedList<String>() val am = AccountManager.get(this) for (account in am.getAccountsByType(App.accountType)) { accountNames.add(account.name) } val data = (application as App).data // delete orphaned address book accounts for (addrBookAccount in am.getAccountsByType(App.addressBookAccountType)) { val addressBook = LocalAddressBook(this, addrBookAccount, null) try { if (!accountNames.contains(addressBook.mainAccount.name)) addressBook.delete() } catch (e: ContactsStorageException) { App.log.log(Level.SEVERE, "Couldn't get address book main account", e) } } if (accountNames.isEmpty()) { data.delete(ServiceEntity::class.java).get().value() } else { data.delete(ServiceEntity::class.java).where(ServiceEntity.ACCOUNT.notIn(accountNames)).get().value() } } companion object { val ACTION_ACCOUNTS_UPDATED = "accountsUpdated" } }
gpl-3.0
08730662c4a12f534e572c1467c61670
29.908333
113
0.651119
4.89314
false
false
false
false
AllanWang/Frost-for-Facebook
app/src/main/kotlin/com/pitchedapps/frost/injectors/JsInjector.kt
1
4195
/* * Copyright 2018 Allan Wang * * 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.pitchedapps.frost.injectors import android.webkit.WebView import androidx.annotation.VisibleForTesting import com.pitchedapps.frost.prefs.Prefs import com.pitchedapps.frost.utils.L import com.pitchedapps.frost.web.FrostWebViewClient import kotlin.random.Random import org.apache.commons.text.StringEscapeUtils class JsBuilder { private val css = StringBuilder() private val js = StringBuilder() private var tag: String? = null fun css(css: String): JsBuilder { this.css.append(StringEscapeUtils.escapeEcmaScript(css)) return this } fun js(content: String): JsBuilder { this.js.append(content) return this } fun single(tag: String): JsBuilder { this.tag = TagObfuscator.obfuscateTag(tag) return this } fun build() = JsInjector(toString()) override fun toString(): String { val tag = this.tag val builder = StringBuilder().apply { append("!function(){") if (css.isNotBlank()) { val cssMin = css.replace(Regex("\\s*\n\\s*"), "") append("var a=document.createElement('style');") append("a.innerHTML='$cssMin';") if (tag != null) { append("a.id='$tag';") } append("document.head.appendChild(a);") } if (js.isNotBlank()) { append(js) } } var content = builder.append("}()").toString() if (tag != null) { content = singleInjector(tag, content) } return content } private fun singleInjector(tag: String, content: String) = StringBuilder() .apply { append("if (!window.hasOwnProperty(\"$tag\")) {") append("console.log(\"Registering $tag\");") append("window.$tag = true;") append(content) append("}") } .toString() } /** Contract for all injectors to allow it to interact properly with a webview */ interface InjectorContract { fun inject(webView: WebView, prefs: Prefs) /** Toggle the injector (usually through Prefs If false, will fallback to an empty action */ fun maybe(enable: Boolean): InjectorContract = if (enable) this else JsActions.EMPTY } /** Helper method to inject multiple functions simultaneously with a single callback */ fun WebView.jsInject(vararg injectors: InjectorContract, prefs: Prefs) { injectors.asSequence().filter { it != JsActions.EMPTY }.forEach { it.inject(this, prefs) } } fun FrostWebViewClient.jsInject(vararg injectors: InjectorContract, prefs: Prefs) = web.jsInject(*injectors, prefs = prefs) /** Wrapper class to convert a function into an injector */ class JsInjector(val function: String) : InjectorContract { override fun inject(webView: WebView, prefs: Prefs) = webView.evaluateJavascript(function, null) } /** Helper object to obfuscate window tags for JS injection. */ @VisibleForTesting internal object TagObfuscator { fun obfuscateTag(tag: String): String { val rnd = Random(tag.hashCode() + salt) val obfuscated = buildString { append(prefix) append('_') appendRandomChars(rnd, 16) } L.v { "TagObfuscator: Obfuscating tag '$tag' to '$obfuscated'" } return obfuscated } private val salt: Long = System.currentTimeMillis() private val prefix: String by lazy { val rnd = Random(System.currentTimeMillis()) buildString { appendRandomChars(rnd, 8) } } private fun Appendable.appendRandomChars(random: Random, count: Int) { for (i in 1..count) { append('a' + random.nextInt(26)) } } }
gpl-3.0
b6f8d389e3e7897fb1e9195e71c13956
30.074074
98
0.677473
4.092683
false
false
false
false
Budincsevity/opensubtitles-api
src/main/kotlin/io/github/budincsevity/OpenSubtitlesAPI/model/builder/SearchResultDataBuilder.kt
1
9734
package io.github.budincsevity.OpenSubtitlesAPI.model.builder import io.github.budincsevity.OpenSubtitlesAPI.model.SearchResultData class SearchResultDataBuilder { var subActualCD: String = "" var movieName: String = "" var subBad: String = "" var movieHash: String = "" var subFileName: String = "" var subSumCD: String = "" var zipDownloadLink: String = "" var movieNameEng: String = "" var subSize: String = "" var iDSubtitleFile: String = "" var subHash: String = "" var subFeatured: String = "" var subAuthorComment: String = "" var subDownloadsCnt: String = "" var subAddDate: String = "" var subLastTS: String = "" var subAutoTranslation: String = "" var movieReleaseName: String = "" var seriesIMDBParent: String = "" var score: String = "" var userNickName: String = "" var subHearingImpaired: String = "" var subTSGroup: String = "" var queryCached: String = "" var subLanguageID: String = "" var subFormat: String = "" var languageName: String = "" var subTranslator: String = "" var seriesEpisode: String = "" var userRank: String = "" var movieImdbRating: String = "" var movieTimeMS: String = "" var movieYear: String = "" var subEncoding: String = "" var queryNumber: String = "" var subHD: String = "" var userID: String = "" var movieByteSize: String = "" var movieFPS: String = "" var subtitlesLink: String = "" var iDSubMovieFile: String = "" var ISO639: String = "" var seriesSeason: String = "" var subFromTrusted: String = "" var subTSGroupHash: String = "" var matchedBy: String = "" var subDownloadLink: String = "" var subRating: String = "" var queryParameters: String = "" var subComments: String = "" var movieKind: String = "" var iDMovie: String = "" var iDMovieImdb: String = "" var subForeignPartsOnly: String = "" var iDSubtitle: String = "" fun withSubActualCD(subActualCD: String): SearchResultDataBuilder { this.subActualCD = subActualCD return this } fun withMovieName(movieName: String): SearchResultDataBuilder { this.movieName = movieName return this } fun withSubBad(subBad: String): SearchResultDataBuilder { this.subBad = subBad return this } fun withMovieHash(movieHash: String): SearchResultDataBuilder { this.movieHash = movieHash return this } fun withSubFileName(subFileName: String): SearchResultDataBuilder { this.subFileName = subFileName return this } fun withSubSumCD(subSumCD: String): SearchResultDataBuilder { this.subSumCD = subSumCD return this } fun withZipDownloadLink(zipDownloadLink: String): SearchResultDataBuilder { this.zipDownloadLink = zipDownloadLink return this } fun withMovieNameEng(movieNameEng: String): SearchResultDataBuilder { this.movieNameEng = movieNameEng return this } fun withSubSize(subSize: String): SearchResultDataBuilder { this.subSize = subSize return this } fun withIDSubtitleFile(iDSubtitleFile: String): SearchResultDataBuilder { this.iDSubtitleFile = iDSubtitleFile return this } fun withSubHash(subHash: String): SearchResultDataBuilder { this.subHash = subHash return this } fun withSubFeatured(subFeatured: String): SearchResultDataBuilder { this.subFeatured = subFeatured return this } fun withSubAuthorComment(subAuthorComment: String): SearchResultDataBuilder { this.subAuthorComment = subAuthorComment return this } fun withSubDownloadsCnt(subDownloadsCnt: String): SearchResultDataBuilder { this.subDownloadsCnt = subDownloadsCnt return this } fun withSubAddDate(subAddDate: String): SearchResultDataBuilder { this.subAddDate = subAddDate return this } fun withSubLastTS(subLastTS: String): SearchResultDataBuilder { this.subLastTS = subLastTS return this } fun withSubAutoTranslation(subAutoTranslation: String): SearchResultDataBuilder { this.subAutoTranslation = subAutoTranslation return this } fun withMovieReleaseName(movieReleaseName: String): SearchResultDataBuilder { this.movieReleaseName = movieReleaseName return this } fun withSeriesIMDBParent(seriesIMDBParent: String): SearchResultDataBuilder { this.seriesIMDBParent = seriesIMDBParent return this } fun withScore(score: String): SearchResultDataBuilder { this.score = score return this } fun withUserNickName(userNickName: String): SearchResultDataBuilder { this.userNickName = userNickName return this } fun withSubHearingImpaired(subHearingImpaired: String): SearchResultDataBuilder { this.subHearingImpaired = subHearingImpaired return this } fun withSubTSGroup(subTSGroup: String): SearchResultDataBuilder { this.subTSGroup = subTSGroup return this } fun withQueryCached(queryCached: String): SearchResultDataBuilder { this.queryCached = queryCached return this } fun withSubLanguageID(subLanguageID: String): SearchResultDataBuilder { this.subLanguageID = subLanguageID return this } fun withSubFormat(subFormat: String): SearchResultDataBuilder { this.subFormat = subFormat return this } fun withLanguageName(languageName: String): SearchResultDataBuilder { this.languageName = languageName return this } fun withSubTranslator(subTranslator: String): SearchResultDataBuilder { this.subTranslator = subTranslator return this } fun withSeriesEpisode(seriesEpisode: String): SearchResultDataBuilder { this.seriesEpisode = seriesEpisode return this } fun withUserRank(userRank: String): SearchResultDataBuilder { this.userRank = userRank return this } fun withMovieImdbRating(movieImdbRating: String): SearchResultDataBuilder { this.movieImdbRating = movieImdbRating return this } fun withMovieTimeMS(movieTimeMS: String): SearchResultDataBuilder { this.movieTimeMS = movieTimeMS return this } fun withMovieYear(movieYear: String): SearchResultDataBuilder { this.movieYear = movieYear return this } fun withSubEncoding(subEncoding: String): SearchResultDataBuilder { this.subEncoding = subEncoding return this } fun withQueryNumber(queryNumber: String): SearchResultDataBuilder { this.queryNumber = queryNumber return this } fun withSubHD(subHD: String): SearchResultDataBuilder { this.subHD = subHD return this } fun withUserID(userID: String): SearchResultDataBuilder { this.userID = userID return this } fun withMovieByteSize(movieByteSize: String): SearchResultDataBuilder { this.movieByteSize = movieByteSize return this } fun withMovieFPS(movieFPS: String): SearchResultDataBuilder { this.movieFPS = movieFPS return this } fun withSubtitlesLink(subtitlesLink: String): SearchResultDataBuilder { this.subtitlesLink = subtitlesLink return this } fun withIDSubMovieFile(iDSubMovieFile: String): SearchResultDataBuilder { this.iDSubMovieFile = iDSubMovieFile return this } fun withISO639(ISO639: String): SearchResultDataBuilder { this.ISO639 = ISO639 return this } fun withSeriesSeason(seriesSeason: String): SearchResultDataBuilder { this.seriesSeason = seriesSeason return this } fun withSubFromTrusted(subFromTrusted: String): SearchResultDataBuilder { this.subFromTrusted = subFromTrusted return this } fun withSubTSGroupHash(subTSGroupHash: String): SearchResultDataBuilder { this.subTSGroupHash = subTSGroupHash return this } fun withMatchedBy(matchedBy: String): SearchResultDataBuilder { this.matchedBy = matchedBy return this } fun withSubDownloadLink(subDownloadLink: String): SearchResultDataBuilder { this.subDownloadLink = subDownloadLink return this } fun withSubRating(subRating: String): SearchResultDataBuilder { this.subRating = subRating return this } fun withQueryParameters(queryParameters: String): SearchResultDataBuilder { this.queryParameters = queryParameters return this } fun withSubComments(subComments: String): SearchResultDataBuilder { this.subComments = subComments return this } fun withMovieKind(movieKind: String): SearchResultDataBuilder { this.movieKind = movieKind return this } fun withIDMovie(iDMovie: String): SearchResultDataBuilder { this.iDMovie = iDMovie return this } fun withIDMovieImdb(iDMovieImdb: String): SearchResultDataBuilder { this.iDMovieImdb = iDMovieImdb return this } fun withSubForeignPartsOnly(subForeignPartsOnly: String): SearchResultDataBuilder { this.subForeignPartsOnly = subForeignPartsOnly return this } fun withIDSubtitle(iDSubtitle: String): SearchResultDataBuilder { this.iDSubtitle = iDSubtitle return this } fun build(): SearchResultData { return SearchResultData(this) } }
mit
81a67f34b821016e78013b0866feb397
27.629412
87
0.672488
4.587182
false
false
false
false
danwallach/XStopwatchComplication
app/src/main/kotlin/org/dwallach/xstopwatchcomplication/StopwatchText.kt
1
6012
/* * XStopwatch / XTimer * Copyright (C) 2014-2016 by Dan Wallach * Home page: http://www.cs.rice.edu/~dwallach/xstopwatch/ * Licensing: http://www.cs.rice.edu/~dwallach/xstopwatch/licensing.html */ package org.dwallach.xstopwatchcomplication import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.PorterDuff import android.graphics.Typeface import android.os.Handler import android.os.Message import android.util.AttributeSet import android.view.View import org.jetbrains.anko.AnkoLogger import org.jetbrains.anko.verbose import org.jetbrains.anko.warn import java.lang.ref.WeakReference /** * This class acts something like android.widget.Chronometer, but that class only knows * how to count up, and we need to be able to go up (for a stopwatch) and down (for a timer). * When running, the text is updated once a second, with text derived from the SharedState * (which might be either StopwatchState or TimerState). */ class StopwatchText : View, AnkoLogger { private var visible = true private var state: SharedState? = null private var shortName: String? = null private val textPaint: Paint /** Handler to update the time once a second in interactive mode. */ private val updateTimeHandler: MyHandler constructor(context: Context, attrs: AttributeSet) : super(context, attrs) constructor(context: Context) : super(context) init { setWillNotDraw(false) textPaint = Paint(Paint.SUBPIXEL_TEXT_FLAG or Paint.HINTING_ON).apply { isAntiAlias = true style = Paint.Style.FILL color = context.getColor(R.color.primary) textAlign = Paint.Align.CENTER typeface = Typeface.MONOSPACE } updateTimeHandler = MyHandler(this) } fun setSharedState(sharedState: SharedState) { verbose { "setting sharedState: $sharedState"} this.state = sharedState this.shortName = sharedState.shortName } override fun onVisibilityChanged(changedView: View?, visibility: Int) { visible = visibility == View.VISIBLE verbose { "$shortName visible: $visible" } state?.isVisible = visible restartRedrawLoop() } fun restartRedrawLoop() { val lState = state ?: return if (lState.isVisible) invalidate() // gets the most current state drawn no matter what if (lState.isVisible && lState.isRunning) { updateTimeHandler.sendEmptyMessage(MSG_UPDATE_TIME) } else { updateTimeHandler.removeMessages(MSG_UPDATE_TIME) } } private var textX: Float = 0f private var textY: Float = 0f override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { verbose { "$shortName size change: $w,$h" } this._width = w this._height = h // TODO: dig deeper into font metrics and find a font size that guarantees we can fit all the chars // http://stackoverflow.com/questions/5033012/auto-scale-textview-text-to-fit-within-bounds/17782522#17782522 val textSize = h * .6f verbose { "$shortName new text size: $textSize" } textPaint.textSize = textSize // // note: metrics.ascent is a *negative* number while metrics.descent is a *positive* number // val metrics = textPaint.fontMetrics val fontHeight = -metrics.ascent + metrics.descent val leftoverHeight = h - fontHeight textY = -metrics.ascent + leftoverHeight / 2f textX = w / 2f // // In some weird cases, we get an onSizeChanged but not an onVisibilityChanged // event, even though visibility did change; Lovely. // onVisibilityChanged(null, View.VISIBLE) } private var _width: Int = 0 private var _height: Int = 0 public override fun onDraw(canvas: Canvas) { val lState = state ?: return verbose { shortName + "onDraw -- visible: " + visible + ", running: " + lState.isRunning } val timeText = lState.displayTime() // verbose { "update text to: " + timeText } if (_width == 0 || _height == 0) { warn { "$shortName zero-width or zero-height, can't draw yet" } return } // clear the screen canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR) canvas.drawText(timeText, textX, textY, textPaint) // TODO add ambient mode } companion object: AnkoLogger { const val MSG_UPDATE_TIME = 0 private class MyHandler internal constructor(stopwatchText: StopwatchText) : Handler(), AnkoLogger { private val stopwatchTextRef = WeakReference(stopwatchText) override val loggerTag = "StopwatchText" // more useful than "Companion" override fun handleMessage(message: Message) { val stopwatchText = stopwatchTextRef.get() ?: return // oops, it died when (message.what) { MSG_UPDATE_TIME -> { TimeWrapper.update() val localTime = TimeWrapper.gmtTime stopwatchText.invalidate() if (stopwatchText.visible && (stopwatchText.state?.isRunning ?: false)) { val timeMs = localTime val delayMs = 1000 - timeMs % 1000 sendEmptyMessageDelayed(MSG_UPDATE_TIME, delayMs) } else { verbose { "${stopwatchText.shortName}: time handler complete" } } } else -> { errorLogAndThrow("unknown message: $message") } } } // TODO add 60Hz redraw loop, use for some cool rendering as in CalWatch } } }
gpl-3.0
dc26bc8ed9d23b5024f86535940a7cf1
32.586592
117
0.616434
4.671329
false
false
false
false
rock3r/detekt
detekt-rules/src/test/resources/cases/FunctionReturningConstantPositive.kt
2
795
@file:Suppress("unused", "UNUSED_PARAMETER") package cases fun functionReturningConstantString() = "1" // reports 1 fun functionReturningConstantString(str: String) = "str: $$" // reports 1 fun functionReturningConstantEscapedString(str: String) = "str: \$str" // reports 1 fun functionReturningConstantChar() = '1' // reports 1 fun functionReturningConstantInt(): Int { // reports 1 return 1 } @Suppress("EqualsOrHashCode") open class FunctionReturningConstant { open fun f() = 1 // reports 1 override fun hashCode() = 1 // reports 1 } interface InterfaceFunctionReturningConstant { fun interfaceFunctionWithImplementation() = 1 // reports 1 class NestedClassFunctionReturningConstant { fun interfaceFunctionWithImplementation() = 1 // reports 1 } }
apache-2.0
6e7d61936aeb9c9d89b54178dc2d5dd9
23.84375
83
0.725786
4.251337
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/utils/ExceptionUtil.kt
1
2928
/* * Copyright (c) 2020 David Allison <[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.utils import android.content.Context import androidx.annotation.CheckResult import com.ichi2.anki.CrashReportService import com.ichi2.anki.R import com.ichi2.anki.UIUtils import java.io.PrintWriter import java.io.StringWriter object ExceptionUtil { fun containsMessage(e: Throwable?, needle: String?): Boolean { if (e == null) { return false } if (containsMessage(e.cause, needle)) { return true } val message = e.message return message != null && message.contains(needle!!) } @CheckResult fun getExceptionMessage(e: Throwable?): String { return getExceptionMessage(e, "\n") } @CheckResult fun getExceptionMessage(e: Throwable?, separator: String?): String { val ret = StringBuilder() var cause: Throwable? = e while (cause != null) { if (cause.localizedMessage != null || cause === e) { if (cause !== e) { ret.append(separator) } ret.append(cause.localizedMessage) } cause = cause.cause } return ret.toString() } /** Whether the exception is, or contains a cause of a given type */ @KotlinCleanup("convert to containsCause<T>(ex)") fun <T> containsCause(ex: Throwable, clazz: Class<T>): Boolean { if (clazz.isInstance(ex)) { return true } val cause = ex.cause ?: return false return containsCause(cause, clazz) } fun getFullStackTrace(ex: Throwable): String { val sw = StringWriter() ex.printStackTrace(PrintWriter(sw)) return sw.toString() } /** Executes a function, and logs the exception to ACRA and shows a toast if an issue occurs */ fun executeSafe(context: Context, origin: String, runnable: (() -> Unit)) { try { runnable.invoke() } catch (e: Exception) { CrashReportService.sendExceptionReport(e, origin) UIUtils.showThemedToast( context, context.getString(R.string.multimedia_editor_something_wrong), true ) } } }
gpl-3.0
d7ddb4d70921ae5efad001ef7056421a
33.046512
99
0.628415
4.403008
false
false
false
false
NooAn/bytheway
app/src/main/java/ru/a1024bits/bytheway/ui/fragments/SearchFragment.kt
1
13790
package ru.a1024bits.bytheway.ui.fragments import android.content.Intent import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.app.AppCompatActivity import android.text.Editable import android.text.TextWatcher import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.WindowManager import android.widget.Toast import com.codetroopers.betterpickers.calendardatepicker.CalendarDatePickerDialogFragment import com.codetroopers.betterpickers.calendardatepicker.MonthAdapter import com.google.android.gms.location.places.AutocompleteFilter import com.google.android.gms.location.places.ui.PlaceAutocomplete import com.google.android.gms.maps.model.LatLng import com.google.firebase.analytics.FirebaseAnalytics import com.google.firebase.crash.FirebaseCrash import kotlinx.android.synthetic.main.fragment_search_block.* import ru.a1024bits.bytheway.R import ru.a1024bits.bytheway.model.Method import ru.a1024bits.bytheway.model.User import ru.a1024bits.bytheway.repository.Filter import ru.a1024bits.bytheway.router.OnFragmentInteractionListener import ru.a1024bits.bytheway.util.* import ru.a1024bits.bytheway.util.Constants.END_DATE import ru.a1024bits.bytheway.util.Constants.FIRST_INDEX_CITY import ru.a1024bits.bytheway.util.Constants.LAST_INDEX_CITY import ru.a1024bits.bytheway.util.Constants.PLACE_AUTOCOMPLETE_REQUEST_CODE_TEXT_FROM import ru.a1024bits.bytheway.util.Constants.PLACE_AUTOCOMPLETE_REQUEST_CODE_TEXT_TO import ru.a1024bits.bytheway.util.Constants.START_DATE import ru.a1024bits.bytheway.util.DateUtils.Companion.getLongFromDate import java.util.* /** * Created by andrey.gusenkov on 29/09/2017 */ class SearchFragment : Fragment() { private lateinit var mFirebaseAnalytics: FirebaseAnalytics private lateinit var dateDialog: CalendarDatePickerDialogFragment private var firstPoint: LatLng? = null private var secondPoint: LatLng? = null var user: User = User() var filter: Filter = Filter() private val FIRST_MARKER_POSITION: Int = 1 private val SECOND_MARKER_POSITION: Int = 2 companion object { fun newInstance(user: User?): SearchFragment { val fragment = SearchFragment() fragment.arguments = Bundle() fragment.user = user ?: User() return fragment } } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater?.inflate(R.layout.fragment_search_block, container, false) activity.window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) mFirebaseAnalytics = FirebaseAnalytics.getInstance(context) try { filter.startDate = user.dates[START_DATE] ?: 0 filter.endDate = user.dates[END_DATE] ?: 0 filter.endBudget = user.budget.toInt() filter.method = user.method filter.endCity = user.cities[LAST_INDEX_CITY] ?: "" filter.startCity = user.cities[FIRST_INDEX_CITY] ?: "" filter.locationStartCity = LatLng(user.cityFromLatLng.latitude, user.cityFromLatLng.longitude) filter.locationEndCity = LatLng(user.cityToLatLng.latitude, user.cityToLatLng.longitude) } catch (e: Exception) { e.printStackTrace() } return view } override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) for (method in user.method.keys) { val icon = when (method) { Method.CAR.link -> iconCar Method.TRAIN.link -> iconTrain Method.BUS.link -> iconBus Method.PLANE.link -> iconPlane Method.HITCHHIKING.link -> iconHitchHicking else -> iconCar } icon.isActivated = user.method[method] == true } listOf(iconCar, iconHitchHicking, iconPlane, iconBus, iconTrain).map { it.setOnClickListener { when (it) { iconCar -> travelCarText.putIntoFilter(Method.CAR.link, filter) iconTrain -> travelTrainText.putIntoFilter(Method.TRAIN.link, filter) iconBus -> travelBusText.putIntoFilter(Method.BUS.link, filter) iconHitchHicking -> travelHitchHikingText.putIntoFilter(Method.HITCHHIKING.link, filter) iconPlane -> travelPlaneText.putIntoFilter(Method.PLANE.link, filter) } } } textFromCity.text = user.cities[FIRST_INDEX_CITY] textFromCity.setOnClickListener { sendIntentForSearch(PLACE_AUTOCOMPLETE_REQUEST_CODE_TEXT_FROM) } text_to_city.text = user.cities[LAST_INDEX_CITY] text_to_city.setOnClickListener { sendIntentForSearch(PLACE_AUTOCOMPLETE_REQUEST_CODE_TEXT_TO) } if (user.dates.size > 0) { if (user.dates[START_DATE] != null && user.dates[START_DATE] != 0L) dateFromValue.text = user.dates[START_DATE]?.getNormallDate() if (user.dates[END_DATE] != null && user.dates[END_DATE] != 0L) dateToValue.text = user.dates[END_DATE]?.getNormallDate() } swap_cities.setOnClickListener { val tempString = textFromCity.text textFromCity.text = text_to_city.text text_to_city.text = tempString filter.endCity = text_to_city.text.toString() filter.startCity = textFromCity.text.toString() val tempLng = filter.locationStartCity filter.locationStartCity = filter.locationEndCity filter.locationEndCity = tempLng updatePoints(filter.locationStartCity, filter.locationEndCity, swap = true) } budgetFromValue.setText(user.budget.toStringOrEmpty) budgetFromValue.filters = arrayOf(DecimalInputFilter()) budgetFromValue.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { } override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { } override fun afterTextChanged(text: Editable?) { filter.endBudget = text.toString().getIntOrNothing() } }) if (user.cityFromLatLng.latitude != 0.0 && user.cityToLatLng.latitude != 0.0 && user.cityToLatLng.longitude != 0.0) { // ставим маркеры на карту updatePoints(LatLng(user.cityFromLatLng.latitude, user.cityFromLatLng.longitude), LatLng(user.cityToLatLng.latitude, user.cityToLatLng.longitude)) } } private fun updatePoints(start: LatLng, end: LatLng, swap: Boolean = false) { firstPoint = start secondPoint = end firstPoint?.let { latLng -> (activity as OnFragmentInteractionListener).onSetPoint(latLng, FIRST_MARKER_POSITION, swap) } secondPoint?.let { latLng -> (activity as OnFragmentInteractionListener).onSetPoint(latLng, SECOND_MARKER_POSITION, swap) } } private fun openDateFromDialog() { val dateFrom = Calendar.getInstance() //current time by default if (filter.startDate > 0L) dateFrom.timeInMillis = filter.startDate dateDialog = CalendarDatePickerDialogFragment() .setFirstDayOfWeek(Calendar.MONDAY) .setThemeCustom(R.style.BythewayDatePickerDialogTheme) .setPreselectedDate(dateFrom.get(Calendar.YEAR), dateFrom.get(Calendar.MONTH), dateFrom.get(Calendar.DAY_OF_MONTH)) dateDialog.setDateRange(MonthAdapter.CalendarDay(System.currentTimeMillis()), null) dateDialog.setOnDateSetListener { _, year, monthOfYear, dayOfMonth -> dateFromValue?.text = StringBuilder(" ") .append(dayOfMonth) .append(" ") .append(context.resources.getStringArray(R.array.months_array)[monthOfYear]) .append(" ") .append(year).toString() filter.startDate = getLongFromDate(dayOfMonth, monthOfYear, year) } dateDialog.show(activity.supportFragmentManager, "") } private fun openDateToDialog() { val dateTo = Calendar.getInstance() //current time by default if (filter.endDate > 0L) dateTo.timeInMillis = filter.endDate dateDialog = CalendarDatePickerDialogFragment() .setFirstDayOfWeek(Calendar.MONDAY) .setThemeCustom(R.style.BythewayDatePickerDialogTheme) .setPreselectedDate(dateTo.get(Calendar.YEAR), dateTo.get(Calendar.MONTH), dateTo.get(Calendar.DAY_OF_MONTH)) dateDialog.setDateRange( MonthAdapter.CalendarDay( if (filter.startDate > 0L) filter.startDate else System.currentTimeMillis()), null) dateDialog.setOnDateSetListener { _, year, monthOfYear, dayOfMonth -> dateToValue?.text = StringBuilder(" ") .append(dayOfMonth) .append(" ") .append(context.resources.getStringArray(R.array.months_array)[monthOfYear]) .append(" ") .append(year).toString() filter.endDate = getLongFromDate(dayOfMonth, monthOfYear, year) } dateDialog.show(activity.supportFragmentManager, "") } override fun onStart() { super.onStart() val now = Calendar.getInstance() dateDialog = CalendarDatePickerDialogFragment() .setFirstDayOfWeek(Calendar.MONDAY) .setThemeCustom(R.style.BythewayDatePickerDialogTheme) .setPreselectedDate(now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH)) dateFromValue.setOnClickListener { openDateFromDialog() mFirebaseAnalytics.logEvent("Search_fragment_str_date_dialog", null) } dateToValue.setOnClickListener { openDateToDialog() mFirebaseAnalytics.logEvent("Search_fragment_end_date_dialog", null) } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) // FIXME refactoring in viewModel when (requestCode) { PLACE_AUTOCOMPLETE_REQUEST_CODE_TEXT_FROM -> when (resultCode) { AppCompatActivity.RESULT_OK -> { val place = PlaceAutocomplete.getPlace(activity, data) textFromCity?.text = place.name firstPoint = place.latLng filter.startCity = place.name.toString() filter.locationStartCity = place.latLng textFromCity?.error = null manageErrorCityEquals(secondPoint) firstPoint?.let { latLng -> (activity as OnFragmentInteractionListener).onSetPoint(latLng, FIRST_MARKER_POSITION) } } else -> { val status = PlaceAutocomplete.getStatus(activity, data) Log.i("LOG", status.statusMessage + " ") if (textFromCity != null) { textFromCity.text = filter.startCity } } } PLACE_AUTOCOMPLETE_REQUEST_CODE_TEXT_TO -> when (resultCode) { AppCompatActivity.RESULT_OK -> { try { val place = PlaceAutocomplete.getPlace(activity, data) text_to_city?.text = place.name secondPoint = place.latLng filter.locationEndCity = place.latLng filter.endCity = place.name.toString() text_to_city?.error = null manageErrorCityEquals(firstPoint) secondPoint?.let { latLng -> (activity as OnFragmentInteractionListener).onSetPoint(latLng, SECOND_MARKER_POSITION) } } catch (e: Exception) { e.printStackTrace() FirebaseCrash.report(e) } } else -> { val status = PlaceAutocomplete.getStatus(activity, data) if (text_to_city != null) text_to_city.text = filter.endCity } } } } private fun manageErrorCityEquals(point: LatLng?) { if (point != null && this.firstPoint?.latitude == this.secondPoint?.latitude && this.firstPoint?.longitude == this.secondPoint?.longitude) { text_to_city?.error = "true" textFromCity?.error = "true" Toast.makeText([email protected], getString(R.string.fill_diff_cities), Toast.LENGTH_SHORT).show() } else { textFromCity?.error = null text_to_city?.error = null } } private fun sendIntentForSearch(code: Int) { try { val typeFilter = AutocompleteFilter.Builder() .setTypeFilter(AutocompleteFilter.TYPE_FILTER_CITIES) .build() val intent = PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY).setFilter(typeFilter).build(activity) startActivityForResult(intent, code) } catch (e: Exception) { e.printStackTrace() } } }
mit
e6b772edec2c89ad961efde2c9c1bc4a
42.305031
158
0.625926
4.608434
false
false
false
false
SimpleMobileTools/Simple-Draw
app/src/main/kotlin/com/simplemobiletools/draw/pro/helpers/Constants.kt
1
511
package com.simplemobiletools.draw.pro.helpers const val BRUSH_COLOR = "brush_color" const val CANVAS_BACKGROUND_COLOR = "canvas_background_color" const val SHOW_BRUSH_SIZE = "show_brush_size" const val BRUSH_SIZE = "brush_size_2" const val LAST_SAVE_FOLDER = "last_save_folder" const val LAST_SAVE_EXTENSION = "last_save_extension" const val ALLOW_ZOOMING_CANVAS = "allow_zooming_canvas" const val FORCE_PORTRAIT_MODE = "force_portrait_mode" const val PNG = "png" const val SVG = "svg" const val JPG = "jpg"
gpl-3.0
5297bf4324cafddef7c6ee95a74fefe6
35.5
61
0.755382
3.078313
false
false
false
false
SchoolPower/SchoolPower-Android
app/src/main/java/com/carbonylgroup/schoolpower/data/Attendance.kt
2
974
package com.carbonylgroup.schoolpower.data import org.json.JSONObject import java.io.Serializable import java.text.SimpleDateFormat import java.util.* /** * Created by carbonyl on 04/11/2017. */ /* Sample: { "code": "E", "description": "Excused Absent", "date": "2017-10-16T16:00:00.000Z", "period": "3(B,D)", "name": "Chinese Social Studies 11" } */ class Attendance(json: JSONObject) : Serializable { val code: String = json.getString("code") val description: String = json.optString("description") val date: String val period: String = json.optString("period") val name: String = json.optString("name", "--") init{ val temp = SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).parse(json.getString("date") .replace("T16:00:00.000Z", "")) temp.time+=24*60*60*1000 date = SimpleDateFormat("yyyy/MM/dd", Locale.CHINA).format(temp) } var isNew = false }
gpl-3.0
6621528e61e66a713d42be71eeed14a1
24.657895
92
0.623203
3.580882
false
false
false
false
SpartaHack/SpartaHack-Android
app/src/main/java/com/spartahack/spartahack_android/MainActivity.kt
1
3530
package com.spartahack.spartahack_android import android.content.Intent import android.os.Bundle import androidx.core.view.GravityCompat import androidx.appcompat.app.ActionBarDrawerToggle import android.view.MenuItem import androidx.drawerlayout.widget.DrawerLayout import com.google.android.material.navigation.NavigationView import androidx.appcompat.app.AppCompatActivity import android.view.Menu import androidx.appcompat.widget.Toolbar import com.spartahack.spartahack_android.tools.Timer import kotlinx.android.synthetic.main.app_bar_main.* import java.lang.System.currentTimeMillis class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val toolbar: Toolbar = findViewById(R.id.toolbar) setSupportActionBar(toolbar) val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout) val navView: NavigationView = findViewById(R.id.nav_view) val toggle = ActionBarDrawerToggle( this, drawerLayout, R.string.navigation_drawer_open, R.string.navigation_drawer_close) drawerLayout.addDrawerListener(toggle) toggle.syncState() navView.setNavigationItemSelectedListener(this) val END_DATE = 1580468400000 // Should be the date of the event val currentDate = currentTimeMillis() val endTimeMills = END_DATE - currentDate val timer = Timer(endTimeMills, 1000, countdownTimer) timer.start() } override fun onBackPressed() { val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout) if (drawerLayout.isDrawerOpen(GravityCompat.START)) { drawerLayout.closeDrawer(GravityCompat.START) } else { super.onBackPressed() } } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. return when (item.itemId) { R.id.action_settings -> true else -> super.onOptionsItemSelected(item) } } override fun onNavigationItemSelected(item: MenuItem): Boolean { // Handle navigation view item clicks here. when (item.itemId) { R.id.nav_home -> { // do nothing. already here } R.id.nav_maps -> { // set activity to maps var intent = Intent(this, MapsActivity::class.java) startActivity(intent) } R.id.nav_faq -> { // set activity to faq var intent = Intent(this, FAQActivity::class.java) startActivity(intent) } R.id.nav_schedule -> { // set activity to schedule var intent = Intent(this, ScheduleActivity::class.java) startActivity(intent) } } val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout) drawerLayout.closeDrawer(GravityCompat.START) return true } }
mit
18bd3161db68d9d84e9522c9193e9804
35.391753
102
0.658074
4.868966
false
false
false
false
RizkiMufrizal/Starter-Project
Starter-BackEnd/src/main/kotlin/org/rizki/mufrizal/starter/backend/domain/oauth2/OAuth2Code.kt
1
890
package org.rizki.mufrizal.starter.backend.domain.oauth2 import javax.persistence.Column import javax.persistence.Entity import javax.persistence.Table import javax.persistence.GenerationType import javax.persistence.GeneratedValue import javax.persistence.Id /** * * @Author Rizki Mufrizal <[email protected]> * @Web <https://RizkiMufrizal.github.io> * @Since 20 August 2017 * @Time 6:05 PM * @Project Starter-BackEnd * @Package org.rizki.mufrizal.starter.backend.domain.oauth2 * @File OAuth2Code * */ @Entity @Table(name = "oauth_code") data class OAuth2Code( @Id @Column(name = "id") @GeneratedValue(strategy = GenerationType.AUTO) val id: Int? = null, @Column(name = "code") val code: String? = null, @Column(name = "authentication", columnDefinition = "BLOB") val authentication: ByteArray? = null )
apache-2.0
869735e68d1a8b89f66fede7f38af9ed
23.75
67
0.697753
3.708333
false
false
false
false
mustafaberkaymutlu/uv-index
base/src/main/java/net/epictimes/uvindex/data/model/Weather.kt
1
3955
package net.epictimes.uvindex.data.model import android.os.Parcel import android.os.Parcelable import com.google.gson.annotations.SerializedName import java.util.* data class Weather( @SerializedName("wind_spd") val windSpeed: Double, @SerializedName("wind_dir") val windDirection: Int, @SerializedName("wind_cdir") val windDirectionAbbreviated: String, @SerializedName("wind_cdir_full") val windDirFull: String, // percent @SerializedName("rh") val relativeHumidity: Double, @SerializedName("dewpt") val dewPoint: Double, // percent @SerializedName("clouds") val cloudCoverage: Int, // d = day / n = night @SerializedName("pod") val partOfDay: String, // mb @SerializedName("pres") val pressure: Double, @SerializedName("slp") val seaLevelPressure: Double, @SerializedName("timezone") val timezone: String, @SerializedName("ts") val lastObservationTimestamp: Int, // default to km @SerializedName("vis") val visibility: Double, @SerializedName("uv") val uvIndex: Double, // degrees @SerializedName("elev_angle") val solarElevationAngle: Int, // degrees @SerializedName("h_angle") val solarHourAngle: Int, // format: YYYY-MM-DD:HH @SerializedName("datetime") val datetime: Date, // default to mm @SerializedName("precip") val precipitation: Double, // format: HH:MM @SerializedName("sunset") val sunsetTime: String, // format: HH:MM @SerializedName("sunrise") val sunriseTime: String, @SerializedName("temp") val temperature: Double, // default to Celcius @SerializedName("app_temp") val apparentTemp: Double ) : Parcelable { constructor(source: Parcel) : this( source.readDouble(), source.readInt(), source.readString(), source.readString(), source.readDouble(), source.readDouble(), source.readInt(), source.readString(), source.readDouble(), source.readDouble(), source.readString(), source.readInt(), source.readDouble(), source.readDouble(), source.readInt(), source.readInt(), source.readSerializable() as Date, source.readDouble(), source.readString(), source.readString(), source.readDouble(), source.readDouble() ) override fun describeContents() = 0 override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) { writeDouble(windSpeed) writeInt(windDirection) writeString(windDirectionAbbreviated) writeString(windDirFull) writeDouble(relativeHumidity) writeDouble(dewPoint) writeInt(cloudCoverage) writeString(partOfDay) writeDouble(pressure) writeDouble(seaLevelPressure) writeString(timezone) writeInt(lastObservationTimestamp) writeDouble(visibility) writeDouble(uvIndex) writeInt(solarElevationAngle) writeInt(solarHourAngle) writeSerializable(datetime) writeDouble(precipitation) writeString(sunsetTime) writeString(sunriseTime) writeDouble(temperature) writeDouble(apparentTemp) } companion object { @JvmField val CREATOR: Parcelable.Creator<Weather> = object : Parcelable.Creator<Weather> { override fun createFromParcel(source: Parcel): Weather = Weather(source) override fun newArray(size: Int): Array<Weather?> = arrayOfNulls(size) } } }
apache-2.0
f9a30c7c19e60e83005c299049cd1743
25.72973
89
0.588622
4.968593
false
false
false
false
minjaesong/terran-basic-java-vm
src/net/torvald/terranvm/runtime/Assembler.kt
1
32943
package net.torvald.terranvm.runtime import net.torvald.terranvm.toReadableBin import net.torvald.terranvm.toReadableOpcode /** * ## Syntax * - Space/Tab/comma is a delimiter. * - Any line starts with # is comment * - Any text after # is a comment * - Labelling: @label_name * - String is surrounded with double quote * - Every line must end with one or more `;`s * * Example program * ``` * // TODO * ``` * This prints out 'Helvetti world!' on the standard output. * * * ## Sections * * TBAS Assembly can be divided into _sections_ that the assembler supports. If no section is given, 'code' is assumed. * * Supported sections: * - stack * - data * - code * * Indentation after section header is optional (and you probably don't want it anyway). * * ### Data * Data section has following syntax: * ``` * type label_name (payload) ; * ``` * Label names are case insensitive. * Available types: * - STRING (BYTES but will use "QUOTES" in the ASM line) * - FLOAT (WORD; payload is interpreted as float) * - INT (WORD; payload is interpreted as int) * - BYTES (byte literals, along with pointer label -- pointer label ONLY!) * * You use your label in code by '@label_name', just like line labels. * * * ### Literals * - Register literals: `r0` throught `r15` * - Hex literals: `CAFEBABEh` * - Integer literals: `80085` * * Defining labels: * ``` * :label_name; * ``` * * Referring labels: * ``` * @label_name * ``` * label returns memory OFFSET! (not an actual address) * * * * NOTE: what we say OFFSET is a memory address divided by four (and word-aligned) * * Created by minjaesong on 2017-05-28. */ class Assembler(val vm: TerranVM) { companion object { private val delimiters = Regex("""[ \t,]+""") private val blankLines = Regex("""(?<=;)[\n ]+""") private val stringMarker = Regex("""\"[^\n]*\"""") private val labelMarker = '@' private val labelDefinitionMarker = ':' private val lineEndMarker = ';' private val commentMarker = '#' private val literalMarker = '"' private val sectionHeading = Regex("""\.[A-Za-z0-9_]+""") private val regexWhitespaceNoSP = Regex("""[\t\r\n\v\f]""") private val prependedSpaces = Regex("""^[\s]+""") private val dataSectActualData = Regex("""^[A-Za-z]+[m \t]+[A-Za-z0-9_]+[m \t]+""") val regexRegisterLiteral = Regex("""^[Rr][0-9]+$""") // same as the compiler val regexHexWhole = Regex("""^([0-9A-Fa-f_]+h)$""") // DIFFERENT FROM the compiler val regexBinWhole = Regex("""^([01_]+b)$""") // DIFFERENT FROM the compiler val regexFPWhole = Regex("""^([-+]?[0-9]*[.][0-9]+[eE]*[-+0-9]*[fF]*|[-+]?[0-9]+[.eEfF][0-9+-]*[fF]?)$""") // same as the assembler val regexIntWhole = Regex("""^([-+]?[0-9_]+)$""") // DIFFERENT FROM the compiler val regexDecBinHexWhole = Regex("""^([0-9A-Fa-f_]+h)|([01_]+b)|([-+]?[0-9_]+)$""") private val labelTable = HashMap<String, Int>() // valid name: @label_name_in_lower_case private var currentSection = ".CODE" val asmSections = hashSetOf<String>(".CODE", ".DATA", ".STACK") val conditions: HashMap<String, Int> = hashMapOf( "" to 0, "Z" to 0x20000000, "NZ" to 0x40000000, "GT" to 0x60000000, "LS" to 0x80000000L.toInt() ) private val primitiveOpcodes: HashMap<String, Int> = hashMapOf( // Mathematical and Register data transfer // "MOV" to 0b110000, "XCHG" to 0b110001, "INC" to 0b110010, "DEC" to 0b110011, "MALLOC" to 0b110100, "FTOI" to 0b110110, "ITOF" to 0b110111, "ITOS" to 0b111000, "STOI" to 0b111001, "FTOS" to 0b111010, "STOF" to 0b111011, "ITOX" to 0b111100, "XTOI" to 0b111101, "JSR" to 0b111110, "RETURN" to 0b111111, "ADD" to 0b000001, "SUB" to 0b000010, "MUL" to 0b000011, "DIV" to 0b000100, "POW" to 0b000101, "MOD" to 0b000110, "ADDINT" to 0b100001, "SUBINT" to 0b100010, "MULINT" to 0b100011, "DIVINT" to 0b100100, "POWINT" to 0b100101, "MODINT" to 0b100110, "SHL" to 0b000111, "SHR" to 0b001000, "USHR" to 0b001001, "AND" to 0b001010, "OR" to 0b001011, "XOR" to 0b001100, "ABS" to 0b010000, "SIN" to 0b010001, "COS" to 0b010010, "TAN" to 0b010011, "FLOOR" to 0b010100, "CEIL" to 0b010101, "ROUND" to 0b010110, "LOG" to 0b010111, "RNDI" to 0b011000, "RND" to 0b011001, "SGN" to 0b011010, "SQRT" to 0b011011, "CBRT" to 0b011100, "INV" to 0b011101, "RAD" to 0b011110, "NOT" to 0b011111, "HALT" to 0, "YIELD" to 32, "PAUSE" to 42, "JCTX" to 44, "RCTX" to 45, "SRR" to 0b10000000, "SXCHG" to 0b10000001, "SRW" to 0b11000000, // Load and Store to memory // "LOADBYTE" to 0b000_0000_0000_0000_00000001000_00_0, "LOADHWORD" to 0b000_0000_0000_0000_00000001000_01_0, "LOADWORD" to 0b000_0000_0000_0000_00000001000_10_0, "STOREBYTE" to 0b000_0000_0000_0000_00000001000_00_1, "STOREHWORD" to 0b000_0000_0000_0000_00000001000_01_1, "STOREWORD" to 0b000_0000_0000_0000_00000001000_10_1, // Compare // "CMP" to 0b000_0000_0000_0000_000001000000_00, "CMPII" to 0b000_0000_0000_0000_000001000000_00, "CMPIF" to 0b000_0000_0000_0000_000001000000_01, "CMPFI" to 0b000_0000_0000_0000_000001000000_10, "CMPFF" to 0b000_0000_0000_0000_000001000000_11, // Load and Store byte/halfword/word immediate // //"LOADBYTEI" to 0b001_0000_0000_00_0000000000000000, //"LOADHWORDI" to 0b001_0000_0000_00_0000000000000000, //"STOREBYTEI" to 0b001_0000_0000_10_0000000000000000, "STOREHWORDI" to 0b001_0000_0000_10_0000000000000000, "LOADWORDI" to 0b001_0000_0000_00_0000000000000000, "LOADWORDILO" to 0b001_0000_0000_00_0000000000000000, // used in Int.toReadableOpcode() "LOADWORDIHI" to 0b001_0000_0000_01_0000000000000000, // used in Int.toReadableOpcode() // Load and Store a word from register to memory // "LOADWORDIMEM" to 0b010.shl(26), "STOREWORDIMEM" to 0b011.shl(26), // Push and Pop // "PUSH" to 0b000_0000_0000_0000_00001000000000, "POP" to 0b000_0000_0000_0000_00001100000000, // Conditional jump (WARNING: USES CUSTOM CONDITION HANDLER!) // /*"JMP" to 0b000_1000.shl(25), "JZ" to 0b001_1000.shl(25), "JNZ" to 0b010_1000.shl(25), "JGT" to 0b011_1000.shl(25), "JLS" to 0b100_1000.shl(25), "JFW" to 0b101_1000.shl(25), "JBW" to 0b110_1000.shl(25),*/ // Jump to Subroutine, Immediate // "JSRI" to 0b101_00000000000000000000000000, // Call peripheral // "CALL" to 0b110_0000_01000000000001_00000000, "MEMSIZE" to 0b110_0000_01000000000010_00000000, "UPTIME" to 0b110_0000_01000000000010_11111111, "INT" to 0x1FFF0000, // Assembler-specific commands // "NOP" to 0b000_0000_000_000_000_0000000000_110000 // MOV r1, r1 ) val opcodes = HashMap<String, Int>() val twoLiners = hashSetOf( "LOADWORDI", "LOADWORDIZ", "LOADWORDINZ", "LOADWORDIGT", "LOADWORDILS" ) /** * @return r: register, b: byte, w: halfword, f: full word (LOADWORDI only!) a: address offset */ fun getOpArgs(opcode: Int): String? { val opcode = opcode.and(0x1FFFFFFF) // drop conditions return when (opcode.ushr(26).and(0b111)) { 0 -> { val mathOp = opcode.and(0x3FFF) if (mathOp == 0) { "" } else if (mathOp == 0b111110) { // JSR "r" } else if (mathOp == 0b011000 || mathOp == 0b011001) { // random number "r" } else if (mathOp in 0b000001..0b001111 || mathOp in 0b100001..0b100110) { "rrr" } else if (mathOp in 0b010000..0b011111) { "rr" } else if (mathOp == 0b110000 || mathOp == 0b110001 || mathOp == 0b110100) { // MOV and XCHG; MALLOC "rr" } else if (mathOp == 0b110010 || mathOp == 0b110011) { // INC, DEC "r" } else if (mathOp in 54..61) { // FTOI, ITOF, ITOS, STOI, FTOS, STOF, ITOX, XTOI "rr" } else if (mathOp in 0b1000000..0b1000111) { // load/store "rrr" } else if (mathOp in 0b10000000..0b10000001 || mathOp == 0b11000000) { // SRR and SXCHG "rr" } else if (mathOp in 0x100..0x103) { // compare "rr" } else if (mathOp == 44) { // JCTX "r" } else if (mathOp == 0x200 || mathOp == 0x300) { // PUSH, POP "r" } else { "" } } 1 -> { val mode = opcode.ushr(16).and(3) return when (mode) { 0 -> "rf" // LOADWORDILO 1 -> "rf" // LOADWORDIHI 2 -> "rrw" // STOREHWORDI else -> throw UnknownOpcodeExpection(opcode) } } 2, 3 -> "ra" // LOAD(STORE)WORDIMEM 4 -> "a" // conditional jump 5 -> "a" // JSRI 6 -> { // FEATURE, CALL, MEMSIZE, UPTIME val cond = opcode.ushr(8).and(0x3FFF) if (cond !in 0x1000..0x1002) throw UnknownOpcodeExpection(opcode) else return "rb" } 7 -> { // INT if (opcode.ushr(8) == 0x1FFF00) return "b" else throw UnknownOpcodeExpection(opcode) } else -> throw UnknownOpcodeExpection(opcode) } } init { // fill up opcodes with conditions conditions.forEach { suffix, bits -> primitiveOpcodes.forEach { mnemo, opcode -> opcodes[mnemo + suffix] = bits or opcode } } opcodes.putAll(mapOf( "JMP" to 0b000_1000.shl(25), "JZ" to 0b001_1000.shl(25), "JNZ" to 0b010_1000.shl(25), "JGT" to 0b011_1000.shl(25), "JLS" to 0b100_1000.shl(25), "JFW" to 0b101_1000.shl(25), "JBW" to 0b110_1000.shl(25) )) } } private var stackSize: Int? = null private var sectionChangeCount = -1 private fun composeJMP(offset: Int) = opcodes["JMP"]!! or offset private fun debug(any: Any?) { if (true) { println(any) } } var flagSpecifyJMP = false var flagSpecifyJMPLocation = -1 private fun putLabel(name: String, pointer: Int) { val name = labelMarker + name.toLowerCase() if (labelTable[name] != null && labelTable[name] != pointer) { // don't delete this check -- every time shit happens, it means somewhere in the code is not right, I FUCKING GUARANTEE // now go bug-killing my fella throw InternalError("Labeldef conflict for $name -- old: ${labelTable[name]}, new: $pointer") } else { if (labelTable[name] == null) debug("->> put label '$name' with pc $pointer") labelTable[name] = pointer } } private fun getLabel(marked_labelname: String): Int { val name = marked_labelname.toLowerCase() return labelTable[name] ?: throw InternalError("Label '$name' not defined") } private fun splitLines(program: String): List<String> { val lines = ArrayList<String>() val sb = StringBuilder() fun split() { var str = sb.toString() // preprocess some // remove prepending whitespace str = str.replace(prependedSpaces, "") lines.add(str) sb.setLength(0) } var literalMode = false var commentMode = false var charCtr = 0 while (charCtr < program.length) { val char = program[charCtr] val charNext = if (charCtr < program.lastIndex) program[charCtr + 1] else null if (!literalMode && !commentMode) { if (char == literalMarker) { sb.append(literalMarker) literalMode = true } else if (char == commentMarker) { commentMode = true } else if (char == lineEndMarker) { split() } else if (!char.toString().matches(regexWhitespaceNoSP)) { sb.append(char) } } else if (!commentMode) { if (char == literalMarker && charNext == lineEndMarker) { // quote end must be "; sb.append(literalMarker) split() literalMode = false } else { sb.append(char) } } else { // comment mode if (char == '\n') { commentMode = false } } charCtr++ } return lines } private fun resetStatus() { labelTable.clear() } fun assemblyToOpcode(line: String): IntArray { fun String.toFloatOrInt(): Int = try { // it's integer this.resolveInt() } catch (e: UnsupportedOperationException) { // it's float this.replace("_", "").toFloat().toRawBits() } val words = line.split(delimiters) val cmd = words[0].toUpperCase() if (opcodes[cmd] == null) { throw InternalError("Invalid assembly: $cmd") } var resultingOpcode = opcodes[cmd]!! if (line.toUpperCase() == "NOP") { return assemblyToOpcode("MOV r1, r1") } else { val arguments = getOpArgs(resultingOpcode) //debug("arguments of ${resultingOpcode.toReadableBin()}: $arguments") debug("arguments of ${resultingOpcode.toReadableOpcode().split(' ')[0]}: $arguments") // check if user had provided right number of arguments if (words.size != arguments!!.length + 1) { throw IllegalArgumentException("'$cmd': Number of arguments doesn't match -- expected ${arguments.length}, got ${words.size - 1} ($words)") } // for each arguments the operation requires... (e.g. "rrr", "rb") arguments.forEachIndexed { index, c -> val word = words[index + 1] if (c == 'f') { // 'f' is only used for LOADWORDI (arg: rf), which outputs TWO opcodes val fullword = word.toFloatOrInt() val lowhalf = fullword.and(0xFFFF) val highhalf = fullword.ushr(16) val loadwordiOp = intArrayOf(resultingOpcode, resultingOpcode or 0x10000) loadwordiOp[0] = loadwordiOp[0] or lowhalf loadwordiOp[1] = loadwordiOp[1] or highhalf debug("$line\t-> ${loadwordiOp[0].toReadableBin()}") debug("$line\t-> ${loadwordiOp[1].toReadableBin()}") return loadwordiOp } else { resultingOpcode = resultingOpcode or when (c) { 'r' -> word.toRegInt().shl(22 - 4 * index) 'b' -> word.resolveInt().and(0xFF) 'w' -> word.resolveInt().and(0xFFFF) 'a' -> word.resolveInt().and(0x3FFFFF) else -> throw IllegalArgumentException("Unknown argument type: $c") } } } } debug("$line\t-> ${resultingOpcode.toReadableBin()}") return intArrayOf(resultingOpcode) } operator fun invoke(userProgram: String): ProgramImage { resetStatus() val ret = ArrayList<Byte>() fun zeroFillToAlignWord(payloadSize: Int) { repeat((4 - (payloadSize % 4)) % 4) { ret.add(0.toByte()) } } val programSpaceStart = vm.st fun getPC() = programSpaceStart + ret.size fun addWord(i: Int) { i.toLittle().forEach { ret.add(it) } } fun addByte(i: Byte) { ret.add(i) } fun addWords(ai: IntArray) { ai.forEach { addWord(it) } } fun Int.toNextWord() = if (this % 4 == 0) this else this.ushr(2).plus(1).shl(2) // pass 1: pre-scan for labels debug("\n\n== Pass 1 ==\n\n") var virtualPC = vm.st debug("*** Start PC: $virtualPC ***") splitLines(userProgram).forEach { lline -> var line = lline.replace(Regex("""^ ?[\n]+"""), "") // do not remove ?, this takes care of spaces prepended on comment marker val words = line.split(delimiters) if (line.isEmpty() || words.isEmpty()) { // NOP } else if (!line.startsWith(labelMarker)) { debug("[TBASASM] line: '$line'") //words.forEach { debug(" $it") } val cmd = words[0].toUpperCase() if (asmSections.contains(cmd)) { // sectioning commands currentSection = cmd sectionChangeCount++ // will continue to next statements } else if (currentSection == ".STACK") { if (stackSize != null) throw Error("Stack already been defined with size of $stackSize") if (sectionChangeCount != 0) throw Error("Stack definition must be the first command of the program") stackSize = words[0].toInt() virtualPC += 4 * stackSize!! } else if (currentSection == ".DATA") { // setup DB // insert JMP instruction that jumps to .code section if (!flagSpecifyJMP) { // write opcode virtualPC += 4 flagSpecifyJMP = true } // data syntax: // type name payload (separated by any delimiters) // e.g.: string hai Hello, world! val type = words[0].toUpperCase() val name = words[1] putLabel(name, virtualPC) // putLabel must be followed by some bytes payload fed to the return array, no gaps in-between when (type) { "STRING" -> { val start = line.indexOf('"') + 1 val end = line.lastIndexOf('"') if (end <= start) throw IllegalArgumentException("malformed string declaration syntax -- must be surrounded with pair of \" (double quote)") val data = line.substring(start, end) // write bytes virtualPC += data.toCString().size virtualPC = virtualPC.toNextWord() } "INT", "FLOAT" -> { // write bytes virtualPC += 4 } "BYTES" -> { (2..words.lastIndex).forEach { if (words[it].matches(regexDecBinHexWhole) && words[it].resolveInt() in 0..255) { // byte literal debug("--> Byte literal payload: ${words[it]}") // write bytes virtualPC += 1 } else if (words[it].startsWith(labelMarker)) { debug("--> Byte label payload: ${words[it]}") // write bytes virtualPC += 4 } else { throw IllegalArgumentException("Illegal byte literal ${words[it]}") } } virtualPC = virtualPC.toNextWord() } else -> throw IllegalArgumentException("Unsupported data type: '$type' (or you missed a semicolon?)") } } else if (currentSection == ".CODE" || currentSection == ".FUNC") { // interpret codes if (flagSpecifyJMP && currentSection == ".CODE") { flagSpecifyJMP = false // write dest (this PC) at flagSpecifyJMPLocation debug("->> CODE section; vPC: $virtualPC") } else if (!flagSpecifyJMP && currentSection == ".FUNC") { // insert JMP instruction that jumps to .code section flagSpecifyJMP = true debug("->> FUNC section; vPC: $virtualPC") virtualPC += 4 } if (cmd.startsWith(labelDefinitionMarker)) { if (line.contains(delimiters)) { throw IllegalArgumentException("missed semicolon: for line '$line'") } putLabel(cmd.drop(1).toLowerCase(), virtualPC) // will continue to next statements } else { // sanitise input if (opcodes[cmd] == null) { throw InternalError("Invalid opcode: $cmd") } debug("->> Accepted command $cmd; vPC: $virtualPC") // write opcode virtualPC += 4 if (cmd in twoLiners) { virtualPC += 4 } } } } else { throw IllegalArgumentException("Invalid line: $line") } } // pass 2: program // --> reset flags flagSpecifyJMP = false // <-- end of reset flags debug("\n\n== Pass 2 ==\n\n") debug("*** Start PC: ${getPC()} ***") splitLines(userProgram).forEach { lline -> var line = lline.replace(Regex("""^ ?[\n]+"""), "") // do not remove ?, this takes care of spaces prepended on comment marker val words = line.split(delimiters) if (line.isEmpty() || words.isEmpty()) { // NOP } else if (!line.startsWith(labelMarker)) { debug("[TBASASM] line: '$line'") words.forEach { debug(" $it") } val cmd = words[0].toUpperCase() if (asmSections.contains(cmd)) { // sectioning commands currentSection = cmd // will continue to next statements } else if (currentSection == ".STACK") { repeat(stackSize ?: 0) { addWord(-1) } } else if (currentSection == ".DATA") { // setup DB // insert JMP instruction that jumps to .code section if (!flagSpecifyJMP) { flagSpecifyJMP = true flagSpecifyJMPLocation = getPC() addWord(composeJMP(0x3FFFFF)) } // data syntax: // type name payload (separated by any delimiters) // e.g.: string hai Hello, world! val type = words[0].toUpperCase() val name = words[1] putLabel(name, getPC()) // putLabel must be followed by some bytes payload fed to the return array, no gaps in-between when (type) { "STRING" -> { debug("->> line: $line") val start = line.indexOf('"') + 1 val end = line.lastIndexOf('"') if (end <= start) throw IllegalArgumentException("malformed string declaration syntax -- must be surrounded with pair of \" (double quote)") val data = line.substring(start, end) debug("--> strStart: $start") debug("--> String payload: '$data'") val theRealPayload = data.toCString() theRealPayload.forEach { addByte(it) } // using toCString(): null terminator is still required as executor requires it (READ_UNTIL_ZERO, literally) debug("--> payload size: ${theRealPayload.size}") zeroFillToAlignWord(theRealPayload.size) } "FLOAT" -> { val number = if (words.getOrNull(2) == null) 0f else words[2].toFloat() debug("--> Float payload: '$number'") number.toLittle().forEach { ret.add(it) } } "INT" -> { val int = if (words.getOrNull(2) == null) 0 else if (words[2].startsWith(labelMarker)) { labelTable[words[2]] ?: throw NullPointerException("Undefined label: ${words[2]}") } else words[2].toInt() debug("--> Int payload: '$int'") int.toLittle().forEach { ret.add(it) } } "BYTES" -> { val addedBytesSize = words.size - 2 (2..words.lastIndex).forEach { if (words[it].matches(regexDecBinHexWhole) && words[it].resolveInt() in 0..255) { // byte literal debug("--> Byte literal payload: ${words[it].resolveInt()}") addByte(words[it].resolveInt().toByte()) } else if (words[it].startsWith(labelMarker)) { debug("--> Byte literal payload (label): ${words[it]}") getLabel(words[it]).toLittle().forEach { ret.add(it) } } else { throw IllegalArgumentException("Illegal byte literal ${words[it]}") } } zeroFillToAlignWord(addedBytesSize) } else -> throw IllegalArgumentException("Unsupported data type: '$type' (or you missed a semicolon?)") } } else if (currentSection == ".CODE" || currentSection == ".FUNC") { // interpret codes if (flagSpecifyJMP && currentSection == ".CODE") { flagSpecifyJMP = false // write dest (this PC) at flagSpecifyJMPLocation debug("[TBASASM] inserting JMP at $flagSpecifyJMPLocation that points to ${getPC()}") val newASM = composeJMP(getPC().ushr(2)).toLittle() for (i in 0..3) { ret[flagSpecifyJMPLocation - programSpaceStart + i] = newASM[i] } } else if (!flagSpecifyJMP && currentSection == ".FUNC") { // insert JMP instruction that jumps to .code section flagSpecifyJMP = true addWord(composeJMP(flagSpecifyJMPLocation.ushr(2))) // set new jmp location flagSpecifyJMPLocation = getPC() } if (cmd.startsWith(labelDefinitionMarker)) { putLabel(cmd.drop(1).toLowerCase(), getPC()) // will continue to next statements } else { addWords(assemblyToOpcode(line)) } } } else { throw IllegalArgumentException("Invalid line: $line") } } // append HALT addWord(0) debug("======== Assembler: Done! ========") return ProgramImage(stackSize ?: 0, ret.toByteArray()) } private fun String.toRegInt() = if (this.matches(regexRegisterLiteral)) this[1].toInt() - 48 // "r0" -> 0 else throw IllegalArgumentException("Illegal register literal: '$this'") private fun String.resolveInt() = if (this.startsWith("0x")) throw IllegalArgumentException("Use h instead of 0x") else if (this.startsWith("0b")) throw IllegalArgumentException("Use b instead of 0b") else if (this.startsWith(labelMarker)) // label? getLabel(this).ushr(2) else if (this.matches(regexHexWhole)) // hex? this.dropLast(1).toLong(16).toInt() // because what the fuck Kotlin? else if (this.matches(regexBinWhole)) // bin? this.dropLast(1).toLong(2).toInt() // because what the fuck Kotlin? else if (this.matches(regexIntWhole)) // number? this.toLong().toInt() // because what the fuck Kotlin? else throw UnsupportedOperationException("Couldn't convert this to integer: '$this'") } /** * @param bytes entire image of the program, including stack area */ data class ProgramImage(val stackSize: Int, val bytes: ByteArray) class UnknownOpcodeExpection(opcode: Int) : InternalError("Unknown opcode: ${opcode.toReadableBin()}") // can't get readable string because of loophole
mit
4ddf788c1fedb23c301e20303e44dca7
36.35034
168
0.455878
4.596484
false
false
false
false
qaware/kubepad
src/main/kotlin/de/qaware/cloud/nativ/kpad/leapmotion/LeapMotionListener.kt
1
3703
/* * The MIT License (MIT) * * Copyright (c) 2016 QAware GmbH, Munich, Germany * * 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 de.qaware.cloud.nativ.kpad.leapmotion import com.leapmotion.leap.* import de.qaware.cloud.nativ.kpad.launchpad.LaunchpadController import org.slf4j.Logger import kotlin.reflect.KProperty /** * The Leap motion listener implementation to handle frames and gestures. */ class LeapMotionListener constructor(private val launchpad: LaunchpadController, private val logger: Logger) : Listener() { var connected = false override fun onConnect(controller: Controller?) { logger.info("Leap Motion device connected.") connected = true } override fun onFrame(controller: Controller?) { val frame = controller?.frame() val gestures = frame?.gestures() for (gesture in gestures!!.iterator()) { when (gesture.type()) { Gesture.Type.TYPE_SWIPE -> { val swipe = SwipeGesture(gesture) if (swipe.state() == Gesture.State.STATE_STOP) { // scale cluster by number of fingers val fingers = frame.fingers()?.count() ?: -1 logger.debug("Detected swipe gesture with {} fingers.", fingers) launchpad.scale(fingers) } } Gesture.Type.TYPE_SCREEN_TAP -> { val screenTap = ScreenTapGesture(gesture) if (screenTap.state() == Gesture.State.STATE_STOP) { // one row up logger.debug("Detected screen tap. One row up.") launchpad.up() } } Gesture.Type.TYPE_KEY_TAP -> { val keyTap = KeyTapGesture(gesture) if (keyTap.state() == Gesture.State.STATE_STOP) { // one row down logger.debug("Detected key tap. One row down.") launchpad.down() } } else -> { // nothing to do } } } } override fun onDisconnect(controller: Controller?) { logger.debug("Leap Motion device disconnected.") connected = false } operator fun getValue(controller: LeapMotionController, property: KProperty<*>): Boolean = connected operator fun setValue(controller: LeapMotionController, property: KProperty<*>, b: Boolean) { this.connected = b } }
mit
e330456d63a0d86867c806beae06449b
38.827957
104
0.599784
4.943925
false
false
false
false
NextFaze/dev-fun
devfun/src/main/java/com/nextfaze/devfun/inject/Android.kt
1
4223
package com.nextfaze.devfun.inject import android.app.Activity import android.app.Application import android.app.Service import android.content.Context import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import androidx.fragment.app.FragmentManager import com.nextfaze.devfun.core.ActivityProvider import com.nextfaze.devfun.internal.android.* import java.util.ArrayDeque import kotlin.reflect.KClass interface AndroidInstanceProvider : AndroidInstanceProviderInternal { override val activity: Activity? } internal class AndroidInstanceProviderImpl(context: Context, private val activityProvider: ActivityProvider) : AndroidInstanceProvider { private val applicationContext = context.applicationContext override val activity: Activity? get() = activityProvider() @Suppress("UNCHECKED_CAST") override fun <T : Any> get(clazz: KClass<out T>): T? { // Activities if (clazz.isSubclassOf<Activity>()) { // if the class is of type activity, then we need to return null if no activity is found (can't return Context as it could result in type error) return activityProvider() as T? } // Application if (clazz.isSubclassOf<Application>()) { return applicationContext as T } // Service if (clazz.isSubclassOf<Service>()) { return applicationContext as T } // Context val activity = activityProvider() if (clazz.isSubclassOf<Context>()) { return (activity ?: applicationContext) as T } // Fragments if (activity is FragmentActivity && clazz.isSubclassOf<Fragment>()) { activity.supportFragmentManager.iterateChildren().forEach { // not sure why, but under some circumstances some of them are null... it ?: return@forEach if (it.isAdded && it::class.isSubclassOf(clazz)) { @Suppress("UNCHECKED_CAST") return it as T } } } // Views if (activity != null && clazz.isSubclassOf<View>()) { activity.findViewById<ViewGroup>(android.R.id.content)?.let { traverseViewHierarchy(it, clazz) }?.let { return it } if (activity is FragmentActivity) { activity.supportFragmentManager.iterateChildren().forEach { fragment -> (fragment?.view as? ViewGroup)?.let { traverseViewHierarchy(it, clazz) }?.let { return it } } } } return null } } // // Fragment Traversal // private val peekChildFragmentManagerMethod = Fragment::class.java.getDeclaredMethod("peekChildFragmentManager").apply { isAccessible = true } private val Fragment.hasChildFragmentManager get() = peekChildFragmentManagerMethod.invoke(this) != null private fun FragmentManager.iterateChildren(): Iterator<Fragment?> { class FragmentManagerIterator : Iterator<Fragment?> { private val iterators = ArrayDeque<Iterator<Fragment?>>().apply { push(fragments.iterator()) } override fun hasNext(): Boolean { while (true) { val it = iterators.peek() ?: return false if (it.hasNext()) { return true } else { iterators.pop() } } } override fun next(): Fragment? { val fragment = iterators.peek().next() if (fragment != null && fragment.hasChildFragmentManager) { iterators.push(fragment.childFragmentManager.iterateChildren()) } return fragment } } return FragmentManagerIterator() } // // View Traversal // private fun <T : Any> traverseViewHierarchy(viewGroup: ViewGroup, clazz: KClass<out T>): T? { viewGroup.children<View>().forEach { if (it::class.isSubclassOf(clazz)) { @Suppress("UNCHECKED_CAST") return it as T } else if (it is ViewGroup) { return traverseViewHierarchy(it, clazz) } } return null }
apache-2.0
d78bb29e508c308a15b7311645004b0d
32.251969
156
0.625148
5.069628
false
false
false
false
trinhlbk1991/vivid
library/src/main/java/com/icetea09/vivid/LoadImagesTask.kt
1
2352
package com.icetea09.vivid import android.content.Context import android.database.Cursor import android.os.AsyncTask import android.provider.MediaStore import com.icetea09.vivid.common.ImageLoaderListener import com.icetea09.vivid.model.Folder import com.icetea09.vivid.model.Image import java.io.File import java.lang.ref.WeakReference import java.util.ArrayList import java.util.HashMap class LoadImagesTask(context: Context, internal var listener: ImageLoaderListener?) : AsyncTask<Void, Int, List<Folder>>() { private val projection = arrayOf(MediaStore.Images.Media._ID, MediaStore.Images.Media.DISPLAY_NAME, MediaStore.Images.Media.DATA, MediaStore.Images.Media.BUCKET_DISPLAY_NAME) internal var contextWeakReference: WeakReference<Context> = WeakReference(context) override fun doInBackground(vararg params: Void): List<Folder>? { val context = contextWeakReference.get() ?: return null val cursor = context.contentResolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null, null, MediaStore.Images.Media.DATE_ADDED) ?: return null val folderMap = HashMap<String, Folder>() if (cursor.moveToLast()) { do { val id = cursor.getLong(cursor.getColumnIndex(projection[0])) val name = cursor.getString(cursor.getColumnIndex(projection[1])) val path = cursor.getString(cursor.getColumnIndex(projection[2])) val bucketDisplayName = cursor.getString(cursor.getColumnIndex(projection[3])) if (path != null) { val file = File(path) if (file.exists()) { val image = Image(id, name, path, false) var folder: Folder? = folderMap[bucketDisplayName] if (folder == null) { folder = Folder(bucketDisplayName) folderMap.put(bucketDisplayName, folder) } folder.images.add(image) } } } while (cursor.moveToPrevious()) } cursor.close() return ArrayList(folderMap.values) } override fun onPostExecute(folders: List<Folder>) { listener?.onImageLoaded(folders) } }
mit
9dad511892704eaf16229f5c5240d7e1
36.935484
124
0.630527
4.704
false
false
false
false
Light-Team/ModPE-IDE-Source
app/src/main/kotlin/com/brackeys/ui/feature/editor/utils/ToolbarManager.kt
1
9488
/* * Copyright 2021 Brackeys IDE contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.brackeys.ui.feature.editor.utils import android.content.res.Configuration import android.view.Menu import android.view.MenuItem import android.view.View import androidx.appcompat.view.ContextThemeWrapper import androidx.appcompat.widget.PopupMenu import androidx.core.view.isVisible import androidx.core.widget.doAfterTextChanged import com.brackeys.ui.R import com.brackeys.ui.databinding.FragmentEditorBinding import com.brackeys.ui.editorkit.model.FindParams import com.brackeys.ui.utils.extensions.makeRightPaddingRecursively class ToolbarManager( private val listener: OnPanelClickListener ) : PopupMenu.OnMenuItemClickListener { var orientation: Int = Configuration.ORIENTATION_UNDEFINED set(value) { field = when (value) { Configuration.ORIENTATION_PORTRAIT -> portrait() Configuration.ORIENTATION_LANDSCAPE -> landscape() else -> Configuration.ORIENTATION_UNDEFINED } } var panel: Panel = Panel.DEFAULT set(value) { field = value updatePanel() } private var isRegex = false private var isMatchCase = true private var isWordsOnly = false private lateinit var binding: FragmentEditorBinding override fun onMenuItemClick(item: MenuItem): Boolean { when (item.itemId) { // File Menu R.id.action_new -> listener.onNewButton() R.id.action_open -> listener.onOpenButton() R.id.action_save -> listener.onSaveButton() R.id.action_save_as -> listener.onSaveAsButton() R.id.action_properties -> listener.onPropertiesButton() R.id.action_close -> listener.onCloseButton() // Edit Menu R.id.action_cut -> listener.onCutButton() R.id.action_copy -> listener.onCopyButton() R.id.action_paste -> listener.onPasteButton() R.id.action_select_all -> listener.onSelectAllButton() R.id.action_select_line -> listener.onSelectLineButton() R.id.action_delete_line -> listener.onDeleteLineButton() R.id.action_duplicate_line -> listener.onDuplicateLineButton() // Find Menu R.id.action_find -> listener.onOpenFindButton() R.id.action_switch_find -> { listener.onCloseReplaceButton() listener.onCloseFindButton() } R.id.action_switch_replace -> { if (panel == Panel.FIND) { listener.onOpenReplaceButton() } else { listener.onCloseReplaceButton() } } R.id.action_goto_line -> listener.onGoToLineButton() R.id.action_regex -> { isRegex = !isRegex listener.onFindInputChanged(binding.inputFind.text.toString()) } R.id.action_match_case -> { isMatchCase = !isMatchCase listener.onFindInputChanged(binding.inputFind.text.toString()) } R.id.action_words_only -> { isWordsOnly = !isWordsOnly listener.onFindInputChanged(binding.inputFind.text.toString()) } // Tools Menu R.id.action_error_checking -> listener.onErrorCheckingButton() R.id.action_insert_color -> listener.onInsertColorButton() // Overflow Menu R.id.action_settings -> listener.onSettingsButton() } return false } fun bind(binding: FragmentEditorBinding) { this.binding = binding orientation = binding.root.resources?.configuration?.orientation ?: Configuration.ORIENTATION_PORTRAIT updatePanel() binding.actionDrawer.setOnClickListener { listener.onDrawerButton() } binding.actionSave.setOnClickListener { listener.onSaveButton() } binding.actionFind.setOnClickListener { listener.onOpenFindButton() } setMenuClickListener(binding.actionFile, R.menu.menu_file) setMenuClickListener(binding.actionEdit, R.menu.menu_edit) setMenuClickListener(binding.actionTools, R.menu.menu_tools) setMenuClickListener(binding.actionFindOverflow, R.menu.menu_find) binding.actionUndo.setOnClickListener { listener.onUndoButton() } binding.actionRedo.setOnClickListener { listener.onRedoButton() } binding.actionReplace.setOnClickListener { listener.onReplaceButton(binding.inputReplace.text.toString()) } binding.actionReplaceAll.setOnClickListener { listener.onReplaceAllButton(binding.inputReplace.text.toString()) } binding.actionDown.setOnClickListener { listener.onNextResultButton() } binding.actionUp.setOnClickListener { listener.onPreviousResultButton() } binding.inputFind.doAfterTextChanged { listener.onFindInputChanged(it.toString()) } } fun findParams(): FindParams { return FindParams( regex = isRegex, matchCase = isMatchCase, wordsOnly = isWordsOnly ) } private fun portrait(): Int { binding.actionSave.visibility = View.GONE binding.actionFind.visibility = View.GONE binding.actionTools.visibility = View.GONE setMenuClickListener(binding.actionOverflow, R.menu.menu_overflow_vertical) return Configuration.ORIENTATION_PORTRAIT } private fun landscape(): Int { binding.actionSave.visibility = View.VISIBLE binding.actionFind.visibility = View.VISIBLE binding.actionTools.visibility = View.VISIBLE setMenuClickListener(binding.actionOverflow, R.menu.menu_overflow_horizontal) return Configuration.ORIENTATION_LANDSCAPE } private fun setMenuClickListener(view: View, menuRes: Int) { view.setOnClickListener { val wrapper = ContextThemeWrapper(it.context, R.style.Widget_AppTheme_PopupMenu) val popupMenu = PopupMenu(wrapper, it) popupMenu.setOnMenuItemClickListener(this) popupMenu.inflate(menuRes) popupMenu.makeRightPaddingRecursively() onPreparePopupMenu(popupMenu.menu) popupMenu.show() } } private fun onPreparePopupMenu(menu: Menu) { val switchReplace = menu.findItem(R.id.action_switch_replace) val regex = menu.findItem(R.id.action_regex) val matchCase = menu.findItem(R.id.action_match_case) val wordsOnly = menu.findItem(R.id.action_words_only) if (panel == Panel.FIND_REPLACE) { switchReplace?.setTitle(R.string.action_close_replace) } regex?.isChecked = isRegex matchCase?.isChecked = isMatchCase wordsOnly?.isChecked = isWordsOnly } private fun updatePanel() { when (panel) { Panel.DEFAULT -> { binding.defaultPanel.isVisible = true binding.findPanel.isVisible = false binding.replacePanel.isVisible = false binding.editor.requestFocus() } Panel.FIND -> { binding.defaultPanel.isVisible = false binding.findPanel.isVisible = true binding.replacePanel.isVisible = false binding.inputFind.requestFocus() } Panel.FIND_REPLACE -> { binding.defaultPanel.isVisible = false binding.findPanel.isVisible = true binding.replacePanel.isVisible = true binding.inputReplace.requestFocus() } } } interface OnPanelClickListener { fun onDrawerButton() fun onNewButton() fun onOpenButton() fun onSaveButton(): Boolean fun onSaveAsButton(): Boolean fun onPropertiesButton(): Boolean fun onCloseButton(): Boolean fun onCutButton(): Boolean fun onCopyButton(): Boolean fun onPasteButton(): Boolean fun onSelectAllButton(): Boolean fun onSelectLineButton(): Boolean fun onDeleteLineButton(): Boolean fun onDuplicateLineButton(): Boolean fun onOpenFindButton(): Boolean fun onCloseFindButton() fun onOpenReplaceButton(): Boolean fun onCloseReplaceButton() fun onGoToLineButton(): Boolean fun onReplaceButton(replaceText: String) fun onReplaceAllButton(replaceText: String) fun onNextResultButton() fun onPreviousResultButton() fun onFindInputChanged(findText: String) fun onErrorCheckingButton() fun onInsertColorButton() fun onUndoButton(): Boolean fun onRedoButton(): Boolean fun onSettingsButton(): Boolean } }
apache-2.0
7e31d5318dd7ce1a6a7d67c0de0504fd
36.211765
110
0.64102
4.833418
false
false
false
false
MarKco/Catchit
catchit/src/main/java/com/ilsecondodasinistra/catchit/DatabaseHelper.kt
1
43289
package com.ilsecondodasinistra.catchit import android.content.Context import android.database.Cursor import android.database.sqlite.SQLiteDatabase import android.util.Log import java.text.ParseException import java.text.SimpleDateFormat import java.util.Date import java.util.LinkedList /** * Created by marco on 17/01/17. */ object DatabaseHelper { val routeForT1MestreVe = "732, 733" val routeForT1VeMestre = "734, 735" val routeForT2MestreMa = "781" val routeForT2MaMestre = "782, 783" val routeForN1 = "712, 713" val routeForN2 = "714" val routeFor12MestreVe = "534" val routeFor12VeMestre = "533" val routeFor15AirportStation = "549, 550" val routeFor15StationAirport = "551, 552" val departingSansovino = "6061" val returningSansovino = "6062" val sansovinoForN = departingSansovino + ", " + returningSansovino val veniceStops = "510, 6084" val veniceStopsFor12 = "501" val cialdini = "6080, 6027, 6081" val stazioneMestre = "6074, 6073" val stazioneMestreFor15 = "613" val viaHermadaStreetSide = "172" val viaHermadaCanalSide = "1172" val airport = "3626" internal var databaseHourFormatter = SimpleDateFormat("HH:mm:ss") //DateFormatter four hours.minutes.seconds private val dateFormatter = SimpleDateFormat("HH:mm:ss") //DateFormatter four hours.minutes.seconds lateinit var db: SQLiteDatabase private fun openDatabase(context: Context): SQLiteDatabase { val dbHelper = MyDatabase(context) dbHelper.setForcedUpgrade() return dbHelper.writableDatabase } private fun closeDatabase(db: SQLiteDatabase) { db.close() } fun getTramAndBusesToVenice(context: Context, yesterdayForQuery: String, now: Date, operator: String, dayForThisQuery: String): List<Bus> { db = openDatabase(context) val tramToVeniceTimes = LinkedList<Bus>() val tramToVenice = "SELECT t.trip_id,\n" + " start_s.stop_name as departure_stop,\n" + "\t start_s.stop_id as departure_stop_id,\n" + " start_st.departure_time as departure_time,\n" + " direction_id as direction,\n" + " end_s.stop_name as arrival_stop,\n" + "\t end_s.stop_id as arrival_stop_id,\n" + " end_st.arrival_time as arrival_time,\n" + " r.route_short_name as route_short_name,\n" + " r.route_long_name as route_long_name\n" + "FROM\n" + "trips t INNER JOIN calendar c ON t.service_id = c.service_id\n" + " INNER JOIN routes r ON t.route_id = r.route_id\n" + " INNER JOIN stop_times start_st ON t.trip_id = start_st.trip_id\n" + " INNER JOIN stops start_s ON start_st.stop_id = start_s.stop_id\n" + " INNER JOIN stop_times end_st ON t.trip_id = end_st.trip_id\n" + " INNER JOIN stops end_s ON end_st.stop_id = end_s.stop_id\n" + "WHERE " + dayForThisQuery + " = 1\n" + " and r.route_id in (" + routeForT1MestreVe + ", " + routeFor12MestreVe + ")\n" + //For ordinary buses " and DATETIME(start_st.departure_time) " + operator + " DATETIME('" + databaseHourFormatter.format(subtractMinutesFromDate(4, now)) + "')\n" + " and departure_stop_id = " + departingSansovino + "\n" + " and end_s.stop_id in (" + veniceStops + ", " + veniceStopsFor12 + ")\n" + " UNION " + "SELECT t.trip_id,\n" + " start_s.stop_name as departure_stop,\n" + "\t start_s.stop_id as departure_stop_id,\n" + " start_st.departure_time as departure_time,\n" + " direction_id as direction,\n" + " end_s.stop_name as arrival_stop,\n" + "\t end_s.stop_id as arrival_stop_id,\n" + " end_st.arrival_time as arrival_time,\n" + " r.route_short_name as route_short_name,\n" + " r.route_long_name as route_long_name\n" + "FROM\n" + "trips t INNER JOIN calendar c ON t.service_id = c.service_id\n" + " INNER JOIN routes r ON t.route_id = r.route_id\n" + " INNER JOIN stop_times start_st ON t.trip_id = start_st.trip_id\n" + " INNER JOIN stops start_s ON start_st.stop_id = start_s.stop_id\n" + " INNER JOIN stop_times end_st ON t.trip_id = end_st.trip_id\n" + " INNER JOIN stops end_s ON end_st.stop_id = end_s.stop_id\n" + "WHERE " + dayForThisQuery + " = 1\n" + " and r.route_id in (" + routeForN1 + ", " + routeForN2 + ")\n" + " and departure_stop_id in (" + sansovinoForN + ")\n" + //For night buses " and DATETIME(start_st.departure_time) " + operator + " DATETIME('" + databaseHourFormatter.format(subtractMinutesFromDate(4, now)) + "')\n" + " and DATETIME(start_st.departure_time) < DATETIME(end_st.arrival_time)\n" + //Needed only because N1 and N2 are circular, so you could get paradoxical results " and end_s.stop_id in (" + veniceStops + ")\n" + " and end_st.late_night IS NULL\n" + " UNION " + "SELECT t.trip_id,\n" + " start_s.stop_name as departure_stop,\n" + "\t start_s.stop_id as departure_stop_id,\n" + " start_st.departure_time as departure_time,\n" + " direction_id as direction,\n" + " end_s.stop_name as arrival_stop,\n" + "\t end_s.stop_id as arrival_stop_id,\n" + " end_st.arrival_time as arrival_time,\n" + " r.route_short_name as route_short_name,\n" + // " end_st.late_night as bus_late_night,\n" + " r.route_long_name as route_long_name\n" + "FROM\n" + "trips t INNER JOIN calendar c ON t.service_id = c.service_id\n" + " INNER JOIN routes r ON t.route_id = r.route_id\n" + " INNER JOIN stop_times start_st ON t.trip_id = start_st.trip_id\n" + " INNER JOIN stops start_s ON start_st.stop_id = start_s.stop_id\n" + " INNER JOIN stop_times end_st ON t.trip_id = end_st.trip_id\n" + " INNER JOIN stops end_s ON end_st.stop_id = end_s.stop_id\n" + "WHERE " + yesterdayForQuery + " = 1\n" + " and r.route_id in (" + routeForN1 + ", " + routeForN2 + ")\n" + " and departure_stop_id in (" + sansovinoForN + ")\n" + //For night buses " and DATETIME(start_st.departure_time) " + operator + " DATETIME('" + databaseHourFormatter.format(subtractMinutesFromDate(4, now)) + "')\n" + " and DATETIME(start_st.departure_time) < DATETIME(end_st.arrival_time)\n" + //Needed only because N1 and N2 are circular, so you could get paradoxical results " and end_s.stop_id in (" + veniceStops + ")\n" + " and end_st.late_night IS NOT NULL\n" + "order by start_st.departure_time asc" // if (BuildConfig.DEBUG) // Log.w("TramToVenice", tramToVenice); val leavingCursor = db.rawQuery(tramToVenice, null) leavingCursor.moveToFirst() if (leavingCursor.count > 0) try { do { val departureStop = leavingCursor.getString(leavingCursor.getColumnIndex("departure_stop")) val departureTime = leavingCursor.getString(leavingCursor.getColumnIndex("departure_time")) val arrivalStop = leavingCursor.getString(leavingCursor.getColumnIndex("arrival_stop")) val arrivalTime = leavingCursor.getString(leavingCursor.getColumnIndex("arrival_time")) val line = leavingCursor.getString(leavingCursor.getColumnIndex("route_short_name")) tramToVeniceTimes.add(Bus(dateFormatter.parse(departureTime), line, departureStop, arrivalStop, dateFormatter.parse(arrivalTime) )) // Log.i("Catchit", "Added a new item: " + departureStop + " " + departureTime + " " + line); } while (leavingCursor.moveToNext()) } catch (e: ParseException) { Log.e("Catchit", "Uff, cheppalle") } leavingCursor.close() db.close() return tramToVeniceTimes } fun getTramAndBusesFromVenice(context: Context, yesterdayForQuery: String, now: Date, operator: String, dayForThisQuery: String): List<Bus> { db = openDatabase(context) val tramToMestreTimes = LinkedList<Bus>() val tramFromVenice = "SELECT t.trip_id,\n" + " start_s.stop_name as departure_stop,\n" + " start_s.stop_id as departure_stop_id,\n" + " start_st.departure_time as departure_time,\n" + " direction_id as direction,\n" + " end_s.stop_name as arrival_stop,\n" + " end_s.stop_id as arrival_stop_id,\n" + " end_st.arrival_time as arrival_time,\n" + " r.route_short_name as short_name,\n" + " r.route_long_name as long_name\n" + "FROM\n" + "trips t INNER JOIN calendar c ON t.service_id = c.service_id\n" + " INNER JOIN routes r ON t.route_id = r.route_id\n" + " INNER JOIN stop_times start_st ON t.trip_id = start_st.trip_id\n" + " INNER JOIN stops start_s ON start_st.stop_id = start_s.stop_id\n" + " INNER JOIN stop_times end_st ON t.trip_id = end_st.trip_id\n" + " INNER JOIN stops end_s ON end_st.stop_id = end_s.stop_id\n" + "WHERE " + dayForThisQuery + " = 1\n" + " and r.route_id in (" + routeForT1VeMestre + ", " + routeFor12VeMestre + ")\n" + //For ordinary buses " and DATETIME(start_st.departure_time) " + operator + " DATETIME('" + databaseHourFormatter.format(subtractMinutesFromDate(4, now)) + "')\n" + " and departure_stop_id in (" + veniceStops + ", " + veniceStopsFor12 + ")\n" + " and end_s.stop_id = " + returningSansovino + "\n" + " UNION " + " SELECT t.trip_id, \n" + " start_s.stop_name as departure_stop,\n" + " start_s.stop_id as departure_stop_id,\n" + " start_st.departure_time as departure_time,\n" + " direction_id as direction,\n" + " end_s.stop_name as arrival_stop,\n" + " end_s.stop_id as arrival_stop_id,\n" + " end_st.arrival_time as arrival_time,\n" + " r.route_short_name as short_name,\n" + " r.route_long_name as long_name\n" + "FROM\n" + "trips t INNER JOIN calendar c ON t.service_id = c.service_id\n" + " INNER JOIN routes r ON t.route_id = r.route_id\n" + " INNER JOIN stop_times start_st ON t.trip_id = start_st.trip_id\n" + " INNER JOIN stops start_s ON start_st.stop_id = start_s.stop_id\n" + " INNER JOIN stop_times end_st ON t.trip_id = end_st.trip_id\n" + " INNER JOIN stops end_s ON end_st.stop_id = end_s.stop_id\n" + "WHERE " + dayForThisQuery + " = 1\n" + " and r.route_id in (" + routeForN1 + ", " + routeForN2 + ")\n" + //For night buses " and DATETIME(start_st.departure_time) " + operator + " DATETIME('" + databaseHourFormatter.format(subtractMinutesFromDate(4, now)) + "')\n" + " and departure_stop_id in (" + veniceStops + ")\n" + " and DATETIME(start_st.departure_time) < DATETIME(end_st.arrival_time)\n" + //Needed only because N1 and N2 are circular, so you could get paradoxical results " and end_s.stop_id in (" + sansovinoForN + ")\n" + " and end_st.late_night IS NULL\n" + " UNION " + "SELECT t.trip_id,\n" + " start_s.stop_name as departure_stop,\n" + "\t start_s.stop_id as departure_stop_id,\n" + " start_st.departure_time as departure_time,\n" + " direction_id as direction,\n" + " end_s.stop_name as arrival_stop,\n" + "\t end_s.stop_id as arrival_stop_id,\n" + " end_st.arrival_time as arrival_time,\n" + " r.route_short_name as route_short_name,\n" + // " end_st.late_night as bus_late_night,\n" + " r.route_long_name as route_long_name\n" + "FROM\n" + "trips t INNER JOIN calendar c ON t.service_id = c.service_id\n" + " INNER JOIN routes r ON t.route_id = r.route_id\n" + " INNER JOIN stop_times start_st ON t.trip_id = start_st.trip_id\n" + " INNER JOIN stops start_s ON start_st.stop_id = start_s.stop_id\n" + " INNER JOIN stop_times end_st ON t.trip_id = end_st.trip_id\n" + " INNER JOIN stops end_s ON end_st.stop_id = end_s.stop_id\n" + "WHERE " + yesterdayForQuery + " = 1\n" + " and r.route_id in (" + routeForN1 + ", " + routeForN2 + ")\n" + " and departure_stop_id in (" + veniceStops + ")\n" + //For night buses " and DATETIME(start_st.departure_time) " + operator + " DATETIME('" + databaseHourFormatter.format(subtractMinutesFromDate(4, now)) + "')\n" + " and DATETIME(start_st.departure_time) < DATETIME(end_st.arrival_time)\n" + //Needed only because N1 and N2 are circular, so you could get paradoxical results " and end_s.stop_id in (" + sansovinoForN + ")\n" + " and end_st.late_night IS NOT NULL\n" + "order by start_st.departure_time asc" // if(BuildConfig.DEBUG) // Log.w("TramFromVenice", tramFromVenice); val comingCursor = db.rawQuery(tramFromVenice, null) comingCursor.moveToFirst() if (comingCursor.count > 0) try { do { val departureStop = comingCursor.getString(comingCursor.getColumnIndex("departure_stop")) val departureTime = comingCursor.getString(comingCursor.getColumnIndex("departure_time")) val arrivalTime = comingCursor.getString(comingCursor.getColumnIndex("arrival_time")) val arrivalStop = comingCursor.getString(comingCursor.getColumnIndex("arrival_stop")) val line = comingCursor.getString(comingCursor.getColumnIndex("short_name")) tramToMestreTimes.add(Bus(dateFormatter.parse(departureTime), line, departureStop, arrivalStop, dateFormatter.parse(arrivalTime))) // Log.i("Catchit", "Added a new item: " + departureStop + " " + departureTime + " " + line); } while (comingCursor.moveToNext()) } catch (e: ParseException) { Log.e("Catchit", "Uff, cheppalle") } comingCursor.close() db.close() return tramToMestreTimes } fun getTramToStation(context: Context, yesterdayForQuery: String, now: Date, operator: String, dayForThisQuery: String): List<Bus> { db = openDatabase(context) val tramToStationTimes = LinkedList<Bus>() //Tram Mestre Centro -> Stazione val tramToStation = "SELECT t.trip_id,\n" + " start_s.stop_name as departure_stop,\n" + "\t start_s.stop_id as departure_stop_id,\n" + " start_st.departure_time,\n" + " direction_id as direction,\n" + " end_s.stop_name as arrival_stop,\n" + "\t end_s.stop_id as arrival_stop_id,\n" + " end_st.arrival_time,\n" + " r.route_short_name\n" + "FROM\n" + "trips t INNER JOIN calendar c ON t.service_id = c.service_id\n" + " INNER JOIN routes r ON t.route_id = r.route_id\n" + " INNER JOIN stop_times start_st ON t.trip_id = start_st.trip_id\n" + " INNER JOIN stops start_s ON start_st.stop_id = start_s.stop_id\n" + " INNER JOIN stop_times end_st ON t.trip_id = end_st.trip_id\n" + " INNER JOIN stops end_s ON end_st.stop_id = end_s.stop_id\n" + "WHERE " + dayForThisQuery + " = 1\n" + " and r.route_id in (" + routeForT2MestreMa + ")\n" + " and DATETIME(start_st.departure_time) " + operator + " DATETIME('" + databaseHourFormatter.format(subtractMinutesFromDate(4, now)) + "')\n" + " and arrival_stop_id in (" + stazioneMestre + ")\n" + " and departure_stop_id in (" + cialdini + ")\n" + "order by start_st.departure_time asc\t" // if(BuildConfig.DEBUG) // Log.w("TramToStation", tramToStation); val leavingTramCursor = db.rawQuery(tramToStation, null) leavingTramCursor.moveToFirst() if (leavingTramCursor.count > 0) try { do { val departureStop = leavingTramCursor.getString(leavingTramCursor.getColumnIndex("departure_stop")) val departureTime = leavingTramCursor.getString(leavingTramCursor.getColumnIndex("departure_time")) val arrivalTime = leavingTramCursor.getString(leavingTramCursor.getColumnIndex("arrival_time")) val arrivalStop = leavingTramCursor.getString(leavingTramCursor.getColumnIndex("arrival_stop")) val line = leavingTramCursor.getString(leavingTramCursor.getColumnIndex("route_short_name")) tramToStationTimes.add(Bus(dateFormatter.parse(departureTime), line, departureStop, arrivalStop, dateFormatter.parse(arrivalTime) )) } while (leavingTramCursor.moveToNext()) } catch (e: ParseException) { Log.e("Catchit", "Uff, cheppalle") } leavingTramCursor.close() db.close() return tramToStationTimes } fun getTramFromStation(context: Context, yesterdayForQuery: String, now: Date, operator: String, dayForThisQuery: String): List<Bus> { db = openDatabase(context) val tramToStationTimes = LinkedList<Bus>() //Tram Mestre Centro -> Stazione val tramToStation = "SELECT t.trip_id,\n" + " start_s.stop_name as departure_stop,\n" + "\t start_s.stop_id as departure_stop_id,\n" + " start_st.departure_time,\n" + " direction_id as direction,\n" + " end_s.stop_name as arrival_stop,\n" + "\t end_s.stop_id as arrival_stop_id,\n" + " end_st.arrival_time,\n" + " r.route_short_name\n" + "FROM\n" + "trips t INNER JOIN calendar c ON t.service_id = c.service_id\n" + " INNER JOIN routes r ON t.route_id = r.route_id\n" + " INNER JOIN stop_times start_st ON t.trip_id = start_st.trip_id\n" + " INNER JOIN stops start_s ON start_st.stop_id = start_s.stop_id\n" + " INNER JOIN stop_times end_st ON t.trip_id = end_st.trip_id\n" + " INNER JOIN stops end_s ON end_st.stop_id = end_s.stop_id\n" + "WHERE " + dayForThisQuery + " = 1\n" + " and r.route_id in (" + routeForT2MaMestre + ")\n" + " and DATETIME(start_st.departure_time) " + operator + " DATETIME('" + databaseHourFormatter.format(subtractMinutesFromDate(4, now)) + "')\n" + " and arrival_stop_id in (" + cialdini + ")\n" + " and departure_stop_id in (" + stazioneMestre + ")\n" + "order by start_st.departure_time asc\t" // if(BuildConfig.DEBUG) // Log.w("TramToStation", tramToStation); val leavingTramCursor = db.rawQuery(tramToStation, null) leavingTramCursor.moveToFirst() if (leavingTramCursor.count > 0) try { do { val departureStop = leavingTramCursor.getString(leavingTramCursor.getColumnIndex("departure_stop")) val departureTime = leavingTramCursor.getString(leavingTramCursor.getColumnIndex("departure_time")) val arrivalTime = leavingTramCursor.getString(leavingTramCursor.getColumnIndex("arrival_time")) val arrivalStop = leavingTramCursor.getString(leavingTramCursor.getColumnIndex("arrival_stop")) val line = leavingTramCursor.getString(leavingTramCursor.getColumnIndex("route_short_name")) tramToStationTimes.add(Bus(dateFormatter.parse(departureTime), line, departureStop, arrivalStop, dateFormatter.parse(arrivalTime) )) } while (leavingTramCursor.moveToNext()) } catch (e: ParseException) { Log.e("Catchit", "Uff, cheppalle") } leavingTramCursor.close() db.close() return tramToStationTimes } fun getCenterToSansovino(context: Context, yesterdayForQuery: String, now: Date, operator: String, dayForThisQuery: String): List<Bus> { db = openDatabase(context) val tramCentroSansovinoTimes = LinkedList<Bus>() val tramFromStation = "SELECT t.trip_id,\n" + " start_s.stop_name as departure_stop,\n" + "\t start_s.stop_id as departure_stop_id,\n" + " start_st.departure_time,\n" + " direction_id as direction,\n" + " end_s.stop_name as arrival_stop,\n" + "\t end_s.stop_id as arrival_stop_id,\n" + " end_st.arrival_time,\n" + " r.route_short_name\n" + "FROM\n" + "trips t INNER JOIN calendar c ON t.service_id = c.service_id\n" + " INNER JOIN routes r ON t.route_id = r.route_id\n" + " INNER JOIN stop_times start_st ON t.trip_id = start_st.trip_id\n" + " INNER JOIN stops start_s ON start_st.stop_id = start_s.stop_id\n" + " INNER JOIN stop_times end_st ON t.trip_id = end_st.trip_id\n" + " INNER JOIN stops end_s ON end_st.stop_id = end_s.stop_id\n" + "WHERE " + dayForThisQuery + " = 1\n" + " and r.route_id in (" + routeForT1MestreVe + ")\n" + " and DATETIME(start_st.departure_time) " + operator + " DATETIME('" + databaseHourFormatter.format(subtractMinutesFromDate(4, now)) + "')\n" + " and departure_stop_id in (" + cialdini + ")\n" + " and arrival_stop_id in (" + departingSansovino + ")\n" + "order by start_st.departure_time asc\t" // if(BuildConfig.DEBUG) // Log.w("tramFromStation", tramFromStation); val comingTramCursor = db.rawQuery(tramFromStation, null) comingTramCursor.moveToFirst() if (comingTramCursor.count > 0) try { do { val departureStop = comingTramCursor.getString(comingTramCursor.getColumnIndex("departure_stop")) val departureTime = comingTramCursor.getString(comingTramCursor.getColumnIndex("departure_time")) val arrivalStop = comingTramCursor.getString(comingTramCursor.getColumnIndex("arrival_stop")) val arrivalTime = comingTramCursor.getString(comingTramCursor.getColumnIndex("arrival_time")) val line = comingTramCursor.getString(comingTramCursor.getColumnIndex("route_short_name")) tramCentroSansovinoTimes.add(Bus(dateFormatter.parse(departureTime), line, departureStop, arrivalStop, dateFormatter.parse(arrivalTime) )) } while (comingTramCursor.moveToNext()) } catch (e: ParseException) { Log.e("Catchit", "Uff, cheppalle") } comingTramCursor.close() db.close() return tramCentroSansovinoTimes } fun getSansovinoToCenter(context: Context, yesterdayForQuery: String, now: Date, operator: String, dayForThisQuery: String): List<Bus> { db = openDatabase(context) val tramSansovinoCentroTimes = LinkedList<Bus>() val tramSansovinoToCentro = "SELECT t.trip_id,\n" + " start_s.stop_name as departure_stop,\n" + "\t start_s.stop_id as departure_stop_id,\n" + " start_st.departure_time,\n" + " direction_id as direction,\n" + " end_s.stop_name as arrival_stop,\n" + "\t end_s.stop_id as arrival_stop_id,\n" + " end_st.arrival_time,\n" + " r.route_short_name\n" + "FROM\n" + "trips t INNER JOIN calendar c ON t.service_id = c.service_id\n" + " INNER JOIN routes r ON t.route_id = r.route_id\n" + " INNER JOIN stop_times start_st ON t.trip_id = start_st.trip_id\n" + " INNER JOIN stops start_s ON start_st.stop_id = start_s.stop_id\n" + " INNER JOIN stop_times end_st ON t.trip_id = end_st.trip_id\n" + " INNER JOIN stops end_s ON end_st.stop_id = end_s.stop_id\n" + "WHERE " + dayForThisQuery + " = 1\n" + " and r.route_id in (" + routeForT1VeMestre + ")\n" + " and DATETIME(start_st.departure_time) " + operator + " DATETIME('" + databaseHourFormatter.format(subtractMinutesFromDate(4, now)) + "')\n" + " and departure_stop_id in (" + returningSansovino + ")\n" + " and arrival_stop_id in (" + cialdini + ")\n" + "order by start_st.departure_time asc\t" // if(BuildConfig.DEBUG) // Log.w("TramToVenice", tramSansovinoToCentro); val leavingToCentroCursor = db.rawQuery(tramSansovinoToCentro, null) leavingToCentroCursor.moveToFirst() if (leavingToCentroCursor.count > 0) try { do { val departureStop = leavingToCentroCursor.getString(leavingToCentroCursor.getColumnIndex("departure_stop")) val departureTime = leavingToCentroCursor.getString(leavingToCentroCursor.getColumnIndex("departure_time")) val arrivalStop = leavingToCentroCursor.getString(leavingToCentroCursor.getColumnIndex("arrival_stop")) val arrivalTime = leavingToCentroCursor.getString(leavingToCentroCursor.getColumnIndex("arrival_time")) val line = leavingToCentroCursor.getString(leavingToCentroCursor.getColumnIndex("route_short_name")) tramSansovinoCentroTimes.add(Bus(dateFormatter.parse(departureTime), line, departureStop, arrivalStop, dateFormatter.parse(arrivalTime) )) // Log.i("Catchit", "Added a new item: " + departureStop + " " + departureTime + " " + line); } while (leavingToCentroCursor.moveToNext()) } catch (e: ParseException) { Log.e("Catchit", "Uff, cheppalle") } leavingToCentroCursor.close() db.close() // if(BuildConfig.DEBUG) // Log.w("TramSansovinoToCentro", tramSansovinoToCentro); return tramSansovinoCentroTimes } fun getHermadaToStation(context: Context, yesterdayForQuery: String, now: Date, operator: String, dayForThisQuery: String): List<Bus> { db = openDatabase(context) val tramCentroSansovinoTimes = LinkedList<Bus>() val tramFromStation = "SELECT t.trip_id,\n" + " start_s.stop_name as departure_stop,\n" + "\t start_s.stop_id as departure_stop_id,\n" + " start_st.departure_time,\n" + " direction_id as direction,\n" + " end_s.stop_name as arrival_stop,\n" + "\t end_s.stop_id as arrival_stop_id,\n" + " end_st.arrival_time,\n" + " r.route_short_name\n" + "FROM\n" + "trips t INNER JOIN calendar c ON t.service_id = c.service_id\n" + " INNER JOIN routes r ON t.route_id = r.route_id\n" + " INNER JOIN stop_times start_st ON t.trip_id = start_st.trip_id\n" + " INNER JOIN stops start_s ON start_st.stop_id = start_s.stop_id\n" + " INNER JOIN stop_times end_st ON t.trip_id = end_st.trip_id\n" + " INNER JOIN stops end_s ON end_st.stop_id = end_s.stop_id\n" + "WHERE " + dayForThisQuery + " = 1\n" + " and r.route_id in (" + routeFor15AirportStation + ")\n" + " and DATETIME(start_st.departure_time) " + operator + " DATETIME('" + databaseHourFormatter.format(subtractMinutesFromDate(4, now)) + "')\n" + " and departure_stop_id = " + viaHermadaStreetSide + "\n" + " and arrival_stop_id = " + stazioneMestreFor15 + "\n" + "order by start_st.departure_time asc\t" // if(BuildConfig.DEBUG) // Log.w("tramFromStation", tramFromStation); val comingTramCursor = db.rawQuery(tramFromStation, null) comingTramCursor.moveToFirst() if (comingTramCursor.count > 0) try { do { val departureStop = comingTramCursor.getString(comingTramCursor.getColumnIndex("departure_stop")) val departureTime = comingTramCursor.getString(comingTramCursor.getColumnIndex("departure_time")) val arrivalStop = comingTramCursor.getString(comingTramCursor.getColumnIndex("arrival_stop")) val arrivalTime = comingTramCursor.getString(comingTramCursor.getColumnIndex("arrival_time")) val line = comingTramCursor.getString(comingTramCursor.getColumnIndex("route_short_name")) tramCentroSansovinoTimes.add(Bus(dateFormatter.parse(departureTime), line, departureStop, arrivalStop, dateFormatter.parse(arrivalTime) )) } while (comingTramCursor.moveToNext()) } catch (e: ParseException) { Log.e("Catchit", "Uff, cheppalle") } comingTramCursor.close() db.close() return tramCentroSansovinoTimes } fun getStationToHermada(context: Context, yesterdayForQuery: String, now: Date, operator: String, dayForThisQuery: String): List<Bus> { db = openDatabase(context) val tramCentroSansovinoTimes = LinkedList<Bus>() val tramFromStation = "SELECT t.trip_id,\n" + " start_s.stop_name as departure_stop,\n" + "\t start_s.stop_id as departure_stop_id,\n" + " start_st.departure_time,\n" + " direction_id as direction,\n" + " end_s.stop_name as arrival_stop,\n" + "\t end_s.stop_id as arrival_stop_id,\n" + " end_st.arrival_time,\n" + " r.route_short_name\n" + "FROM\n" + "trips t INNER JOIN calendar c ON t.service_id = c.service_id\n" + " INNER JOIN routes r ON t.route_id = r.route_id\n" + " INNER JOIN stop_times start_st ON t.trip_id = start_st.trip_id\n" + " INNER JOIN stops start_s ON start_st.stop_id = start_s.stop_id\n" + " INNER JOIN stop_times end_st ON t.trip_id = end_st.trip_id\n" + " INNER JOIN stops end_s ON end_st.stop_id = end_s.stop_id\n" + "WHERE " + dayForThisQuery + " = 1\n" + " and r.route_id in (" + routeFor15StationAirport + ")\n" + " and DATETIME(start_st.departure_time) " + operator + " DATETIME('" + databaseHourFormatter.format(subtractMinutesFromDate(4, now)) + "')\n" + " and departure_stop_id = " + stazioneMestreFor15 + "\n" + " and arrival_stop_id = " + viaHermadaCanalSide + "\n" + "order by start_st.departure_time asc\t" // if(BuildConfig.DEBUG) // Log.w("tramFromStation", tramFromStation); val comingTramCursor = db.rawQuery(tramFromStation, null) comingTramCursor.moveToFirst() if (comingTramCursor.count > 0) try { do { val departureStop = comingTramCursor.getString(comingTramCursor.getColumnIndex("departure_stop")) val departureTime = comingTramCursor.getString(comingTramCursor.getColumnIndex("departure_time")) val arrivalStop = comingTramCursor.getString(comingTramCursor.getColumnIndex("arrival_stop")) val arrivalTime = comingTramCursor.getString(comingTramCursor.getColumnIndex("arrival_time")) val line = comingTramCursor.getString(comingTramCursor.getColumnIndex("route_short_name")) tramCentroSansovinoTimes.add(Bus(dateFormatter.parse(departureTime), line, departureStop, arrivalStop, dateFormatter.parse(arrivalTime) )) } while (comingTramCursor.moveToNext()) } catch (e: ParseException) { Log.e("Catchit", "Uff, cheppalle") } comingTramCursor.close() db.close() return tramCentroSansovinoTimes } fun getHermadaToAirport(context: Context, yesterdayForQuery: String, now: Date, operator: String, dayForThisQuery: String): List<Bus> { db = openDatabase(context) val tramCentroSansovinoTimes = LinkedList<Bus>() val tramFromStation = "SELECT t.trip_id,\n" + " start_s.stop_name as departure_stop,\n" + "\t start_s.stop_id as departure_stop_id,\n" + " start_st.departure_time,\n" + " direction_id as direction,\n" + " end_s.stop_name as arrival_stop,\n" + "\t end_s.stop_id as arrival_stop_id,\n" + " end_st.arrival_time,\n" + " r.route_short_name\n" + "FROM\n" + "trips t INNER JOIN calendar c ON t.service_id = c.service_id\n" + " INNER JOIN routes r ON t.route_id = r.route_id\n" + " INNER JOIN stop_times start_st ON t.trip_id = start_st.trip_id\n" + " INNER JOIN stops start_s ON start_st.stop_id = start_s.stop_id\n" + " INNER JOIN stop_times end_st ON t.trip_id = end_st.trip_id\n" + " INNER JOIN stops end_s ON end_st.stop_id = end_s.stop_id\n" + "WHERE " + dayForThisQuery + " = 1\n" + " and r.route_id in (" + routeFor15StationAirport + ")\n" + " and DATETIME(start_st.departure_time) " + operator + " DATETIME('" + databaseHourFormatter.format(subtractMinutesFromDate(4, now)) + "')\n" + " and departure_stop_id in (" + viaHermadaCanalSide + ")\n" + " and arrival_stop_id in (" + airport + ")\n" + "order by start_st.departure_time asc\t" // if(BuildConfig.DEBUG) // Log.w("tramFromStation", tramFromStation); val comingTramCursor = db.rawQuery(tramFromStation, null) comingTramCursor.moveToFirst() if (comingTramCursor.count > 0) try { do { val departureStop = comingTramCursor.getString(comingTramCursor.getColumnIndex("departure_stop")) val departureTime = comingTramCursor.getString(comingTramCursor.getColumnIndex("departure_time")) val arrivalStop = comingTramCursor.getString(comingTramCursor.getColumnIndex("arrival_stop")) val arrivalTime = comingTramCursor.getString(comingTramCursor.getColumnIndex("arrival_time")) val line = comingTramCursor.getString(comingTramCursor.getColumnIndex("route_short_name")) tramCentroSansovinoTimes.add(Bus(dateFormatter.parse(departureTime), line, departureStop, arrivalStop, dateFormatter.parse(arrivalTime) )) } while (comingTramCursor.moveToNext()) } catch (e: ParseException) { Log.e("Catchit", "Uff, cheppalle") } comingTramCursor.close() db.close() return tramCentroSansovinoTimes } fun getAirportToHermada(context: Context, yesterdayForQuery: String, now: Date, operator: String, dayForThisQuery: String): List<Bus> { db = openDatabase(context) val tramCentroSansovinoTimes = LinkedList<Bus>() val tramFromStation = "SELECT t.trip_id,\n" + " start_s.stop_name as departure_stop,\n" + "\t start_s.stop_id as departure_stop_id,\n" + " start_st.departure_time,\n" + " direction_id as direction,\n" + " end_s.stop_name as arrival_stop,\n" + "\t end_s.stop_id as arrival_stop_id,\n" + " end_st.arrival_time,\n" + " r.route_short_name\n" + "FROM\n" + "trips t INNER JOIN calendar c ON t.service_id = c.service_id\n" + " INNER JOIN routes r ON t.route_id = r.route_id\n" + " INNER JOIN stop_times start_st ON t.trip_id = start_st.trip_id\n" + " INNER JOIN stops start_s ON start_st.stop_id = start_s.stop_id\n" + " INNER JOIN stop_times end_st ON t.trip_id = end_st.trip_id\n" + " INNER JOIN stops end_s ON end_st.stop_id = end_s.stop_id\n" + "WHERE " + dayForThisQuery + " = 1\n" + " and r.route_id in (" + routeFor15AirportStation + ")\n" + " and DATETIME(start_st.departure_time) " + operator + " DATETIME('" + databaseHourFormatter.format(subtractMinutesFromDate(4, now)) + "')\n" + " and departure_stop_id in (" + airport + ")\n" + " and arrival_stop_id in (" + viaHermadaStreetSide + ")\n" + "order by start_st.departure_time asc\t" if (BuildConfig.DEBUG) Log.w("tramFromStation", tramFromStation) val comingTramCursor = db.rawQuery(tramFromStation, null) comingTramCursor.moveToFirst() if (comingTramCursor.count > 0) try { do { val departureStop = comingTramCursor.getString(comingTramCursor.getColumnIndex("departure_stop")) val departureTime = comingTramCursor.getString(comingTramCursor.getColumnIndex("departure_time")) val arrivalStop = comingTramCursor.getString(comingTramCursor.getColumnIndex("arrival_stop")) val arrivalTime = comingTramCursor.getString(comingTramCursor.getColumnIndex("arrival_time")) val line = comingTramCursor.getString(comingTramCursor.getColumnIndex("route_short_name")) tramCentroSansovinoTimes.add(Bus(dateFormatter.parse(departureTime), line, departureStop, arrivalStop, dateFormatter.parse(arrivalTime) )) } while (comingTramCursor.moveToNext()) } catch (e: ParseException) { Log.e("Catchit", "Uff, cheppalle") } comingTramCursor.close() db.close() return tramCentroSansovinoTimes } /* * Convenience method to add a specified number of minutes to a Date object * From: http://stackoverflow.com/questions/9043981/how-to-add-minutes-to-my-date * @param minutes The number of minutes to subtract * @param beforeTime The time that will have minutes subtracted from it * @return A date object with the specified number of minutes added to it */ fun subtractMinutesFromDate(minutes: Int, beforeTime: Date): java.util.Date { val ONE_MINUTE_IN_MILLIS: Long = 60000//millisecs val curTimeInMs = beforeTime.time val afterAddingMins = Date(curTimeInMs - minutes * ONE_MINUTE_IN_MILLIS) return afterAddingMins } }
gpl-3.0
ed4f327cebc4e31d1c2dd26bf3893312
52.708437
176
0.534916
3.830207
false
false
false
false
wiltonlazary/kotlin-native
samples/tetris/src/tetrisMain/kotlin/Tetris.kt
1
15926
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the license/LICENSE.txt file. */ package sample.tetris import kotlinx.cinterop.* import platform.posix.* typealias Field = Array<ByteArray> enum class Move { LEFT, RIGHT, DOWN, ROTATE } enum class PlacementResult(val linesCleared: Int = 0, val bonus: Int = 0) { NOTHING, GAMEOVER, // For values of bonuses see https://tetris.wiki/Scoring SINGLE(1, 40), DOUBLE(2, 100), TRIPLE(3, 300), TETRIS(4, 1200) } const val EMPTY: Byte = 0 const val CELL1: Byte = 1 const val CELL2: Byte = 2 const val CELL3: Byte = 3 const val BRICK: Byte = -1 class Point(var x: Int, var y: Int) operator fun Point.plus(other: Point): Point { return Point(x + other.x, y + other.y) } class PiecePosition(piece: Piece, private val origin: Point) { private var p = piece.origin val x get() = p.x + origin.x val y get() = p.y + origin.y var state: Int get private set val numberOfStates = piece.numberOfStates init { state = 0 } fun makeMove(move: Move) { when (move) { Move.LEFT -> --p.y Move.RIGHT -> ++p.y Move.DOWN -> ++p.x Move.ROTATE -> state = (state + 1) % numberOfStates } } fun unMakeMove(move: Move) { when (move) { Move.LEFT -> ++p.y Move.RIGHT -> --p.y Move.DOWN -> --p.x Move.ROTATE -> state = (state + numberOfStates - 1) % numberOfStates } } } /* * We use Nintendo Rotation System, right-handed version. * See https://tetris.wiki/Nintendo_Rotation_System */ enum class Piece(private val origin_: Point, private vararg val states: Field) { T(Point(-1, -2), arrayOf( byteArrayOf(EMPTY, EMPTY, EMPTY), byteArrayOf(CELL1, CELL1, CELL1), byteArrayOf(EMPTY, CELL1, EMPTY)), arrayOf( byteArrayOf(EMPTY, CELL1, EMPTY), byteArrayOf(CELL1, CELL1, EMPTY), byteArrayOf(EMPTY, CELL1, EMPTY)), arrayOf( byteArrayOf(EMPTY, CELL1, EMPTY), byteArrayOf(CELL1, CELL1, CELL1), byteArrayOf(EMPTY, EMPTY, EMPTY)), arrayOf( byteArrayOf(EMPTY, CELL1, EMPTY), byteArrayOf(EMPTY, CELL1, CELL1), byteArrayOf(EMPTY, CELL1, EMPTY)) ), J(Point(-1, -2), arrayOf( byteArrayOf(EMPTY, EMPTY, EMPTY), byteArrayOf(CELL2, CELL2, CELL2), byteArrayOf(EMPTY, EMPTY, CELL2)), arrayOf( byteArrayOf(EMPTY, CELL2, EMPTY), byteArrayOf(EMPTY, CELL2, EMPTY), byteArrayOf(CELL2, CELL2, EMPTY)), arrayOf( byteArrayOf(CELL2, EMPTY, EMPTY), byteArrayOf(CELL2, CELL2, CELL2), byteArrayOf(EMPTY, EMPTY, EMPTY)), arrayOf( byteArrayOf(EMPTY, CELL2, CELL2), byteArrayOf(EMPTY, CELL2, EMPTY), byteArrayOf(EMPTY, CELL2, EMPTY)) ), Z(Point(-1, -2), arrayOf( byteArrayOf(EMPTY, EMPTY, EMPTY), byteArrayOf(CELL3, CELL3, EMPTY), byteArrayOf(EMPTY, CELL3, CELL3)), arrayOf( byteArrayOf(EMPTY, EMPTY, CELL3), byteArrayOf(EMPTY, CELL3, CELL3), byteArrayOf(EMPTY, CELL3, EMPTY)) ), O(Point(0, -1), arrayOf( byteArrayOf(CELL1, CELL1), byteArrayOf(CELL1, CELL1)) ), S(Point(-1, -2), arrayOf( byteArrayOf(EMPTY, EMPTY, EMPTY), byteArrayOf(EMPTY, CELL2, CELL2), byteArrayOf(CELL2, CELL2, EMPTY)), arrayOf( byteArrayOf(EMPTY, CELL2, EMPTY), byteArrayOf(EMPTY, CELL2, CELL2), byteArrayOf(EMPTY, EMPTY, CELL2)) ), L(Point(-1, -2), arrayOf( byteArrayOf(EMPTY, EMPTY, EMPTY), byteArrayOf(CELL3, CELL3, CELL3), byteArrayOf(CELL3, EMPTY, EMPTY)), arrayOf( byteArrayOf(CELL3, CELL3, EMPTY), byteArrayOf(EMPTY, CELL3, EMPTY), byteArrayOf(EMPTY, CELL3, EMPTY)), arrayOf( byteArrayOf(EMPTY, EMPTY, CELL3), byteArrayOf(CELL3, CELL3, CELL3), byteArrayOf(EMPTY, EMPTY, EMPTY)), arrayOf( byteArrayOf(EMPTY, CELL3, EMPTY), byteArrayOf(EMPTY, CELL3, EMPTY), byteArrayOf(EMPTY, CELL3, CELL3)) ), I(Point(-2, -2), arrayOf( byteArrayOf(EMPTY, EMPTY, EMPTY, EMPTY), byteArrayOf(EMPTY, EMPTY, EMPTY, EMPTY), byteArrayOf(CELL1, CELL1, CELL1, CELL1), byteArrayOf(EMPTY, EMPTY, EMPTY, EMPTY)), arrayOf( byteArrayOf(EMPTY, EMPTY, CELL1, EMPTY), byteArrayOf(EMPTY, EMPTY, CELL1, EMPTY), byteArrayOf(EMPTY, EMPTY, CELL1, EMPTY), byteArrayOf(EMPTY, EMPTY, CELL1, EMPTY)) ); val origin get() = Point(origin_.x, origin_.y) val numberOfStates: Int = states.size fun canBePlaced(field: Field, position: PiecePosition): Boolean { val piece = states[position.state] val x = position.x val y = position.y for (i in piece.indices) { val pieceRow = piece[i] val boardRow = field[x + i] for (j in pieceRow.indices) { if (pieceRow[j] != EMPTY && boardRow[y + j] != EMPTY) return false } } return true } fun place(field: Field, position: PiecePosition) { val piece = states[position.state] val x = position.x val y = position.y for (i in piece.indices) { val pieceRow = piece[i] for (j in pieceRow.indices) { if (pieceRow[j] != EMPTY) field[x + i][y + j] = pieceRow[j] } } } fun unPlace(field: Field, position: PiecePosition) { val piece = states[position.state] val x = position.x val y = position.y for (i in piece.indices) { val pieceRow = piece[i] for (j in pieceRow.indices) { if (pieceRow[j] != EMPTY) field[x + i][y + j] = EMPTY } } } } interface GameFieldVisualizer { fun drawCell(x: Int, y: Int, cell: Byte) fun drawNextPieceCell(x: Int, y: Int, cell: Byte) fun setInfo(linesCleared: Int, level: Int, score: Int, tetrises: Int) fun refresh() } enum class UserCommand { LEFT, RIGHT, DOWN, DROP, ROTATE, EXIT } interface UserInput { fun readCommands(): List<UserCommand> } class GameField(val width: Int, val height: Int, val visualizer: GameFieldVisualizer) { private val MARGIN = 4 private val field: Field private val origin: Point private val nextPieceField: Field init { field = Array<ByteArray>(height + MARGIN * 2) { ByteArray(width + MARGIN * 2) } for (i in field.indices) { val row = field[i] for (j in row.indices) { if (i >= (MARGIN + height) // Bottom (field is flipped over). || (j < MARGIN) // Left || (j >= MARGIN + width)) // Right row[j] = BRICK } } // Coordinates are relative to the central axis and top of the field. origin = Point(MARGIN, MARGIN + (width + 1) / 2) nextPieceField = Array<ByteArray>(4) { ByteArray(4) } } lateinit var currentPiece: Piece lateinit var nextPiece: Piece lateinit var currentPosition: PiecePosition fun reset() { for (i in 0..height - 1) for (j in 0..width - 1) field[i + MARGIN][j + MARGIN] = 0 srand(time(null).toUInt()) nextPiece = getNextPiece(false) switchCurrentPiece() } private fun randInt() = (rand() and 32767) or ((rand() and 32767) shl 15) private fun getNextPiece(denyPrevious: Boolean): Piece { val pieces = Piece.values() if (!denyPrevious) return pieces[randInt() % pieces.size] while (true) { val nextPiece = pieces[randInt() % pieces.size] if (nextPiece != currentPiece) return nextPiece } } private fun switchCurrentPiece() { currentPiece = nextPiece nextPiece = getNextPiece(denyPrevious = true) // Forbid repeating the same piece for better distribution. currentPosition = PiecePosition(currentPiece, origin) } fun makeMove(move: Move): Boolean { currentPosition.makeMove(move) if (currentPiece.canBePlaced(field, currentPosition)) return true currentPosition.unMakeMove(move) return false } /** * Places current piece at its current location. */ fun place(): PlacementResult { currentPiece.place(field, currentPosition) val linesCleared = clearLines() if (isOutOfBorders()) return PlacementResult.GAMEOVER switchCurrentPiece() if (!currentPiece.canBePlaced(field, currentPosition)) return PlacementResult.GAMEOVER when (linesCleared) { 1 -> return PlacementResult.SINGLE 2 -> return PlacementResult.DOUBLE 3 -> return PlacementResult.TRIPLE 4 -> return PlacementResult.TETRIS else -> return PlacementResult.NOTHING } } private fun clearLines(): Int { val clearedLines = mutableListOf<Int>() for (i in 0..height - 1) { val row = field[i + MARGIN] if ((0..width - 1).all { j -> row[j + MARGIN] != EMPTY }) { clearedLines.add(i + MARGIN) (0..width - 1).forEach { j -> row[j + MARGIN] = EMPTY } } } if (clearedLines.size == 0) return 0 draw(false) visualizer.refresh() sleep(500) for (i in clearedLines) { for (k in i - 1 downTo 1) for (j in 0..width - 1) field[k + 1][j + MARGIN] = field[k][j + MARGIN] } draw(false) visualizer.refresh() return clearedLines.size } private fun isOutOfBorders(): Boolean { for (i in 0..MARGIN - 1) for (j in 0..width - 1) if (field[i][j + MARGIN] != EMPTY) return true return false } fun draw() { draw(true) drawNextPiece() } private fun drawNextPiece() { for (i in 0..3) for (j in 0..3) nextPieceField[i][j] = 0 nextPiece.place(nextPieceField, PiecePosition(nextPiece, Point(1, 2))) for (i in 0..3) for (j in 0..3) visualizer.drawNextPieceCell(i, j, nextPieceField[i][j]) } private fun draw(drawCurrentPiece: Boolean) { if (drawCurrentPiece) currentPiece.place(field, currentPosition) for (i in 0..height - 1) for (j in 0..width - 1) visualizer.drawCell(i, j, field[i + MARGIN][j + MARGIN]) if (drawCurrentPiece) currentPiece.unPlace(field, currentPosition) } } class Game(width: Int, height: Int, val visualizer: GameFieldVisualizer, val userInput: UserInput) { private val field = GameField(width, height, visualizer) private var gameOver = true private var startLevel = 0 private var leveledUp = false private var level = 0 private var linesClearedAtCurrentLevel = 0 private var linesCleared = 0 private var tetrises = 0 private var score = 0 /* * For speed constants and level up thresholds see https://tetris.wiki/Tetris_(NES,_Nintendo) */ private val speeds = intArrayOf(48, 43, 38, 33, 28, 23, 18, 13, 8, 6, 5, 5, 5, 4, 4, 4, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2) private val levelUpThreshold get() = if (leveledUp) 10 else minOf(startLevel * 10 + 10, maxOf(100, startLevel * 10 - 50)) private val speed get() = if (level < 29) speeds[level] else 1 private var ticks = 0 fun startNewGame(level: Int) { gameOver = false startLevel = level leveledUp = false this.level = level linesClearedAtCurrentLevel = 0 linesCleared = 0 tetrises = 0 score = 0 ticks = 0 field.reset() visualizer.setInfo(linesCleared, level, score, tetrises) field.draw() visualizer.refresh() mainLoop() } private fun placePiece() { val placementResult = field.place() ticks = 0 when (placementResult) { PlacementResult.NOTHING -> return PlacementResult.GAMEOVER -> { gameOver = true return } else -> { linesCleared += placementResult.linesCleared linesClearedAtCurrentLevel += placementResult.linesCleared score += placementResult.bonus * (level + 1) if (placementResult == PlacementResult.TETRIS) ++tetrises val levelUpThreshold = levelUpThreshold if (linesClearedAtCurrentLevel >= levelUpThreshold) { ++level linesClearedAtCurrentLevel -= levelUpThreshold leveledUp = true } visualizer.setInfo(linesCleared, level, score, tetrises) } } } /* * Number of additional gravity shifts before locking a piece landed on the ground. * This is needed in order to let user to move a piece to the left/right before locking. */ private val LOCK_DELAY = 1 private fun mainLoop() { var attemptsToLock = 0 while (!gameOver) { sleep(1000 / 60) // Refresh rate - 60 frames per second. val commands = userInput.readCommands() for (cmd in commands) { val success: Boolean when (cmd) { UserCommand.EXIT -> return UserCommand.LEFT -> success = field.makeMove(Move.LEFT) UserCommand.RIGHT -> success = field.makeMove(Move.RIGHT) UserCommand.ROTATE -> success = field.makeMove(Move.ROTATE) UserCommand.DOWN -> { success = field.makeMove(Move.DOWN) if (!success) placePiece() } UserCommand.DROP -> { while (field.makeMove(Move.DOWN)) { } success = true placePiece() } } if (success) { field.draw() visualizer.refresh() } } ++ticks if (ticks < speed) continue if (!field.makeMove(Move.DOWN)) { if (++attemptsToLock >= LOCK_DELAY) { placePiece() attemptsToLock = 0 } } field.draw() visualizer.refresh() ticks -= speed } } }
apache-2.0
b22ca8ce5551e150ce40b79320afb7d4
31.435845
113
0.521851
4.310149
false
false
false
false
FFlorien/AmpachePlayer
app/src/main/java/be/florien/anyflow/data/server/AmpacheApi.kt
1
3324
package be.florien.anyflow.data.server import be.florien.anyflow.data.server.model.* import retrofit2.Response import retrofit2.http.GET import retrofit2.http.Query /** * Retrofit interface for Ampache */ interface AmpacheApi { @GET("server/json.server.php") suspend fun authenticate( @Query("action") action: String = "handshake", @Query("timestamp") time: String, @Query("version") version: String = "380001", @Query("auth") auth: String, @Query("user") user: String) : AmpacheAuthentication @GET("server/json.server.php") suspend fun ping( @Query("action") action: String = "ping", @Query("auth") auth: String) : AmpachePing @GET("server/json.server.php") suspend fun getSongs( @Query("action") action: String = "songs", @Query("add") add: String = "1970-01-01", @Query("auth") auth: String, @Query("limit") limit: Int, @Query("offset") offset: Int) : List<AmpacheSong> @GET("server/json.server.php") suspend fun getArtists( @Query("action") action: String = "artists", @Query("add") add: String = "1970-01-01", @Query("auth") auth: String, @Query("limit") limit: Int, @Query("offset") offset: Int) : Response<List<AmpacheArtist>> @GET("server/json.server.php") suspend fun getAlbums( @Query("action") action: String = "albums", @Query("add") add: String = "1970-01-01", @Query("auth") auth: String, @Query("limit") limit: Int, @Query("offset") offset: Int) : List<AmpacheAlbum> @GET("server/json.server.php") suspend fun getTags( @Query("action") action: String = "tags", @Query("add") add: String = "1970-01-01", @Query("auth") auth: String, @Query("limit") limit: Int, @Query("offset") offset: Int) : List<AmpacheTag> @GET("server/json.server.php") suspend fun getPlaylists( @Query("action") action: String = "playlists", @Query("auth") auth: String, @Query("limit") limit: Int, @Query("offset") offset: Int, @Query("hide_search") hideSearch: Int = 1) : List<AmpachePlayList> @GET("server/json.server.php") suspend fun getPlaylistSongs( @Query("action") action: String = "playlist_songs", @Query("filter") filter: String, @Query("auth") auth: String, @Query("limit") limit: Int, @Query("offset") offset: Int) : List<AmpacheSongId> @GET("server/json.server.php") suspend fun createPlaylist( @Query("action") action: String = "playlist_create", @Query("auth") auth: String, @Query("name") name: String, @Query("type") type: String = "private") @GET("server/json.server.php") suspend fun addToPlaylist( @Query("action") action: String = "playlist_add_song", @Query("filter") filter: Long, @Query("auth") auth: String, @Query("song") songId: Long, @Query("check") check: Int = 1) }
gpl-3.0
af19c115a738646447611c87c29725a9
34
66
0.545126
3.995192
false
false
false
false
d9n/intellij-rust
src/main/kotlin/org/rust/ide/inspections/RsTryMacroInspection.kt
1
1396
package org.rust.ide.inspections import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.project.Project import org.rust.lang.core.psi.RsTryExpr import org.rust.lang.core.psi.RsTryMacro import org.rust.lang.core.psi.RsVisitor import org.rust.lang.core.psi.RsPsiFactory /** * Change `try!` macro to `?` operator. */ class RsTryMacroInspection : RsLocalInspectionTool() { override fun getDisplayName() = "try! macro usage" override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitTryMacro(o: RsTryMacro) = holder.registerProblem( o.macroInvocation, "try! macro can be replaced with ? operator", object : LocalQuickFix { override fun getName() = "Change try! to ?" override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val macro = descriptor.psiElement.parent as RsTryMacro val body = macro.tryMacroArgs?.expr ?: return val tryExpr = RsPsiFactory(project).createExpression("${body.text}?") as RsTryExpr macro.replace(tryExpr) } } ) } }
mit
ab7ef9c4987d2542f3adcc36199721b5
37.777778
102
0.663324
4.653333
false
false
false
false
sinnerschrader/account-tool
src/main/kotlin/com/sinnerschrader/s2b/accounttool/logic/DateTimeHelper.kt
1
1479
package com.sinnerschrader.s2b.accounttool.logic import org.apache.commons.lang3.time.DateUtils import org.slf4j.LoggerFactory import java.text.ParseException import java.time.LocalDate import java.time.LocalDateTime import java.time.ZoneId import java.time.format.DateTimeFormatter import java.time.temporal.ChronoUnit import java.util.* /** * Helper Utils class for converting legacy Date objects into new Java Time API Objects and versa. */ object DateTimeHelper { private val LOG = LoggerFactory.getLogger(DateTimeHelper::class.java) fun toDate(dateTime: LocalDateTime) = Date.from(dateTime.atZone(ZoneId.systemDefault()).toInstant())!! fun toDate(date: LocalDate) = Date.from(date.atStartOfDay(ZoneId.systemDefault()).toInstant())!! fun toDateString(date: LocalDate, pattern: String) = DateTimeFormatter.ofPattern(pattern).format(date)!! fun toDate(date: String, vararg pattern: String) = try { DateUtils.parseDate(date, *pattern) } catch (pe: ParseException) { LOG.warn("Could not parse date string {} with pattern {}", date, pattern) null } fun toLocalDateTime(date: Date) = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault())!! fun toLocalDate(date: Date) = LocalDate.from(date.toInstant())!! fun getDurationString(start: LocalDateTime, end: LocalDateTime, unit: ChronoUnit) = unit.between(start, end).toString() + " " + unit.name }
mit
bd41d9e5c41284abf34f5612406568d4
41.257143
141
0.719405
4.388724
false
false
false
false
material-components/material-components-android-examples
Owl/app/src/main/java/com/materialstudies/owl/util/GraphicsExtensions.kt
1
2083
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.materialstudies.owl.util import android.graphics.Canvas import android.graphics.Paint import android.graphics.Path import android.graphics.Rect import android.graphics.RectF import android.graphics.Shader import androidx.core.graphics.toRectF import com.google.android.material.shape.RoundedCornerTreatment import com.google.android.material.shape.ShapeAppearanceModel class CornerRounding( val topLeftRadius: Float = 0f, val topRightRadius: Float = 0f, val bottomRightRadius: Float = 0f, val bottomLeftRadius: Float = 0f ) // To FloatArray suitable for Path#addRoundRect fun CornerRounding.toFloatArray(): FloatArray { return floatArrayOf( topLeftRadius, topLeftRadius, topRightRadius, topRightRadius, bottomRightRadius, bottomRightRadius, bottomLeftRadius, bottomLeftRadius ) } fun ShapeAppearanceModel?.toCornerRounding(bounds: RectF): CornerRounding { if (this == null) return CornerRounding() return CornerRounding( topLeftCornerSize.getCornerSize(bounds), topRightCornerSize.getCornerSize(bounds), bottomRightCornerSize.getCornerSize(bounds), bottomLeftCornerSize.getCornerSize(bounds) ) } private val path = Path() fun Canvas.drawRoundedRect( location: RectF, cornerRadii: CornerRounding, paint: Paint ) { path.apply { reset() addRoundRect(location, cornerRadii.toFloatArray(), Path.Direction.CW) } drawPath(path, paint) }
apache-2.0
d2ba96c58e3d40c838a3a81bbd9df419
30.089552
77
0.745079
4.268443
false
false
false
false
shlusiak/Freebloks-Android
app/src/main/java/de/saschahlusiak/freebloks/view/effects/ShapeFadeEffect.kt
1
1310
package de.saschahlusiak.freebloks.view.effects import de.saschahlusiak.freebloks.model.Turn import de.saschahlusiak.freebloks.view.BoardRenderer import de.saschahlusiak.freebloks.view.scene.Scene import javax.microedition.khronos.opengles.GL11 import kotlin.math.cos class ShapeFadeEffect(model: Scene, turn: Turn, private val numberOfIterations: Float) : AbsShapeEffect(model, turn) { private val timePerIteration = 1.1f private val fromAlpha = 0.15f private val toAlpha = 1.0f override fun isDone(): Boolean { return time > timePerIteration * numberOfIterations } override fun render(gl: GL11, renderer: BoardRenderer) { /* every timePerIteration needs to match 2 * PI */ val amp = cos(time / timePerIteration * Math.PI.toFloat() * 2.0f) * 0.5f + 0.5f val alpha = fromAlpha + amp * (toAlpha - fromAlpha) gl.glPushMatrix() gl.glTranslatef( -BoardRenderer.stoneSize * (scene.board.width - 1).toFloat() + BoardRenderer.stoneSize * 2.0f * x.toFloat(), 0f, -BoardRenderer.stoneSize * (scene.board.height - 1).toFloat() + BoardRenderer.stoneSize * 2.0f * y.toFloat()) renderer.renderShape(gl, color, shape, orientation, alpha * BoardRenderer.defaultStoneAlpha) gl.glPopMatrix() } }
gpl-2.0
1a68553930cd0be1c3714cab25403356
42.7
121
0.69542
3.742857
false
false
false
false
panpf/sketch
sketch-extensions/src/main/java/com/github/panpf/sketch/drawable/SectorProgressDrawable.kt
1
5192
/* * Copyright (C) 2022 panpf <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.panpf.sketch.drawable import android.animation.ValueAnimator import android.content.res.Resources import android.graphics.Canvas import android.graphics.Color import android.graphics.ColorFilter import android.graphics.Paint import android.graphics.Paint.Style.FILL import android.graphics.Paint.Style.STROKE import android.graphics.PixelFormat import android.graphics.RectF import com.github.panpf.sketch.util.format /** * Sector Progress Drawable */ class SectorProgressDrawable( private val size: Int = (50f * Resources.getSystem().displayMetrics.density + 0.5f).toInt(), private val backgroundColor: Int = 0x44000000, private val strokeColor: Int = Color.WHITE, private val progressColor: Int = Color.WHITE, private val strokeWidth: Float = size * 0.02f, ) : ProgressDrawable() { private val backgroundPaint = Paint().apply { isAntiAlias = true color = backgroundColor } private val strokePaint = Paint().apply { isAntiAlias = true color = strokeColor strokeWidth = [email protected] style = STROKE } private val progressPaint = Paint().apply { isAntiAlias = true style = FILL color = progressColor } private val progressOval = RectF() private var _progress: Float = 0f set(value) { field = value invalidateSelf() if (value >= 1f) { onProgressEnd?.invoke() } } private var progressAnimator: ValueAnimator? = null override var progress: Float get() = _progress set(value) { val newValue = value.format(1).coerceAtLeast(0f).coerceAtMost(1f) if (newValue != _progress) { if (_progress == 0f && newValue == 1f) { // Here is the loading of the local image, no loading progress, quickly complete _progress = newValue } else if (newValue > _progress) { animationUpdateProgress(newValue) } else { // If newValue is less than _progress, you can reset it quickly _progress = newValue } } } override var onProgressEnd: (() -> Unit)? = null private fun animationUpdateProgress(newProgress: Float) { progressAnimator?.cancel() progressAnimator = ValueAnimator.ofFloat(_progress, newProgress).apply { addUpdateListener { if (isActive()) { _progress = animatedValue as Float } else { it?.cancel() } } duration = 300 } progressAnimator?.start() } override fun draw(canvas: Canvas) { val progress = _progress.takeIf { it >= 0f } ?: return val bounds = bounds.takeIf { !it.isEmpty } ?: return val saveCount = canvas.save() // background val widthRadius = bounds.width() / 2f val heightRadius = bounds.height() / 2f val radius = widthRadius.coerceAtMost(heightRadius) val cx = bounds.left + widthRadius val cy = bounds.top + heightRadius canvas.drawCircle(cx, cy, radius, backgroundPaint) // stroke canvas.drawCircle(cx, cy, radius, strokePaint) // progress val space = strokeWidth * 3 progressOval.set( cx - radius + space, cy - radius + space, cx + radius - space, cy + radius - space, ) val sweepAngle = progress.coerceAtLeast(0.01f) * 360f canvas.drawArc(progressOval, 270f, sweepAngle, true, progressPaint) canvas.restoreToCount(saveCount) } override fun setAlpha(alpha: Int) { backgroundPaint.alpha = alpha strokePaint.alpha = alpha progressPaint.alpha = alpha } override fun setColorFilter(colorFilter: ColorFilter?) { backgroundPaint.colorFilter = colorFilter strokePaint.colorFilter = colorFilter progressPaint.colorFilter = colorFilter } override fun getOpacity(): Int = PixelFormat.TRANSLUCENT override fun setVisible(visible: Boolean, restart: Boolean): Boolean { val changed = super.setVisible(visible, restart) if (changed && !visible) { progressAnimator?.cancel() } return changed } override fun getIntrinsicWidth(): Int = size override fun getIntrinsicHeight(): Int = size }
apache-2.0
1f8a236581b6ac85a30f487c165f4a2b
32.076433
100
0.621148
4.834264
false
false
false
false
GlimpseFramework/glimpse-framework-android
android/src/main/kotlin/glimpse/android/io/RawResource.kt
1
1103
package glimpse.android.io import android.content.Context import glimpse.models.Mesh import glimpse.models.loadObjMeshes import glimpse.textures.Texture import glimpse.textures.TextureBuilder import glimpse.textures.loadTexture import java.io.InputStream /** * Android raw resource. * * @property context Android context. * @property id Resource ID. */ class RawResource(val context: Context, val id: Int) { /** * Newly opened resource input stream. */ val inputStream: InputStream get() = context.resources.openRawResource(id) /** * Lines in the resource file. */ val lines: List<String> by lazy { inputStream.reader().readLines() } /** * Builds three-dimensional meshes from OBJ file resource. */ fun loadObjMeshes(): List<Mesh> = lines.loadObjMeshes() /** * Builds texture initialized with an [init] function. */ fun loadTexture(init: TextureBuilder.() -> Unit = {}): Texture = inputStream.loadTexture { init() } } /** * Returns an Android raw resource with the given [id] in this [Context]. */ fun Context.rawResource(id: Int) = RawResource(this, id)
apache-2.0
4bc446867517b64502f6ec69182b97fe
22.978261
75
0.717135
3.738983
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/activity/LinkHandlerActivity.kt
1
41462
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.activity import android.app.Activity import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.net.Uri import android.os.BadParcelableException import android.os.Bundle import android.support.design.widget.FloatingActionButton import android.support.v4.app.Fragment import android.support.v4.app.FragmentManager import android.support.v4.app.FragmentManager.FragmentLifecycleCallbacks import android.support.v4.app.NavUtils import android.support.v4.view.ViewCompat import android.support.v4.view.WindowCompat import android.support.v4.view.WindowInsetsCompat import android.support.v7.widget.Toolbar import android.text.TextUtils import android.view.KeyEvent import android.view.MenuItem import android.view.View import android.view.Window import kotlinx.android.synthetic.main.activity_link_handler.* import org.mariotaku.kpreferences.get import org.mariotaku.ktextension.set import org.mariotaku.ktextension.toDoubleOr import de.vanita5.twittnuker.Constants.* import de.vanita5.twittnuker.R import de.vanita5.twittnuker.activity.iface.IControlBarActivity import de.vanita5.twittnuker.activity.iface.IControlBarActivity.ControlBarShowHideHelper import de.vanita5.twittnuker.constant.* import de.vanita5.twittnuker.exception.NoAccountException import de.vanita5.twittnuker.fragment.* import de.vanita5.twittnuker.fragment.filter.FiltersFragment import de.vanita5.twittnuker.fragment.filter.FiltersImportBlocksFragment import de.vanita5.twittnuker.fragment.filter.FiltersImportMutesFragment import de.vanita5.twittnuker.fragment.filter.FiltersSubscriptionsFragment import de.vanita5.twittnuker.fragment.iface.IBaseFragment import de.vanita5.twittnuker.fragment.iface.IBaseFragment.SystemWindowInsetsCallback import de.vanita5.twittnuker.fragment.iface.IFloatingActionButtonFragment import de.vanita5.twittnuker.fragment.iface.IToolBarSupportFragment import de.vanita5.twittnuker.fragment.iface.SupportFragmentCallback import de.vanita5.twittnuker.fragment.message.MessageConversationInfoFragment import de.vanita5.twittnuker.fragment.message.MessageNewConversationFragment import de.vanita5.twittnuker.fragment.message.MessagesConversationFragment import de.vanita5.twittnuker.fragment.message.MessagesEntriesFragment import de.vanita5.twittnuker.fragment.search.MastodonSearchFragment import de.vanita5.twittnuker.fragment.search.SearchFragment import de.vanita5.twittnuker.fragment.status.StatusFragment import de.vanita5.twittnuker.fragment.statuses.* import de.vanita5.twittnuker.fragment.users.* import de.vanita5.twittnuker.graphic.ActionBarColorDrawable import de.vanita5.twittnuker.graphic.EmptyDrawable import de.vanita5.twittnuker.model.UserKey import de.vanita5.twittnuker.model.analyzer.PurchaseFinished import de.vanita5.twittnuker.util.* import de.vanita5.twittnuker.util.KeyboardShortcutsHandler.KeyboardShortcutCallback import de.vanita5.twittnuker.util.linkhandler.TwidereLinkMatcher import de.vanita5.twittnuker.util.theme.getCurrentThemeResource class LinkHandlerActivity : BaseActivity(), SystemWindowInsetsCallback, IControlBarActivity, SupportFragmentCallback { private lateinit var multiSelectHandler: MultiSelectEventHandler private lateinit var controlBarShowHideHelper: ControlBarShowHideHelper private var finishOnly: Boolean = false private var actionBarHeight: Int = 0 private var subtitle: CharSequence? = null private var hideOffsetNotSupported: Boolean = false private lateinit var fragmentLifecycleCallbacks: FragmentLifecycleCallbacks override val currentVisibleFragment: Fragment? get() = supportFragmentManager.findFragmentByTag("content_fragment") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) multiSelectHandler = MultiSelectEventHandler(this) controlBarShowHideHelper = ControlBarShowHideHelper(this) multiSelectHandler.dispatchOnCreate() fragmentLifecycleCallbacks = object : FragmentManager.FragmentLifecycleCallbacks() { override fun onFragmentViewCreated(fm: FragmentManager, f: Fragment, v: View, savedState: Bundle?) { if (f is IToolBarSupportFragment) { setSupportActionBar(f.toolbar) } } } supportFragmentManager.registerFragmentLifecycleCallbacks(fragmentLifecycleCallbacks, false) val uri = intent.data ?: run { finish() return } val linkId = TwidereLinkMatcher.match(uri) var transactionRequired = false intent.setExtrasClassLoader(classLoader) val fragment: Fragment = currentVisibleFragment ?: try { transactionRequired = true createFragmentForIntent(this, linkId, intent) ?: run { finish() return } } catch (e: NoAccountException) { val selectIntent = Intent(this, AccountSelectorActivity::class.java) val accountHost: String? = intent.getStringExtra(EXTRA_ACCOUNT_HOST) ?: uri.getQueryParameter(QUERY_PARAM_ACCOUNT_HOST) ?: e.accountHost val accountType: String? = intent.getStringExtra(EXTRA_ACCOUNT_TYPE) ?: uri.getQueryParameter(QUERY_PARAM_ACCOUNT_TYPE) ?: e.accountType selectIntent.putExtra(EXTRA_SINGLE_SELECTION, true) selectIntent.putExtra(EXTRA_SELECT_ONLY_ITEM_AUTOMATICALLY, true) selectIntent.putExtra(EXTRA_ACCOUNT_HOST, accountHost) selectIntent.putExtra(EXTRA_ACCOUNT_TYPE, accountType) selectIntent.putExtra(EXTRA_START_INTENT, intent) startActivity(selectIntent) finish() return } val contentFragmentId: Int if (fragment is IToolBarSupportFragment) { if (!fragment.setupWindow(this)) { supportRequestWindowFeature(Window.FEATURE_NO_TITLE) supportRequestWindowFeature(WindowCompat.FEATURE_ACTION_MODE_OVERLAY) } ViewCompat.setOnApplyWindowInsetsListener(window.findViewById(android.R.id.content), this) contentFragmentId = android.R.id.content } else { setContentView(R.layout.activity_link_handler) val toolbar = this.toolbar if (toolbar != null) { if (supportActionBar != null) { toolbar.visibility = View.GONE windowOverlay?.visibility = View.GONE } else { toolbar.visibility = View.VISIBLE windowOverlay?.visibility = View.VISIBLE setSupportActionBar(toolbar) } } actionsButton?.setOnClickListener { val f = currentVisibleFragment as? IFloatingActionButtonFragment f?.onActionClick("link_handler") } contentView.applyWindowInsetsListener = this contentFragmentId = R.id.contentFragment } setupActionBarOption() if (transactionRequired) { val ft = supportFragmentManager.beginTransaction() ft.replace(contentFragmentId, fragment, "content_fragment") ft.commit() } setTitle(linkId, uri) finishOnly = uri.getQueryParameter(QUERY_PARAM_FINISH_ONLY)?.toBoolean() == true val theme = overrideTheme supportActionBar?.setBackgroundDrawable(ActionBarColorDrawable.create(theme.colorToolbar, true)) contentView?.statusBarColor = theme.statusBarColor if (fragment is IToolBarSupportFragment) { ThemeUtils.setCompatContentViewOverlay(window, EmptyDrawable()) } updateActionsButton() } override fun onDestroy() { supportFragmentManager.unregisterFragmentLifecycleCallbacks(fragmentLifecycleCallbacks) super.onDestroy() } override fun onStart() { super.onStart() multiSelectHandler.dispatchOnStart() } override fun onStop() { multiSelectHandler.dispatchOnStop() super.onStop() } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { when (requestCode) { REQUEST_PURCHASE_EXTRA_FEATURES -> { if (resultCode == Activity.RESULT_OK) { Analyzer.log(PurchaseFinished.create(data!!)) } } else -> { super.onActivityResult(requestCode, resultCode, data) } } } override fun triggerRefresh(position: Int): Boolean { return false } override fun onApplyWindowInsets(v: View, insets: WindowInsetsCompat): WindowInsetsCompat { val result = super.onApplyWindowInsets(v, insets) val fragment = currentVisibleFragment if (fragment is IBaseFragment<*>) { fragment.requestApplyInsets() } if (fragment is IToolBarSupportFragment) { return result } contentView?.statusBarHeight = insets.systemWindowInsetTop - controlBarHeight return result.consumeSystemWindowInsets() } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { if (finishOnly) { finish() } else { NavUtils.navigateUpFromSameTask(this) } return true } } return super.onOptionsItemSelected(item) } override fun onAttachFragment(fragment: Fragment?) { super.onAttachFragment(fragment) updateActionsButton() } override fun handleKeyboardShortcutSingle(handler: KeyboardShortcutsHandler, keyCode: Int, event: KeyEvent, metaState: Int): Boolean { if (shouldFragmentTakeAllKeyboardShortcuts()) { return handleFragmentKeyboardShortcutSingle(handler, keyCode, event, metaState) } if (handleFragmentKeyboardShortcutSingle(handler, keyCode, event, metaState)) return true val action = handler.getKeyAction(KeyboardShortcutConstants.CONTEXT_TAG_NAVIGATION, keyCode, event, metaState) if (KeyboardShortcutConstants.ACTION_NAVIGATION_BACK == action) { onBackPressed() return true } return handler.handleKey(this, null, keyCode, event, metaState) } private fun shouldFragmentTakeAllKeyboardShortcuts(): Boolean { val fragment = currentVisibleFragment return fragment is KeyboardShortcutsHandler.TakeAllKeyboardShortcut } override fun handleKeyboardShortcutRepeat(handler: KeyboardShortcutsHandler, keyCode: Int, repeatCount: Int, event: KeyEvent, metaState: Int): Boolean { if (shouldFragmentTakeAllKeyboardShortcuts()) { handleFragmentKeyboardShortcutRepeat(handler, keyCode, repeatCount, event, metaState) } if (handleFragmentKeyboardShortcutRepeat(handler, keyCode, repeatCount, event, metaState)) return true return super.handleKeyboardShortcutRepeat(handler, keyCode, repeatCount, event, metaState) } override fun isKeyboardShortcutHandled(handler: KeyboardShortcutsHandler, keyCode: Int, event: KeyEvent, metaState: Int): Boolean { if (isFragmentKeyboardShortcutHandled(handler, keyCode, event, metaState)) return true return super.isKeyboardShortcutHandled(handler, keyCode, event, metaState) } private fun isFragmentKeyboardShortcutHandled(handler: KeyboardShortcutsHandler, keyCode: Int, event: KeyEvent, metaState: Int): Boolean { val fragment = currentVisibleFragment if (fragment is KeyboardShortcutCallback) { return fragment.isKeyboardShortcutHandled(handler, keyCode, event, metaState) } return false } override fun setSupportActionBar(toolbar: Toolbar?) { super.setSupportActionBar(toolbar) setupActionBarOption() } fun setSubtitle(subtitle: CharSequence?) { this.subtitle = subtitle setupActionBarOption() } override fun setControlBarVisibleAnimate(visible: Boolean, listener: ControlBarShowHideHelper.ControlBarAnimationListener?) { // Currently only search page needs this pattern, so we only enable this feature for it. actionsButton?.let { fab -> if (fab.isEnabled) { if (visible) { fab.show() } else { fab.hide() } } } if (currentVisibleFragment !is HideUiOnScroll) return controlBarShowHideHelper.setControlBarVisibleAnimate(visible, listener) } override var controlBarOffset: Float get() { val fragment = currentVisibleFragment val actionBar = supportActionBar if (fragment is IToolBarSupportFragment) { return fragment.controlBarOffset } else if (actionBar != null) { return actionBar.hideOffset / controlBarHeight.toFloat() } return 0f } set(offset) { val fragment = currentVisibleFragment val actionBar = supportActionBar if (fragment is IToolBarSupportFragment) { fragment.controlBarOffset = offset } else if (actionBar != null && !hideOffsetNotSupported) { try { actionBar.hideOffset = (controlBarHeight * offset).toInt() } catch (e: UnsupportedOperationException) { // Some device will throw this exception hideOffsetNotSupported = true } } notifyControlBarOffsetChanged() } override val controlBarHeight: Int get() { val fragment = currentVisibleFragment val actionBar = supportActionBar var height = 0 if (fragment is IToolBarSupportFragment) { fragment.controlBarHeight } else if (actionBar != null) { height = actionBar.height } if (height != 0) return height if (actionBarHeight != 0) return actionBarHeight actionBarHeight = ThemeUtils.getActionBarHeight(this) return actionBarHeight } override fun getThemeResource(preferences: SharedPreferences, theme: String, themeColor: Int): Int { if (preferences[floatingDetailedContentsKey]) { return super.getThemeResource(preferences, theme, themeColor) } return getCurrentThemeResource(this, theme, R.style.Theme_Twidere) } private fun setTitle(linkId: Int, uri: Uri): Boolean { setSubtitle(null) when (linkId) { LINK_ID_STATUS -> { setTitle(R.string.title_status) } LINK_ID_USER -> { setTitle(R.string.title_user) } LINK_ID_USER_TIMELINE -> { setTitle(R.string.title_statuses) } LINK_ID_USER_FAVORITES -> { if (preferences[iWantMyStarsBackKey]) { setTitle(R.string.title_favorites) } else { setTitle(R.string.title_likes) } } LINK_ID_USER_FOLLOWERS -> { setTitle(R.string.title_followers) } LINK_ID_USER_FRIENDS -> { setTitle(R.string.title_following) } LINK_ID_USER_BLOCKS -> { setTitle(R.string.title_blocked_users) } LINK_ID_MUTES_USERS -> { setTitle(R.string.action_twitter_muted_users) } LINK_ID_USER_LIST -> { setTitle(R.string.title_user_list) } LINK_ID_GROUP -> { setTitle(R.string.group) } LINK_ID_USER_LISTS -> { setTitle(R.string.user_lists) } LINK_ID_USER_GROUPS -> { setTitle(R.string.groups) } LINK_ID_USER_LIST_TIMELINE -> { setTitle(R.string.list_timeline) } LINK_ID_USER_LIST_MEMBERS -> { setTitle(R.string.list_members) } LINK_ID_USER_LIST_SUBSCRIBERS -> { setTitle(R.string.list_subscribers) } LINK_ID_USER_LIST_MEMBERSHIPS -> { setTitle(R.string.lists_following_user) } LINK_ID_SAVED_SEARCHES -> { setTitle(R.string.saved_searches) } LINK_ID_USER_MENTIONS -> { setTitle(R.string.user_mentions) } LINK_ID_INCOMING_FRIENDSHIPS -> { setTitle(R.string.incoming_friendships) } LINK_ID_ITEMS -> { }// TODO show title LINK_ID_USER_MEDIA_TIMELINE -> { setTitle(R.string.media) } LINK_ID_STATUS_RETWEETERS -> { setTitle(R.string.title_users_retweeted_this) } LINK_ID_STATUS_FAVORITERS -> { if (preferences[iWantMyStarsBackKey]) { setTitle(R.string.title_users_favorited_this) } else { setTitle(R.string.title_users_liked_this) } } LINK_ID_SEARCH -> { setTitle(R.string.title_search) setSubtitle(uri.getQueryParameter(QUERY_PARAM_QUERY)) } LINK_ID_MASTODON_SEARCH -> { setTitle(R.string.title_search) setSubtitle(uri.getQueryParameter(QUERY_PARAM_QUERY)) } LINK_ID_ACCOUNTS -> { setTitle(R.string.title_accounts) } LINK_ID_DRAFTS -> { setTitle(R.string.title_drafts) } LINK_ID_FILTERS -> { setTitle(R.string.title_filters) } LINK_ID_MAP -> { setTitle(R.string.action_view_map) } LINK_ID_PROFILE_EDITOR -> { setTitle(R.string.title_edit_profile) } LINK_ID_MESSAGES -> { title = getString(R.string.title_direct_messages) } LINK_ID_MESSAGES_CONVERSATION -> { title = getString(R.string.title_direct_messages) } LINK_ID_MESSAGES_CONVERSATION_NEW -> { title = getString(R.string.title_direct_messages_conversation_new) } LINK_ID_MESSAGES_CONVERSATION_INFO -> { title = getString(R.string.title_direct_messages_conversation_info) } LINK_ID_INTERACTIONS -> { title = getString(R.string.interactions) } LINK_ID_PUBLIC_TIMELINE -> { title = getString(R.string.title_public_timeline) } LINK_ID_NETWORK_PUBLIC_TIMELINE -> { title = getString(R.string.title_network_public_timeline) } LINK_ID_FILTERS_IMPORT_BLOCKS -> { title = getString(R.string.title_select_users) } LINK_ID_FILTERS_IMPORT_MUTES -> { title = getString(R.string.title_select_users) } LINK_ID_FILTERS_SUBSCRIPTIONS_ADD, LINK_ID_FILTERS_SUBSCRIPTIONS -> { title = getString(R.string.title_manage_filter_subscriptions) } else -> { title = getString(R.string.app_name) } } return true } private fun handleFragmentKeyboardShortcutRepeat(handler: KeyboardShortcutsHandler, keyCode: Int, repeatCount: Int, event: KeyEvent, metaState: Int): Boolean { val fragment = currentVisibleFragment if (fragment is KeyboardShortcutCallback) { return fragment.handleKeyboardShortcutRepeat(handler, keyCode, repeatCount, event, metaState) } return false } private fun handleFragmentKeyboardShortcutSingle(handler: KeyboardShortcutsHandler, keyCode: Int, event: KeyEvent, metaState: Int): Boolean { val fragment = currentVisibleFragment if (fragment is KeyboardShortcutCallback) { if (fragment.handleKeyboardShortcutSingle(handler, keyCode, event, metaState)) { return true } } return false } private fun setupActionBarOption() { val actionBar = supportActionBar if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true) actionBar.subtitle = subtitle } } private fun updateActionsButton() { val fab = window.findViewById<FloatingActionButton>(R.id.actionsButton) ?: return val fragment = currentVisibleFragment as? IFloatingActionButtonFragment val info = fragment?.getActionInfo("link_handler") ?: run { fab.visibility = View.GONE fab.isEnabled = false return } fab.visibility = View.VISIBLE fab.isEnabled = true fab.setImageResource(info.icon) fab.contentDescription = info.title } @Throws(NoAccountException::class) private fun createFragmentForIntent(context: Context, linkId: Int, intent: Intent): Fragment? { intent.setExtrasClassLoader(classLoader) val extras = intent.extras val uri = intent.data val fragment: Fragment if (uri == null) return null val args = Bundle() if (extras != null) { try { args.putAll(extras) } catch (e: BadParcelableException) { // When called by external app with wrong params return null } } var userHost: String? = null var accountType: String? = null var accountRequired = true when (linkId) { LINK_ID_ACCOUNTS -> { accountRequired = false fragment = AccountsManagerFragment() } LINK_ID_DRAFTS -> { accountRequired = false fragment = DraftsFragment() } LINK_ID_FILTERS -> { accountRequired = false fragment = FiltersFragment() } LINK_ID_PROFILE_EDITOR -> { fragment = UserProfileEditorFragment() } LINK_ID_MAP -> { accountRequired = false if (!args.containsKey(EXTRA_LATITUDE) && !args.containsKey(EXTRA_LONGITUDE)) { val lat = uri.getQueryParameter(QUERY_PARAM_LAT).toDoubleOr(Double.NaN) val lng = uri.getQueryParameter(QUERY_PARAM_LNG).toDoubleOr(Double.NaN) if (lat.isNaN() || lng.isNaN()) return null args.putDouble(EXTRA_LATITUDE, lat) args.putDouble(EXTRA_LONGITUDE, lng) } fragment = MapFragmentFactory.instance.createMapFragment(context) } LINK_ID_STATUS -> { fragment = StatusFragment() if (!args.containsKey(EXTRA_STATUS_ID)) { val paramStatusId = uri.getQueryParameter(QUERY_PARAM_STATUS_ID) args.putString(EXTRA_STATUS_ID, paramStatusId) } } LINK_ID_USER -> { fragment = UserFragment() val paramScreenName = uri.getQueryParameter(QUERY_PARAM_SCREEN_NAME) val paramProfileUrl = uri.getQueryParameter(QUERY_PARAM_PROFILE_URL) val paramUserKey = uri.getUserKeyQueryParameter() if (!args.containsKey(EXTRA_SCREEN_NAME)) { args.putString(EXTRA_SCREEN_NAME, paramScreenName) } if (!args.containsKey(EXTRA_USER_KEY)) { args.putParcelable(EXTRA_USER_KEY, paramUserKey) } if (!args.containsKey(EXTRA_PROFILE_URL)) { args.putString(EXTRA_PROFILE_URL, paramProfileUrl) } if (paramUserKey != null) { userHost = paramUserKey.host } accountType = uri.getQueryParameter(QUERY_PARAM_ACCOUNT_TYPE) } LINK_ID_USER_LIST_MEMBERSHIPS -> { fragment = UserListMembershipsFragment() val paramScreenName = uri.getQueryParameter(QUERY_PARAM_SCREEN_NAME) val paramUserKey = uri.getUserKeyQueryParameter() if (!args.containsKey(EXTRA_SCREEN_NAME)) { args.putString(EXTRA_SCREEN_NAME, paramScreenName) } if (!args.containsKey(EXTRA_USER_KEY)) { args.putParcelable(EXTRA_USER_KEY, paramUserKey) } } LINK_ID_USER_TIMELINE -> { fragment = UserTimelineFragment() val paramScreenName = uri.getQueryParameter(QUERY_PARAM_SCREEN_NAME) val paramProfileUrl = uri.getQueryParameter(QUERY_PARAM_PROFILE_URL) val paramUserKey = uri.getUserKeyQueryParameter() if (!args.containsKey(EXTRA_SCREEN_NAME)) { args.putString(EXTRA_SCREEN_NAME, paramScreenName) } if (!args.containsKey(EXTRA_USER_KEY)) { args.putParcelable(EXTRA_USER_KEY, paramUserKey) } if (!args.containsKey(EXTRA_PROFILE_URL)) { args.putString(EXTRA_PROFILE_URL, paramProfileUrl) } if (TextUtils.isEmpty(paramScreenName) && paramUserKey == null) return null } LINK_ID_USER_MEDIA_TIMELINE -> { fragment = UserMediaTimelineFragment() val paramScreenName = uri.getQueryParameter(QUERY_PARAM_SCREEN_NAME) val paramUserKey = uri.getUserKeyQueryParameter() if (!args.containsKey(EXTRA_SCREEN_NAME)) { args.putString(EXTRA_SCREEN_NAME, paramScreenName) } if (!args.containsKey(EXTRA_USER_KEY)) { args.putParcelable(EXTRA_USER_KEY, paramUserKey) } if (TextUtils.isEmpty(paramScreenName) && paramUserKey == null) return null } LINK_ID_USER_FAVORITES -> { fragment = UserFavoritesFragment() val paramScreenName = uri.getQueryParameter(QUERY_PARAM_SCREEN_NAME) val paramUserKey = uri.getUserKeyQueryParameter() if (!args.containsKey(EXTRA_SCREEN_NAME)) { args.putString(EXTRA_SCREEN_NAME, paramScreenName) } if (!args.containsKey(EXTRA_USER_KEY)) { args.putParcelable(EXTRA_USER_KEY, paramUserKey) } if (!args.containsKey(EXTRA_SCREEN_NAME) && !args.containsKey(EXTRA_USER_KEY)) return null } LINK_ID_USER_FOLLOWERS -> { fragment = UserFollowersFragment() val paramScreenName = uri.getQueryParameter(QUERY_PARAM_SCREEN_NAME) val paramUserKey = uri.getUserKeyQueryParameter() if (!args.containsKey(EXTRA_SCREEN_NAME)) { args.putString(EXTRA_SCREEN_NAME, paramScreenName) } if (!args.containsKey(EXTRA_USER_KEY)) { args.putParcelable(EXTRA_USER_KEY, paramUserKey) } if (TextUtils.isEmpty(paramScreenName) && paramUserKey == null) return null } LINK_ID_USER_FRIENDS -> { fragment = UserFriendsFragment() val paramScreenName = uri.getQueryParameter(QUERY_PARAM_SCREEN_NAME) val paramUserKey = uri.getUserKeyQueryParameter() if (!args.containsKey(EXTRA_SCREEN_NAME)) { args.putString(EXTRA_SCREEN_NAME, paramScreenName) } if (!args.containsKey(EXTRA_USER_KEY)) { args.putParcelable(EXTRA_USER_KEY, paramUserKey) } if (TextUtils.isEmpty(paramScreenName) && paramUserKey == null) return null } LINK_ID_USER_BLOCKS -> { fragment = UserBlocksListFragment() args[EXTRA_SIMPLE_LAYOUT] = true } LINK_ID_MUTES_USERS -> { fragment = MutesUsersListFragment() args[EXTRA_SIMPLE_LAYOUT] = true } LINK_ID_MESSAGES -> { fragment = MessagesEntriesFragment() } LINK_ID_MESSAGES_CONVERSATION -> { fragment = MessagesConversationFragment() accountRequired = true val conversationId = uri.getQueryParameter(QUERY_PARAM_CONVERSATION_ID) ?: return null args.putString(EXTRA_CONVERSATION_ID, conversationId) } LINK_ID_MESSAGES_CONVERSATION_NEW -> { fragment = MessageNewConversationFragment() accountRequired = true } LINK_ID_MESSAGES_CONVERSATION_INFO -> { fragment = MessageConversationInfoFragment() val conversationId = uri.getQueryParameter(QUERY_PARAM_CONVERSATION_ID) ?: return null args.putString(EXTRA_CONVERSATION_ID, conversationId) accountRequired = true } LINK_ID_INTERACTIONS -> { fragment = InteractionsTimelineFragment() } LINK_ID_PUBLIC_TIMELINE -> { fragment = PublicTimelineFragment() } LINK_ID_NETWORK_PUBLIC_TIMELINE -> { fragment = NetworkPublicTimelineFragment() } LINK_ID_USER_LIST -> { fragment = UserListFragment() val paramScreenName = uri.getQueryParameter(QUERY_PARAM_SCREEN_NAME) val paramUserKey = uri.getUserKeyQueryParameter() val paramListId = uri.getQueryParameter(QUERY_PARAM_LIST_ID) val paramListName = uri.getQueryParameter(QUERY_PARAM_LIST_NAME) if ((TextUtils.isEmpty(paramListName) || TextUtils.isEmpty(paramScreenName) && paramUserKey == null) && TextUtils.isEmpty(paramListId)) { return null } args.putString(EXTRA_LIST_ID, paramListId) args.putParcelable(EXTRA_USER_KEY, paramUserKey) args.putString(EXTRA_SCREEN_NAME, paramScreenName) args.putString(EXTRA_LIST_NAME, paramListName) } LINK_ID_GROUP -> { fragment = GroupFragment() val paramGroupId = uri.getQueryParameter(QUERY_PARAM_GROUP_ID) val paramGroupName = uri.getQueryParameter(QUERY_PARAM_GROUP_NAME) if (TextUtils.isEmpty(paramGroupId) && TextUtils.isEmpty(paramGroupName)) return null args.putString(EXTRA_GROUP_ID, paramGroupId) args.putString(EXTRA_GROUP_NAME, paramGroupName) } LINK_ID_USER_LISTS -> { fragment = ListsFragment() val paramScreenName = uri.getQueryParameter(QUERY_PARAM_SCREEN_NAME) val paramUserKey = uri.getUserKeyQueryParameter() if (!args.containsKey(EXTRA_SCREEN_NAME)) { args.putString(EXTRA_SCREEN_NAME, paramScreenName) } if (!args.containsKey(EXTRA_USER_KEY)) { args.putParcelable(EXTRA_USER_KEY, paramUserKey) } if (TextUtils.isEmpty(paramScreenName) && paramUserKey == null) return null } LINK_ID_USER_GROUPS -> { fragment = UserGroupsFragment() val paramScreenName = uri.getQueryParameter(QUERY_PARAM_SCREEN_NAME) val paramUserKey = uri.getUserKeyQueryParameter() if (!args.containsKey(EXTRA_SCREEN_NAME)) { args.putString(EXTRA_SCREEN_NAME, paramScreenName) } if (!args.containsKey(EXTRA_USER_KEY)) { args.putParcelable(EXTRA_USER_KEY, paramUserKey) } if (TextUtils.isEmpty(paramScreenName) && paramUserKey == null) return null } LINK_ID_USER_LIST_TIMELINE -> { fragment = UserListTimelineFragment() val paramScreenName = uri.getQueryParameter(QUERY_PARAM_SCREEN_NAME) val paramUserKey = uri.getUserKeyQueryParameter() val paramListId = uri.getQueryParameter(QUERY_PARAM_LIST_ID) val paramListName = uri.getQueryParameter(QUERY_PARAM_LIST_NAME) if ((TextUtils.isEmpty(paramListName) || TextUtils.isEmpty(paramScreenName) && paramUserKey == null) && TextUtils.isEmpty(paramListId)) { return null } args.putString(EXTRA_LIST_ID, paramListId) args.putParcelable(EXTRA_USER_KEY, paramUserKey) args.putString(EXTRA_SCREEN_NAME, paramScreenName) args.putString(EXTRA_LIST_NAME, paramListName) } LINK_ID_USER_LIST_MEMBERS -> { fragment = UserListMembersFragment() val paramScreenName = uri.getQueryParameter(QUERY_PARAM_SCREEN_NAME) val paramUserKey = uri.getUserKeyQueryParameter() val paramListId = uri.getQueryParameter(QUERY_PARAM_LIST_ID) val paramListName = uri.getQueryParameter(QUERY_PARAM_LIST_NAME) if ((TextUtils.isEmpty(paramListName) || TextUtils.isEmpty(paramScreenName) && paramUserKey == null) && TextUtils.isEmpty(paramListId)) return null args.putString(EXTRA_LIST_ID, paramListId) args.putParcelable(EXTRA_USER_KEY, paramUserKey) args.putString(EXTRA_SCREEN_NAME, paramScreenName) args.putString(EXTRA_LIST_NAME, paramListName) } LINK_ID_USER_LIST_SUBSCRIBERS -> { fragment = UserListSubscribersFragment() val paramScreenName = uri.getQueryParameter(QUERY_PARAM_SCREEN_NAME) val paramUserKey = uri.getUserKeyQueryParameter() val paramListId = uri.getQueryParameter(QUERY_PARAM_LIST_ID) val paramListName = uri.getQueryParameter(QUERY_PARAM_LIST_NAME) if (TextUtils.isEmpty(paramListId) && (TextUtils.isEmpty(paramListName) || TextUtils.isEmpty(paramScreenName) && paramUserKey == null)) return null args.putString(EXTRA_LIST_ID, paramListId) args.putParcelable(EXTRA_USER_KEY, paramUserKey) args.putString(EXTRA_SCREEN_NAME, paramScreenName) args.putString(EXTRA_LIST_NAME, paramListName) } LINK_ID_SAVED_SEARCHES -> { fragment = SavedSearchesListFragment() } LINK_ID_USER_MENTIONS -> { fragment = UserMentionsFragment() val paramScreenName = uri.getQueryParameter(QUERY_PARAM_SCREEN_NAME) if (!args.containsKey(EXTRA_SCREEN_NAME) && !TextUtils.isEmpty(paramScreenName)) { args.putString(EXTRA_SCREEN_NAME, paramScreenName) } if (TextUtils.isEmpty(args.getString(EXTRA_SCREEN_NAME))) return null } LINK_ID_INCOMING_FRIENDSHIPS -> { fragment = IncomingFriendshipsFragment() } LINK_ID_ITEMS -> { accountRequired = false fragment = ItemsListFragment() } LINK_ID_STATUS_RETWEETERS -> { fragment = StatusRetweetersListFragment() if (!args.containsKey(EXTRA_STATUS_ID)) { val paramStatusId = uri.getQueryParameter(QUERY_PARAM_STATUS_ID) args.putString(EXTRA_STATUS_ID, paramStatusId) } } LINK_ID_STATUS_FAVORITERS -> { fragment = StatusFavoritersListFragment() if (!args.containsKey(EXTRA_STATUS_ID)) { val paramStatusId = uri.getQueryParameter(QUERY_PARAM_STATUS_ID) args.putString(EXTRA_STATUS_ID, paramStatusId) } } LINK_ID_SEARCH -> { val paramQuery = uri.getQueryParameter(QUERY_PARAM_QUERY) if (!args.containsKey(EXTRA_QUERY) && !TextUtils.isEmpty(paramQuery)) { args.putString(EXTRA_QUERY, paramQuery) } if (!args.containsKey(EXTRA_QUERY)) { return null } fragment = SearchFragment() } LINK_ID_MASTODON_SEARCH -> { val paramQuery = uri.getQueryParameter(QUERY_PARAM_QUERY) if (!args.containsKey(EXTRA_QUERY) && !TextUtils.isEmpty(paramQuery)) { args.putString(EXTRA_QUERY, paramQuery) } if (!args.containsKey(EXTRA_QUERY)) { return null } fragment = MastodonSearchFragment() } LINK_ID_FILTERS_IMPORT_BLOCKS -> { fragment = FiltersImportBlocksFragment() } LINK_ID_FILTERS_IMPORT_MUTES -> { fragment = FiltersImportMutesFragment() } LINK_ID_FILTERS_SUBSCRIPTIONS -> { fragment = FiltersSubscriptionsFragment() accountRequired = false } LINK_ID_FILTERS_SUBSCRIPTIONS_ADD -> { val url = uri.getQueryParameter("url") ?: return null val name = uri.getQueryParameter("name") fragment = FiltersSubscriptionsFragment() args.putString(IntentConstants.EXTRA_ACTION, FiltersSubscriptionsFragment.ACTION_ADD_URL_SUBSCRIPTION) args.putString(FiltersSubscriptionsFragment.EXTRA_ADD_SUBSCRIPTION_URL, url) args.putString(FiltersSubscriptionsFragment.EXTRA_ADD_SUBSCRIPTION_NAME, name) accountRequired = false } else -> { return null } } var accountKey = args.getParcelable<UserKey>(EXTRA_ACCOUNT_KEY) if (accountKey == null) { accountKey = uri.getQueryParameter(QUERY_PARAM_ACCOUNT_KEY)?.let(UserKey::valueOf) } if (accountKey == null) { val accountId = uri.getQueryParameter(CompatibilityConstants.QUERY_PARAM_ACCOUNT_ID) val paramAccountName = uri.getQueryParameter(QUERY_PARAM_ACCOUNT_NAME) DataStoreUtils.prepareDatabase(context) if (accountId != null) { accountKey = DataStoreUtils.findAccountKey(context, accountId) args.putParcelable(EXTRA_ACCOUNT_KEY, accountKey) } else if (paramAccountName != null) { accountKey = DataStoreUtils.findAccountKeyByScreenName(context, paramAccountName) } } if (accountRequired && accountKey == null) { val exception = NoAccountException() exception.accountHost = userHost exception.accountType = accountType throw exception } args.putParcelable(EXTRA_ACCOUNT_KEY, accountKey) fragment.arguments = args return fragment } interface HideUiOnScroll private fun Uri.getUserKeyQueryParameter() : UserKey? { val value = getQueryParameter(QUERY_PARAM_USER_KEY) ?: getQueryParameter(QUERY_PARAM_USER_ID) return value?.let(UserKey::valueOf) } }
gpl-3.0
7b52e2f4c8e02500fc1a804243cc32e8
43.15655
156
0.597366
5.086114
false
false
false
false
ejeinc/VR-MultiView-UDP
controller-android/src/main/java/com/eje_c/multilink/controller/VideosFragment.kt
1
1142
package com.eje_c.multilink.controller import android.arch.lifecycle.Observer import android.support.v4.app.Fragment import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.widget.TextView import com.eje_c.multilink.controller.db.VideoEntity import org.androidannotations.annotations.AfterViews import org.androidannotations.annotations.EFragment import org.androidannotations.annotations.ViewById @EFragment(R.layout.fragment_videos) open class VideosFragment : Fragment() { @ViewById lateinit var recyclerView: RecyclerView @ViewById lateinit var videoCount: TextView @AfterViews fun init() { val adapter = VideoListAdapter() recyclerView.adapter = adapter recyclerView.layoutManager = LinearLayoutManager(context) App.db.videoDao.query().observe(this, Observer<List<VideoEntity>> { data -> if (data != null) { // Show videos adapter.list = data // Show count of videos videoCount.text = data.size.toString() } }) } }
apache-2.0
8b4cf7712055ff7de232c73d462fc20a
27.575
83
0.69965
4.531746
false
false
false
false
JoachimR/Bible2net
app/src/main/java/de/reiss/bible2net/theword/widget/WidgetRemoteViewsFactory.kt
1
3390
package de.reiss.bible2net.theword.widget import android.content.Context import android.content.Intent import android.os.Build import android.util.TypedValue import android.view.View import android.widget.RemoteViews import android.widget.RemoteViewsService import de.reiss.bible2net.theword.App import de.reiss.bible2net.theword.R import de.reiss.bible2net.theword.logger.logError import de.reiss.bible2net.theword.logger.logWarn import de.reiss.bible2net.theword.preferences.AppPreferences import de.reiss.bible2net.theword.util.htmlize import java.util.ArrayList class WidgetRemoteViewsFactory(private val context: Context) : RemoteViewsService.RemoteViewsFactory { private val list = ArrayList<CharSequence>() private val appPreferences: AppPreferences by lazy { App.component.appPreferences } private val widgetRefresher: WidgetRefresher by lazy { App.component.widgetRefresher } override fun onCreate() { } override fun onDestroy() { } /** * From the documentation: * expensive tasks can be safely performed synchronously within this method. * In the interim, the old data will be displayed within the widget. */ override fun onDataSetChanged() { list.clear() list.add(htmlize(widgetRefresher.retrieveWidgetText())) } override fun getCount() = list.size override fun getItemId(position: Int) = position.toLong() override fun hasStableIds() = false override fun getLoadingView() = null override fun getViewTypeCount() = 1 override fun getViewAt(position: Int): RemoteViews { val remoteViewRow = RemoteViews(context.packageName, R.layout.widget_layout_list_row) try { applyUi(remoteViewRow) } catch (e: Exception) { logError(e) { "Error when trying to set widget" } } return remoteViewRow } private fun applyUi(remoteViewRow: RemoteViews) { val list = list val item = if (list.isNotEmpty()) list.first() else { logWarn { "widget list is empty when trying to apply" } return } remoteViewRow.apply { val widgetCentered = appPreferences.widgetCentered() val textView = if (widgetCentered) R.id.tv_widget_content_centered else R.id.tv_widget_content_uncentered setViewVisibility( R.id.tv_widget_content_centered, if (widgetCentered) View.VISIBLE else View.GONE ) setViewVisibility( R.id.tv_widget_content_uncentered, if (widgetCentered) View.GONE else View.VISIBLE ) setTextViewText(textView, item) setTextColor(textView, appPreferences.widgetFontColor()) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { setTextViewTextSize( textView, TypedValue.COMPLEX_UNIT_SP, appPreferences.widgetFontSize() ) } else { setFloat(textView, "setTextSize", appPreferences.widgetFontSize()) } // widget click event setOnClickFillInIntent(R.id.widget_row_root, Intent()) // background color set in WidgetProvider } } }
gpl-3.0
05fad0873c0689d13e8c029ee9e32d9f
29.540541
93
0.641888
4.781382
false
false
false
false
AndroidX/androidx
benchmark/benchmark-macro/src/main/java/androidx/benchmark/macro/perfetto/Slice.kt
3
1414
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.benchmark.macro.perfetto import androidx.annotation.RestrictTo import androidx.benchmark.macro.perfetto.server.QueryResultIterator @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) data class Slice( val name: String, val ts: Long, val dur: Long ) { val endTs: Long = ts + dur val frameId = name.substringAfterLast(" ").toIntOrNull() fun contains(targetTs: Long): Boolean { return targetTs >= ts && targetTs <= (ts + dur) } } /** * Convenient function to immediately retrieve a list of slices. * Note that this method is provided for convenience and exhausts the iterator. */ internal fun QueryResultIterator.toSlices(): List<Slice> = toList { Slice(name = it["name"] as String, ts = it["ts"] as Long, dur = it["dur"] as Long) }
apache-2.0
555c7baad48122304da60a0f29c34a0f
31.906977
90
0.712871
4.074928
false
false
false
false
TeamWizardry/LibrarianLib
modules/scribe/src/main/kotlin/com/teamwizardry/librarianlib/scribe/nbt/ArraySerializerFactory.kt
1
2458
package com.teamwizardry.librarianlib.scribe.nbt import dev.thecodewarrior.mirror.Mirror import dev.thecodewarrior.mirror.type.ArrayMirror import dev.thecodewarrior.mirror.type.TypeMirror import dev.thecodewarrior.prism.DeserializationException import dev.thecodewarrior.prism.SerializationException import dev.thecodewarrior.prism.base.analysis.ArrayAnalyzer import net.minecraft.nbt.NbtCompound import net.minecraft.nbt.NbtElement import net.minecraft.nbt.NbtList internal class ArraySerializerFactory(prism: NbtPrism): NBTSerializerFactory(prism, Mirror.reflect<Array<*>>()) { override fun create(mirror: TypeMirror): NbtSerializer<*> { return ArraySerializer(prism, mirror as ArrayMirror) } class ArraySerializer(prism: NbtPrism, type: ArrayMirror): NbtSerializer<Array<Any?>>(type) { private val analyzer = ArrayAnalyzer<Any?, NbtSerializer<*>>(prism, type) @Suppress("UNCHECKED_CAST") override fun deserialize(tag: NbtElement): Array<Any?> { analyzer.getReader().use { state -> @Suppress("NAME_SHADOWING") val tag = tag.expectType<NbtList>("tag") state.reserve(tag.size) tag.forEachIndexed { i, it -> try { val entry = it.expectType<NbtCompound>("element $i") if (entry.contains("V")) state.add(state.serializer.read(entry.expect("V"))) else state.add(null) } catch (e: Exception) { throw DeserializationException("Error deserializing element $i", e) } } return state.build() } } override fun serialize(value: Array<Any?>): NbtElement { analyzer.getWriter(value).use { state -> val tag = NbtList() for(i in 0 until state.size) { val v = state.get(i) try { val entry = NbtCompound() if (v != null) entry.put("V", state.serializer.write(v)) tag.add(entry) } catch (e: Exception) { throw SerializationException("Error serializing element $i", e) } } return tag } } } }
lgpl-3.0
00b0ac7924b7e5e9e977d112e4bae29c
39.966667
113
0.555736
5.026585
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/ide/inspections/lints/RsLintInspection.kt
3
5854
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.inspections.lints import com.intellij.codeInspection.* import com.intellij.codeInspection.util.InspectionMessage import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiComment import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiNamedElement import org.rust.ide.inspections.RsLocalInspectionTool import org.rust.ide.inspections.RsProblemsHolder import org.rust.ide.inspections.lints.RsLintLevel.* import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.* abstract class RsLintInspection : RsLocalInspectionTool() { protected abstract fun getLint(element: PsiElement): RsLint? override val isSyntaxOnly: Boolean = true protected fun RsProblemsHolder.registerLintProblem( element: PsiElement, @InspectionMessage descriptionTemplate: String, lintHighlightingType: RsLintHighlightingType = RsLintHighlightingType.DEFAULT, fixes: List<LocalQuickFix> = emptyList() ) { registerProblem(element, descriptionTemplate, getProblemHighlightType(element, lintHighlightingType), *fixes.toTypedArray()) } protected fun RsProblemsHolder.registerLintProblem( element: PsiElement, @InspectionMessage descriptionTemplate: String, rangeInElement: TextRange, lintHighlightingType: RsLintHighlightingType = RsLintHighlightingType.DEFAULT, fixes: List<LocalQuickFix> = emptyList() ) { val highlightType = getProblemHighlightType(element, lintHighlightingType) registerProblem(element, descriptionTemplate, highlightType, rangeInElement, *fixes.toTypedArray()) } private fun getProblemHighlightType( element: PsiElement, lintHighlightingType: RsLintHighlightingType ): ProblemHighlightType { val lint = getLint(element) ?: return ProblemHighlightType.WARNING return when (lint.levelFor(element)) { ALLOW -> lintHighlightingType.allow WARN -> lintHighlightingType.warn DENY -> lintHighlightingType.deny FORBID -> lintHighlightingType.forbid } } override fun isSuppressedFor(element: PsiElement): Boolean { if (super.isSuppressedFor(element)) return true return getLint(element)?.levelFor(element) == ALLOW } // TODO: fix quick fix order in UI override fun getBatchSuppressActions(element: PsiElement?): Array<SuppressQuickFix> { val fixes = super.getBatchSuppressActions(element).toMutableList() if (element == null) return fixes.toTypedArray() val lint = getLint(element) ?: return fixes.toTypedArray() for (ancestor in element.ancestors) { val action = when (ancestor) { is RsLetDecl, is RsFieldDecl, is RsEnumVariant, is RsItemElement, is RsFile -> { var target = when (ancestor) { is RsLetDecl -> "statement" is RsFieldDecl -> "field" is RsEnumVariant -> "enum variant" is RsStructItem -> "struct" is RsEnumItem -> "enum" is RsFunction -> "fn" is RsTypeAlias -> "type" is RsConstant -> "const" is RsModItem -> "mod" is RsImplItem -> "impl" is RsTraitItem -> "trait" is RsUseItem -> "use" is RsFile -> "file" else -> null } if (target != null) { val name = (ancestor as? PsiNamedElement)?.name if (name != null) { target += " $name" } RsSuppressQuickFix(ancestor as RsDocAndAttributeOwner, lint, target) } else { null } } is RsExprStmt -> { val expr = ancestor.expr if (expr is RsOuterAttributeOwner) RsSuppressQuickFix(expr, lint, "statement") else null } else -> null } if (action != null) { fixes += action } } return fixes.toTypedArray() } } private class RsSuppressQuickFix( suppressAt: RsDocAndAttributeOwner, private val lint: RsLint, private val target: String ) : LocalQuickFixOnPsiElement(suppressAt), ContainerBasedSuppressQuickFix { override fun getFamilyName(): String = "Suppress warnings" override fun getText(): String = "Suppress `${lint.id}` for $target" override fun isAvailable(project: Project, context: PsiElement): Boolean = context.isValid override fun isSuppressAll(): Boolean = false override fun getContainer(context: PsiElement?): PsiElement? = startElement?.takeIf { it !is RsFile } override fun invoke(project: Project, file: PsiFile, suppressAt: PsiElement, endElement: PsiElement) { val attr = Attribute("allow", lint.id) when (suppressAt) { is RsOuterAttributeOwner -> { val anchor = suppressAt.outerAttrList.firstOrNull() ?: suppressAt.firstChild suppressAt.addOuterAttribute(attr, anchor) } is RsInnerAttributeOwner -> { val anchor = suppressAt.children.first { it !is RsInnerAttr && it !is PsiComment } ?: return suppressAt.addInnerAttribute(attr, anchor) } } } }
mit
989f980c481cbdc8ec9fe095a79b3f5a
38.554054
132
0.607619
5.31216
false
false
false
false
twilio/video-quickstart-android
exampleCustomVideoSink/src/main/java/com/twilio/video/examples/customvideosink/CustomVideoSinkVideoActivity.kt
1
4010
package com.twilio.video.examples.customvideosink import android.Manifest import android.app.Activity import android.content.pm.PackageManager import android.os.Bundle import android.support.v4.app.ActivityCompat import android.support.v4.content.ContextCompat import android.view.View import android.widget.ImageView import android.widget.TextView import android.widget.Toast import com.twilio.video.CameraCapturer import com.twilio.video.LocalVideoTrack import com.twilio.video.VideoView import tvi.webrtc.Camera1Enumerator /** * This example demonstrates how to implement a custom renderer. Here we render the contents * of our [CameraCapturer] to a video view and to a snapshot renderer which allows user to * grab the latest frame rendered. When the camera view is tapped the frame is updated. */ class CustomVideoSinkVideoActivity : Activity() { private lateinit var localVideoView: VideoView private lateinit var snapshotImageView: ImageView private lateinit var tapForSnapshotTextView: TextView private val snapshotVideoRenderer by lazy { SnapshotVideoSink(snapshotImageView) } private val frontCameraId by lazy { val camera1Enumerator = Camera1Enumerator() val cameraId = camera1Enumerator.deviceNames.find { camera1Enumerator.isFrontFacing(it) } requireNotNull(cameraId) } private val localVideoTrack by lazy { LocalVideoTrack.create( this, true, CameraCapturer( this, frontCameraId, null ) ) } public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_custom_renderer) localVideoView = findViewById<View>(R.id.local_video) as VideoView snapshotImageView = findViewById<View>(R.id.image_view) as ImageView tapForSnapshotTextView = findViewById<View>(R.id.tap_video_snapshot) as TextView /* * Check camera permissions. Needed in Android M. */ if (!checkPermissionForCamera()) { requestPermissionForCamera() } else { addVideo() } } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<String>, grantResults: IntArray ) { if (requestCode == CAMERA_PERMISSION_REQUEST_CODE) { var cameraPermissionGranted = true for (grantResult in grantResults) { cameraPermissionGranted = cameraPermissionGranted and (grantResult == PackageManager.PERMISSION_GRANTED) } if (cameraPermissionGranted) { addVideo() } else { Toast.makeText( this, R.string.permissions_needed, Toast.LENGTH_LONG ).show() } } } override fun onDestroy() { localVideoTrack?.removeSink(localVideoView) localVideoTrack?.removeSink(snapshotVideoRenderer) localVideoTrack?.release() super.onDestroy() } private fun addVideo() { localVideoTrack?.addSink(localVideoView) localVideoTrack?.addSink(snapshotVideoRenderer) localVideoView.setOnClickListener { tapForSnapshotTextView.visibility = View.GONE snapshotVideoRenderer.takeSnapshot() } } private fun checkPermissionForCamera(): Boolean { val resultCamera = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) return resultCamera == PackageManager.PERMISSION_GRANTED } private fun requestPermissionForCamera() { ActivityCompat.requestPermissions( this, arrayOf(Manifest.permission.CAMERA), CAMERA_PERMISSION_REQUEST_CODE ) } companion object { private const val CAMERA_PERMISSION_REQUEST_CODE = 100 } }
mit
9050b9da57ae87b3b393cd48c5708cfa
32.697479
98
0.661347
5.194301
false
false
false
false
Undin/intellij-rust
src/test/kotlin/org/rust/lang/core/completion/RsExternCrateCompletionTest.kt
2
2085
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.completion import org.rust.ProjectDescriptor import org.rust.WithStdlibAndDependencyRustProjectDescriptor @ProjectDescriptor(WithStdlibAndDependencyRustProjectDescriptor::class) class RsExternCrateCompletionTest : RsCompletionTestBase() { fun `test extern crate`() = doSingleCompletionByFileTree(""" //- dep-lib/lib.rs //- lib.rs extern crate dep_l/*caret*/ """, """ extern crate dep_lib_target/*caret*/ """) fun `test extern crate does not suggest core`() = checkNoCompletion(""" extern crate cor/*caret*/ """) fun `test extern crate does not suggest our crate`() = checkNoCompletionByFileTree(""" //- lib.rs extern crate tes/*caret*/ """) fun `test complete lib target of our package`() = doSingleCompletionByFileTree(""" //- lib.rs //- main.rs extern crate tes/*caret*/ """, """ extern crate test_package/*caret*/ """) fun `test extern crate does not suggest transitive dependency`() = checkNoCompletion(""" extern crate trans_l/*caret*/ """) fun `test absolute path suggest dependency`() = checkContainsCompletionByFileTree("test_package", """ //- lib.rs //- main.rs fn main() { ::test_packa/*caret*/ } """) fun `test absolute path suggest std`() = checkContainsCompletionByFileTree("std", """ //- lib.rs //- main.rs fn main() { ::st/*caret*/ } """) fun `test absolute path suggest aliased extern crate`() = checkContainsCompletionByFileTree( listOf("test_package", "test_package2"), """ //- lib.rs //- main.rs extern crate test_package as test_package2; fn main() { ::test_packa/*caret*/ } """) fun `test absolute path don't suggest self`() = checkNoCompletionByFileTree(""" //- lib.rs fn main() { ::self/*caret*/ } """) }
mit
29bf93fb261284ec4fd2539d05cfcb30
27.175676
105
0.59952
4.706546
false
true
false
false
HabitRPG/habitrpg-android
Habitica/src/main/java/com/habitrpg/android/habitica/utils/ContentDeserializer.kt
2
5785
package com.habitrpg.android.habitica.utils import com.google.firebase.perf.FirebasePerformance import com.google.gson.JsonDeserializationContext import com.google.gson.JsonDeserializer import com.google.gson.JsonElement import com.google.gson.JsonParseException import com.google.gson.reflect.TypeToken import com.habitrpg.android.habitica.extensions.getAsString import com.habitrpg.android.habitica.models.ContentGear import com.habitrpg.android.habitica.models.ContentResult import com.habitrpg.android.habitica.models.FAQArticle import com.habitrpg.android.habitica.models.Skill import com.habitrpg.android.habitica.models.inventory.Customization import com.habitrpg.android.habitica.models.inventory.Egg import com.habitrpg.android.habitica.models.inventory.Equipment import com.habitrpg.android.habitica.models.inventory.Food import com.habitrpg.android.habitica.models.inventory.HatchingPotion import com.habitrpg.android.habitica.models.inventory.Mount import com.habitrpg.android.habitica.models.inventory.Pet import com.habitrpg.android.habitica.models.inventory.QuestContent import com.habitrpg.android.habitica.models.inventory.SpecialItem import io.realm.RealmList import java.lang.reflect.Type class ContentDeserializer : JsonDeserializer<ContentResult> { @Throws(JsonParseException::class) override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): ContentResult { val deserializeTrace = FirebasePerformance.getInstance().newTrace("ContentDeserialize") deserializeTrace.start() val result = ContentResult() val obj = json.asJsonObject result.potion = context.deserialize(obj.get("potion"), Equipment::class.java) result.armoire = context.deserialize(obj.get("armoire"), Equipment::class.java) result.gear = context.deserialize(obj.get("gear"), ContentGear::class.java) for (entry in obj.get("quests").asJsonObject.entrySet()) { result.quests.add(context.deserialize(entry.value, QuestContent::class.java)) result.quests.forEach { it.key = it.key } } for (entry in obj.get("eggs").asJsonObject.entrySet()) { result.eggs.add(context.deserialize(entry.value, Egg::class.java)) } for (entry in obj.get("food").asJsonObject.entrySet()) { result.food.add(context.deserialize(entry.value, Food::class.java)) } for (entry in obj.get("hatchingPotions").asJsonObject.entrySet()) { result.hatchingPotions.add(context.deserialize(entry.value, HatchingPotion::class.java)) } val pets = obj.getAsJsonObject("petInfo") for (key in pets.keySet()) { val pet = Pet() val petObj = pets.getAsJsonObject(key) pet.animal = petObj.getAsString("egg") pet.color = petObj.getAsString("potion") pet.key = petObj.getAsString("key") pet.text = petObj.getAsString("text") pet.type = petObj.getAsString("type") if (pet.type == "premium") { pet.premium = true } result.pets.add(pet) } val mounts = obj.getAsJsonObject("mountInfo") for (key in mounts.keySet()) { val mount = Mount() val mountObj = mounts.getAsJsonObject(key) mount.animal = mountObj.getAsString("egg") mount.color = mountObj.getAsString("potion") mount.key = mountObj.getAsString("key") mount.text = mountObj.getAsString("text") mount.type = mountObj.getAsString("type") if (mount.type == "premium") { mount.premium = true } result.mounts.add(mount) } for ((classname, value) in obj.getAsJsonObject("spells").entrySet()) { val classObject = value.asJsonObject for ((_, value1) in classObject.entrySet()) { val skillObject = value1.asJsonObject val skill = Skill() skill.key = skillObject.get("key").asString skill.text = skillObject.get("text").asString skill.notes = skillObject.get("notes").asString skill.key = skillObject.get("key").asString skill.target = skillObject.get("target").asString skill.habitClass = classname skill.mana = skillObject.get("mana").asInt val lvlElement = skillObject.get("lvl") if (lvlElement != null) { skill.lvl = lvlElement.asInt } result.spells.add(skill) } } if (obj.has("special")) { for (entry in obj.get("special").asJsonObject.entrySet()) { result.special.add(context.deserialize(entry.value, SpecialItem::class.java)) } } result.appearances = context.deserialize(obj.get("appearances"), object : TypeToken<RealmList<Customization>>() {}.type) result.backgrounds = context.deserialize(obj.get("backgrounds"), object : TypeToken<RealmList<Customization>>() {}.type) val noBackground = Customization() noBackground.customizationSet = "incentiveBackgrounds" noBackground.customizationSetName = "Login Incentive" noBackground.identifier = "" noBackground.price = 0 noBackground.type = "background" result.backgrounds.add(noBackground) result.faq = context.deserialize(obj.get("faq"), object : TypeToken<RealmList<FAQArticle>>() {}.type) deserializeTrace.stop() return result } }
gpl-3.0
13920adcc0e4f52d598be494a7871c93
43.912698
128
0.641141
4.555118
false
false
false
false
ryan652/EasyCrypt
easycrypt/src/main/java/com/pvryan/easycrypt/randomorg/RandomOrgRequest.kt
1
1124
/* * Copyright 2018 Priyank Vasa * 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.pvryan.easycrypt.randomorg /** * Request structure for api.random.org */ internal data class RandomOrgRequest( val jsonrpc: String = "2.0", val method: String = "generateIntegers", val params: Params = RandomOrgRequest.Params(), val id: Int = 679 ) { data class Params( val apiKey: String = "", val n: Int = 32, val min: Int = 0, val max: Int = 255, val replacement: Boolean = false, val base: Int = 16 ) }
apache-2.0
c4540064d0915c16b1207b7716d761d6
31.114286
75
0.653025
4.117216
false
false
false
false
androidx/androidx
compose/material3/material3/samples/src/main/java/androidx/compose/material3/samples/SwitchSample.kt
3
2313
/* * 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. */ package androidx.compose.material3.samples import androidx.annotation.Sampled import androidx.compose.foundation.layout.size import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Check import androidx.compose.material3.Icon import androidx.compose.material3.Switch import androidx.compose.material3.SwitchDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics import androidx.compose.ui.tooling.preview.Preview @Preview @Sampled @Composable fun SwitchSample() { var checked by remember { mutableStateOf(true) } Switch( modifier = Modifier.semantics { contentDescription = "Demo" }, checked = checked, onCheckedChange = { checked = it }) } @Preview @Sampled @Composable fun SwitchWithThumbIconSample() { var checked by remember { mutableStateOf(true) } // Icon isn't focusable, no need for content description val icon: (@Composable () -> Unit)? = if (checked) { { Icon( imageVector = Icons.Filled.Check, contentDescription = null, modifier = Modifier.size(SwitchDefaults.IconSize), ) } } else { null } Switch( modifier = Modifier.semantics { contentDescription = "Demo with icon" }, checked = checked, onCheckedChange = { checked = it }, thumbContent = icon ) }
apache-2.0
7b8fda2a94b58db5314376609ab9ed37
31.591549
80
0.721141
4.482558
false
false
false
false
androidx/androidx
compose/material/material/src/androidAndroidTest/kotlin/androidx/compose/material/MaterialRippleThemeTest.kt
3
41353
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.material import android.os.Build import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.interaction.DragInteraction import androidx.compose.foundation.Indication import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.interaction.Interaction import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.interaction.PressInteraction import androidx.compose.foundation.indication import androidx.compose.foundation.interaction.FocusInteraction import androidx.compose.foundation.interaction.HoverInteraction import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.ripple.LocalRippleTheme import androidx.compose.material.ripple.RippleAlpha import androidx.compose.material.ripple.RippleTheme import androidx.compose.material.ripple.rememberRipple import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.testutils.assertAgainstGolden import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.asAndroidBitmap import androidx.compose.ui.graphics.compositeOver import androidx.compose.ui.platform.testTag import androidx.compose.ui.semantics.semantics import androidx.compose.ui.test.captureToImage import androidx.compose.ui.test.junit4.ComposeContentTestRule import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.unit.dp import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import androidx.test.filters.SdkSuppress import androidx.test.screenshot.AndroidXScreenshotTestRule import com.google.common.truth.Truth import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith /** * Test for the [RippleTheme] provided by [MaterialTheme], to verify colors and opacity in * different configurations. */ @LargeTest @RunWith(AndroidJUnit4::class) @SdkSuppress(minSdkVersion = Build.VERSION_CODES.O) class MaterialRippleThemeTest { @get:Rule val rule = createComposeRule() @get:Rule val screenshotRule = AndroidXScreenshotTestRule(GOLDEN_MATERIAL) @Test fun bounded_lightTheme_highLuminance_pressed() { val interactionSource = MutableInteractionSource() val contentColor = Color.White val scope = rule.setRippleContent( interactionSource = interactionSource, bounded = true, lightTheme = true, contentColor = contentColor ) assertRippleMatches( scope, interactionSource, PressInteraction.Press(Offset(10f, 10f)), "ripple_bounded_light_highluminance_pressed", calculateResultingRippleColor(contentColor, rippleOpacity = 0.24f) ) } @Test fun bounded_lightTheme_highLuminance_hovered() { val interactionSource = MutableInteractionSource() val contentColor = Color.White val scope = rule.setRippleContent( interactionSource = interactionSource, bounded = true, lightTheme = true, contentColor = contentColor ) assertRippleMatches( scope, interactionSource, HoverInteraction.Enter(), "ripple_bounded_light_highluminance_hovered", calculateResultingRippleColor(contentColor, rippleOpacity = 0.08f) ) } @Test fun bounded_lightTheme_highLuminance_focused() { val interactionSource = MutableInteractionSource() val contentColor = Color.White val scope = rule.setRippleContent( interactionSource = interactionSource, bounded = true, lightTheme = true, contentColor = contentColor ) assertRippleMatches( scope, interactionSource, FocusInteraction.Focus(), "ripple_bounded_light_highluminance_focused", calculateResultingRippleColor(contentColor, rippleOpacity = 0.24f) ) } @Test fun bounded_lightTheme_highLuminance_dragged() { val interactionSource = MutableInteractionSource() val contentColor = Color.White val scope = rule.setRippleContent( interactionSource = interactionSource, bounded = true, lightTheme = true, contentColor = contentColor ) assertRippleMatches( scope, interactionSource, DragInteraction.Start(), "ripple_bounded_light_highluminance_dragged", calculateResultingRippleColor(contentColor, rippleOpacity = 0.16f) ) } @Test fun bounded_lightTheme_lowLuminance_pressed() { val interactionSource = MutableInteractionSource() val contentColor = Color.Black val scope = rule.setRippleContent( interactionSource = interactionSource, bounded = true, lightTheme = true, contentColor = contentColor ) assertRippleMatches( scope, interactionSource, PressInteraction.Press(Offset(10f, 10f)), "ripple_bounded_light_lowluminance_pressed", calculateResultingRippleColor(contentColor, rippleOpacity = 0.12f) ) } @Test fun bounded_lightTheme_lowLuminance_hovered() { val interactionSource = MutableInteractionSource() val contentColor = Color.Black val scope = rule.setRippleContent( interactionSource = interactionSource, bounded = true, lightTheme = true, contentColor = contentColor ) assertRippleMatches( scope, interactionSource, HoverInteraction.Enter(), "ripple_bounded_light_lowluminance_hovered", calculateResultingRippleColor(contentColor, rippleOpacity = 0.04f) ) } @Test fun bounded_lightTheme_lowLuminance_focused() { val interactionSource = MutableInteractionSource() val contentColor = Color.Black val scope = rule.setRippleContent( interactionSource = interactionSource, bounded = true, lightTheme = true, contentColor = contentColor ) assertRippleMatches( scope, interactionSource, FocusInteraction.Focus(), "ripple_bounded_light_lowluminance_focused", calculateResultingRippleColor(contentColor, rippleOpacity = 0.12f) ) } @Test fun bounded_lightTheme_lowLuminance_dragged() { val interactionSource = MutableInteractionSource() val contentColor = Color.Black val scope = rule.setRippleContent( interactionSource = interactionSource, bounded = true, lightTheme = true, contentColor = contentColor ) assertRippleMatches( scope, interactionSource, DragInteraction.Start(), "ripple_bounded_light_lowluminance_dragged", calculateResultingRippleColor(contentColor, rippleOpacity = 0.08f) ) } @Test fun bounded_darkTheme_highLuminance_pressed() { val interactionSource = MutableInteractionSource() val contentColor = Color.White val scope = rule.setRippleContent( interactionSource = interactionSource, bounded = true, lightTheme = false, contentColor = contentColor ) assertRippleMatches( scope, interactionSource, PressInteraction.Press(Offset(10f, 10f)), "ripple_bounded_dark_highluminance_pressed", calculateResultingRippleColor(contentColor, rippleOpacity = 0.10f) ) } @Test fun bounded_darkTheme_highLuminance_hovered() { val interactionSource = MutableInteractionSource() val contentColor = Color.White val scope = rule.setRippleContent( interactionSource = interactionSource, bounded = true, lightTheme = false, contentColor = contentColor ) assertRippleMatches( scope, interactionSource, HoverInteraction.Enter(), "ripple_bounded_dark_highluminance_hovered", calculateResultingRippleColor(contentColor, rippleOpacity = 0.04f) ) } @Test fun bounded_darkTheme_highLuminance_focused() { val interactionSource = MutableInteractionSource() val contentColor = Color.White val scope = rule.setRippleContent( interactionSource = interactionSource, bounded = true, lightTheme = false, contentColor = contentColor ) assertRippleMatches( scope, interactionSource, FocusInteraction.Focus(), "ripple_bounded_dark_highluminance_focused", calculateResultingRippleColor(contentColor, rippleOpacity = 0.12f) ) } @Test fun bounded_darkTheme_highLuminance_dragged() { val interactionSource = MutableInteractionSource() val contentColor = Color.White val scope = rule.setRippleContent( interactionSource = interactionSource, bounded = true, lightTheme = false, contentColor = contentColor ) assertRippleMatches( scope, interactionSource, DragInteraction.Start(), "ripple_bounded_dark_highluminance_dragged", calculateResultingRippleColor(contentColor, rippleOpacity = 0.08f) ) } @Test fun bounded_darkTheme_lowLuminance_pressed() { val interactionSource = MutableInteractionSource() val contentColor = Color.Black val scope = rule.setRippleContent( interactionSource = interactionSource, bounded = true, lightTheme = false, contentColor = contentColor ) assertRippleMatches( scope, interactionSource, PressInteraction.Press(Offset(10f, 10f)), "ripple_bounded_dark_lowluminance_pressed", // Low luminance content in dark theme should use a white ripple by default calculateResultingRippleColor(Color.White, rippleOpacity = 0.10f) ) } @Test fun bounded_darkTheme_lowLuminance_hovered() { val interactionSource = MutableInteractionSource() val contentColor = Color.Black val scope = rule.setRippleContent( interactionSource = interactionSource, bounded = true, lightTheme = false, contentColor = contentColor ) assertRippleMatches( scope, interactionSource, HoverInteraction.Enter(), "ripple_bounded_dark_lowluminance_hovered", // Low luminance content in dark theme should use a white ripple by default calculateResultingRippleColor(Color.White, rippleOpacity = 0.04f) ) } @Test fun bounded_darkTheme_lowLuminance_focused() { val interactionSource = MutableInteractionSource() val contentColor = Color.Black val scope = rule.setRippleContent( interactionSource = interactionSource, bounded = true, lightTheme = false, contentColor = contentColor ) assertRippleMatches( scope, interactionSource, FocusInteraction.Focus(), "ripple_bounded_dark_lowluminance_focused", // Low luminance content in dark theme should use a white ripple by default calculateResultingRippleColor(Color.White, rippleOpacity = 0.12f) ) } @Test fun bounded_darkTheme_lowLuminance_dragged() { val interactionSource = MutableInteractionSource() val contentColor = Color.Black val scope = rule.setRippleContent( interactionSource = interactionSource, bounded = true, lightTheme = false, contentColor = contentColor ) assertRippleMatches( scope, interactionSource, DragInteraction.Start(), "ripple_bounded_dark_lowluminance_dragged", // Low luminance content in dark theme should use a white ripple by default calculateResultingRippleColor(Color.White, rippleOpacity = 0.08f) ) } @Test fun unbounded_lightTheme_highLuminance_pressed() { val interactionSource = MutableInteractionSource() val contentColor = Color.White val scope = rule.setRippleContent( interactionSource = interactionSource, bounded = false, lightTheme = true, contentColor = contentColor ) assertRippleMatches( scope, interactionSource, PressInteraction.Press(Offset(10f, 10f)), "ripple_unbounded_light_highluminance_pressed", calculateResultingRippleColor(contentColor, rippleOpacity = 0.24f) ) } @Test fun unbounded_lightTheme_highLuminance_hovered() { val interactionSource = MutableInteractionSource() val contentColor = Color.White val scope = rule.setRippleContent( interactionSource = interactionSource, bounded = false, lightTheme = true, contentColor = contentColor ) assertRippleMatches( scope, interactionSource, HoverInteraction.Enter(), "ripple_unbounded_light_highluminance_hovered", calculateResultingRippleColor(contentColor, rippleOpacity = 0.08f) ) } @Test fun unbounded_lightTheme_highLuminance_focused() { val interactionSource = MutableInteractionSource() val contentColor = Color.White val scope = rule.setRippleContent( interactionSource = interactionSource, bounded = false, lightTheme = true, contentColor = contentColor ) assertRippleMatches( scope, interactionSource, FocusInteraction.Focus(), "ripple_unbounded_light_highluminance_focused", calculateResultingRippleColor(contentColor, rippleOpacity = 0.24f) ) } @Test fun unbounded_lightTheme_highLuminance_dragged() { val interactionSource = MutableInteractionSource() val contentColor = Color.White val scope = rule.setRippleContent( interactionSource = interactionSource, bounded = false, lightTheme = true, contentColor = contentColor ) assertRippleMatches( scope, interactionSource, DragInteraction.Start(), "ripple_unbounded_light_highluminance_dragged", calculateResultingRippleColor(contentColor, rippleOpacity = 0.16f) ) } @Test fun unbounded_lightTheme_lowLuminance_pressed() { val interactionSource = MutableInteractionSource() val contentColor = Color.Black val scope = rule.setRippleContent( interactionSource = interactionSource, bounded = false, lightTheme = true, contentColor = contentColor ) assertRippleMatches( scope, interactionSource, PressInteraction.Press(Offset(10f, 10f)), "ripple_unbounded_light_lowluminance_pressed", calculateResultingRippleColor(contentColor, rippleOpacity = 0.12f) ) } @Test fun unbounded_lightTheme_lowLuminance_hovered() { val interactionSource = MutableInteractionSource() val contentColor = Color.Black val scope = rule.setRippleContent( interactionSource = interactionSource, bounded = false, lightTheme = true, contentColor = contentColor ) assertRippleMatches( scope, interactionSource, HoverInteraction.Enter(), "ripple_unbounded_light_lowluminance_hovered", calculateResultingRippleColor(contentColor, rippleOpacity = 0.04f) ) } @Test fun unbounded_lightTheme_lowLuminance_focused() { val interactionSource = MutableInteractionSource() val contentColor = Color.Black val scope = rule.setRippleContent( interactionSource = interactionSource, bounded = false, lightTheme = true, contentColor = contentColor ) assertRippleMatches( scope, interactionSource, FocusInteraction.Focus(), "ripple_unbounded_light_lowluminance_focused", calculateResultingRippleColor(contentColor, rippleOpacity = 0.12f) ) } @Test fun unbounded_lightTheme_lowLuminance_dragged() { val interactionSource = MutableInteractionSource() val contentColor = Color.Black val scope = rule.setRippleContent( interactionSource = interactionSource, bounded = false, lightTheme = true, contentColor = contentColor ) assertRippleMatches( scope, interactionSource, DragInteraction.Start(), "ripple_unbounded_light_lowluminance_dragged", calculateResultingRippleColor(contentColor, rippleOpacity = 0.08f) ) } @Test fun unbounded_darkTheme_highLuminance_pressed() { val interactionSource = MutableInteractionSource() val contentColor = Color.White val scope = rule.setRippleContent( interactionSource = interactionSource, bounded = false, lightTheme = false, contentColor = contentColor ) assertRippleMatches( scope, interactionSource, PressInteraction.Press(Offset(10f, 10f)), "ripple_unbounded_dark_highluminance_pressed", calculateResultingRippleColor(contentColor, rippleOpacity = 0.10f) ) } @Test fun unbounded_darkTheme_highLuminance_hovered() { val interactionSource = MutableInteractionSource() val contentColor = Color.White val scope = rule.setRippleContent( interactionSource = interactionSource, bounded = false, lightTheme = false, contentColor = contentColor ) assertRippleMatches( scope, interactionSource, HoverInteraction.Enter(), "ripple_unbounded_dark_highluminance_hovered", calculateResultingRippleColor(contentColor, rippleOpacity = 0.04f) ) } @Test fun unbounded_darkTheme_highLuminance_focused() { val interactionSource = MutableInteractionSource() val contentColor = Color.White val scope = rule.setRippleContent( interactionSource = interactionSource, bounded = false, lightTheme = false, contentColor = contentColor ) assertRippleMatches( scope, interactionSource, FocusInteraction.Focus(), "ripple_unbounded_dark_highluminance_focused", calculateResultingRippleColor(contentColor, rippleOpacity = 0.12f) ) } @Test fun unbounded_darkTheme_highLuminance_dragged() { val interactionSource = MutableInteractionSource() val contentColor = Color.White val scope = rule.setRippleContent( interactionSource = interactionSource, bounded = false, lightTheme = false, contentColor = contentColor ) assertRippleMatches( scope, interactionSource, DragInteraction.Start(), "ripple_unbounded_dark_highluminance_dragged", calculateResultingRippleColor(contentColor, rippleOpacity = 0.08f) ) } @Test fun unbounded_darkTheme_lowLuminance_pressed() { val interactionSource = MutableInteractionSource() val contentColor = Color.Black val scope = rule.setRippleContent( interactionSource = interactionSource, bounded = false, lightTheme = false, contentColor = contentColor ) assertRippleMatches( scope, interactionSource, PressInteraction.Press(Offset(10f, 10f)), "ripple_unbounded_dark_lowluminance_pressed", // Low luminance content in dark theme should use a white ripple by default calculateResultingRippleColor(Color.White, rippleOpacity = 0.10f) ) } @Test fun unbounded_darkTheme_lowLuminance_hovered() { val interactionSource = MutableInteractionSource() val contentColor = Color.Black val scope = rule.setRippleContent( interactionSource = interactionSource, bounded = false, lightTheme = false, contentColor = contentColor ) assertRippleMatches( scope, interactionSource, HoverInteraction.Enter(), "ripple_unbounded_dark_lowluminance_hovered", // Low luminance content in dark theme should use a white ripple by default calculateResultingRippleColor(Color.White, rippleOpacity = 0.04f) ) } @Test fun unbounded_darkTheme_lowLuminance_focused() { val interactionSource = MutableInteractionSource() val contentColor = Color.Black val scope = rule.setRippleContent( interactionSource = interactionSource, bounded = false, lightTheme = false, contentColor = contentColor ) assertRippleMatches( scope, interactionSource, FocusInteraction.Focus(), "ripple_unbounded_dark_lowluminance_focused", // Low luminance content in dark theme should use a white ripple by default calculateResultingRippleColor(Color.White, rippleOpacity = 0.12f) ) } @Test fun unbounded_darkTheme_lowLuminance_dragged() { val interactionSource = MutableInteractionSource() val contentColor = Color.Black val scope = rule.setRippleContent( interactionSource = interactionSource, bounded = false, lightTheme = false, contentColor = contentColor ) assertRippleMatches( scope, interactionSource, DragInteraction.Start(), "ripple_unbounded_dark_lowluminance_dragged", // Low luminance content in dark theme should use a white ripple by default calculateResultingRippleColor(Color.White, rippleOpacity = 0.08f) ) } @Test fun customRippleTheme_pressed() { val interactionSource = MutableInteractionSource() val contentColor = Color.Black val rippleColor = Color.Red val expectedAlpha = 0.5f val rippleAlpha = RippleAlpha(expectedAlpha, expectedAlpha, expectedAlpha, expectedAlpha) val rippleTheme = object : RippleTheme { @Composable override fun defaultColor() = rippleColor @Composable override fun rippleAlpha() = rippleAlpha } var scope: CoroutineScope? = null rule.setContent { scope = rememberCoroutineScope() MaterialTheme { CompositionLocalProvider(LocalRippleTheme provides rippleTheme) { Surface(contentColor = contentColor) { Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { RippleBoxWithBackground( interactionSource, rememberRipple(), bounded = true ) } } } } } val expectedColor = calculateResultingRippleColor( rippleColor, rippleOpacity = expectedAlpha ) assertRippleMatches( scope!!, interactionSource, PressInteraction.Press(Offset(10f, 10f)), "ripple_customtheme_pressed", expectedColor ) } @Test fun customRippleTheme_hovered() { val interactionSource = MutableInteractionSource() val contentColor = Color.Black val rippleColor = Color.Red val expectedAlpha = 0.5f val rippleAlpha = RippleAlpha(expectedAlpha, expectedAlpha, expectedAlpha, expectedAlpha) val rippleTheme = object : RippleTheme { @Composable override fun defaultColor() = rippleColor @Composable override fun rippleAlpha() = rippleAlpha } var scope: CoroutineScope? = null rule.setContent { scope = rememberCoroutineScope() MaterialTheme { CompositionLocalProvider(LocalRippleTheme provides rippleTheme) { Surface(contentColor = contentColor) { Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { RippleBoxWithBackground( interactionSource, rememberRipple(), bounded = true ) } } } } } val expectedColor = calculateResultingRippleColor( rippleColor, rippleOpacity = expectedAlpha ) assertRippleMatches( scope!!, interactionSource, HoverInteraction.Enter(), "ripple_customtheme_hovered", expectedColor ) } @Test fun customRippleTheme_focused() { val interactionSource = MutableInteractionSource() val contentColor = Color.Black val rippleColor = Color.Red val expectedAlpha = 0.5f val rippleAlpha = RippleAlpha(expectedAlpha, expectedAlpha, expectedAlpha, expectedAlpha) val rippleTheme = object : RippleTheme { @Composable override fun defaultColor() = rippleColor @Composable override fun rippleAlpha() = rippleAlpha } var scope: CoroutineScope? = null rule.setContent { scope = rememberCoroutineScope() MaterialTheme { CompositionLocalProvider(LocalRippleTheme provides rippleTheme) { Surface(contentColor = contentColor) { Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { RippleBoxWithBackground( interactionSource, rememberRipple(), bounded = true ) } } } } } val expectedColor = calculateResultingRippleColor( rippleColor, rippleOpacity = expectedAlpha ) assertRippleMatches( scope!!, interactionSource, FocusInteraction.Focus(), "ripple_customtheme_focused", expectedColor ) } @Test fun customRippleTheme_dragged() { val interactionSource = MutableInteractionSource() val contentColor = Color.Black val rippleColor = Color.Red val expectedAlpha = 0.5f val rippleAlpha = RippleAlpha(expectedAlpha, expectedAlpha, expectedAlpha, expectedAlpha) val rippleTheme = object : RippleTheme { @Composable override fun defaultColor() = rippleColor @Composable override fun rippleAlpha() = rippleAlpha } var scope: CoroutineScope? = null rule.setContent { scope = rememberCoroutineScope() MaterialTheme { CompositionLocalProvider(LocalRippleTheme provides rippleTheme) { Surface(contentColor = contentColor) { Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { RippleBoxWithBackground( interactionSource, rememberRipple(), bounded = true ) } } } } } val expectedColor = calculateResultingRippleColor( rippleColor, rippleOpacity = expectedAlpha ) assertRippleMatches( scope!!, interactionSource, DragInteraction.Start(), "ripple_customtheme_dragged", expectedColor ) } /** * Note: no corresponding test for pressed ripples since RippleForeground does not update the * color of currently active ripples unless they are being drawn on the UI thread * (which should only happen if the target radius also changes). */ @Test fun themeChangeDuringRipple_dragged() { val interactionSource = MutableInteractionSource() fun createRippleTheme(color: Color, alpha: Float) = object : RippleTheme { val rippleAlpha = RippleAlpha(alpha, alpha, alpha, alpha) @Composable override fun defaultColor() = color @Composable override fun rippleAlpha() = rippleAlpha } val initialColor = Color.Red val initialAlpha = 0.5f var rippleTheme by mutableStateOf(createRippleTheme(initialColor, initialAlpha)) var scope: CoroutineScope? = null rule.setContent { scope = rememberCoroutineScope() MaterialTheme { CompositionLocalProvider(LocalRippleTheme provides rippleTheme) { Surface(contentColor = Color.Black) { Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { RippleBoxWithBackground( interactionSource, rememberRipple(), bounded = true ) } } } } } rule.runOnIdle { scope!!.launch { interactionSource.emit(DragInteraction.Start()) } } rule.waitForIdle() with(rule.onNodeWithTag(Tag)) { val centerPixel = captureToImage().asAndroidBitmap() .run { getPixel(width / 2, height / 2) } val expectedColor = calculateResultingRippleColor(initialColor, rippleOpacity = initialAlpha) Truth.assertThat(Color(centerPixel)).isEqualTo(expectedColor) } val newColor = Color.Green // TODO: changing alpha for existing state layers is not currently supported val newAlpha = 0.5f rule.runOnUiThread { rippleTheme = createRippleTheme(newColor, newAlpha) } with(rule.onNodeWithTag(Tag)) { val centerPixel = captureToImage().asAndroidBitmap() .run { getPixel(width / 2, height / 2) } val expectedColor = calculateResultingRippleColor(newColor, rippleOpacity = newAlpha) Truth.assertThat(Color(centerPixel)).isEqualTo(expectedColor) } } @Test fun contentColorProvidedAfterRememberRipple() { val interactionSource = MutableInteractionSource() val alpha = 0.5f val rippleAlpha = RippleAlpha(alpha, alpha, alpha, alpha) val expectedRippleColor = Color.Red val theme = object : RippleTheme { @Composable override fun defaultColor() = LocalContentColor.current @Composable override fun rippleAlpha() = rippleAlpha } var scope: CoroutineScope? = null rule.setContent { scope = rememberCoroutineScope() MaterialTheme { CompositionLocalProvider(LocalRippleTheme provides theme) { Surface(contentColor = Color.Black) { // Create ripple where contentColor is black val ripple = rememberRipple() Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { Surface(contentColor = expectedRippleColor) { // Ripple is used where contentColor is red, so the instance // should get the red color when it is created RippleBoxWithBackground(interactionSource, ripple, bounded = true) } } } } } } rule.runOnIdle { scope!!.launch { interactionSource.emit(PressInteraction.Press(Offset(10f, 10f))) } } rule.waitForIdle() // Ripples are drawn on the RenderThread, not the main (UI) thread, so we can't wait for // synchronization. Instead just wait until after the ripples are finished animating. Thread.sleep(300) with(rule.onNodeWithTag(Tag)) { val centerPixel = captureToImage().asAndroidBitmap() .run { getPixel(width / 2, height / 2) } val expectedColor = calculateResultingRippleColor(expectedRippleColor, rippleOpacity = alpha) Truth.assertThat(Color(centerPixel)).isEqualTo(expectedColor) } } /** * Asserts that the ripple matches the screenshot with identifier [goldenIdentifier], and * that the resultant color of the ripple on screen matches [expectedCenterPixelColor]. * * @param interactionSource the [MutableInteractionSource] driving the ripple * @param interaction the [Interaction] to assert for * @param goldenIdentifier the identifier for the corresponding screenshot * @param expectedCenterPixelColor the expected color for the pixel at the center of the * [RippleBoxWithBackground] */ private fun assertRippleMatches( scope: CoroutineScope, interactionSource: MutableInteractionSource, interaction: Interaction, goldenIdentifier: String, expectedCenterPixelColor: Color ) { // Pause the clock if we are drawing a state layer if (interaction !is PressInteraction) { rule.mainClock.autoAdvance = false } // Start ripple rule.runOnIdle { scope.launch { interactionSource.emit(interaction) } } // Advance to the end of the ripple / state layer animation rule.waitForIdle() if (interaction is PressInteraction) { // Ripples are drawn on the RenderThread, not the main (UI) thread, so we can't wait for // synchronization. Instead just wait until after the ripples are finished animating. Thread.sleep(300) } else { rule.mainClock.advanceTimeBy(milliseconds = 300) } // Capture and compare screenshots val screenshot = rule.onNodeWithTag(Tag) .captureToImage() screenshot.assertAgainstGolden(screenshotRule, goldenIdentifier) // Compare expected and actual pixel color val centerPixel = screenshot .asAndroidBitmap() .run { getPixel(width / 2, height / 2) } Truth.assertThat(Color(centerPixel)).isEqualTo(expectedCenterPixelColor) } } /** * Generic Button like component with a border that allows injecting an [Indication], and has a * background with the same color around it - this makes the ripple contrast better and make it * more visible in screenshots. * * @param interactionSource the [MutableInteractionSource] that is used to drive the ripple state * @param ripple ripple [Indication] placed inside the surface * @param bounded whether [ripple] is bounded or not - this controls the clipping behavior */ @Composable private fun RippleBoxWithBackground( interactionSource: MutableInteractionSource, ripple: Indication, bounded: Boolean ) { Box(Modifier.semantics(mergeDescendants = true) {}.testTag(Tag)) { Surface( Modifier.padding(25.dp), color = RippleBoxBackgroundColor ) { val shape = RoundedCornerShape(20) // If the ripple is bounded, we want to clip to the shape, otherwise don't clip as // the ripple should draw outside the bounds. val clip = if (bounded) Modifier.clip(shape) else Modifier Box( Modifier.padding(25.dp).width(40.dp).height(40.dp) .border(BorderStroke(2.dp, Color.Black), shape) .background(color = RippleBoxBackgroundColor, shape = shape) .then(clip) .indication( interactionSource = interactionSource, indication = ripple ) ) {} } } } /** * Sets the content to a [RippleBoxWithBackground] with a [MaterialTheme] and surrounding [Surface] * * @param interactionSource [MutableInteractionSource] used to drive the ripple inside the * [RippleBoxWithBackground] * @param bounded whether the ripple inside the [RippleBoxWithBackground] is bounded * @param lightTheme whether the theme is light or dark * @param contentColor the contentColor that will be used for the ripple color */ private fun ComposeContentTestRule.setRippleContent( interactionSource: MutableInteractionSource, bounded: Boolean, lightTheme: Boolean, contentColor: Color ): CoroutineScope { var scope: CoroutineScope? = null setContent { scope = rememberCoroutineScope() val colors = if (lightTheme) lightColors() else darkColors() MaterialTheme(colors) { Surface(contentColor = contentColor) { Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { RippleBoxWithBackground(interactionSource, rememberRipple(bounded), bounded) } } } } waitForIdle() return scope!! } /** * Blends ([contentColor] with [rippleOpacity]) on top of [RippleBoxBackgroundColor] to provide * the resulting RGB color that can be used for pixel comparison. */ private fun calculateResultingRippleColor( contentColor: Color, rippleOpacity: Float ) = contentColor.copy(alpha = rippleOpacity).compositeOver(RippleBoxBackgroundColor) private val RippleBoxBackgroundColor = Color.Blue private const val Tag = "Ripple"
apache-2.0
5f02dda8f0867f29ce262ead418c9cb7
31.207165
100
0.609508
5.663243
false
false
false
false
androidx/androidx
room/room-compiler-processing/src/test/java/androidx/room/compiler/processing/XAnnotationBoxTest.kt
3
31580
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.compiler.processing import androidx.room.compiler.codegen.XTypeName import androidx.room.compiler.codegen.asClassName import androidx.room.compiler.processing.testcode.JavaAnnotationWithDefaults import androidx.room.compiler.processing.testcode.JavaAnnotationWithEnum import androidx.room.compiler.processing.testcode.JavaAnnotationWithEnumArray import androidx.room.compiler.processing.testcode.JavaAnnotationWithPrimitiveArray import androidx.room.compiler.processing.testcode.JavaAnnotationWithTypeReferences import androidx.room.compiler.processing.testcode.JavaEnum import androidx.room.compiler.processing.testcode.MainAnnotation import androidx.room.compiler.processing.testcode.OtherAnnotation import androidx.room.compiler.processing.testcode.RepeatableJavaAnnotation import androidx.room.compiler.processing.testcode.TestSuppressWarnings import androidx.room.compiler.processing.util.Source import androidx.room.compiler.processing.util.XTestInvocation import androidx.room.compiler.processing.util.compileFiles import androidx.room.compiler.processing.util.getField import androidx.room.compiler.processing.util.getMethodByJvmName import androidx.room.compiler.processing.util.getParameter import androidx.room.compiler.processing.util.runProcessorTest import androidx.room.compiler.processing.util.runProcessorTestWithoutKsp import androidx.room.compiler.processing.util.typeName import com.google.common.truth.Truth.assertThat import com.google.common.truth.Truth.assertWithMessage import com.squareup.javapoet.ClassName import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized @RunWith(Parameterized::class) class XAnnotationBoxTest( private val preCompiled: Boolean ) { private fun runTest( sources: List<Source>, handler: (XTestInvocation) -> Unit ) { if (preCompiled) { val compiled = compileFiles(sources) val hasKotlinSources = sources.any { it is Source.KotlinSource } val kotlinSources = if (hasKotlinSources) { listOf( Source.kotlin("placeholder.kt", "class PlaceholderKotlin") ) } else { emptyList() } val newSources = kotlinSources + Source.java( "PlaceholderJava", "public class " + "PlaceholderJava {}" ) runProcessorTest( sources = newSources, handler = handler, classpath = compiled ) } else { runProcessorTest( sources = sources, handler = handler ) } } @Test fun readSimpleAnnotationValue() { val source = Source.java( "foo.bar.Baz", """ package foo.bar; import androidx.room.compiler.processing.testcode.TestSuppressWarnings; @TestSuppressWarnings({"warning1", "warning 2"}) public class Baz { } """.trimIndent() ) runTest( sources = listOf(source) ) { val element = it.processingEnv.requireTypeElement("foo.bar.Baz") val annotationBox = element.getAnnotation(TestSuppressWarnings::class) assertThat(annotationBox).isNotNull() assertThat( annotationBox!!.value.value ).isEqualTo( arrayOf("warning1", "warning 2") ) } } @Test fun typeReference() { val mySource = Source.java( "foo.bar.Baz", """ package foo.bar; import androidx.room.compiler.processing.testcode.MainAnnotation; import androidx.room.compiler.processing.testcode.OtherAnnotation; @MainAnnotation( typeList = {String.class, Integer.class}, singleType = Long.class, intMethod = 3, doubleMethodWithDefault = 3.0, floatMethodWithDefault = 3f, charMethodWithDefault = '3', byteMethodWithDefault = 3, shortMethodWithDefault = 3, longMethodWithDefault = 3L, boolMethodWithDefault = false, otherAnnotationArray = { @OtherAnnotation( value = "other list 1" ), @OtherAnnotation("other list 2"), }, singleOtherAnnotation = @OtherAnnotation("other single") ) public class Baz { } """.trimIndent() ) // re-enable after fixing b/175144186 runProcessorTestWithoutKsp( listOf(mySource) ) { val element = it.processingEnv.requireTypeElement("foo.bar.Baz") element.getAnnotation(MainAnnotation::class)!!.let { annotation -> assertThat( annotation.getAsTypeList("typeList") ).containsExactly( it.processingEnv.requireType(java.lang.String::class), it.processingEnv.requireType(java.lang.Integer::class) ) assertThat( annotation.getAsType("singleType") ).isEqualTo( it.processingEnv.requireType(java.lang.Long::class) ) assertThat(annotation.value.intMethod).isEqualTo(3) assertThat(annotation.value.doubleMethodWithDefault).isEqualTo(3.0) assertThat(annotation.value.floatMethodWithDefault).isEqualTo(3f) assertThat(annotation.value.charMethodWithDefault).isEqualTo('3') assertThat(annotation.value.byteMethodWithDefault).isEqualTo(3) assertThat(annotation.value.shortMethodWithDefault).isEqualTo(3) assertThat(annotation.value.longMethodWithDefault).isEqualTo(3) assertThat(annotation.value.boolMethodWithDefault).isEqualTo(false) annotation.getAsAnnotationBox<OtherAnnotation>("singleOtherAnnotation") .let { other -> assertThat(other.value.value).isEqualTo("other single") } annotation.getAsAnnotationBoxArray<OtherAnnotation>("otherAnnotationArray") .let { boxArray -> assertThat(boxArray).hasLength(2) assertThat(boxArray[0].value.value).isEqualTo("other list 1") assertThat(boxArray[1].value.value).isEqualTo("other list 2") } } } } @Test fun readSimpleAnnotationValue_kotlin() { val source = Source.kotlin( "Foo.kt", """ import androidx.room.compiler.processing.testcode.TestSuppressWarnings @TestSuppressWarnings("warning1", "warning 2") class Subject { } """.trimIndent() ) runTest( sources = listOf(source) ) { val element = it.processingEnv.requireTypeElement("Subject") val annotationBox = element.getAnnotation(TestSuppressWarnings::class) assertThat(annotationBox).isNotNull() assertThat( annotationBox!!.value.value ).isEqualTo( arrayOf("warning1", "warning 2") ) } } @Test fun typeReference_kotlin() { val mySource = Source.kotlin( "Foo.kt", """ import androidx.room.compiler.processing.testcode.MainAnnotation import androidx.room.compiler.processing.testcode.OtherAnnotation @MainAnnotation( typeList = [String::class, Int::class], singleType = Long::class, intMethod = 3, doubleMethodWithDefault = 3.0, floatMethodWithDefault = 3f, charMethodWithDefault = '3', byteMethodWithDefault = 3, shortMethodWithDefault = 3, longMethodWithDefault = 3L, boolMethodWithDefault = false, otherAnnotationArray = [ OtherAnnotation( value = "other list 1" ), OtherAnnotation( value = "other list 2" ) ], singleOtherAnnotation = OtherAnnotation("other single") ) public class Subject { } """.trimIndent() ) runTest( listOf(mySource) ) { invocation -> val element = invocation.processingEnv.requireTypeElement("Subject") element.getAnnotation(MainAnnotation::class)!!.let { annotation -> assertThat( annotation.getAsTypeList("typeList").map { it.asTypeName() } ).containsExactly( String::class.asClassName(), XTypeName.PRIMITIVE_INT ) assertThat( annotation.getAsType("singleType") ).isEqualTo( invocation.processingEnv.requireType(Long::class.typeName()) ) assertThat(annotation.value.intMethod).isEqualTo(3) assertThat(annotation.value.doubleMethodWithDefault).isEqualTo(3.0) assertThat(annotation.value.floatMethodWithDefault).isEqualTo(3f) assertThat(annotation.value.charMethodWithDefault).isEqualTo('3') assertThat(annotation.value.byteMethodWithDefault).isEqualTo(3) assertThat(annotation.value.shortMethodWithDefault).isEqualTo(3) assertThat(annotation.value.longMethodWithDefault).isEqualTo(3) assertThat(annotation.value.boolMethodWithDefault).isEqualTo(false) annotation.getAsAnnotationBox<OtherAnnotation>("singleOtherAnnotation") .let { other -> assertThat(other.value.value).isEqualTo("other single") } annotation.getAsAnnotationBoxArray<OtherAnnotation>("otherAnnotationArray") .let { boxArray -> assertThat(boxArray).hasLength(2) assertThat(boxArray[0].value.value).isEqualTo("other list 1") assertThat(boxArray[1].value.value).isEqualTo("other list 2") } } } } @Test fun typeReferenceArray_singleItemInJava() { val src = Source.java( "Subject", """ import androidx.room.compiler.processing.testcode.JavaAnnotationWithTypeReferences; @JavaAnnotationWithTypeReferences(String.class) class Subject { } """.trimIndent() ) runTest( sources = listOf(src) ) { invocation -> val subject = invocation.processingEnv.requireTypeElement("Subject") val annotationValue = subject.getAnnotation( JavaAnnotationWithTypeReferences::class )?.getAsTypeList("value") assertThat(annotationValue?.map { it.typeName }).containsExactly( ClassName.get(String::class.java) ) } } @Test fun propertyAnnotations() { val src = Source.kotlin( "Foo.kt", """ import androidx.room.compiler.processing.testcode.OtherAnnotation import androidx.room.compiler.processing.testcode.TestSuppressWarnings class Subject { @TestSuppressWarnings("onProp1") var prop1:Int = TODO() @get:TestSuppressWarnings("onGetter2") @set:TestSuppressWarnings("onSetter2") @field:TestSuppressWarnings("onField2") @setparam:TestSuppressWarnings("onSetterParam2") var prop2:Int = TODO() @get:TestSuppressWarnings("onGetter3") @set:TestSuppressWarnings("onSetter3") @setparam:TestSuppressWarnings("onSetterParam3") var prop3:Int @OtherAnnotation("_onGetter3") get() = 3 @OtherAnnotation("_onSetter3") set(@OtherAnnotation("_onSetterParam3") value) = Unit } """.trimIndent() ) runTest(sources = listOf(src)) { invocation -> val subject = invocation.processingEnv.requireTypeElement("Subject") subject.getField("prop1").assertHasSuppressWithValue("onProp1") subject.getMethodByJvmName("getProp1").assertDoesNotHaveAnnotation() subject.getMethodByJvmName("setProp1").assertDoesNotHaveAnnotation() subject.getMethodByJvmName("setProp1").parameters.first().assertDoesNotHaveAnnotation() subject.getField("prop2").assertHasSuppressWithValue("onField2") subject.getMethodByJvmName("getProp2").assertHasSuppressWithValue("onGetter2") subject.getMethodByJvmName("setProp2").assertHasSuppressWithValue("onSetter2") subject.getMethodByJvmName("setProp2").parameters.first().assertHasSuppressWithValue( "onSetterParam2" ) subject.getMethodByJvmName("getProp3").assertHasSuppressWithValue("onGetter3") subject.getMethodByJvmName("setProp3").assertHasSuppressWithValue("onSetter3") subject.getMethodByJvmName("setProp3").parameters.first().assertHasSuppressWithValue( "onSetterParam3" ) assertThat( subject.getMethodByJvmName("getProp3").getOtherAnnotationValue() ).isEqualTo("_onGetter3") assertThat( subject.getMethodByJvmName("setProp3").getOtherAnnotationValue() ).isEqualTo("_onSetter3") val otherAnnotationValue = subject.getMethodByJvmName("setProp3").parameters.first().getOtherAnnotationValue() assertThat( otherAnnotationValue ).isEqualTo("_onSetterParam3") } } @Test fun methodAnnotations() { val src = Source.kotlin( "Foo.kt", """ import androidx.room.compiler.processing.testcode.OtherAnnotation import androidx.room.compiler.processing.testcode.TestSuppressWarnings class Subject { fun noAnnotations(x:Int): Unit = TODO() @TestSuppressWarnings("onMethod") fun methodAnnotation( @TestSuppressWarnings("onParam") annotated:Int, notAnnotated:Int ): Unit = TODO() } """.trimIndent() ) runTest(sources = listOf(src)) { invocation -> val subject = invocation.processingEnv.requireTypeElement("Subject") subject.getMethodByJvmName("noAnnotations").let { method -> method.assertDoesNotHaveAnnotation() method.getParameter("x").assertDoesNotHaveAnnotation() } subject.getMethodByJvmName("methodAnnotation").let { method -> method.assertHasSuppressWithValue("onMethod") method.getParameter("annotated").assertHasSuppressWithValue("onParam") method.getParameter("notAnnotated").assertDoesNotHaveAnnotation() } } } @Test fun constructorParameterAnnotations() { val src = Source.kotlin( "Foo.kt", """ import androidx.room.compiler.processing.testcode.TestSuppressWarnings @TestSuppressWarnings("onClass") data class Subject( @field:TestSuppressWarnings("onField") @param:TestSuppressWarnings("onConstructorParam") @get:TestSuppressWarnings("onGetter") @set:TestSuppressWarnings("onSetter") var x:Int ) """.trimIndent() ) runTest(sources = listOf(src)) { invocation -> val subject = invocation.processingEnv.requireTypeElement("Subject") subject.assertHasSuppressWithValue("onClass") assertThat(subject.getConstructors()).hasSize(1) val constructor = subject.getConstructors().single() constructor.getParameter("x").assertHasSuppressWithValue("onConstructorParam") subject.getMethodByJvmName("getX").assertHasSuppressWithValue("onGetter") subject.getMethodByJvmName("setX").assertHasSuppressWithValue("onSetter") subject.getField("x").assertHasSuppressWithValue("onField") } } @Test fun defaultValues() { val kotlinSrc = Source.kotlin( "KotlinClass.kt", """ import androidx.room.compiler.processing.testcode.JavaAnnotationWithDefaults @JavaAnnotationWithDefaults class KotlinClass """.trimIndent() ) val javaSrc = Source.java( "JavaClass.java", """ import androidx.room.compiler.processing.testcode.JavaAnnotationWithDefaults; @JavaAnnotationWithDefaults class JavaClass {} """.trimIndent() ) runTest(sources = listOf(kotlinSrc, javaSrc)) { invocation -> listOf("KotlinClass", "JavaClass") .map { invocation.processingEnv.requireTypeElement(it) }.forEach { typeElement -> val annotation = typeElement.getAnnotation(JavaAnnotationWithDefaults::class) checkNotNull(annotation) assertThat(annotation.value.intVal).isEqualTo(3) assertThat(annotation.value.intArrayVal).isEqualTo(intArrayOf(1, 3, 5)) assertThat(annotation.value.stringArrayVal).isEqualTo(arrayOf("x", "y")) assertThat(annotation.value.stringVal).isEqualTo("foo") assertThat( annotation.getAsType("typeVal")?.rawType?.typeName ).isEqualTo( ClassName.get(HashMap::class.java) ) assertThat( annotation.getAsTypeList("typeArrayVal").map { it.rawType.typeName } ).isEqualTo( listOf(ClassName.get(LinkedHashMap::class.java)) ) assertThat( annotation.value.enumVal ).isEqualTo( JavaEnum.DEFAULT ) assertThat( annotation.value.enumArrayVal ).isEqualTo( arrayOf(JavaEnum.VAL1, JavaEnum.VAL2) ) assertThat( annotation.getAsAnnotationBox<OtherAnnotation>("otherAnnotationVal") .value.value ).isEqualTo("def") assertThat( annotation .getAsAnnotationBoxArray<OtherAnnotation>("otherAnnotationArrayVal") .map { it.value.value } ).containsExactly("v1") } } } @Test fun javaPrimitiveArray() { val javaSrc = Source.java( "JavaSubject.java", """ import androidx.room.compiler.processing.testcode.*; class JavaSubject { @JavaAnnotationWithPrimitiveArray( intArray = {1, 2, 3}, doubleArray = {1.0,2.0,3.0}, floatArray = {1f,2f,3f}, charArray = {'1','2','3'}, byteArray = {1,2,3}, shortArray = {1,2,3}, longArray = {1,2,3}, booleanArray = {true, false} ) Object annotated1; } """.trimIndent() ) val kotlinSrc = Source.kotlin( "KotlinSubject.kt", """ import androidx.room.compiler.processing.testcode.*; class KotlinSubject { @JavaAnnotationWithPrimitiveArray( intArray = [1, 2, 3], doubleArray = [1.0,2.0,3.0], floatArray = [1f,2f,3f], charArray = ['1','2','3'], byteArray = [1,2,3], shortArray = [1,2,3], longArray = [1,2,3], booleanArray = [true, false], ) val annotated1:Any = TODO() } """.trimIndent() ) runTest( sources = listOf(javaSrc, kotlinSrc) ) { invocation -> arrayOf("JavaSubject", "KotlinSubject").map { invocation.processingEnv.requireTypeElement(it) }.forEach { subject -> val annotation = subject.getField("annotated1").getAnnotation( JavaAnnotationWithPrimitiveArray::class ) assertThat( annotation?.value?.intArray ).isEqualTo( intArrayOf(1, 2, 3) ) assertThat( annotation?.value?.doubleArray ).isEqualTo( doubleArrayOf(1.0, 2.0, 3.0) ) assertThat( annotation?.value?.floatArray ).isEqualTo( floatArrayOf(1f, 2f, 3f) ) assertThat( annotation?.value?.charArray ).isEqualTo( charArrayOf('1', '2', '3') ) assertThat( annotation?.value?.byteArray ).isEqualTo( byteArrayOf(1, 2, 3) ) assertThat( annotation?.value?.shortArray ).isEqualTo( shortArrayOf(1, 2, 3) ) assertThat( annotation?.value?.longArray ).isEqualTo( longArrayOf(1, 2, 3) ) assertThat( annotation?.value?.booleanArray ).isEqualTo( booleanArrayOf(true, false) ) } } } @Test fun javaEnum() { val javaSrc = Source.java( "JavaSubject.java", """ import androidx.room.compiler.processing.testcode.*; class JavaSubject { @JavaAnnotationWithEnum(JavaEnum.VAL1) Object annotated1; } """.trimIndent() ) val kotlinSrc = Source.kotlin( "KotlinSubject.kt", """ import androidx.room.compiler.processing.testcode.*; class KotlinSubject { @JavaAnnotationWithEnum(JavaEnum.VAL1) val annotated1: Any = TODO() } """.trimIndent() ) runTest( sources = listOf(javaSrc, kotlinSrc) ) { invocation -> arrayOf("JavaSubject", "KotlinSubject").map { invocation.processingEnv.requireTypeElement(it) }.forEach { subject -> val annotation = subject.getField("annotated1").getAnnotation( JavaAnnotationWithEnum::class ) assertThat( annotation?.value?.value ).isEqualTo( JavaEnum.VAL1 ) } } } @Test fun javaEnumArray() { val javaSrc = Source.java( "JavaSubject.java", """ import androidx.room.compiler.processing.testcode.*; class JavaSubject { @JavaAnnotationWithEnumArray(enumArray = {JavaEnum.VAL1, JavaEnum.VAL2}) Object annotated1; } """.trimIndent() ) val kotlinSrc = Source.kotlin( "KotlinSubject.kt", """ import androidx.room.compiler.processing.testcode.*; class KotlinSubject { @JavaAnnotationWithEnumArray(enumArray = [JavaEnum.VAL1, JavaEnum.VAL2]) val annotated1:Any = TODO() } """.trimIndent() ) runTest( sources = listOf(javaSrc, kotlinSrc) ) { invocation -> arrayOf("JavaSubject", "KotlinSubject").map { invocation.processingEnv.requireTypeElement(it) }.forEach { subject -> val annotation = subject.getField("annotated1").getAnnotation( JavaAnnotationWithEnumArray::class ) assertThat( annotation?.value?.enumArray ).isEqualTo( arrayOf(JavaEnum.VAL1, JavaEnum.VAL2) ) } } } @Test fun javaRepeatableAnnotation() { val javaSrc = Source.java( "JavaSubject", """ import ${RepeatableJavaAnnotation::class.qualifiedName}; @RepeatableJavaAnnotation("x") @RepeatableJavaAnnotation("y") @RepeatableJavaAnnotation("z") public class JavaSubject {} """.trimIndent() ) val kotlinSrc = Source.kotlin( "KotlinSubject.kt", """ import ${RepeatableJavaAnnotation::class.qualifiedName} // TODO update when https://youtrack.jetbrains.com/issue/KT-12794 is fixed. // right now, kotlin does not support repeatable annotations. @RepeatableJavaAnnotation.List( RepeatableJavaAnnotation("x"), RepeatableJavaAnnotation("y"), RepeatableJavaAnnotation("z") ) public class KotlinSubject """.trimIndent() ) runTest( sources = listOf(javaSrc, kotlinSrc) ) { invocation -> listOf("JavaSubject", "KotlinSubject") .map(invocation.processingEnv::requireTypeElement) .forEach { subject -> val annotations = subject.getAnnotations( RepeatableJavaAnnotation::class ) assertThat( subject.hasAnnotation( RepeatableJavaAnnotation::class ) ).isTrue() val values = annotations .map { it.value.value } assertWithMessage(subject.qualifiedName) .that(values) .containsExactly("x", "y", "z") } } } @Test fun javaRepeatableAnnotation_notRepeated() { val javaSrc = Source.java( "JavaSubject", """ import ${RepeatableJavaAnnotation::class.qualifiedName}; @RepeatableJavaAnnotation("x") public class JavaSubject {} """.trimIndent() ) val kotlinSrc = Source.kotlin( "KotlinSubject.kt", """ import ${RepeatableJavaAnnotation::class.qualifiedName} @RepeatableJavaAnnotation("x") public class KotlinSubject """.trimIndent() ) runTest( sources = listOf(javaSrc, kotlinSrc) ) { invocation -> listOf("JavaSubject", "KotlinSubject") .map(invocation.processingEnv::requireTypeElement) .forEach { subject -> val annotations = subject.getAnnotations( RepeatableJavaAnnotation::class ) assertThat( subject.hasAnnotation( RepeatableJavaAnnotation::class ) ).isTrue() val values = annotations .map { it.value.value } assertWithMessage(subject.qualifiedName) .that(values) .containsExactly("x") } } } // helper function to read what we need private fun XAnnotated.getSuppressValues(): Array<String>? { return this.getAnnotation(TestSuppressWarnings::class)?.value?.value } private fun XAnnotated.assertHasSuppressWithValue(vararg expected: String) { assertWithMessage("has suppress annotation $this") .that(this.hasAnnotation(TestSuppressWarnings::class)) .isTrue() assertWithMessage("has suppress annotation $this") .that(this.hasAnyAnnotation(TestSuppressWarnings::class)) .isTrue() assertWithMessage("$this") .that(this.hasAnnotationWithPackage(TestSuppressWarnings::class.java.packageName)) .isTrue() assertWithMessage("$this") .that(getSuppressValues()) .isEqualTo(expected) } private fun XAnnotated.assertDoesNotHaveAnnotation() { assertWithMessage("$this") .that(this.hasAnnotation(TestSuppressWarnings::class)) .isFalse() assertWithMessage("$this") .that(this.hasAnyAnnotation(TestSuppressWarnings::class)) .isFalse() assertWithMessage("$this") .that(this.hasAnnotationWithPackage(TestSuppressWarnings::class.java.packageName)) .isFalse() assertWithMessage("$this") .that(this.getSuppressValues()) .isNull() } private fun XAnnotated.getOtherAnnotationValue(): String? { return this.getAnnotation(OtherAnnotation::class)?.value?.value } companion object { @JvmStatic @Parameterized.Parameters(name = "preCompiled_{0}") fun params() = arrayOf(false, true) } }
apache-2.0
cc3b3f1aa05fd5885bb9df125cb6ad55
37.987654
99
0.539012
5.603265
false
true
false
false