repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
55 values
size
stringlengths
2
6
content
stringlengths
55
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
979
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
ntemplon/legends-of-omterra
core/src/com/jupiter/europa/scene2d/ui/EuropaButton.kt
1
3002
/* * The MIT License * * Copyright 2015 Nathan Templon. * * 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 com.jupiter.europa.scene2d.ui import com.badlogic.gdx.Input import com.badlogic.gdx.scenes.scene2d.InputEvent import com.badlogic.gdx.scenes.scene2d.ui.Skin import com.badlogic.gdx.scenes.scene2d.ui.TextButton import com.badlogic.gdx.scenes.scene2d.utils.ClickListener import com.jupiter.ganymede.event.Event import com.jupiter.ganymede.event.Listener /** * @author Nathan Templon */ public class EuropaButton : TextButton { // Fields private val clicked = Event<ClickEvent>() // Initialization public constructor(text: String, style: TextButton.TextButtonStyle) : super(text, style) { this.init() } public constructor(text: String, skin: Skin) : super(text, skin) { this.init() } // Public Methods public fun addClickListener(listener: Listener<ClickEvent>): Boolean { return this.clicked.addListener(listener) } public fun addClickListener(listener: (ClickEvent) -> Unit): Boolean = this.clicked.addListener(listener) public fun removeClickListener(listener: Listener<ClickEvent>): Boolean { return this.clicked.removeListener(listener) } public fun removeClickListener(listener: (ClickEvent) -> Unit): Boolean = this.clicked.removeListener(listener) // Private Methods private fun init() { this.addListener(object : ClickListener() { override fun clicked(event: InputEvent?, x: Float, y: Float) { if (event!!.getButton() == Input.Buttons.LEFT && [email protected]()) { [email protected](ClickEvent(event, x, y)) [email protected](false) } } }) } // Nested Classes public inner data class ClickEvent(public val event: InputEvent, public val x: Float, public val y: Float) }
mit
b341024e1d3236506af1eba7e7f32de4
34.317647
115
0.710193
4.388889
false
false
false
false
jtransc/jtransc
jtransc-utils/src/com/jtransc/vfs/syncvfs.kt
1
22678
/* * Copyright 2016 Carlos Ballesteros Velasco * * 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.jtransc.vfs import com.jtransc.env.OS import com.jtransc.error.* import com.jtransc.io.ProcessUtils import com.jtransc.io.readExactBytes import com.jtransc.text.ToString import com.jtransc.text.splitLast import com.jtransc.vfs.node.FileNode import com.jtransc.vfs.node.FileNodeTree import java.io.* import java.net.URL import java.net.URLDecoder import java.nio.charset.Charset import java.util.* import java.util.zip.GZIPInputStream import java.util.zip.ZipEntry import java.util.zip.ZipFile import java.util.zip.ZipInputStream data class SyncVfsStat( val file: SyncVfsFile, val size: Long, val mtime: Date, val isDirectory: Boolean, val isSymlink: Boolean, val exists: Boolean, val mode: FileMode, val inode: Long = 0L ) { val name: String get() = file.name val path: String get() = file.path val isFile: Boolean get() = !isDirectory companion object { fun notExists(file: SyncVfsFile) = SyncVfsStat( file = file, size = 0L, mtime = Date(), isDirectory = false, isSymlink = false, exists = false, mode = FileMode.FULL_ACCESS ) } } class SyncVfsFile(internal val vfs: SyncVfs, val path: String) { val size: Long get() = stat().size val mtime: Date get() = stat().mtime fun setMtime(time: Date) = vfs.setMtime(path, time) fun stat(): SyncVfsStat = vfs.stat(path) fun chmod(mode: FileMode): Unit = vfs.chmod(path, mode) fun symlinkTo(target: String): Unit = vfs.symlink(path, target) fun read(): ByteArray = vfs.read(path) fun readBytes(): ByteArray = read() fun readOrNull(): ByteArray? = if (exists) read() else null inline fun <reified T : Any> readSpecial(): T = readSpecial(T::class.java) fun <T> readSpecial(clazz: Class<T>): T = vfs.readSpecial(clazz, path) fun write(data: ByteArray): Unit = vfs.write(path, data) fun readString(encoding: Charset = Charsets.UTF_8): String = encoding.toString(vfs.read(path)) fun readLines(encoding: Charset = Charsets.UTF_8): List<String> = this.readString(encoding).lines() val exists: Boolean get() = vfs.exists(path) val isDirectory: Boolean get() = stat().isDirectory fun remove(): Unit = vfs.remove(path) fun removeIfExists(): Unit = if (exists) remove() else Unit companion object { val pathSeparator by lazy { System.getProperty("path.separator") ?: ":" } val fileSeparator by lazy { System.getProperty("file.separator") ?: "/" } } fun getPaths(): List<String> { val env = getenv("PATH") ?: "" return env.split(pathSeparator) } fun getenv(key: String): String? = vfs.getenv(key) fun exec(cmdAndArgs: List<String>, options: ExecOptions = ExecOptions()): ProcessResult = vfs.exec(path, cmdAndArgs.first(), cmdAndArgs.drop(1), options) fun exec(cmd: String, args: List<String>, options: ExecOptions): ProcessResult = vfs.exec(path, cmd, args, options) fun exec(cmd: String, args: List<String>, env: Map<String, String> = mapOf()): ProcessResult = exec(cmd, args, ExecOptions(passthru = false, env = env)) fun exec(cmd: String, vararg args: String, env: Map<String, String> = mapOf()): ProcessResult = exec(cmd, args.toList(), ExecOptions(passthru = false, env = env)) fun passthru(cmd: String, args: List<String>, filter: ((line: String) -> Boolean)? = null, env: Map<String, String> = mapOf()): ProcessResult = exec(cmd, args, ExecOptions(passthru = true, filter = filter, env = env)) fun passthru(cmd: String, vararg args: String, filter: ((line: String) -> Boolean)? = null, env: Map<String, String> = mapOf()): ProcessResult = exec(cmd, args.toList(), ExecOptions(passthru = true, filter = filter, env = env)) val name: String get() = path.substringAfterLast('/') val realpath: String get() = jailCombinePath(vfs.absolutePath, path) val realpathOS: String get() = if (OS.isWindows) realpath.replace('/', '\\') else realpath val realfile: File get() = File(realpathOS) fun listdir(): Iterable<SyncVfsStat> = vfs.listdir(path) fun listdirRecursive(): Iterable<SyncVfsStat> = listdirRecursive({ true }) fun listdirRecursive(filter: (stat: SyncVfsStat) -> Boolean): Iterable<SyncVfsStat> { //log("REALPATH: ${this.realpath}") return listdir().flatMap { //log("item:${it.path}") if (filter(it)) { if (it.isDirectory) { //log("directory! ${it.path}") listOf(it) + it.file.listdirRecursive() } else { //log("file! ${it.path}") listOf(it) } } else { listOf() } } } fun firstRecursive(filter: (stat: SyncVfsStat) -> Boolean): SyncVfsStat { for (item in listdirRecursive()) { if (filter(item)) return item } invalidOp("No item on SyncVfsFile.firstRecursive") } fun mkdir(): Unit = vfs.mkdir(path) fun rmdir(): Unit = vfs.rmdir(path) fun ensuredir(): SyncVfsFile { if (path == "") return this if (!parent.exists) parent.ensuredir() mkdir() return this } fun ensureParentDir(): SyncVfsFile { parent.ensuredir() return this } fun rmdirRecursively(): Unit { for (item in this.listdir()) { if (item.isDirectory) { item.file.rmdirRecursively() } else { item.file.remove() } } this.rmdir() } fun rmdirRecursivelyIfExists(): Unit { if (exists) return rmdirRecursively(); } fun access(path: String): SyncVfsFile = SyncVfsFile(vfs, combinePaths(this.path, path)); operator fun get(path: String): SyncVfsFile = access(path) operator fun set(path: String, content: String) = set(path, content.toByteArray(UTF8)) operator fun set(path: String, content: ToString) = set(path, content.toString().toByteArray(UTF8)) operator fun set(path: String, content: SyncVfsFile) = set(path, content.readBytes()) operator fun set(path: String, content: ByteArray) { val file = access(path).ensureParentDir() if (!file.exists || !file.read().contentEquals(content)) { file.write(content) } } operator fun contains(path: String): Boolean = access(path).exists fun jailAccess(path: String): SyncVfsFile = access(path).jail() fun jail(): SyncVfsFile = AccessSyncVfs(vfs, path).root(); override fun toString() = "SyncVfsFile($vfs, '$path')" fun write(data: String, encoding: Charset = UTF8): SyncVfsFile = writeString(data, encoding) fun writeString(data: String, encoding: Charset = UTF8): SyncVfsFile { write(data.toByteArray(encoding)) return this } fun dumpTree() { println("<dump>") for (path in listdirRecursive()) { println(path) } println("</dump>") } fun copyTo(that: SyncVfsFile): Unit = that.ensureParentDir().write(this.read()) fun copyTreeTo(that: SyncVfsFile, filter: (from: SyncVfsFile, to: SyncVfsFile) -> Boolean = { from, to -> true }, doLog: Boolean = true): Unit { if (doLog) com.jtransc.log.log("copyTreeTo " + this.realpath + " -> " + that.realpath) val stat = this.stat() if (stat.isDirectory) { that.mkdir() for (node in this.listdir()) { node.file.copyTreeTo(that[node.name], filter, doLog = doLog) } } else { this.copyTo(that) } } fun toDumpString(): String { return listdirRecursive().filter { it.isFile }.map { "// ${it.path}:\n${it.file.readString()}" }.joinToString("\n") } } data class ExecOptions( val passthru: Boolean = false, val filter: ((line: String) -> Boolean)? = null, val env: Map<String, String> = mapOf(), val sysexec: Boolean = false, val fixencoding: Boolean = true, val fixLineEndings: Boolean = true ) { val redirect: Boolean get() = passthru } open class SyncVfs { final fun root() = SyncVfsFile(this, "") operator fun get(path: String) = root()[path] open val absolutePath: String = "" open fun read(path: String): ByteArray { throw NotImplementedException() } open fun <T> readSpecial(clazz: Class<T>, path: String): T { throw NotImplementedException() } open fun write(path: String, data: ByteArray): Unit { throw NotImplementedException() } open fun listdir(path: String): Iterable<SyncVfsStat> { throw NotImplementedException() } open fun mkdir(path: String): Unit { throw NotImplementedException() } open fun rmdir(path: String): Unit { throw NotImplementedException() } open fun getenv(key: String): String? { return System.getenv(key) } open fun exec(path: String, cmd: String, args: List<String>, options: ExecOptions): ProcessResult { throw NotImplementedException() } open fun exists(path: String): Boolean { try { return stat(path).exists } catch (e: Throwable) { return false } } open fun remove(path: String): Unit { throw NotImplementedException() } open fun stat(path: String): SyncVfsStat { val file = SyncVfsFile(this, path) return try { val data = read(path) SyncVfsStat( file = file, size = data.size.toLong(), mtime = Date(), isDirectory = false, exists = true, isSymlink = false, mode = FileMode.FULL_ACCESS ) } catch (e: IOException) { SyncVfsStat.notExists(file) } //throw NotImplementedException() } open fun chmod(path: String, mode: FileMode): Unit { throw NotImplementedException() } open fun symlink(link: String, target: String): Unit { throw NotImplementedException() } open fun setMtime(path: String, time: Date) { throw NotImplementedException() } } fun FileNode.toSyncStat(vfs: SyncVfs, path: String): SyncVfsStat { return SyncVfsStat( file = SyncVfsFile(vfs, path), size = this.size(), mtime = this.mtime(), isDirectory = this.isDirectory(), isSymlink = this.isSymlink(), exists = true, mode = this.mode() ) } open class _MemoryVfs : BaseTreeVfs(FileNodeTree()) { } private class _LocalVfs : SyncVfs() { override val absolutePath: String get() = "" override fun read(path: String): ByteArray = RawIo.fileRead(path) override fun write(path: String, data: ByteArray): Unit = RawIo.fileWrite(path, data) override fun listdir(path: String): Iterable<SyncVfsStat> = RawIo.listdir(path).map { it.toSyncStat(this, "$path/${it.name}") } override fun mkdir(path: String): Unit = RawIo.mkdir(path) override fun rmdir(path: String): Unit = RawIo.rmdir(path) override fun exec(path: String, cmd: String, args: List<String>, options: ExecOptions): ProcessResult = RawIo.execOrPassthruSync(path, cmd, args, options) override fun exists(path: String): Boolean = RawIo.fileExists(path) override fun remove(path: String): Unit = RawIo.fileRemove(path) override fun stat(path: String): SyncVfsStat = RawIo.fileStat(path).toSyncStat(this, path) override fun chmod(path: String, mode: FileMode): Unit = Unit.apply { RawIo.chmod(path, mode) } override fun symlink(link: String, target: String): Unit = RawIo.symlink(link, target) override fun setMtime(path: String, time: Date) = RawIo.setMtime(path, time) } fun File.toSyncStat(vfs: SyncVfs, path: String) = SyncVfsStat( file = SyncVfsFile(vfs, path), size = this.length(), mtime = Date(this.lastModified()), isDirectory = this.isDirectory, //isSymlink = java.nio.file.Files.isSymbolicLink(java.nio.file.Paths.get(this.toURI())), isSymlink = false, exists = true, mode = FileMode.FULL_ACCESS ) abstract class ProxySyncVfs : SyncVfs() { abstract protected fun transform(path: String): SyncVfsFile open protected fun transformStat(stat: SyncVfsStat): SyncVfsStat = stat override val absolutePath: String get() = transform("").realpath override fun read(path: String): ByteArray = transform(path).read() override fun <T> readSpecial(clazz: Class<T>, path: String): T = transform(path).readSpecial(clazz) override fun write(path: String, data: ByteArray): Unit = transform(path).write(data) // @TODO: Probably transform SyncVfsStat! override fun listdir(path: String): Iterable<SyncVfsStat> = transform(path).listdir().map { transformStat(it) } override fun mkdir(path: String): Unit { transform(path).mkdir() } override fun rmdir(path: String): Unit { transform(path).rmdir() } override fun exec(path: String, cmd: String, args: List<String>, options: ExecOptions): ProcessResult = transform(path).exec(cmd, args, options) override fun exists(path: String): Boolean = transform(path).exists override fun remove(path: String): Unit = transform(path).remove() override fun stat(path: String): SyncVfsStat = transformStat(transform(path).stat()) override fun chmod(path: String, mode: FileMode): Unit = transform(path).chmod(mode) override fun symlink(link: String, target: String): Unit = transform(link).symlinkTo(transform(target).path) override fun setMtime(path: String, time: Date) = transform(path).setMtime(time) } // @TODO: paths should not start with "/" private class AccessSyncVfs(val parent: SyncVfs, val path: String) : ProxySyncVfs() { override fun transform(path: String): SyncVfsFile = SyncVfsFile(parent, jailCombinePath(this.path, path)) override fun transformStat(stat: SyncVfsStat): SyncVfsStat { // @TODO: Do this better! val statFilePath = "/" + stat.file.path.trimStart('/') val thisPath = "/" + this.path.trimStart('/') if (!statFilePath.startsWith(thisPath)) { throw InvalidOperationException("Assertion failed $statFilePath must start with $thisPath") } return SyncVfsStat( file = SyncVfsFile(this, "/" + statFilePath.removePrefix(thisPath)), size = stat.size, mtime = stat.mtime, isDirectory = stat.isDirectory, isSymlink = stat.isSymlink, exists = true, mode = stat.mode ) } override fun toString(): String = "AccessSyncVfs($parent, $path)" } private class _LogSyncVfs(val parent: SyncVfs) : ProxySyncVfs() { override fun transform(path: String): SyncVfsFile = SyncVfsFile(parent, path) override fun write(path: String, data: ByteArray): Unit { println("Writting $parent($path) with ${data.toString(UTF8)}") super.write(path, data) } } private class _UrlVfs : SyncVfs() { override fun read(path: String): ByteArray { val fixedUrl = Regex("^http(s?):/([^/])").replace(path, "http$1://$2") val connection = URL(fixedUrl).openConnection() connection.allowUserInteraction = false connection.connectTimeout = 10000 connection.readTimeout = 10000 connection.addRequestProperty("Accept-Language", "en-US,en;q=0.8"); connection.addRequestProperty("User-Agent", "Mozilla"); //connection.addRequestProperty("Referer", fixedUrl); //println(connection.headerFields) val sin = connection.inputStream; val sout = ByteArrayOutputStream(); sin.copyTo(sout) return sout.toByteArray() } } fun RootUrlVfs(): SyncVfsFile = _UrlVfs().root() fun UrlVfs(url: String): SyncVfsFile = _UrlVfs().root().jailAccess(url) fun UrlVfs(url: URL): SyncVfsFile = _UrlVfs().root().jailAccess(url.toExternalForm()) fun RootLocalVfs(): SyncVfsFile = _LocalVfs().root() fun MergeVfs(nodes: List<SyncVfsFile>) = if (nodes.isNotEmpty()) MergedSyncVfs(nodes).root() else MemoryVfs() fun MergedLocalAndJars(paths: List<String>) = MergeVfs(LocalAndJars(paths)) fun LocalAndJars(paths: List<String>): List<SyncVfsFile> { return paths.map { if (it.endsWith(".jar")) ZipVfs(it) else LocalVfs(File(it)) } } fun CompressedVfs(file: File): SyncVfsFile { val npath = file.absolutePath.toLowerCase() return if (npath.endsWith(".tar.gz")) { TarVfs(GZIPInputStream(file.inputStream()).readBytes()) } else if (npath.endsWith(".zip") || npath.endsWith(".jar")) { ZipVfs(file) } else if (npath.endsWith(".tar")) { TarVfs(file) } else { invalidOp("Don't know how to handle compressed file: $file") } } /* fun ZipVfs(path: String): SyncVfsFile = ZipSyncVfs(ZipFile(path)).root() fun ZipVfs(file: File): SyncVfsFile = ZipSyncVfs(ZipFile(file)).root() fun ZipVfs(content: ByteArray): SyncVfsFile { val tempFile = createTempFile("jtransc-zip") tempFile.writeBytes(content) return ZipSyncVfs(ZipFile(tempFile)).root() } */ fun ResourcesVfs(clazz: Class<*>): SyncVfsFile = ResourcesSyncVfs(clazz).root() @Deprecated("Use File instead", ReplaceWith("LocalVfs(File(path))", "java.io.File")) fun LocalVfs(path: String): SyncVfsFile = RootLocalVfs().access(path).jail() fun UnjailedLocalVfs(file: File): SyncVfsFile = RootLocalVfs().access(file.absolutePath) fun LocalVfs(file: File): SyncVfsFile = _LocalVfs().root().access(file.absolutePath).jail() fun LocalVfsEnsureDirs(file: File): SyncVfsFile { ignoreErrors { file.mkdirs() } return _LocalVfs().root().access(file.absolutePath).jail() } fun CwdVfs(): SyncVfsFile = LocalVfs(File(RawIo.cwd())) fun CwdVfs(path: String): SyncVfsFile = CwdVfs().jailAccess(path) fun ScriptVfs(): SyncVfsFile = LocalVfs(File(RawIo.script())) fun MemoryVfs(): SyncVfsFile = _MemoryVfs().root() fun MemoryVfs(vararg files: Pair<String, String>): SyncVfsFile { val vfs = _MemoryVfs().root() for (file in files) { vfs.access(file.first).ensureParentDir().writeString(file.second) } return vfs } fun GetClassJar(clazz: Class<*>): File { val classLoader = VfsPath::class.java.classLoader val classFilePath = clazz.name.replace('.', '/') + ".class" //println(classFilePath) //println(classLoader) val classUrl = classLoader.getResource(classFilePath) //path. //println(path) val regex = Regex("^file:(.*?)!(.*?)$") val result = regex.find(classUrl.path)!! val jarPath = result.groups[1]!!.value return File(URLDecoder.decode(jarPath, Charsets.UTF_8.name())) } fun MemoryVfsBin(vararg files: Pair<String, ByteArray>): SyncVfsFile { val vfs = _MemoryVfs().root() for (file in files) { vfs.access(file.first).ensureParentDir().write(file.second) } return vfs } fun MemoryVfsFile(content: String, name: String = "file"): SyncVfsFile { return MemoryVfs(name to content).access(name) } fun MemoryVfsFileBin(content: ByteArray, name: String = "file"): SyncVfsFile { return MemoryVfsBin(name to content).access(name) } fun LogVfs(parent: SyncVfsFile): SyncVfsFile = _LogSyncVfs(parent.jail().vfs).root() fun SyncVfsFile.log() = LogVfs(this) fun normalizePath(path: String): String { val out = ArrayList<String>(); for (chunk in path.replace('\\', '/').split('/')) { when (chunk) { ".." -> if (out.size > 0) out.removeAt(0) "." -> Unit "" -> if (out.size == 0) out.add("") else -> out.add(chunk) } } return out.joinToString("/") } fun combinePaths(vararg paths: String): String { return normalizePath(paths.filter { it != "" }.joinToString("/")) } fun jailCombinePath(base: String, access: String): String { return combinePaths(base, normalizePath(access)) } class VfsPath(val path: String) data class UserKey<T>(val name: String) inline fun <reified T : Any> UserKey(): UserKey<T> = UserKey<T>(T::class.java.name) interface IUserData { operator fun <T : Any> contains(key: UserKey<T>): Boolean operator fun <T : Any?> get(key: UserKey<T>): T? operator fun <T : Any> set(key: UserKey<T>, value: T) } fun <T : Any> IUserData.getCached(key: UserKey<T>, builder: () -> T): T { if (key !in this) this[key] = builder() return this[key]!! } @Suppress("UNCHECKED_CAST") class UserData : IUserData { private val dict = hashMapOf<Any, Any>() override operator fun <T : Any> contains(key: UserKey<T>): Boolean = key in dict override operator fun <T : Any?> get(key: UserKey<T>): T? = dict[key] as T? override operator fun <T : Any> set(key: UserKey<T>, value: T) { dict.put(key, value) } } object Path { fun parent(path: String): String = if (path.contains('/')) path.substringBeforeLast('/') else "" fun withoutExtension(path: String): String = path.substringBeforeLast('.') fun withExtension(path: String, ext: String): String = withoutExtension(path) + ".$ext" fun withBaseName(path: String, name: String): String = "${parent(path)}/$name" } val SyncVfsFile.parent: SyncVfsFile get() { //println("Path: '${path}', Parent: '${Path.parent(path)}'") return SyncVfsFile(vfs, Path.parent(path)) } val SyncVfsFile.withoutExtension: SyncVfsFile get() = SyncVfsFile(vfs, Path.withoutExtension(path)) fun SyncVfsFile.withExtension(ext: String): SyncVfsFile = SyncVfsFile(vfs, Path.withExtension(path, ext)) fun SyncVfsFile.withBaseName(baseName: String): SyncVfsFile = parent.access(baseName) private class MergedSyncVfs(val nodes: List<SyncVfsFile>) : SyncVfs() { init { if (nodes.isEmpty()) throw InvalidArgumentException("Nodes can't be empty") } override val absolutePath: String = "#merged#" //private val nodesSorted = nodes.reversed() val nodesSorted = nodes private fun <T> op(path: String, act: String, action: (node: SyncVfsFile) -> T): T { var lastError: Throwable? = null for (node in nodesSorted) { try { return action(node) } catch(t: Throwable) { lastError = t } } throw RuntimeException("Can't $act file '$path' : $lastError") } override fun read(path: String): ByteArray = op(path, "read") { it[path].read() } override fun write(path: String, data: ByteArray) = op(path, "write") { it[path].write(data) } override fun <T> readSpecial(clazz: Class<T>, path: String): T = op(path, "readSpecial") { it[path].readSpecial(clazz) } override fun listdir(path: String): Iterable<SyncVfsStat> { //op(path, "listdir") { it[path].listdir() } return nodesSorted.flatMap { it.listdir() } } override fun mkdir(path: String) = op(path, "mkdir") { it[path].mkdir() } override fun rmdir(path: String) = op(path, "rmdir") { it[path].rmdir() } override fun exec(path: String, cmd: String, args: List<String>, options: ExecOptions): ProcessResult { return op(path, "exec") { it[path].exec(cmd, args, options) } } override fun remove(path: String) = op(path, "remove") { it[path].remove() } override fun stat(path: String): SyncVfsStat { var lastStat: SyncVfsStat? = null for (node in nodesSorted) { val stat = node[path].stat() lastStat = stat if (stat.exists) break //println(stat) } return lastStat!! } override fun setMtime(path: String, time: Date) = op(path, "setMtime") { it[path].setMtime(time) } override fun toString(): String = "MergedSyncVfs(" + this.nodes.joinToString(", ") + ")" } private class ResourcesSyncVfs(val clazz: Class<*>) : SyncVfs() { val classLoader = clazz.classLoader override fun read(path: String): ByteArray { return classLoader.getResourceAsStream(path).readBytes() } } fun SyncVfsFile.getUnmergedFiles(): List<SyncVfsFile> { val vfs = this.vfs if (vfs is MergedSyncVfs) { return vfs.nodes.map { it[this.path] } } else { return listOf(this) } }
apache-2.0
a64923f07e6be372e0da91113387dade
33.414264
228
0.702134
3.300538
false
false
false
false
square/moshi
moshi-kotlin-codegen/src/main/java/com/squareup/moshi/kotlin/codegen/api/DelegateKey.kt
1
3873
/* * Copyright (C) 2018 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.moshi.kotlin.codegen.api import com.squareup.kotlinpoet.AnnotationSpec import com.squareup.kotlinpoet.ClassName import com.squareup.kotlinpoet.CodeBlock import com.squareup.kotlinpoet.KModifier import com.squareup.kotlinpoet.MemberName import com.squareup.kotlinpoet.NameAllocator import com.squareup.kotlinpoet.ParameterSpec import com.squareup.kotlinpoet.ParameterizedTypeName import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy import com.squareup.kotlinpoet.PropertySpec import com.squareup.kotlinpoet.TypeName import com.squareup.kotlinpoet.TypeVariableName import com.squareup.kotlinpoet.WildcardTypeName import com.squareup.kotlinpoet.asClassName import com.squareup.kotlinpoet.joinToCode import com.squareup.moshi.JsonAdapter import java.util.Locale /** A JsonAdapter that can be used to encode and decode a particular field. */ @InternalMoshiCodegenApi public data class DelegateKey( private val type: TypeName, private val jsonQualifiers: List<AnnotationSpec>, ) { public val nullable: Boolean get() = type.isNullable /** Returns an adapter to use when encoding and decoding this property. */ internal fun generateProperty( nameAllocator: NameAllocator, typeRenderer: TypeRenderer, moshiParameter: ParameterSpec, propertyName: String ): PropertySpec { val qualifierNames = jsonQualifiers.joinToString("") { "At${it.typeName.rawType().simpleName}" } val adapterName = nameAllocator.newName( "${type.toVariableName().replaceFirstChar { it.lowercase(Locale.US) }}${qualifierNames}Adapter", this ) val adapterTypeName = JsonAdapter::class.asClassName().parameterizedBy(type) val standardArgs = arrayOf( moshiParameter, typeRenderer.render(type) ) val (initializerString, args) = when { jsonQualifiers.isEmpty() -> ", %M()" to arrayOf(MemberName("kotlin.collections", "emptySet")) else -> { ", setOf(%L)" to arrayOf(jsonQualifiers.map { it.asInstantiationExpression() }.joinToCode()) } } val finalArgs = arrayOf(*standardArgs, *args, propertyName) return PropertySpec.builder(adapterName, adapterTypeName, KModifier.PRIVATE) .initializer("%N.adapter(%L$initializerString, %S)", *finalArgs) .build() } } private fun AnnotationSpec.asInstantiationExpression(): CodeBlock { // <Type>(args) return CodeBlock.of( "%T(%L)", typeName, members.joinToCode() ) } /** * Returns a suggested variable name derived from a list of type names. This just concatenates, * yielding types like MapOfStringLong. */ private fun List<TypeName>.toVariableNames() = joinToString("") { it.toVariableName() } /** Returns a suggested variable name derived from a type name, like nullableListOfString. */ private fun TypeName.toVariableName(): String { val base = when (this) { is ClassName -> simpleName is ParameterizedTypeName -> rawType.simpleName + "Of" + typeArguments.toVariableNames() is WildcardTypeName -> (inTypes + outTypes).toVariableNames() is TypeVariableName -> name + bounds.toVariableNames() else -> throw IllegalArgumentException("Unrecognized type! $this") } return if (isNullable) { "Nullable$base" } else { base } }
apache-2.0
959e0edd4d40e00aef80b889aea75d3f
34.53211
102
0.742577
4.461982
false
false
false
false
squins/ooverkommelig
main/src/commonMain/kotlin/org/ooverkommelig/SubGraphDefinitionCommon.kt
1
1904
package org.ooverkommelig import org.ooverkommelig.definition.DelegateOfObjectToCreateEagerly import org.ooverkommelig.definition.ObjectCreatingDefinition import org.ooverkommelig.definition.ObjectlessLifecycle import org.ooverkommelig.definition.SubGraphDefinitionOwner import org.ooverkommelig.definition.SubGraphDefinitionOwnerCommon import kotlin.reflect.KProperty abstract class SubGraphDefinitionCommon : SubGraphDefinitionOwner() { private val objectlessLifecycles = mutableListOf<ObjectlessLifecycle>() internal val delegatesOfObjectsToCreateEagerly = mutableListOf<DelegateOfObjectToCreateEagerly<*>>() private var owner: SubGraphDefinitionOwnerCommon? = null internal fun setOwner(newOwner: SubGraphDefinitionOwnerCommon) { check(owner == null) { "Tried to set the owner multiple times." } owner = newOwner } override val objectGraphDefinition: ObjectGraphDefinition get() = owner?.objectGraphDefinition ?: throw IllegalStateException("Owner of: $name, has not been initialized. Use 'add(...)' to add the sub graph to its owner when you create it.") protected fun lifecycle(description: String, init: () -> Unit, dispose: () -> Unit) { objectlessLifecycles += ObjectlessLifecycle(name, description, init, dispose) } override fun allObjectlessLifecycles() = super.allObjectlessLifecycles() + objectlessLifecycles override fun allObjectsToCreateEagerly() = super.allObjectsToCreateEagerly() + delegatesOfObjectsToCreateEagerly.map { delegate -> delegate.getValue() } internal abstract fun addDefinitionProperty(property: KProperty<*>, returnsSameObjectForAllRetrievals: Boolean) internal fun <TObject> handleCreation(definition: ObjectCreatingDefinition<TObject>, argument: Any?, creator: () -> TObject) = objectGraphDefinition.handleCreation(definition, argument, creator) }
mit
b61cae77d3e2278a47e3d7754a1906cf
47.820513
161
0.777836
5.216438
false
false
false
false
openMF/android-client
mifosng-android/src/main/java/com/mifos/mifosxdroid/online/clientlist/ClientListPresenter.kt
1
7353
package com.mifos.mifosxdroid.online.clientlist import com.mifos.api.datamanager.DataManagerClient import com.mifos.mifosxdroid.R import com.mifos.mifosxdroid.base.BasePresenter import com.mifos.objects.client.Client import com.mifos.objects.client.Page import com.mifos.utils.EspressoIdlingResource import rx.Subscriber import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers import rx.subscriptions.CompositeSubscription import java.util.* import javax.inject.Inject /** * Created by Rajan Maurya on 6/6/16. * This Presenter Holds the All Logic to request to DataManagerClient and DataManagerClient, Take * care of that From Where Data will come Database or REST API. */ class ClientListPresenter @Inject constructor(private val mDataManagerClient: DataManagerClient) : BasePresenter<ClientListMvpView?>() { private var mSubscriptions: CompositeSubscription? = null private var mDbClientList: List<Client> private var mSyncClientList: List<Client>? private val limit = 100 private var loadmore = false private var mRestApiClientSyncStatus = false private var mDatabaseClientSyncStatus = false override fun attachView(mvpView: ClientListMvpView?) { super.attachView(mvpView) mSubscriptions = CompositeSubscription() } override fun detachView() { super.detachView() mSubscriptions!!.unsubscribe() } /** * Loading Client List from Rest API and setting loadmore status * * @param loadmore Status, need ClientList page other then first. * @param offset Index from Where ClientList will be fetched. */ fun loadClients(loadmore: Boolean, offset: Int) { this.loadmore = loadmore loadClients(true, offset, limit) } /** * Showing Client List in View, If loadmore is true call showLoadMoreClients(...) and else * call showClientList(...). */ fun showClientList(clients: List<Client>?) { if (loadmore) { mvpView!!.showLoadMoreClients(clients) } else { mvpView!!.showClientList(clients) } } /** * This Method will called, when Parent (Fragment or Activity) will be true. * If Parent Fragment is true there is no need to fetch ClientList, Just show the Parent * (Fragment or Activity) ClientList in View * * @param clients List<Client></Client>> */ fun showParentClients(clients: List<Client>?) { mvpView!!.unregisterSwipeAndScrollListener() if (clients!!.size == 0) { mvpView!!.showEmptyClientList(R.string.client) } else { mRestApiClientSyncStatus = true mSyncClientList = clients setAlreadyClientSyncStatus() } } /** * Setting ClientSync Status True when mRestApiClientSyncStatus && mDatabaseClientSyncStatus * are true. */ fun setAlreadyClientSyncStatus() { if (mRestApiClientSyncStatus && mDatabaseClientSyncStatus) { showClientList(checkClientAlreadySyncedOrNot(mSyncClientList)) } } /** * This Method fetching Client List from Rest API. * * @param paged True Enabling the Pagination of the API * @param offset Value give from which position Fetch ClientList * @param limit Maximum size of the Center */ fun loadClients(paged: Boolean, offset: Int, limit: Int) { EspressoIdlingResource.increment() // App is busy until further notice. checkViewAttached() mvpView!!.showProgressbar(true) mSubscriptions!!.add(mDataManagerClient.getAllClients(paged, offset, limit) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(object : Subscriber<Page<Client?>?>() { override fun onCompleted() {} override fun onError(e: Throwable) { mvpView!!.showProgressbar(false) if (loadmore) { mvpView!!.showMessage(R.string.failed_to_load_client) } else { mvpView!!.showError() } EspressoIdlingResource.decrement() // App is idle. } override fun onNext(clientPage: Page<Client?>?) { mSyncClientList = clientPage!!.pageItems as List<Client>? if ((mSyncClientList as MutableList<Client>?)!!.size == 0 && !loadmore) { mvpView!!.showEmptyClientList(R.string.client) mvpView!!.unregisterSwipeAndScrollListener() } else if ((mSyncClientList as MutableList<Client>?)!!.size == 0 && loadmore) { mvpView!!.showMessage(R.string.no_more_clients_available) } else { mRestApiClientSyncStatus = true setAlreadyClientSyncStatus() } mvpView!!.showProgressbar(false) EspressoIdlingResource.decrement() // App is idle. } })) } /** * This Method Loading the Client From Database. It request Observable to DataManagerClient * and DataManagerClient Request to DatabaseHelperClient to load the Client List Page from the * Client_Table and As the Client List Page is loaded DataManagerClient gives the Client List * Page after getting response from DatabaseHelperClient */ fun loadDatabaseClients() { checkViewAttached() mSubscriptions!!.add(mDataManagerClient.allDatabaseClients .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(object : Subscriber<Page<Client?>?>() { override fun onCompleted() {} override fun onError(e: Throwable) { mvpView!!.showMessage(R.string.failed_to_load_db_clients) } override fun onNext(clientPage: Page<Client?>?) { mDatabaseClientSyncStatus = true mDbClientList = clientPage!!.pageItems as List<Client> setAlreadyClientSyncStatus() } }) ) } /** * This Method Filtering the Clients Loaded from Server is already sync or not. If yes the * put the client.setSync(true) and view will show those clients as sync already to user * * @param * @return Page<Client> </Client> */ fun checkClientAlreadySyncedOrNot(clients: List<Client>?): List<Client>? { if (mDbClientList.size != 0) { for (dbClient in mDbClientList) { for (syncClient in clients!!) { if (dbClient.id == syncClient.id) { syncClient.isSync = true break } } } } return clients } companion object { private val LOG_TAG = ClientListPresenter::class.java.simpleName } init { mDbClientList = ArrayList() mSyncClientList = ArrayList() } }
mpl-2.0
81e045a500d6e5b2778f36e1dcc520fb
38.117021
136
0.600707
5.185472
false
false
false
false
google/kiosk-app-reference-implementation
app/src/main/java/com/ape/apps/sample/baypilot/util/alarm/AlarmReceiver.kt
1
2315
/* * Copyright 2022 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 * * 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.ape.apps.sample.baypilot.util.alarm import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.util.Log import androidx.work.OneTimeWorkRequestBuilder import androidx.work.WorkManager import androidx.work.workDataOf import com.ape.apps.sample.baypilot.util.worker.DatabaseSyncWorker class AlarmReceiver : BroadcastReceiver() { companion object { private const val TAG = "BayPilotAlarmReceiver" const val EXTRA_REQUEST_CODE = "requestCode" const val EXTRA_DUE_DATE = "DUE_DATE" const val ACTION_LOCK = "LOCK" const val ACTION_NOTIFICATION = "NOTIFICATION" } override fun onReceive(context: Context, intent: Intent) { Log.d( TAG, "Lock onReceive() called with: action ${intent.action} with " + "${intent.getIntExtra(EXTRA_REQUEST_CODE, 0)}" ) val dueDate = intent.getStringExtra(EXTRA_DUE_DATE) val workAction = when (intent.action) { ACTION_LOCK -> DatabaseSyncWorker.ACTION_LOCK_DEVICE ACTION_NOTIFICATION -> DatabaseSyncWorker.ACTION_SEND_NOTIFICATION else -> return } startWorker(context, workAction, dueDate ?: "") } private fun startWorker(context: Context, workAction: String, dueDate: String) { val inputData = workDataOf( DatabaseSyncWorker.WORK_ACTION to workAction, DatabaseSyncWorker.ALARM_DUE_DATE to dueDate ) val uploadWorkRequest = OneTimeWorkRequestBuilder<DatabaseSyncWorker>().apply { setInputData(inputData) // setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST) }.build() WorkManager .getInstance(context) .enqueue(uploadWorkRequest) } }
apache-2.0
5ff6448877d0a84b601f80c48171ad65
31.166667
82
0.723542
4.247706
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/anki/MediaRegistration.kt
1
8711
/* * Copyright (c) 2021 Akshay Jadhav <[email protected]> * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package com.ichi2.anki import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.net.Uri import androidx.annotation.CheckResult import com.ichi2.anki.UIUtils.showThemedToast import com.ichi2.anki.multimediacard.fields.ImageField import com.ichi2.compat.CompatHelper import com.ichi2.libanki.exception.EmptyMediaException import com.ichi2.utils.ContentResolverUtil.getFileName import com.ichi2.utils.FileUtil.getFileNameAndExtension import timber.log.Timber import java.io.* /** * RegisterMediaForWebView is used for registering media in temp path, * this class is required in summer note class for paste image event and in visual editor activity for importing media, * (extracted code to avoid duplication of code). */ class MediaRegistration(private val context: Context) { // Use the same HTML if the same image is pasted multiple times. private val mPastedImageCache = HashMap<String, String?>() /** * Loads an image into the collection.media directory and returns a HTML reference * @param uri The uri of the image to load * @return HTML referring to the loaded image */ @Throws(IOException::class) fun loadImageIntoCollection(uri: Uri): String? { val fileName: String val filename = getFileName(context.contentResolver, uri) val fd = openInputStreamWithURI(uri) val fileNameAndExtension = getFileNameAndExtension(filename) fileName = if (checkFilename(fileNameAndExtension!!)) { "${fileNameAndExtension.key}-name" } else { fileNameAndExtension.key } var clipCopy: File var bytesWritten: Long openInputStreamWithURI(uri).use { copyFd -> // no conversion to jpg in cases of gif and jpg and if png image with alpha channel if (shouldConvertToJPG(fileNameAndExtension.value, copyFd)) { clipCopy = File.createTempFile(fileName, ".jpg") bytesWritten = CompatHelper.compat.copyFile(fd, clipCopy.absolutePath) // return null if jpg conversion false. if (!convertToJPG(clipCopy)) { return null } } else { clipCopy = File.createTempFile(fileName, fileNameAndExtension.value) bytesWritten = CompatHelper.compat.copyFile(fd, clipCopy.absolutePath) } } val tempFilePath = clipCopy.absolutePath // register media for webView if (!registerMediaForWebView(tempFilePath)) { return null } Timber.d("File was %d bytes", bytesWritten) if (bytesWritten > MEDIA_MAX_SIZE) { Timber.w("File was too large: %d bytes", bytesWritten) showThemedToast(context, context.getString(R.string.note_editor_paste_too_large), false) File(tempFilePath).delete() return null } val field = ImageField() field.hasTemporaryMedia = true field.extraImagePathRef = tempFilePath return field.formattedValue } @Throws(FileNotFoundException::class) private fun openInputStreamWithURI(uri: Uri): InputStream { return context.contentResolver.openInputStream(uri)!! } private fun convertToJPG(file: File): Boolean { val bm = BitmapFactory.decodeFile(file.absolutePath) try { FileOutputStream(file.absolutePath).use { outStream -> bm.compress(Bitmap.CompressFormat.JPEG, 100, outStream) outStream.flush() } } catch (e: IOException) { Timber.w("MediaRegistration : Unable to convert file to png format") CrashReportService.sendExceptionReport(e, "Unable to convert file to png format") showThemedToast(context, context.resources.getString(R.string.multimedia_editor_png_paste_error, e.message), true) return false } return true // successful conversion to jpg. } private fun shouldConvertToJPG(fileNameExtension: String, fileStream: InputStream): Boolean { if (".jpg" == fileNameExtension) { return false // we are already a jpg, no conversion } if (".gif" == fileNameExtension) { return false // gifs may have animation, conversion would ruin them } if (".png" == fileNameExtension && doesInputStreamContainTransparency(fileStream)) { return false // pngs with transparency would be ruined by conversion } return true } private fun checkFilename(fileNameAndExtension: Map.Entry<String, String>): Boolean { return fileNameAndExtension.key.length <= 3 } fun onImagePaste(uri: Uri): String? { return try { // check if cache already holds registered file or not if (!mPastedImageCache.containsKey(uri.toString())) { mPastedImageCache[uri.toString()] = loadImageIntoCollection(uri) } mPastedImageCache[uri.toString()] } catch (ex: NullPointerException) { // Tested under FB Messenger and GMail, both apps do nothing if this occurs. // This typically works if the user copies again - don't know the exact cause // java.lang.SecurityException: Permission Denial: opening provider // org.chromium.chrome.browser.util.ChromeFileProvider from ProcessRecord{80125c 11262:com.ichi2.anki/u0a455} // (pid=11262, uid=10455) that is not exported from UID 10057 Timber.w(ex, "Failed to paste image") null } catch (ex: SecurityException) { Timber.w(ex, "Failed to paste image") null } catch (e: Exception) { // NOTE: This is happy path coding which works on Android 9. CrashReportService.sendExceptionReport("File is invalid issue:8880", "RegisterMediaForWebView:onImagePaste URI of file:$uri") Timber.w(e, "Failed to paste image") showThemedToast(context, context.getString(R.string.multimedia_editor_something_wrong), false) null } } @CheckResult fun registerMediaForWebView(imagePath: String?): Boolean { if (imagePath == null) { // Nothing to register - continue with execution. return true } Timber.i("Adding media to collection: %s", imagePath) val f = File(imagePath) return try { CollectionHelper.instance.getCol(context)!!.media.addFile(f) true } catch (e: IOException) { Timber.w(e, "Failed to add file") false } catch (e: EmptyMediaException) { Timber.w(e, "Failed to add file") false } } companion object { private const val MEDIA_MAX_SIZE = 5 * 1000 * 1000 private const val COLOR_GREY = 0 const val COLOR_TRUE = 2 private const val COLOR_INDEX = 3 private const val COLOR_GREY_ALPHA = 4 private const val COLOR_TRUE_ALPHA = 6 /** * given an inputStream of a file, * returns true if found that it has transparency (in its header) * code: https://stackoverflow.com/a/31311718/14148406 */ private fun doesInputStreamContainTransparency(inputStream: InputStream): Boolean { try { // skip: png signature,header chunk declaration,width,height,bitDepth : inputStream.skip((12 + 4 + 4 + 4 + 1).toLong()) when (inputStream.read()) { COLOR_GREY_ALPHA, COLOR_TRUE_ALPHA -> return true COLOR_INDEX, COLOR_GREY, COLOR_TRUE -> return false } return true } catch (e: Exception) { Timber.w(e, "Failed to check transparency of inputStream") } return false } } }
gpl-3.0
476e9545c2d78a78aef33bb92a3b9402
41.492683
137
0.639307
4.665774
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/anki/dialogs/ConfirmationDialog.kt
1
3008
/**************************************************************************************** * Copyright (c) 2015 Timothy Rae <[email protected]> * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 3 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************************/ package com.ichi2.anki.dialogs import android.os.Bundle import androidx.fragment.app.DialogFragment import com.afollestad.materialdialogs.MaterialDialog import com.ichi2.anki.R /** * This is a reusable convenience class which makes it easy to show a confirmation dialog as a DialogFragment. * Create a new instance, call setArgs(...), setConfirm(), and setCancel() then show it via the fragment manager as usual. */ class ConfirmationDialog : DialogFragment() { private var mConfirm = Runnable {} // Do nothing by default private var mCancel = Runnable {} // Do nothing by default fun setArgs(message: String?) { setArgs("", message) } fun setArgs(title: String?, message: String?) { val args = Bundle() args.putString("message", message) args.putString("title", title) arguments = args } fun setConfirm(confirm: Runnable) { mConfirm = confirm } fun setCancel(cancel: Runnable) { mCancel = cancel } override fun onCreateDialog(savedInstanceState: Bundle?): MaterialDialog { super.onCreate(savedInstanceState) val res = requireActivity().resources val title = requireArguments().getString("title") return MaterialDialog(requireActivity()).show { title(text = (if ("" == title) res.getString(R.string.app_name) else title)!!) message(text = requireArguments().getString("message")!!) positiveButton(R.string.dialog_ok) { mConfirm.run() } negativeButton(R.string.dialog_cancel) { mCancel.run() } } } }
gpl-3.0
b698ae398962ee942d38e5e295705c15
45.276923
122
0.530585
5.469091
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/anki/noteeditor/Toolbar.kt
1
16169
/* * 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.anki.noteeditor import android.annotation.SuppressLint import android.app.Activity import android.content.Context import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.drawable.BitmapDrawable import android.graphics.drawable.Drawable import android.util.AttributeSet import android.util.DisplayMetrics import android.view.* import android.widget.FrameLayout import android.widget.LinearLayout import androidx.annotation.ColorInt import androidx.annotation.DrawableRes import androidx.annotation.IdRes import androidx.appcompat.widget.AppCompatImageButton import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat import com.afollestad.materialdialogs.MaterialDialog import com.afollestad.materialdialogs.list.listItems import com.ichi2.anki.AnkiDroidApp import com.ichi2.anki.NoteEditor import com.ichi2.anki.R import com.ichi2.anki.UIUtils.convertDpToPixel import com.ichi2.libanki.Utils import com.ichi2.utils.ViewGroupUtils import com.ichi2.utils.ViewGroupUtils.getAllChildrenRecursive import timber.log.Timber import java.util.* import kotlin.math.ceil /** * Handles the toolbar inside [com.ichi2.anki.NoteEditor] * * * Handles a number of buttons which arbitrarily format selected text, or insert an item at the cursor * * Text is formatted as HTML * * if a tag with an empty body is inserted, we want the cursor in the middle: `<b>|</b>` * * Handles the "default" buttons: [setupDefaultButtons], [displayFontSizeDialog], [displayInsertHeadingDialog] * * Handles custom buttons with arbitrary prefixes and suffixes: [mCustomButtons] * * Handles generating the 'icon' for these custom buttons: [createDrawableForString] * * Handles CTRL+ the tag of the button: [onKeyUp]. Allows for Ctrl+1..9 shortcuts * * Handles adding a dynamic number of buttons and aligning them into rows: [insertItem] * * And handles whether these should be stacked or scrollable: [shouldScrollToolbar] */ class Toolbar : FrameLayout { var formatListener: TextFormatListener? = null private val mToolbar: LinearLayout private val mToolbarLayout: LinearLayout /** A list of buttons, typically user-defined which modify text + selection */ private val mCustomButtons: MutableList<View> = ArrayList() private val mRows: MutableList<LinearLayout> = ArrayList() /** * TODO HACK until API 21 - can be removed once tested. * * inside NoteEditor: use [insertItem] instead of accessing this * and remove [R.id.note_editor_toolbar_button_cloze] from [R.layout.note_editor_toolbar] */ var clozeIcon: View? = null private set private var mStringPaint: Paint? = null constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) init { LayoutInflater.from(context).inflate(R.layout.note_editor_toolbar, this, true) mStringPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { textSize = convertDpToPixel(24F, context) color = Color.BLACK textAlign = Paint.Align.CENTER } mToolbar = findViewById(R.id.editor_toolbar_internal) mToolbarLayout = findViewById(R.id.toolbar_layout) clozeIcon = findViewById(R.id.note_editor_toolbar_button_cloze) setupDefaultButtons() } /** Sets up the "standard" buttons to insert bold, italics etc... */ private fun setupDefaultButtons() { // sets up a button click to wrap text with the prefix/suffix. So "aa" becomes "<b>aa</b>" fun setupButtonWrappingText(@IdRes id: Int, prefix: String, suffix: String) = findViewById<View>(id).setOnClickListener { onFormat(TextWrapper(prefix, suffix)) } setupButtonWrappingText(R.id.note_editor_toolbar_button_bold, "<b>", "</b>") setupButtonWrappingText(R.id.note_editor_toolbar_button_italic, "<em>", "</em>") setupButtonWrappingText(R.id.note_editor_toolbar_button_underline, "<u>", "</u>") setupButtonWrappingText(R.id.note_editor_toolbar_button_insert_mathjax, "\\(", "\\)") setupButtonWrappingText(R.id.note_editor_toolbar_button_horizontal_rule, "<hr>", "") findViewById<View>(R.id.note_editor_toolbar_button_font_size).setOnClickListener { displayFontSizeDialog() } findViewById<View>(R.id.note_editor_toolbar_button_title).setOnClickListener { displayInsertHeadingDialog() } } /** * If a button is assigned a tag, Ctrl+Tag will invoke the button * Typically used for Ctrl + 1..9 with custom buttons */ override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean { // hack to see if only CTRL is pressed - might not be perfect. // I'll avoid checking "function" here as it may be required to press Ctrl if (!event.isCtrlPressed || event.isAltPressed || event.isShiftPressed || event.isMetaPressed) { return false } val c: Char = try { event.getUnicodeChar(0).toChar() } catch (e: Exception) { Timber.w(e) return false } if (c == '\u0000') { return false } val expected = c.toString() for (v in getAllChildrenRecursive(this)) { if (Utils.equals(expected, v.tag)) { Timber.i("Handling Ctrl + %s", c) v.performClick() return true } } return super.onKeyUp(keyCode, event) } fun insertItem(@IdRes id: Int, @DrawableRes drawable: Int, runnable: Runnable): AppCompatImageButton { // we use the light theme here to ensure the tint is black on both // A null theme can be passed after colorControlNormal is defined (API 25) val themeContext: Context = ContextThemeWrapper(context, R.style.Theme_Light_Compat) val d = VectorDrawableCompat.create(context.resources, drawable, themeContext.theme) return insertItem(id, d, runnable) } fun insertItem(id: Int, drawable: Drawable?, formatter: TextFormatter): View { return insertItem(id, drawable, Runnable { onFormat(formatter) }) } fun insertItem(@IdRes id: Int, drawable: Drawable?, runnable: Runnable): AppCompatImageButton { val context = context val button = AppCompatImageButton(context) button.id = id button.background = drawable /* Style didn't work int buttonStyle = R.style.note_editor_toolbar_button; ContextThemeWrapper context = new ContextThemeWrapper(getContext(), buttonStyle); AppCompatImageButton button = new AppCompatImageButton(context, null, buttonStyle); */ // apply style val margin = convertDpToPixel(8F, context).toInt() val params = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) params.gravity = Gravity.CENTER params.setMargins(margin, margin / 2, margin, margin / 2) button.layoutParams = params val twoDp = ceil((2 / context.resources.displayMetrics.density).toDouble()).toInt() button.setPadding(twoDp, twoDp, twoDp, twoDp) // end apply style val shouldScroll = AnkiDroidApp.getSharedPrefs(AnkiDroidApp.instance) .getBoolean(NoteEditor.PREF_NOTE_EDITOR_SCROLL_TOOLBAR, true) if (shouldScroll) { mToolbar.addView(button, mToolbar.childCount) } else { addViewToToolbar(button) } mCustomButtons.add(button) button.setOnClickListener { runnable.run() } // Hack - items are truncated from the scrollview val v = findViewById<View>(R.id.toolbar_layout) val expectedWidth = getVisibleItemCount(mToolbar) * convertDpToPixel(48F, context) val width = screenWidth val p = LayoutParams(v.layoutParams) p.gravity = Gravity.CENTER_VERTICAL or if (expectedWidth > width) Gravity.START else Gravity.CENTER_HORIZONTAL v.layoutParams = p return button } @Suppress("DEPRECATION") private val screenWidth: Int get() { val displayMetrics = DisplayMetrics() (context as Activity).windowManager .defaultDisplay .getMetrics(displayMetrics) return displayMetrics.widthPixels } /** Clears all items added by [insertItem] */ fun clearCustomItems() { for (v in mCustomButtons) { (v.parent as ViewGroup).removeView(v) } mCustomButtons.clear() } /** * Displays a dialog which allows the HTML size codes to be inserted around text (xx-small to xx-large) * * @see [R.array.html_size_codes] */ @SuppressLint("CheckResult") private fun displayFontSizeDialog() { val results = resources.getStringArray(R.array.html_size_codes) // Might be better to add this as a fragment - let's see. MaterialDialog(context).show { listItems(R.array.html_size_code_labels) { _: MaterialDialog, index: Int, _: CharSequence -> val formatter = TextWrapper( prefix = "<span style=\"font-size:${results[index]}\">", suffix = "</span>" ) onFormat(formatter) } title(R.string.menu_font_size) } } /** * Displays a dialog which allows `<h1>` to `<h6>` to be inserted */ @SuppressLint("CheckResult") private fun displayInsertHeadingDialog() { MaterialDialog(context).show { listItems(items = listOf("h1", "h2", "h3", "h4", "h5")) { _: MaterialDialog, _: Int, charSequence: CharSequence -> val formatter = TextWrapper(prefix = "<$charSequence>", suffix = "</$charSequence>") onFormat(formatter) } title(R.string.insert_heading) } } /** Given a string [text], generates a [Drawable] which can be used as a button icon */ fun createDrawableForString(text: String): Drawable { val baseline = -mStringPaint!!.ascent() val size = (baseline + mStringPaint!!.descent() + 0.5f).toInt() val image = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888) val canvas = Canvas(image) canvas.drawText(text, size / 2f, baseline, mStringPaint!!) return BitmapDrawable(resources, image) } /** Returns the number of top-level children of [layout] that are visible */ private fun getVisibleItemCount(layout: LinearLayout): Int = ViewGroupUtils.getAllChildren(layout).count { it.visibility == VISIBLE } private fun addViewToToolbar(button: AppCompatImageButton) { val expectedWidth = getVisibleItemCount(mToolbar) * convertDpToPixel(48F, context) val width = screenWidth if (expectedWidth <= width) { mToolbar.addView(button, mToolbar.childCount) return } var spaceLeft = false if (mRows.isNotEmpty()) { val row = mRows.last() val expectedRowWidth = getVisibleItemCount(row) * convertDpToPixel(48F, context) if (expectedRowWidth <= width) { row.addView(button, row.childCount) spaceLeft = true } } if (!spaceLeft) { val row = LinearLayout(context) val params = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT) row.layoutParams = params row.orientation = LinearLayout.HORIZONTAL row.addView(button) mRows.add(row) mToolbarLayout.addView(mRows.last()) } } /** * If a [formatListener] is attached, supply it with the provided [TextFormatter] so that * the current selection of text can be formatted, and the selection can be changed. * * The listener determines the appropriate selection of text to be formatted and handles * selection changes */ fun onFormat(formatter: TextFormatter) { formatListener?.performFormat(formatter) } fun setIconColor(@ColorInt color: Int) { ViewGroupUtils.getAllChildren(mToolbar) .forEach { (it as AppCompatImageButton).setColorFilter(color) } mStringPaint!!.color = color } /** @see performFormat */ fun interface TextFormatListener { /** * A function which accepts a [TextFormatter] and performs some formatting, handling selection changes * In the note editor: this takes the [TextFormatter], determines the correct EditText and selection, * applies the [TextFormatter] to the selection, and ensures the selection is valid * * We use a [TextFormatter] to ensure that the selection is correct after the modification */ fun performFormat(formatter: TextFormatter) } /** * A function which takes and returns a [StringFormat] structure * Providing a method of inserting text and knowledge of how the selection should change */ fun interface TextFormatter { /** * A function which takes and returns a [StringFormat] structure * Providing a method of inserting text and knowledge of how the selection should change */ fun format(s: String): StringFormat } /** * A [TextFormatter] which wraps the selected string with [prefix] and [suffix] * If there's no selected, the cursor is in the middle of the prefix and suffix * If there is text selected, the whole string is selected */ class TextWrapper(private val prefix: String, private val suffix: String) : TextFormatter { override fun format(s: String): StringFormat { return StringFormat(result = prefix + s + suffix).apply { if (s.isEmpty()) { // if there's no selection: place the cursor between the start and end tag selectionStart = prefix.length selectionEnd = prefix.length } else { // otherwise, wrap the newly formatted context selectionStart = 0 selectionEnd = result.length } } } } /** * Defines a string insertion, and the selection which should occur once the string is inserted * * @param result The string which should be inserted * * @param selectionStart * The number of characters inside [result] where the selection should start * For example: in {{c1::}}, we should set this to 6, to start after the :: * * @param selectionEnd * The number of character inside [result] where the selection should end * If the input was empty, we typically want this between the start and end tags * If not, at the end of the string */ data class StringFormat( var result: String = "", var selectionStart: Int = 0, var selectionEnd: Int = 0 ) }
gpl-3.0
4eb3be98ec7f42c0a05a387fc4fa8f44
42.23262
143
0.659101
4.585649
false
false
false
false
ebraminio/DroidPersianCalendar
PersianCalendar/src/main/java/com/byagowi/persiancalendar/ui/preferences/locationathan/location/LocationAdapter.kt
1
2064
package com.byagowi.persiancalendar.ui.preferences.locationathan.location import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.byagowi.persiancalendar.* import com.byagowi.persiancalendar.databinding.ListItemCityNameBinding import com.byagowi.persiancalendar.entities.CityItem import com.byagowi.persiancalendar.utils.language import com.byagowi.persiancalendar.utils.layoutInflater class LocationAdapter( private val locationPreferenceDialog: LocationPreferenceDialog, private val cities: List<CityItem> ) : RecyclerView.Adapter<LocationAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ViewHolder( ListItemCityNameBinding.inflate(parent.context.layoutInflater, parent, false) ) override fun onBindViewHolder(holder: ViewHolder, position: Int) = holder.bind(cities[position]) override fun getItemCount(): Int = cities.size inner class ViewHolder(private val binding: ListItemCityNameBinding) : RecyclerView.ViewHolder(binding.root), View.OnClickListener { fun bind(cityEntity: CityItem) = binding.let { it.root.setOnClickListener(this) when (language) { LANG_EN_IR, LANG_EN_US, LANG_JA -> { it.city.text = cityEntity.en it.country.text = cityEntity.countryEn } LANG_CKB -> { it.city.text = cityEntity.ckb it.country.text = cityEntity.countryCkb } LANG_AR -> { it.city.text = cityEntity.ar it.country.text = cityEntity.countryAr } else -> { it.city.text = cityEntity.fa it.country.text = cityEntity.countryFa } } Unit } override fun onClick(view: View) = locationPreferenceDialog.selectItem(cities[adapterPosition].key) } }
gpl-3.0
79e2123642526379a5b49ace3021d84f
36.527273
85
0.640988
4.8
false
false
false
false
googlecodelabs/maps-platform-101-android
solution/app/src/main/java/com/google/codelabs/buildyourfirstmap/MarkerInfoWindowAdapter.kt
2
1751
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.codelabs.buildyourfirstmap import android.content.Context import android.view.LayoutInflater import android.view.View import android.widget.TextView import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.model.Marker import com.google.codelabs.buildyourfirstmap.place.Place class MarkerInfoWindowAdapter(private val context: Context) : GoogleMap.InfoWindowAdapter { override fun getInfoContents(marker: Marker): View? { // 1. Get tag val place = marker.tag as? Place ?: return null // 2. Inflate view and set title, address and rating val view = LayoutInflater.from(context).inflate(R.layout.marker_info_contents, null) view.findViewById<TextView>(R.id.text_view_title).text = place.name view.findViewById<TextView>(R.id.text_view_address).text = place.address view.findViewById<TextView>(R.id.text_view_rating).text = "Rating: %.2f".format(place.rating) return view } override fun getInfoWindow(marker: Marker): View? { // Return null to indicate that the default window (white bubble) should be used return null } }
apache-2.0
be936663c4dc7417cf35c1edc93c74b1
39.744186
101
0.733866
4.091121
false
false
false
false
lure0xaos/CoffeeTime
app/src/main/kotlin/gargoyle/ct/ui/impl/CTBlockerContent.kt
1
4731
package gargoyle.ct.ui.impl import gargoyle.ct.preferences.CTPreferences import gargoyle.ct.task.CTTaskUpdatable import gargoyle.ct.task.impl.CTTask import gargoyle.ct.ui.CTBlockerTextProvider import gargoyle.ct.ui.CTInformer import gargoyle.ct.ui.CTWindow import gargoyle.ct.ui.impl.control.CTControlWindowImpl import gargoyle.ct.ui.util.CTDragHelper import gargoyle.ct.util.log.Log import java.awt.BorderLayout import java.awt.Color import java.awt.Component import java.awt.Font import java.awt.event.ComponentAdapter import java.awt.event.ComponentEvent import java.io.ObjectInputStream import javax.swing.BorderFactory import javax.swing.JLabel import javax.swing.JPanel import javax.swing.SwingConstants import kotlin.math.min class CTBlockerContent(private val preferences: CTPreferences, big: Boolean) : JPanel(), CTTaskUpdatable, CTWindow, CTInformer { private val big: Boolean private val lblInfo: JLabel private val lblMain: JLabel private var textProvider: CTBlockerTextProvider private var draggable = false init { textProvider = CTBlockerTextProviderImpl(preferences) this.big = big layout = BorderLayout() lblMain = createMainLabel() lblMain.addComponentListener(ContentComponentListener(this, lblMain)) add(lblMain, BorderLayout.CENTER) lblInfo = createInfoLabel() lblInfo.addComponentListener(ContentComponentListener(this, lblInfo)) add(lblInfo, BorderLayout.SOUTH) } private fun createInfoLabel(): JLabel { val label = JLabel() label.isOpaque = true label.background = Color.BLACK label.foreground = Color.GRAY label.alignmentX = ALIGNMENT_RIGHT label.border = BorderFactory.createEmptyBorder( GAP, GAP, GAP, GAP ) label.horizontalAlignment = SwingConstants.RIGHT adjust(this, label) return label } private fun createMainLabel(): JLabel { val label = JLabel() label.isOpaque = true label.background = Color.BLACK label.foreground = Color.WHITE label.alignmentX = ALIGNMENT_CENTER label.horizontalAlignment = SwingConstants.CENTER adjust(this, label) return label } override fun destroy() { isVisible = false } override fun showMe() { isVisible = true if (!draggable) { draggable = true CTDragHelper.makeDraggable(this, CTControlWindowImpl.SNAP) } } override fun doUpdate(task: CTTask, currentMillis: Long) { lblInfo.text = textProvider.getInfoText(currentMillis) val visible = textProvider.isVisible(task, currentMillis) isVisible = visible if (visible) { showText(textProvider.getColor(task, currentMillis), textProvider.getBlockerText(task, currentMillis, big)) } } override fun showText(foreground: Color, text: String) { setForeground(foreground) lblMain.foreground = foreground lblMain.text = text adjust(this, lblMain) if (isVisible) { Log.debug(text) repaint() } else { showMe() } } private fun readObject(`in`: ObjectInputStream) { `in`.defaultReadObject() textProvider = CTBlockerTextProviderImpl(preferences) } override fun setBackground(bg: Color) { // super.setBackground(color); if (isDisplayable) lblMain.background = bg } private class ContentComponentListener(private val container: CTBlockerContent, private val label: JLabel) : ComponentAdapter() { override fun componentResized(e: ComponentEvent) { adjust(container, label) } override fun componentShown(e: ComponentEvent) { adjust(container, label) } } companion object { private const val ALIGNMENT_CENTER = 0.5f private const val ALIGNMENT_RIGHT = 1.0f private const val FONT_SIZE = 12 private const val GAP = 10 private const val MARGIN = 1.1 fun adjust(container: Component, label: JLabel) { if (!container.isVisible || container.height == 0) return val font = Font(Font.DIALOG, Font.PLAIN, FONT_SIZE) label.font = font label.font = Font( Font.DIALOG, Font.PLAIN, min( (FONT_SIZE * label.width / (MARGIN * label.getFontMetrics(font).stringWidth(label.text))).toInt(), label.height ) ) } } }
unlicense
658b8a97ca5d012652016da44ee02479
30.125
119
0.639188
4.638235
false
false
false
false
wordpress-mobile/WordPress-Stores-Android
example/src/main/java/org/wordpress/android/fluxc/example/ui/customer/search/WooCustomersSearchAdapter.kt
2
4133
package org.wordpress.android.fluxc.example.ui.customer.search import android.annotation.SuppressLint import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.annotation.LayoutRes import androidx.paging.PagedListAdapter import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.ViewHolder import kotlinx.android.synthetic.main.list_item_woo_customer.view.* import org.wordpress.android.fluxc.example.MainExampleActivity import org.wordpress.android.fluxc.example.R import org.wordpress.android.fluxc.example.ui.customer.search.CustomerListItemType.CustomerItem import org.wordpress.android.fluxc.example.ui.customer.search.CustomerListItemType.LoadingItem import javax.inject.Inject private const val VIEW_TYPE_ITEM = 0 private const val VIEW_TYPE_LOADING = 1 class WooCustomersSearchAdapter @Inject constructor( context: MainExampleActivity ) : PagedListAdapter<CustomerListItemType, ViewHolder>(customerListDiffItemCallback) { private val layoutInflater = LayoutInflater.from(context) @Suppress("UseCheckOrError") override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return when (viewType) { VIEW_TYPE_ITEM -> CustomerItemViewHolder(inflateView(R.layout.list_item_woo_customer, parent)) VIEW_TYPE_LOADING -> LoadingViewHolder(inflateView(R.layout.list_item_skeleton, parent)) else -> throw IllegalStateException("View type $viewType is not supported") } } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val item = getItem(position) if (holder is CustomerItemViewHolder) { holder.onBind((item as CustomerItem)) } } private fun inflateView(@LayoutRes layoutId: Int, parent: ViewGroup) = layoutInflater.inflate( layoutId, parent, false ) override fun getItemViewType(position: Int): Int { return when (getItem(position)) { is CustomerItem -> VIEW_TYPE_ITEM else -> VIEW_TYPE_LOADING } } private class LoadingViewHolder(view: View) : RecyclerView.ViewHolder(view) private class CustomerItemViewHolder(val view: View) : RecyclerView.ViewHolder(view) { @SuppressLint("SetTextI18n") fun onBind(item: CustomerItem) { with(view) { tvCustomerRemoteId.text = "ID: ${item.remoteCustomerId}" tvCustomerName.text = "${item.firstName} ${item.lastName}" tvCustomerEmail.text = item.email tvCustomerRole.text = item.role } } } } private val customerListDiffItemCallback = object : DiffUtil.ItemCallback<CustomerListItemType>() { override fun areItemsTheSame(oldItem: CustomerListItemType, newItem: CustomerListItemType): Boolean { if (oldItem is LoadingItem && newItem is LoadingItem) { return oldItem.remoteCustomerId == newItem.remoteCustomerId } return if (oldItem is CustomerItem && newItem is CustomerItem) { oldItem.remoteCustomerId == newItem.remoteCustomerId } else { false } } override fun areContentsTheSame(oldItem: CustomerListItemType, newItem: CustomerListItemType): Boolean { if (oldItem is LoadingItem && newItem is LoadingItem) return true return if (oldItem is CustomerItem && newItem is CustomerItem) { oldItem.firstName == newItem.firstName && oldItem.lastName == newItem.lastName && oldItem.email == newItem.email && oldItem.role == newItem.role } else { false } } } sealed class CustomerListItemType { data class LoadingItem(val remoteCustomerId: Long) : CustomerListItemType() data class CustomerItem( val remoteCustomerId: Long, val firstName: String?, val lastName: String, val email: String, val role: String ) : CustomerListItemType() }
gpl-2.0
a4c006b09fbae2ca27c19e6910757aee
38.740385
108
0.691991
4.772517
false
false
false
false
jonnyzzz/spring_io_2017
src/v7-guava-collision/v7-core/src/main/java/loader_plugins.kt
2
1170
package plugin.extensions.core import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.event.ContextStartedEvent import org.springframework.context.event.EventListener import org.springframework.stereotype.Component import plugin.extensions.Extension @Component class PluginLoader( val detector: PluginDetector, val registry: ExtensionRegistry ) { init { println("I'm plugin loader") } @EventListener fun onContextStarted(e: ContextStartedEvent) { println("PluginLoader: loading plugins...") val packages = detector.detectPlugins().map { "plugin.extensions.$it" } val parentContext = e.applicationContext packages.forEach { val context = AnnotationConfigApplicationContext() context.parent = parentContext context.displayName = "plugin: $it" context.scan(it) context.refresh() context.getBeansOfType(Extension::class.java) .values .forEach { registry.register(it) } } } } @Component class PluginDetector { fun detectPlugins() = listOf("plugin_1", "plugin_2") }
apache-2.0
486a3422af5a2ede1e759d0d7730a841
25.590909
80
0.708547
4.736842
false
false
false
false
timusus/Shuttle
app/src/main/java/com/simplecity/amp_library/ui/dialog/FileInfoDialog.kt
1
6964
package com.simplecity.amp_library.ui.dialog import android.annotation.SuppressLint import android.app.Dialog import android.content.Context import android.os.Bundle import android.support.v4.app.DialogFragment import android.support.v4.app.FragmentManager import android.view.LayoutInflater import android.view.View import android.widget.TextView import com.afollestad.materialdialogs.MaterialDialog import com.simplecity.amp_library.R import com.simplecity.amp_library.R.id.album import com.simplecity.amp_library.R.id.artist import com.simplecity.amp_library.model.FileObject import com.simplecity.amp_library.utils.FileHelper class FileInfoDialog : DialogFragment() { private var fileObject: FileObject? = null override fun onAttach(context: Context?) { super.onAttach(context) fileObject = arguments!!.getSerializable(ARG_FILE_OBJECT) as FileObject } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { @SuppressLint("InflateParams") val view = (context!!.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater).inflate(R.layout.dialog_song_info, null) val titleView = view.findViewById<View>(R.id.title) val titleKey = titleView.findViewById<TextView>(R.id.key) titleKey.setText(R.string.song_title) val titleValue = titleView.findViewById<TextView>(R.id.value) titleValue.text = fileObject!!.tagInfo.trackName val trackNumberView = view.findViewById<View>(R.id.track_number) val trackNumberKey = trackNumberView.findViewById<TextView>(R.id.key) trackNumberKey.setText(R.string.track_number) val trackNumberValue = trackNumberView.findViewById<TextView>(R.id.value) if (fileObject!!.tagInfo.trackTotal != 0) { trackNumberValue.text = String.format(context!!.getString(R.string.track_count), fileObject!!.tagInfo.trackNumber.toString(), fileObject!!.tagInfo.trackTotal.toString()) } else { trackNumberValue.text = fileObject!!.tagInfo.trackNumber.toString() } val artistView = view.findViewById<View>(artist) val artistKey = artistView.findViewById<TextView>(R.id.key) artistKey.setText(R.string.artist_title) val artistValue = artistView.findViewById<TextView>(R.id.value) artistValue.text = fileObject!!.tagInfo.artistName val albumView = view.findViewById<View>(album) val albumKey = albumView.findViewById<TextView>(R.id.key) albumKey.setText(R.string.album_title) val albumValue = albumView.findViewById<TextView>(R.id.value) albumValue.text = fileObject!!.tagInfo.albumName val genreView = view.findViewById<View>(R.id.genre) val genreKey = genreView.findViewById<TextView>(R.id.key) genreKey.setText(R.string.genre_title) val genreValue = genreView.findViewById<TextView>(R.id.value) genreValue.text = fileObject!!.tagInfo.genre val albumArtistView = view.findViewById<View>(R.id.album_artist) val albumArtistKey = albumArtistView.findViewById<TextView>(R.id.key) albumArtistKey.setText(R.string.album_artist_title) val albumArtistValue = albumArtistView.findViewById<TextView>(R.id.value) albumArtistValue.text = fileObject!!.tagInfo.albumArtistName val durationView = view.findViewById<View>(R.id.duration) val durationKey = durationView.findViewById<TextView>(R.id.key) durationKey.setText(R.string.sort_song_duration) val durationValue = durationView.findViewById<TextView>(R.id.value) durationValue.text = fileObject!!.getTimeString(context) val pathView = view.findViewById<View>(R.id.path) val pathKey = pathView.findViewById<TextView>(R.id.key) pathKey.setText(R.string.song_info_path) val pathValue = pathView.findViewById<TextView>(R.id.value) pathValue.text = fileObject!!.path + "/" + fileObject!!.name + "." + fileObject!!.extension val discNumberView = view.findViewById<View>(R.id.disc_number) val discNumberKey = discNumberView.findViewById<TextView>(R.id.key) discNumberKey.setText(R.string.disc_number) val discNumberValue = discNumberView.findViewById<TextView>(R.id.value) if (fileObject!!.tagInfo.discTotal != 0) { discNumberValue.text = String.format(context!!.getString(R.string.track_count), fileObject!!.tagInfo.discNumber.toString(), fileObject!!.tagInfo.discTotal.toString()) } else { discNumberValue.text = fileObject!!.tagInfo.discNumber.toString() } val fileSizeView = view.findViewById<View>(R.id.file_size) val fileSizeKey = fileSizeView.findViewById<TextView>(R.id.key) fileSizeKey.setText(R.string.song_info_file_size) val fileSizeValue = fileSizeView.findViewById<TextView>(R.id.value) fileSizeValue.text = FileHelper.getHumanReadableSize(fileObject!!.size) val formatView = view.findViewById<View>(R.id.format) val formatKey = formatView.findViewById<TextView>(R.id.key) formatKey.setText(R.string.song_info_format) val formatValue = formatView.findViewById<TextView>(R.id.value) formatValue.text = fileObject!!.tagInfo.format val bitrateView = view.findViewById<View>(R.id.bitrate) val bitrateKey = bitrateView.findViewById<TextView>(R.id.key) bitrateKey.setText(R.string.song_info_bitrate) val bitrateValue = bitrateView.findViewById<TextView>(R.id.value) bitrateValue.text = fileObject!!.tagInfo.bitrate + context!!.getString(R.string.song_info_bitrate_suffix) val samplingRateView = view.findViewById<View>(R.id.sample_rate) val samplingRateKey = samplingRateView.findViewById<TextView>(R.id.key) samplingRateKey.setText(R.string.song_info_sample_Rate) val samplingRateValue = samplingRateView.findViewById<TextView>(R.id.value) samplingRateValue.text = (fileObject!!.tagInfo.sampleRate / 1000).toString() + context!!.getString(R.string.song_info_sample_rate_suffix) val playCountView = view.findViewById<View>(R.id.play_count) playCountView.visibility = View.GONE return MaterialDialog.Builder(context!!) .title(context!!.getString(R.string.dialog_song_info_title)) .customView(view, false) .negativeText(R.string.close) .show() } fun show(fragmentManager: FragmentManager) { show(fragmentManager, TAG) } companion object { private const val TAG = "FileInfoDialog" private const val ARG_FILE_OBJECT = "file" fun newInstance(fileObject: FileObject): FileInfoDialog { val args = Bundle() args.putSerializable(ARG_FILE_OBJECT, fileObject) val fragment = FileInfoDialog() fragment.arguments = args return fragment } } }
gpl-3.0
4901ffb6c6cd821164779a2b16af3d68
46.054054
181
0.705485
4.079672
false
false
false
false
AoEiuV020/PaNovel
reader/src/main/java/cc/aoeiuv020/reader/margins.kt
1
814
package cc.aoeiuv020.reader import cc.aoeiuv020.pager.IMarginsImpl /** * 阅读器页面中有显示时间,电量之类的, * 每一个都可以设置留白,可以禁用, * 为了隐藏pager模块的接口IMargins而声明一个自己的接口, * 不继承IMargins主要是, * app依赖reader, reader依赖pager, * app使用reader中继承pager接口的接口也会编译出错,stub截断就过不去, * * Created by AoEiuV020 on 2018.06.17-16:07:30. */ interface ItemMargins { /** * 对应的东西是否显示, */ val enabled: Boolean val left: Int val top: Int val right: Int val bottom: Int } fun ItemMargins.toIMargins() = IMarginsImpl( left = this.left, top = this.top, right = this.right, bottom = this.bottom )
gpl-3.0
00ec0ded7f4bf396e4a6e34f0fa23cce
18.903226
47
0.662338
2.621277
false
false
false
false
andrei-heidelbacher/metanalysis
chronolens-core/src/test/kotlin/org/chronolens/core/parsing/ParserTest.kt
1
2157
/* * Copyright 2017-2021 Andrei Heidelbacher <[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 org.chronolens.core.parsing import org.junit.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertTrue class ParserTest { @Test fun `test can parse language with provided parser returns true`() { assertTrue(Parser.canParse("Test.mock")) } @Test fun `test can parse unknown language returns false`() { assertFalse(Parser.canParse("file.mp3")) } @Test fun `test parse source with errors returns syntax error`() { val result = Parser.parse( path = "res.mock", rawSource = "{\"invalid\":2" ) assertEquals(Result.SyntaxError, result) } @Test fun `test parse invalid path throws`() { assertFailsWith<IllegalArgumentException> { Parser.parse( path = "res:/Test.mock", rawSource = """ { "@class": "SourceFile", "path": "res:/Test.mock" } """.trimIndent() ) } } @Test fun `test parsed source with different path throws`() { assertFailsWith<IllegalStateException> { Parser.parse( path = "Test.mock", rawSource = """ { "@class": "SourceFile", "path": "Main.mock" } """.trimIndent() ) } } }
apache-2.0
dd52cffcd2a4c99abb9f5b2eb077d328
30.26087
77
0.579509
4.751101
false
true
false
false
dafi/photoshelf
core/src/main/java/com/ternaryop/photoshelf/util/notification/ThrowableNotification.kt
1
2600
package com.ternaryop.photoshelf.util.notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.graphics.Color import androidx.core.app.NotificationCompat import com.ternaryop.photoshelf.core.R import com.ternaryop.utils.dialog.getExceptionMessageChain const val THROWABLE_CHANNEL_ID = "errorId" const val THROWABLE_CHANNEL_NAME = "Error" const val EXTRA_NOTIFICATION_TAG = "com.ternaryop.photoshelf.util.extra.NOTIFICATION_TAG" private const val NOTIFICATION_TAG = "com.ternaryop.notification.error" fun Throwable.notify(context: Context, title: String, actionTitle: String, intent: Intent, offsetId: Int) { intent.putExtra(EXTRA_NOTIFICATION_TAG, NOTIFICATION_TAG) // use offsetId to preserve extras for different notifications val pendingIntent = PendingIntent.getBroadcast(context, offsetId, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_ONE_SHOT) val builder = NotificationCompat.Builder(context, THROWABLE_CHANNEL_ID) .setSmallIcon(R.drawable.stat_notify_error) .setContentTitle(title) .setContentText(localizedMessage) .setPriority(NotificationCompat.PRIORITY_MAX) .addAction(R.drawable.stat_notify_error, actionTitle, pendingIntent) createErrorNotificationChannel(context).notify(NOTIFICATION_TAG, offsetId, builder.build()) } fun Throwable.notify(context: Context, title: String, ticker: String? = null, offsetId: Int = 0) { val builder = NotificationCompat.Builder(context, THROWABLE_CHANNEL_ID) .setSmallIcon(R.drawable.stat_notify_error) .setContentText(title) .setTicker(ticker) .setPriority(NotificationCompat.PRIORITY_MAX) .setAutoCancel(true) // remove notification when user clicks on it .setupMultiLineNotification("Error", getExceptionMessageChain()) // add offsetId to ensure every notification is shown createErrorNotificationChannel(context).notify(NOTIFICATION_TAG, offsetId, builder.build()) } @Suppress("MagicNumber") fun createErrorNotificationChannel(context: Context): NotificationManager { val channel = NotificationChannel(THROWABLE_CHANNEL_ID, THROWABLE_CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH) channel.enableLights(true) channel.lightColor = Color.RED channel.enableVibration(true) channel.vibrationPattern = longArrayOf(100, 200, 300, 400, 500, 400, 300, 200, 400) return context.notificationManager.also { it.createNotificationChannel(channel) } }
mit
6ee27907b2ffb3efcbc2ba02ebb0da09
46.272727
138
0.779231
4.459691
false
false
false
false
rcgroot/open-gpstracker-ng
studio/app/src/androidTestMock/java/nl/sogeti/android/gpstracker/ng/util/DrawableMatcher.kt
1
3171
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: René de Groot ** Copyright: (c) 2016 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker 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. * * OpenGPSTracker 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 OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.ng.util import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.drawable.BitmapDrawable import android.graphics.drawable.Drawable import android.view.View import android.widget.ImageView import androidx.appcompat.content.res.AppCompatResources.getDrawable import org.hamcrest.Description import org.hamcrest.TypeSafeMatcher class DrawableMatcher(val id: Int) : TypeSafeMatcher<View>() { override fun describeTo(description: Description?) { description?.appendText("has matching drawable resource") } override fun matchesSafely(item: View?): Boolean { var matches = false if (item is ImageView) { val expectedDrawable = getDrawable(item.context, id) if (expectedDrawable != null) { val expectedBitmap = renderDrawable(expectedDrawable) val itemBitmap: Bitmap val itemDrawable = item.drawable if (itemDrawable is BitmapDrawable) { itemBitmap = itemDrawable.bitmap } else { itemBitmap = renderDrawable(itemDrawable) } matches = itemBitmap.sameAs(expectedBitmap) } } return matches } private fun renderDrawable(itemDrawable: Drawable): Bitmap { val itemBitmap = Bitmap.createBitmap(itemDrawable.intrinsicWidth, itemDrawable.intrinsicHeight, Bitmap.Config.ARGB_8888); val canvas = Canvas(itemBitmap) itemDrawable.setBounds(0, 0, canvas.width, canvas.height) itemDrawable.draw(canvas) return itemBitmap } }
gpl-3.0
016b7cef3b37f76dabd9d7c5133f16b9
40.710526
129
0.624921
5.080128
false
false
false
false
fallGamlet/DnestrCinema
app/src/main/java/com/fallgamlet/dnestrcinema/ui/movie/today/TodayMoviesFragment.kt
1
3732
package com.fallgamlet.dnestrcinema.ui.movie.today import android.os.Bundle import android.view.View import androidx.core.view.isVisible import androidx.lifecycle.Observer import androidx.recyclerview.widget.DefaultItemAnimator import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import butterknife.BindView import butterknife.ButterKnife import com.fallgamlet.dnestrcinema.R import com.fallgamlet.dnestrcinema.domain.models.MovieItem import com.fallgamlet.dnestrcinema.ui.base.BaseFragment import com.fallgamlet.dnestrcinema.ui.movie.DividerItemDecoration import com.fallgamlet.dnestrcinema.ui.movie.MovieRecyclerAdapter class TodayMoviesFragment : BaseFragment() { @BindView(R.id.swipeLayout) protected lateinit var swipeLayout: SwipeRefreshLayout @BindView(R.id.listView) protected lateinit var listView: RecyclerView @BindView(R.id.placeholderView) protected lateinit var placeholderView: View private lateinit var viewModel: TodayMoviesViewModelImpl private lateinit var listAdapter: MovieRecyclerAdapter override val layoutId: Int = R.layout.fragment_movies override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewModel = getViewModelProvider().get(TodayMoviesViewModelImpl::class.java) val viewState = viewModel.viewState setErrorLive(viewState.error) setLoadingLive(viewState.loading) viewState.movies.observe(this, Observer { onMovieListChanged(it) }) } private fun onMovieListChanged(items: List<MovieItem>) { val hasData = items.isNotEmpty() placeholderView.isVisible = !hasData listView.isVisible = hasData listAdapter.setData(items) listAdapter.notifyDataSetChanged() } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) ButterKnife.bind(this, view) view.setOnClickListener { } initSwipeLayout() initListView() viewModel.refreshViewState() } private fun initSwipeLayout() { swipeLayout.setOnRefreshListener { viewModel.loadData() } swipeLayout.setColorSchemeResources( R.color.colorPrimary, R.color.colorPrimaryDark, R.color.colorAccent ) } private fun initListView() { val context = listView.context listAdapter = MovieRecyclerAdapter(R.layout.movie_item_now) listAdapter.setListener(object : MovieRecyclerAdapter.OnAdapterListener { override fun onItemPressed(item: MovieItem, pos: Int) { viewModel.onMovieSelected(item) } override fun onItemSchedulePressed(item: MovieItem, pos: Int) {} override fun onItemBuyTicketPressed(item: MovieItem, pos: Int) { viewModel.onTicketBuySelected(item) } }) listView.adapter = listAdapter listView.layoutManager = LinearLayoutManager(context) listView.itemAnimator = object : DefaultItemAnimator() { override fun canReuseUpdatedViewHolder(viewHolder: RecyclerView.ViewHolder): Boolean { return true } } listView.addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL_LIST).apply { val left = resources.getDimension(R.dimen.ImageDividerLeft).toInt() setPaddingStart(left) }) } override fun onLoading(value: Boolean?) { super.onLoading(value) swipeLayout.isRefreshing = value == true } }
gpl-3.0
a96ba3fac0d357fa62ad013cbc9e0bac
33.238532
110
0.71329
5.226891
false
false
false
false
apollo-rsps/apollo
game/src/main/kotlin/org/apollo/game/plugin/kotlin/message/ButtonClick.kt
1
1794
package org.apollo.game.plugin.kotlin.message import org.apollo.game.message.handler.MessageHandler import org.apollo.game.message.impl.ButtonMessage import org.apollo.game.model.World import org.apollo.game.model.entity.Player import org.apollo.game.plugin.kotlin.KotlinPluginScript import org.apollo.game.plugin.kotlin.MessageListenable import org.apollo.game.plugin.kotlin.PlayerContext import org.apollo.game.plugin.kotlin.PredicateContext /** * Registers a listener for [ButtonMessage]s that occur on the given [button] id. * * ``` * on(ButtonClick, button = 416) { * player.sendMessage("You click the button.") * } * ``` */ fun KotlinPluginScript.on( listenable: ButtonClick.Companion, button: Int, callback: ButtonClick.() -> Unit ) { registerListener(listenable, ButtonPredicateContext(button), callback) } class ButtonClick(override val player: Player, val button: Int) : PlayerContext { companion object : MessageListenable<ButtonMessage, ButtonClick, ButtonPredicateContext>() { override val type = ButtonMessage::class override fun createHandler( world: World, predicateContext: ButtonPredicateContext?, callback: ButtonClick.() -> Unit ): MessageHandler<ButtonMessage> { return object : MessageHandler<ButtonMessage>(world) { override fun handle(player: Player, message: ButtonMessage) { if (predicateContext == null || predicateContext.button == message.widgetId) { val context = ButtonClick(player, message.widgetId) context.callback() } } } } } } class ButtonPredicateContext(val button: Int) : PredicateContext
isc
9f5cb9fe98f4e7bb55026ad347e06325
31.053571
98
0.673356
4.462687
false
false
false
false
Light-Team/ModPE-IDE-Source
languages/language-base/src/main/kotlin/com/brackeys/ui/language/base/span/SyntaxHighlightSpan.kt
1
1376
/* * 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.language.base.span import android.text.TextPaint import android.text.style.CharacterStyle data class SyntaxHighlightSpan( private val span: StyleSpan, var start: Int, var end: Int ) : CharacterStyle(), Comparable<SyntaxHighlightSpan> { override fun updateDrawState(textPaint: TextPaint?) { textPaint?.color = span.color textPaint?.isFakeBoldText = span.bold textPaint?.isUnderlineText = span.underline if (span.italic) { textPaint?.textSkewX = -0.1f } if (span.strikethrough) { textPaint?.flags = TextPaint.STRIKE_THRU_TEXT_FLAG } } override fun compareTo(other: SyntaxHighlightSpan): Int { return start - other.start } }
apache-2.0
cdc58d83596d6d6b65d1c6f61e8db170
31.023256
75
0.697674
4.286604
false
false
false
false
wiltonlazary/kotlin-native
samples/videoplayer/src/videoPlayerMain/kotlin/SDLAudio.kt
1
2973
/* * 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.videoplayer import kotlin.native.concurrent.Worker import kotlinx.cinterop.* import sdl.* import platform.posix.memset import platform.posix.memcpy enum class SampleFormat { INVALID, S16 } data class AudioOutput(val sampleRate: Int, val channels: Int, val sampleFormat: SampleFormat) private fun SampleFormat.toSDLFormat(): SDL_AudioFormat? = when (this) { SampleFormat.S16 -> AUDIO_S16SYS.convert() SampleFormat.INVALID -> null } class SDLAudio(val player: VideoPlayer) : DisposableContainer() { private var state = State.STOPPED fun start(audio: AudioOutput) { stop() val audioFormat = audio.sampleFormat.toSDLFormat() ?: return println("SDL Audio: Playing output with ${audio.channels} channels, ${audio.sampleRate} samples per second") memScoped { // TODO: better mechanisms to ensure we have same output format here and in resampler of the decoder. val spec = alloc<SDL_AudioSpec>().apply { freq = audio.sampleRate format = audioFormat channels = audio.channels.convert() silence = 0u samples = 4096u userdata = player.worker.asCPointer() callback = staticCFunction(::audioCallback) } val realSpec = alloc<SDL_AudioSpec>() if (SDL_OpenAudio(spec.ptr, realSpec.ptr) < 0) throwSDLError("SDL_OpenAudio") // TODO: ensure real spec matches what we asked for. state = State.PAUSED resume() } } fun pause() { state = state.transition(State.PLAYING, State.PAUSED) { SDL_PauseAudio(1) } } fun resume() { state = state.transition(State.PAUSED, State.PLAYING) { SDL_PauseAudio(0) } } fun stop() { pause() state = state.transition(State.PAUSED, State.STOPPED) { SDL_CloseAudio() } } } private fun audioCallback(userdata: COpaquePointer?, buffer: CPointer<Uint8Var>?, length: Int) { // This handler will be invoked in the audio thread, so reinit runtime. kotlin.native.initRuntimeIfNeeded() val decoder = DecoderWorker(Worker.fromCPointer(userdata)) var outPosition = 0 while (outPosition < length) { val frame = decoder.nextAudioFrame(length - outPosition) if (frame != null) { val toCopy = minOf(length - outPosition, frame.size - frame.position) memcpy(buffer + outPosition, frame.buffer.pointed.data + frame.position, toCopy.convert()) frame.unref() outPosition += toCopy } else { // println("Decoder returned nothing!") memset(buffer + outPosition, 0, (length - outPosition).convert()) break } } }
apache-2.0
0045df97f296dec88ef65fb0976243de
33.569767
116
0.629331
4.253219
false
false
false
false
wiltonlazary/kotlin-native
performance/shared/src/main/kotlin/org/jetbrains/benchmarksLauncher/launcher.kt
1
8653
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:OptIn(ExperimentalCli::class) package org.jetbrains.benchmarksLauncher import org.jetbrains.report.BenchmarkResult import kotlinx.cli.* data class RecordTimeMeasurement( val status: BenchmarkResult.Status, val iteration: Int, val warmupCount: Int, val durationNs: Double) abstract class Launcher { abstract val benchmarks: BenchmarksCollection fun add(name: String, benchmark: AbstractBenchmarkEntry) { benchmarks[name] = benchmark } fun runBenchmark(benchmarkInstance: Any?, benchmark: AbstractBenchmarkEntry, repeatNumber: Int): Long { var i = repeatNumber return if (benchmark is BenchmarkEntryWithInit) { cleanup() measureNanoTime { while (i-- > 0) benchmark.lambda(benchmarkInstance!!) cleanup() } } else if (benchmark is BenchmarkEntry) { cleanup() measureNanoTime { while (i-- > 0) benchmark.lambda() cleanup() } } else if (benchmark is BenchmarkEntryManual) { error("runBenchmark cannot run manual benchmark") } else { error("Unknown benchmark type $benchmark") } } enum class LogLevel { DEBUG, OFF } class Logger(val level: LogLevel = LogLevel.OFF) { fun log(message: String, messageLevel: LogLevel = LogLevel.DEBUG, usePrefix: Boolean = true) { if (messageLevel == level) { if (usePrefix) { printStderr("[$level][${currentTime()}] $message") } else { printStderr("$message") } } } } fun runBenchmark(logger: Logger, numWarmIterations: Int, numberOfAttempts: Int, name: String, recordMeasurement: (RecordTimeMeasurement) -> Unit, benchmark: AbstractBenchmarkEntry) { val benchmarkInstance = (benchmark as? BenchmarkEntryWithInit)?.ctor?.invoke() logger.log("Warm up iterations for benchmark $name\n") runBenchmark(benchmarkInstance, benchmark, numWarmIterations) val expectedDuration = 2000L * 1_000_000 // 2s var autoEvaluatedNumberOfMeasureIteration = 1 if (benchmark.useAutoEvaluatedNumberOfMeasure) { val time = runBenchmark(benchmarkInstance, benchmark, 1) if (time < expectedDuration) // Made auto evaluated number of measurements to be a multiple of 4. // Loops which iteration number is a multiple of 4 execute optimally, // because of different optimizations on processor (e.g. LSD) autoEvaluatedNumberOfMeasureIteration = ((expectedDuration / time).toInt() / 4 + 1) * 4 } logger.log("Running benchmark $name ") for (k in 0.until(numberOfAttempts)) { logger.log(".", usePrefix = false) var i = autoEvaluatedNumberOfMeasureIteration val time = runBenchmark(benchmarkInstance, benchmark, i) val scaledTime = time * 1.0 / autoEvaluatedNumberOfMeasureIteration // Save benchmark object recordMeasurement(RecordTimeMeasurement(BenchmarkResult.Status.PASSED, k, numWarmIterations, scaledTime)) } logger.log("\n", usePrefix = false) } fun launch(numWarmIterations: Int, numberOfAttempts: Int, prefix: String = "", filters: Collection<String>? = null, filterRegexes: Collection<String>? = null, verbose: Boolean): List<BenchmarkResult> { val logger = if (verbose) Logger(LogLevel.DEBUG) else Logger() val regexes = filterRegexes?.map { it.toRegex() } ?: listOf() val filterSet = filters?.toHashSet() ?: hashSetOf() // Filter benchmarks using given filters, or run all benchmarks if none were given. val runningBenchmarks = if (filterSet.isNotEmpty() || regexes.isNotEmpty()) { benchmarks.filterKeys { benchmark -> benchmark in filterSet || regexes.any { it.matches(benchmark) } } } else benchmarks if (runningBenchmarks.isEmpty()) { printStderr("No matching benchmarks found\n") error("No matching benchmarks found") } val benchmarkResults = mutableListOf<BenchmarkResult>() for ((name, benchmark) in runningBenchmarks) { val recordMeasurement : (RecordTimeMeasurement) -> Unit = { benchmarkResults.add(BenchmarkResult( "$prefix$name", it.status, it.durationNs / 1000, BenchmarkResult.Metric.EXECUTION_TIME, it.durationNs / 1000, it.iteration + 1, it.warmupCount)) } try { runBenchmark(logger, numWarmIterations, numberOfAttempts, name, recordMeasurement, benchmark) } catch (e: Throwable) { printStderr("Failure while running benchmark $name: $e\n") benchmarkResults.add(BenchmarkResult( "$prefix$name", BenchmarkResult.Status.FAILED, 0.0, BenchmarkResult.Metric.EXECUTION_TIME, 0.0, numberOfAttempts, numWarmIterations) ) } } return benchmarkResults } fun benchmarksListAction() { benchmarks.keys.forEach { println(it) } } } abstract class BenchmarkArguments(argParser: ArgParser) class BaseBenchmarkArguments(argParser: ArgParser): BenchmarkArguments(argParser) { val warmup by argParser.option(ArgType.Int, shortName = "w", description = "Number of warm up iterations") .default(20) val repeat by argParser.option(ArgType.Int, shortName = "r", description = "Number of each benchmark run"). default(60) val prefix by argParser.option(ArgType.String, shortName = "p", description = "Prefix added to benchmark name") .default("") val output by argParser.option(ArgType.String, shortName = "o", description = "Output file") val filter by argParser.option(ArgType.String, shortName = "f", description = "Benchmark to run").multiple() val filterRegex by argParser.option(ArgType.String, shortName = "fr", description = "Benchmark to run, described by a regular expression").multiple() val verbose by argParser.option(ArgType.Boolean, shortName = "v", description = "Verbose mode of running") .default(false) } object BenchmarksRunner { fun parse(args: Array<String>, benchmarksListAction: ()->Unit): BenchmarkArguments? { class List: Subcommand("list", "Show list of benchmarks") { override fun execute() { benchmarksListAction() } } // Parse args. val argParser = ArgParser("benchmark") argParser.subcommands(List()) val argumentsValues = BaseBenchmarkArguments(argParser) return if (argParser.parse(args).commandName == "benchmark") argumentsValues else null } fun collect(results: List<BenchmarkResult>, arguments: BenchmarkArguments) { if (arguments is BaseBenchmarkArguments) { JsonReportCreator(results).printJsonReport(arguments.output) } } fun runBenchmarks(args: Array<String>, run: (parser: BenchmarkArguments) -> List<BenchmarkResult>, parseArgs: (args: Array<String>, benchmarksListAction: ()->Unit) -> BenchmarkArguments? = this::parse, collect: (results: List<BenchmarkResult>, arguments: BenchmarkArguments) -> Unit = this::collect, benchmarksListAction: ()->Unit) { val arguments = parseArgs(args, benchmarksListAction) arguments?.let { val results = run(arguments) collect(results, arguments) } } }
apache-2.0
cc913056284a46378a2cec34a9151cf2
42.482412
124
0.616896
4.891464
false
false
false
false
genobis/tornadofx
src/main/java/tornadofx/Component.kt
1
43208
@file:Suppress("UNCHECKED_CAST") package tornadofx import com.sun.deploy.uitoolkit.impl.fx.HostServicesFactory import com.sun.javafx.application.HostServicesDelegate import javafx.beans.binding.BooleanExpression import javafx.beans.property.* import javafx.collections.FXCollections import javafx.concurrent.Task import javafx.event.EventDispatchChain import javafx.event.EventHandler import javafx.event.EventTarget import javafx.fxml.FXMLLoader import javafx.geometry.Orientation import javafx.scene.Node import javafx.scene.Parent import javafx.scene.Scene import javafx.scene.control.* import javafx.scene.image.Image import javafx.scene.image.ImageView import javafx.scene.input.Clipboard import javafx.scene.input.KeyCode import javafx.scene.input.KeyCombination import javafx.scene.input.KeyEvent import javafx.scene.input.KeyEvent.KEY_PRESSED import javafx.scene.layout.BorderPane import javafx.scene.layout.Pane import javafx.scene.paint.Paint import javafx.stage.Modality import javafx.stage.Stage import javafx.stage.StageStyle import javafx.stage.Window import java.io.InputStream import java.io.StringReader import java.net.URL import java.nio.file.Files import java.nio.file.Path import java.util.* import java.util.logging.Logger import java.util.prefs.Preferences import javax.json.Json import kotlin.properties.ReadOnlyProperty import kotlin.reflect.* @Deprecated("Injectable was a misnomer", ReplaceWith("ScopedInstance")) interface Injectable : ScopedInstance interface ScopedInstance interface Configurable { val config: ConfigProperties val configPath: Path fun loadConfig() = ConfigProperties(this).apply { if (Files.exists(configPath)) Files.newInputStream(configPath).use { load(it) } } } class ConfigProperties(val configurable: Configurable) : Properties() { fun set(pair: Pair<String, Any?>) { val value = pair.second?.let { (it as? JsonModel)?.toJSON()?.toString() ?: it.toString() } set(pair.first, value) } fun string(key: String, defaultValue: String? = null) = getProperty(key, defaultValue) fun boolean(key: String, defaultValue: Boolean? = false) = getProperty(key)?.toBoolean() ?: defaultValue fun double(key: String, defaultValue: Double? = null) = getProperty(key)?.toDouble() ?: defaultValue fun int(key: String, defaultValue: Int? = null) = getProperty(key)?.toInt() ?: defaultValue fun jsonObject(key: String) = getProperty(key)?.let { Json.createReader(StringReader(it)).readObject() } fun jsonArray(key: String) = getProperty(key)?.let { Json.createReader(StringReader(it)).readArray() } inline fun <reified M : JsonModel> jsonModel(key: String) = jsonObject(key)?.toModel<M>() fun save() { val path = configurable.configPath.apply { if (!Files.exists(parent)) Files.createDirectories(parent) } Files.newOutputStream(path).use { output -> store(output, "") } } } abstract class Component : Configurable { open val scope: Scope = FX.inheritScopeHolder.get() val workspace: Workspace get() = scope.workspace val paramsProperty = SimpleObjectProperty<Map<String, Any?>>(FX.inheritParamHolder.get() ?: mapOf()) val params: Map<String, Any?> get() = paramsProperty.value val subscribedEvents = HashMap<KClass<out FXEvent>, ArrayList<FXEventRegistration>>() /** * Path to component specific configuration settings. Defaults to javaClass.properties inside * the configured configBasePath of the application (By default conf in the current directory). */ override val configPath: Path get() = app.configBasePath.resolve("${javaClass.name}.properties") override val config: ConfigProperties by lazy { loadConfig() } val clipboard: Clipboard by lazy { Clipboard.getSystemClipboard() } val hostServices: HostServicesDelegate get() = HostServicesFactory.getInstance(FX.application) inline fun <reified T : Component> find(params: Map<*, Any?>? = null, noinline op: (T.() -> Unit)? = null): T = find(T::class, scope, params).apply { op?.invoke(this) } fun <T : Component> find(type: KClass<T>, params: Map<*, Any?>? = null, op: (T.() -> Unit)? = null) = find(type, scope, params).apply { op?.invoke(this) } @JvmOverloads fun <T : Component> find(componentType: Class<T>, params: Map<*, Any?>? = null, scope: Scope = [email protected]): T = find(componentType.kotlin, scope, params) fun <T : Any> k(javaClass: Class<T>): KClass<T> = javaClass.kotlin /** * Store and retrieve preferences. * * Preferences are stored automatically in a OS specific way. * <ul> * <li>Windows stores it in the registry at HKEY_CURRENT_USER/Software/JavaSoft/....</li> * <li>Mac OS stores it at ~/Library/Preferences/com.apple.java.util.prefs.plist</li> * <li>Linux stores it at ~/.java</li> * </ul> */ fun preferences(nodename: String? = null, op: Preferences.() -> Unit) { val node = if (nodename != null) Preferences.userRoot().node(nodename) else Preferences.userNodeForPackage(FX.getApplication(scope)!!.javaClass) op(node) } val properties by lazy { FXCollections.observableHashMap<Any, Any>() } val log by lazy { Logger.getLogger([email protected]) } val app: App get() = FX.application as App private val _messages: SimpleObjectProperty<ResourceBundle> = object : SimpleObjectProperty<ResourceBundle>() { override fun get(): ResourceBundle? { if (super.get() == null) { try { val bundle = ResourceBundle.getBundle([email protected], FX.locale, FXResourceBundleControl) (bundle as? FXPropertyResourceBundle)?.inheritFromGlobal() set(bundle) } catch (ex: Exception) { FX.log.fine("No Messages found for ${javaClass.name} in locale ${FX.locale}, using global bundle") set(FX.messages) } } return super.get() } } var messages: ResourceBundle get() = _messages.get() set(value) = _messages.set(value) val resources: ResourceLookup by lazy { ResourceLookup(this) } inline fun <reified T> inject(overrideScope: Scope = scope, params: Map<String, Any?>? = null): ReadOnlyProperty<Component, T> where T : Component, T : ScopedInstance = object : ReadOnlyProperty<Component, T> { override fun getValue(thisRef: Component, property: KProperty<*>) = find<T>(overrideScope, params) } inline fun <reified T> param(defaultValue: T? = null): ReadOnlyProperty<Component, T> = object : ReadOnlyProperty<Component, T> { override fun getValue(thisRef: Component, property: KProperty<*>): T { val param = thisRef.params[property.name] as? T if (param == null) { if (defaultValue != null) return defaultValue @Suppress("ALWAYS_NULL") if (property.returnType.isMarkedNullable) return defaultValue as T throw IllegalStateException("param for name [$property.name] has not been set") } else { return param } } } @Deprecated("No need to use the nullableParam anymore, use param instead", ReplaceWith("param(defaultValue)")) inline fun <reified T> nullableParam(defaultValue: T? = null) = param(defaultValue) inline fun <reified T : Fragment> fragment(overrideScope: Scope = scope, params: Map<String, Any?>): ReadOnlyProperty<Component, T> = object : ReadOnlyProperty<Component, T> { var fragment: T? = null override fun getValue(thisRef: Component, property: KProperty<*>): T { if (fragment == null) fragment = find(overrideScope, params) return fragment!! } } inline fun <reified T : Any> di(name: String? = null): ReadOnlyProperty<Component, T> = object : ReadOnlyProperty<Component, T> { var injected: T? = null override fun getValue(thisRef: Component, property: KProperty<*>): T { if (FX.dicontainer == null) { throw AssertionError("Injector is not configured, so bean of type ${T::class} cannot be resolved") } else { if (injected == null) injected = FX.dicontainer?.let { if (name != null) { it.getInstance(name) } else { it.getInstance() } } } return injected!! } } val primaryStage: Stage get() = FX.getPrimaryStage(scope)!! // This is here for backwards compatibility. Removing it would require an import for the tornadofx.ui version infix fun <T> Task<T>.ui(func: (T) -> Unit) = success(func) @Deprecated("Clashes with Region.background, so runAsync is a better name", ReplaceWith("runAsync"), DeprecationLevel.WARNING) fun <T> background(func: FXTask<*>.() -> T) = task(func = func) /** * Perform the given operation on an ScopedInstance of the specified type asynchronousyly. * * MyController::class.runAsync { functionOnMyController() } ui { processResultOnUiThread(it) } */ inline fun <reified T, R> KClass<T>.runAsync(noinline op: T.() -> R) where T : Component, T : ScopedInstance = task { op(find(scope)) } /** * Perform the given operation on an ScopedInstance class function member asynchronousyly. * * CustomerController::listContacts.runAsync(customerId) { processResultOnUiThread(it) } */ inline fun <reified InjectableType, reified ReturnType> KFunction1<InjectableType, ReturnType>.runAsync(noinline doOnUi: ((ReturnType) -> Unit)? = null): Task<ReturnType> where InjectableType : Component, InjectableType : ScopedInstance { val t = task { invoke(find(scope)) } if (doOnUi != null) t.ui(doOnUi) return t } /** * Perform the given operation on an ScopedInstance class function member asynchronousyly. * * CustomerController::listCustomers.runAsync { processResultOnUiThread(it) } */ inline fun <reified InjectableType, reified P1, reified ReturnType> KFunction2<InjectableType, P1, ReturnType>.runAsync(p1: P1, noinline doOnUi: ((ReturnType) -> Unit)? = null) where InjectableType : Component, InjectableType : ScopedInstance = task { invoke(find(scope), p1) }.apply { if (doOnUi != null) ui(doOnUi) } inline fun <reified InjectableType, reified P1, reified P2, reified ReturnType> KFunction3<InjectableType, P1, P2, ReturnType>.runAsync(p1: P1, p2: P2, noinline doOnUi: ((ReturnType) -> Unit)? = null) where InjectableType : Component, InjectableType : ScopedInstance = task { invoke(find(scope), p1, p2) }.apply { if (doOnUi != null) ui(doOnUi) } inline fun <reified InjectableType, reified P1, reified P2, reified P3, reified ReturnType> KFunction4<InjectableType, P1, P2, P3, ReturnType>.runAsync(p1: P1, p2: P2, p3: P3, noinline doOnUi: ((ReturnType) -> Unit)? = null) where InjectableType : Component, InjectableType : ScopedInstance = task { invoke(find(scope), p1, p2, p3) }.apply { if (doOnUi != null) ui(doOnUi) } inline fun <reified InjectableType, reified P1, reified P2, reified P3, reified P4, reified ReturnType> KFunction5<InjectableType, P1, P2, P3, P4, ReturnType>.runAsync(p1: P1, p2: P2, p3: P3, p4: P4, noinline doOnUi: ((ReturnType) -> Unit)? = null) where InjectableType : Component, InjectableType : ScopedInstance = task { invoke(find(scope), p1, p2, p3, p4) }.apply { if (doOnUi != null) ui(doOnUi) } /** * Find the given property inside the given ScopedInstance. Useful for assigning a property from a View or Controller * in any Component. Example: * * val person = find(UserController::currentPerson) */ inline fun <reified InjectableType, T> get(prop: KProperty1<InjectableType, T>): T where InjectableType : Component, InjectableType : ScopedInstance { val injectable = find<InjectableType>(scope) return prop.get(injectable) } inline fun <reified InjectableType, T> set(prop: KMutableProperty1<InjectableType, T>, value: T) where InjectableType : Component, InjectableType : ScopedInstance { val injectable = find<InjectableType>(scope) return prop.set(injectable, value) } /** * Runs task in background. If not set directly, looks for `TaskStatus` instance in current scope. */ fun <T> runAsync(status: TaskStatus? = find(scope), func: FXTask<*>.() -> T) = task(status, func) @Suppress("UNCHECKED_CAST") inline fun <reified T : FXEvent> subscribe(times: Number? = null, noinline action: EventContext.(T) -> Unit): FXEventRegistration { val registration = FXEventRegistration(T::class, this, times?.toLong(), action as EventContext.(FXEvent) -> Unit) subscribedEvents.getOrPut(T::class) { ArrayList() }.add(registration) val fireNow = (this as? UIComponent)?.isDocked ?: true if (fireNow) FX.eventbus.subscribe<T>(scope, registration) return registration } @Suppress("UNCHECKED_CAST") inline fun <reified T : FXEvent> unsubscribe(noinline action: EventContext.(T) -> Unit) { subscribedEvents[T::class]?.removeAll { it.action == action } FX.eventbus.unsubscribe(action) } fun <T : FXEvent> fire(event: T) { FX.eventbus.fire(event) } } abstract class Controller : Component(), ScopedInstance const val UI_COMPONENT_PROPERTY = "tornadofx.uicomponent" abstract class UIComponent(viewTitle: String? = "", icon: Node? = null) : Component(), EventTarget { override fun buildEventDispatchChain(tail: EventDispatchChain?): EventDispatchChain { throw UnsupportedOperationException("not implemented") } val iconProperty: ObjectProperty<Node> = SimpleObjectProperty(icon) var icon by iconProperty val isDockedProperty: ReadOnlyBooleanProperty = SimpleBooleanProperty() val isDocked by isDockedProperty var fxmlLoader: FXMLLoader? = null var modalStage: Stage? = null internal var muteDocking = false abstract val root: Parent internal val wrapperProperty = SimpleObjectProperty<Parent>() internal fun getRootWrapper(): Parent = wrapperProperty.value ?: root private var isInitialized = false val currentWindow: Window? get() = modalStage ?: root.scene?.window ?: FX.primaryStage open val refreshable: BooleanExpression get() = properties.getOrPut("tornadofx.refreshable") { SimpleBooleanProperty(Workspace.defaultRefreshable) } as BooleanExpression open val savable: BooleanExpression get() = properties.getOrPut("tornadofx.savable") { SimpleBooleanProperty(Workspace.defaultSavable) } as BooleanExpression open val closeable: BooleanExpression get() = properties.getOrPut("tornadofx.closeable") { SimpleBooleanProperty(Workspace.defaultCloseable) } as BooleanExpression open val deletable: BooleanExpression get() = properties.getOrPut("tornadofx.deletable") { SimpleBooleanProperty(Workspace.defaultDeletable) } as BooleanExpression open val creatable: BooleanExpression get() = properties.getOrPut("tornadofx.creatable") { SimpleBooleanProperty(Workspace.defaultCreatable) } as BooleanExpression open val complete: BooleanExpression get() = properties.getOrPut("tornadofx.complete") { SimpleBooleanProperty(Workspace.defaultComplete) } as BooleanExpression var isComplete: Boolean get() = complete.value set(value) { (complete as? BooleanProperty)?.value = value } fun wrapper(op: () -> Parent) { FX.ignoreParentBuilder = FX.IgnoreParentBuilder.Once wrapperProperty.value = op() } fun savableWhen(savable: () -> BooleanExpression) { properties["tornadofx.savable"] = savable() } fun completeWhen(complete: () -> BooleanExpression) { properties["tornadofx.complete"] = complete() } fun deletableWhen(deletable: () -> BooleanExpression) { properties["tornadofx.deletable"] = deletable() } fun creatableWhen(creatable: () -> BooleanExpression) { properties["tornadofx.creatable"] = creatable() } fun closeableWhen(closeable: () -> BooleanExpression) { properties["tornadofx.closeable"] = closeable() } fun refreshableWhen(refreshable: () -> BooleanExpression) { properties["tornadofx.refreshable"] = refreshable() } fun whenSaved(onSave: () -> Unit) { properties["tornadofx.onSave"] = onSave } fun whenCreated(onCreate: () -> Unit) { properties["tornadofx.onCreate"] = onCreate } fun whenDeleted(onDelete: () -> Unit) { properties["tornadofx.onDelete"] = onDelete } fun whenRefreshed(onRefresh: () -> Unit) { properties["tornadofx.onRefresh"] = onRefresh } /** * Forward the Workspace button states and actions to the TabPane, which * in turn will forward these states and actions to whatever View is represented * by the currently active Tab. */ fun TabPane.connectWorkspaceActions() { savableWhen { savable } whenSaved { onSave() } creatableWhen { creatable } whenCreated { onCreate() } deletableWhen { deletable } whenDeleted { onDelete() } refreshableWhen { refreshable } whenRefreshed { onRefresh() } } /** * Forward the Workspace button states and actions to the given UIComponent. * This will override the currently active forwarding to the docked UIComponent. * * When another UIComponent is docked, that UIComponent will be the new receiver for the * Workspace states and actions, hence voiding this call. */ fun forwardWorkspaceActions(uiComponent: UIComponent) { savableWhen { uiComponent.savable } whenSaved { uiComponent.onSave() } deletableWhen { uiComponent.deletable } whenDeleted { uiComponent.onDelete() } refreshableWhen { uiComponent.refreshable } whenRefreshed { uiComponent.onRefresh() } } /** * Callback that runs before the Workspace navigates back in the View stack. Return false to veto the navigation. */ open fun onNavigateBack() = true /** * Callback that runs before the Workspace navigates forward in the View stack. Return false to veto the navigation. */ open fun onNavigateForward() = true var onDockListeners: MutableList<(UIComponent) -> Unit>? = null var onUndockListeners: MutableList<(UIComponent) -> Unit>? = null val accelerators = HashMap<KeyCombination, () -> Unit>() fun disableSave() { properties["tornadofx.savable"] = SimpleBooleanProperty(false) } fun disableRefresh() { properties["tornadofx.refreshable"] = SimpleBooleanProperty(false) } fun disableCreate() { properties["tornadofx.creatable"] = SimpleBooleanProperty(false) } fun disableDelete() { properties["tornadofx.deletable"] = SimpleBooleanProperty(false) } fun disableClose() { properties["tornadofx.closeable"] = SimpleBooleanProperty(false) } fun init() { if (isInitialized) return root.properties[UI_COMPONENT_PROPERTY] = this root.parentProperty().addListener({ _, oldParent, newParent -> if (modalStage != null) return@addListener if (newParent == null && oldParent != null && isDocked) callOnUndock() if (newParent != null && newParent != oldParent && !isDocked) callOnDock() }) root.sceneProperty().addListener({ _, oldParent, newParent -> if (modalStage != null || root.parent != null) return@addListener if (newParent == null && oldParent != null && isDocked) callOnUndock() if (newParent != null && newParent != oldParent && !isDocked) { // Call undock when window closes newParent.windowProperty().onChangeOnce { it?.showingProperty()?.onChange { if (!it && isDocked) callOnUndock() } } callOnDock() } }) isInitialized = true } val currentStage: Stage? get() { val stage = (currentWindow as? Stage) if (stage == null) FX.log.warning { "CurrentStage not available for $this" } return stage } fun setWindowMinSize(width: Number, height: Number) = currentStage?.apply { minWidth = width.toDouble() minHeight = height.toDouble() } fun setWindowMaxSize(width: Number, height: Number) = currentStage?.apply { maxWidth = width.toDouble() maxHeight = height.toDouble() } private val acceleratorListener: EventHandler<KeyEvent> by lazy { EventHandler<KeyEvent> { event -> accelerators.keys.asSequence().find { it.match(event) }?.apply { accelerators[this]?.invoke() event.consume() } } } /** * Add a key listener to the current scene and look for matches against the * `accelerators` map in this UIComponent. */ private fun enableAccelerators() { root.scene?.addEventFilter(KEY_PRESSED, acceleratorListener) root.sceneProperty().addListener { obs, old, new -> old?.removeEventFilter(KEY_PRESSED, acceleratorListener) new?.addEventFilter(KEY_PRESSED, acceleratorListener) } } private fun disableAccelerators() { root.scene?.removeEventFilter(KEY_PRESSED, acceleratorListener) } /** * Called when a Component is detached from the Scene */ open fun onUndock() { } /** * Called when a Component becomes the Scene root or * when its root node is attached to another Component. * @see UIComponent.add */ open fun onDock() { } open fun onRefresh() { (properties["tornadofx.onRefresh"] as? () -> Unit)?.invoke() } /** * Save callback which is triggered when the Save button in the Workspace * is clicked, or when the Next button in a Wizard is clicked. * * For Wizard pages, you should set the complete state of the Page after save * to signal whether the Wizard can move to the next page or finish. * * For Wizards, you should set the complete state of the Wizard * after save to signal whether the Wizard can be closed. */ open fun onSave() { (properties["tornadofx.onSave"] as? () -> Unit)?.invoke() } /** * Create callback which is triggered when the Creaste button in the Workspace * is clicked. */ open fun onCreate() { (properties["tornadofx.onCreate"] as? () -> Unit)?.invoke() } open fun onDelete() { (properties["tornadofx.onDelete"] as? () -> Unit)?.invoke() } open fun onGoto(source: UIComponent) { source.replaceWith(this) } fun goto(target: UIComponent) { target.onGoto(this) } inline fun <reified T : UIComponent> goto(params: Map<String, Any?>) = find<T>(params).onGoto(this) internal fun callOnDock() { if (!isInitialized) init() if (muteDocking) return if (!isDocked) attachLocalEventBusListeners() (isDockedProperty as SimpleBooleanProperty).value = true enableAccelerators() onDock() onDockListeners?.forEach { it.invoke(this) } } private fun attachLocalEventBusListeners() { subscribedEvents.forEach { event, actions -> actions.forEach { FX.eventbus.subscribe(event, scope, it) } } } private fun detachLocalEventBusListeners() { subscribedEvents.forEach { event, actions -> actions.forEach { FX.eventbus.unsubscribe(event, it.action) } } } internal fun callOnUndock() { if (muteDocking) return detachLocalEventBusListeners() (isDockedProperty as SimpleBooleanProperty).value = false disableAccelerators() onUndock() onUndockListeners?.forEach { it.invoke(this) } } fun Button.shortcut(combo: String) = shortcut(KeyCombination.valueOf(combo)) @Deprecated("Use shortcut instead", ReplaceWith("shortcut(combo)")) fun Button.accelerator(combo: KeyCombination) = shortcut(combo) /** * Add the key combination as a shortcut for this Button's action. */ fun Button.shortcut(combo: KeyCombination) { accelerators[combo] = { fire() } } /** * Configure an action for a key combination. */ fun shortcut(combo: KeyCombination, action: () -> Unit) { accelerators[combo] = action } fun <T> shortcut(combo: KeyCombination, command: Command<T>, param: T? = null) { accelerators[combo] = { command.execute(param) } } /** * Configure an action for a key combination. */ fun shortcut(combo: String, action: () -> Unit) = shortcut(KeyCombination.valueOf(combo), action) inline fun <reified C: UIComponent> BorderPane.top() = top(C::class) fun <C : UIComponent> BorderPane.top(nodeType: KClass<C>) = setRegion(scope, BorderPane::topProperty, nodeType) inline fun <reified C: UIComponent> BorderPane.right() = right(C::class) fun <C : UIComponent> BorderPane.right(nodeType: KClass<C>) = setRegion(scope, BorderPane::rightProperty, nodeType) inline fun <reified C: UIComponent> BorderPane.bottom() = bottom(C::class) fun <C : UIComponent> BorderPane.bottom(nodeType: KClass<C>) = setRegion(scope, BorderPane::bottomProperty, nodeType) inline fun <reified C: UIComponent> BorderPane.left() = left(C::class) fun <C : UIComponent> BorderPane.left(nodeType: KClass<C>) = setRegion(scope, BorderPane::leftProperty, nodeType) inline fun <reified C: UIComponent> BorderPane.center() = center(C::class) fun <C : UIComponent> BorderPane.center(nodeType: KClass<C>) = setRegion(scope, BorderPane::centerProperty, nodeType) fun <S, T> TableColumn<S, T>.cellFormat(formatter: TableCell<S, T>.(T) -> Unit) = cellFormat(scope, formatter) fun <S, T, F : TableCellFragment<S, T>> TableColumn<S, T>.cellFragment(fragment: KClass<F>) = cellFragment(scope, fragment) fun <T, F : TreeCellFragment<T>> TreeView<T>.cellFragment(fragment: KClass<F>) = cellFragment(scope, fragment) /** * Calculate a unique Node per item and set this Node as the graphic of the TableCell. * * To support this feature, a custom cellFactory is automatically installed, unless an already * compatible cellFactory is found. The cellFactories installed via #cellFormat already knows * how to retrieve cached values. */ fun <S, T> TableColumn<S, T>.cellCache(cachedGraphicProvider: (T) -> Node) = cellCache(scope, cachedGraphicProvider) fun EventTarget.slideshow(scope: Scope = [email protected], op: Slideshow.() -> Unit) = opcr(this, Slideshow(scope), op) fun <T, F : ListCellFragment<T>> ListView<T>.cellFragment(fragment: KClass<F>) = cellFragment(scope, fragment) fun <T> ListView<T>.cellFormat(formatter: (ListCell<T>.(T) -> Unit)) = cellFormat(scope, formatter) fun <T> ListView<T>.onEdit(eventListener: ListCell<T>.(EditEventType, T?) -> Unit) = onEdit(scope, eventListener) fun <T> ListView<T>.cellCache(cachedGraphicProvider: (T) -> Node) = cellCache(scope, cachedGraphicProvider) fun <S> TableColumn<S, out Number?>.useProgressBar(afterCommit: ((TableColumn.CellEditEvent<S, Number?>) -> Unit)? = null) = useProgressBar(scope, afterCommit) fun <T> ComboBox<T>.cellFormat(formatButtonCell: Boolean = true, formatter: ListCell<T>.(T) -> Unit) = cellFormat(scope, formatButtonCell, formatter) inline fun <reified T: UIComponent> Drawer.item(scope: Scope = [email protected], params: Map<*, Any?>? = null, expanded: Boolean = false, showHeader: Boolean = false, noinline op: (DrawerItem.() -> Unit)? = null) = item(T::class, scope, params, expanded, showHeader, op) fun Drawer.item(uiComponent: KClass<out UIComponent>, scope: Scope = [email protected], params: Map<*, Any?>? = null, expanded: Boolean = false, showHeader: Boolean = false, op: (DrawerItem.() -> Unit)? = null) = item(find(uiComponent, scope, params), expanded, showHeader, op) @JvmName("addView") fun <T : View> EventTarget.add(type: KClass<T>, params: Map<*, Any?>? = null){ plusAssign(find(type, scope, params).root) } inline fun <reified T: View> EventTarget.add(vararg params: Pair<*, Any?>) = add(T::class,params.toMap()) @JvmName("addFragmentByClass") inline fun <reified T : Fragment> EventTarget.add(type: KClass<T>, params: Map<*, Any?>? = null, noinline op: (T.() -> Unit)? = null) { val fragment: T = find(type, scope, params) plusAssign(fragment.root) op?.invoke(fragment) } inline fun <reified T: Fragment> EventTarget.add(vararg params: Pair<*, Any?>, noinline op: (T.() -> Unit)) = add(T::class,params.toMap(),op) fun <T : UIComponent> EventTarget.add(uiComponent: Class<T>) = add(find(uiComponent)) inline fun <reified T : UIComponent> EventTarget.add() = add(find(T::class)) fun EventTarget.add(uiComponent: UIComponent) = plusAssign(uiComponent.root) fun EventTarget.add(child: Node) = plusAssign(child) @JvmName("plusView") operator fun <T : View> EventTarget.plusAssign(type: KClass<T>) = plusAssign(find(type, scope).root) @JvmName("plusFragment") operator fun <T : Fragment> EventTarget.plusAssign(type: KClass<T>) = plusAssign(find(type, scope).root) protected inline fun <reified T: UIComponent> openInternalWindow( scope: Scope = [email protected], icon: Node? = null, modal: Boolean = true, owner: Node = root, escapeClosesWindow: Boolean = true, closeButton: Boolean = true, overlayPaint: Paint = c("#000", 0.4), params: Map<*, Any?>? = null ) = openInternalWindow(T::class, scope, icon, modal,owner,escapeClosesWindow, closeButton, overlayPaint, params) protected fun openInternalWindow(view: KClass<out UIComponent>, scope: Scope = [email protected], icon: Node? = null, modal: Boolean = true, owner: Node = root, escapeClosesWindow: Boolean = true, closeButton: Boolean = true, overlayPaint: Paint = c("#000", 0.4), params: Map<*, Any?>? = null) = InternalWindow(icon, modal, escapeClosesWindow, closeButton, overlayPaint).open(find(view, scope, params), owner) protected fun openInternalWindow(view: UIComponent, icon: Node? = null, modal: Boolean = true, owner: Node = root, escapeClosesWindow: Boolean = true, closeButton: Boolean = true, overlayPaint: Paint = c("#000", 0.4)) = InternalWindow(icon, modal, escapeClosesWindow, closeButton, overlayPaint).open(view, owner) protected fun openInternalBuilderWindow(title: String, scope: Scope = [email protected], icon: Node? = null, modal: Boolean = true, owner: Node = root, escapeClosesWindow: Boolean = true, closeButton: Boolean = true, overlayPaint: Paint = c("#000", 0.4), rootBuilder: UIComponent.() -> Parent) = InternalWindow(icon, modal, escapeClosesWindow, closeButton, overlayPaint).open(BuilderFragment(scope, title, rootBuilder), owner) @JvmOverloads fun openWindow(stageStyle: StageStyle = StageStyle.DECORATED, modality: Modality = Modality.NONE, escapeClosesWindow: Boolean = true, owner: Window? = currentWindow, block: Boolean = false, resizable: Boolean? = null) = openModal(stageStyle, modality, escapeClosesWindow, owner, block, resizable) @JvmOverloads fun openModal(stageStyle: StageStyle = StageStyle.DECORATED, modality: Modality = Modality.APPLICATION_MODAL, escapeClosesWindow: Boolean = true, owner: Window? = currentWindow, block: Boolean = false, resizable: Boolean? = null): Stage? { if (modalStage == null) { require(getRootWrapper() is Parent) { "Only Parent Fragments can be opened in a Modal" } modalStage = Stage(stageStyle) // modalStage needs to be set before this code to make close() work in blocking mode with(modalStage!!) { if (resizable != null) isResizable = resizable titleProperty().bind(titleProperty) initModality(modality) if (owner != null) initOwner(owner) if (getRootWrapper().scene != null) { scene = getRootWrapper().scene [email protected]["tornadofx.scene"] = getRootWrapper().scene } else { Scene(getRootWrapper()).apply { if (escapeClosesWindow) { addEventFilter(KeyEvent.KEY_PRESSED) { if (it.code == KeyCode.ESCAPE) close() } } FX.applyStylesheetsTo(this) val primaryStage = FX.getPrimaryStage(scope) if (primaryStage != null) icons += primaryStage.icons scene = this [email protected]["tornadofx.scene"] = this } } hookGlobalShortcuts() showingProperty().onChange { if (it) { if (owner != null) { x = owner.x + (owner.width / 2) - (scene.width / 2) y = owner.y + (owner.height / 2) - (scene.height / 2) } callOnDock() if (FX.reloadStylesheetsOnFocus || FX.reloadViewsOnFocus) { configureReloading() } } else { modalStage = null callOnUndock() } } if (block) showAndWait() else show() } } else { if (!modalStage!!.isShowing) modalStage!!.show() } return modalStage } private fun Stage.configureReloading() { if (FX.reloadStylesheetsOnFocus) reloadStylesheetsOnFocus() if (FX.reloadViewsOnFocus) reloadViewsOnFocus() } @Deprecated("Use close() instead", replaceWith = ReplaceWith("close()")) fun closeModal() = close() fun close() { modalStage?.apply { close() modalStage = null } root.findParent<InternalWindow>()?.close() (root.properties["tornadofx.tab"] as? Tab)?.apply { tabPane?.tabs?.remove(this) } } open val titleProperty: StringProperty = SimpleStringProperty(viewTitle) var title: String get() = titleProperty.get() ?: "" set(value) = titleProperty.set(value) open val headingProperty: StringProperty = SimpleStringProperty().apply { bind(titleProperty) } var heading: String get() = headingProperty.get() ?: "" set(value) { if (headingProperty.isBound) headingProperty.unbind() headingProperty.set(value) } /** * Load an FXML file from the specified location, or from a file with the same package and name as this UIComponent * if not specified. If the FXML file specifies a controller (handy for content completion in FXML editors) * set the `hasControllerAttribute` parameter to true. This ensures that the `fx:controller` attribute is ignored * by the loader so that this UIComponent can still be the controller for the FXML file. * * Important: If you specify `hasControllerAttribute = true` when infact no `fx:controller` attribute is present, * no controller will be set at all. Make sure to only specify this parameter if you actually have the `fx:controller` * attribute in your FXML. */ fun <T : Node> fxml(location: String? = null, hasControllerAttribute: Boolean = false, root: Any? = null): ReadOnlyProperty<UIComponent, T> = object : ReadOnlyProperty<UIComponent, T> { val value: T = loadFXML(location, hasControllerAttribute, root) override fun getValue(thisRef: UIComponent, property: KProperty<*>) = value } @JvmOverloads fun <T : Node> loadFXML(location: String? = null, hasControllerAttribute: Boolean = false, root: Any? = null): T { val componentType = [email protected] val targetLocation = location ?: componentType.simpleName + ".fxml" val fxml = requireNotNull(componentType.getResource(targetLocation)){"FXML not found for $componentType in $targetLocation"} fxmlLoader = FXMLLoader(fxml).apply { resources = [email protected] if (root != null) setRoot(root) if (hasControllerAttribute) { setControllerFactory { this@UIComponent } } else { setController(this@UIComponent) } } return fxmlLoader!!.load() } fun <T : Any> fxid(propName: String? = null) = object : ReadOnlyProperty<UIComponent, T> { override fun getValue(thisRef: UIComponent, property: KProperty<*>): T { val key = propName ?: property.name val value = thisRef.fxmlLoader!!.namespace[key] if (value == null) { log.warning("Property $key of $thisRef was not resolved because there is no matching fx:id in ${thisRef.fxmlLoader!!.location}") } else { return value as T } throw IllegalArgumentException("Property $key does not match fx:id declaration") } } inline fun <reified T : Parent> EventTarget.include(scope: Scope = [email protected], hasControllerAttribute: Boolean = false, location: String): T { val loader = object : Fragment() { override val scope = scope override val root: T by fxml(location, hasControllerAttribute) } addChildIfPossible(loader.root) return loader.root } /** * Create an fragment by supplying an inline builder expression and optionally open it if the openModality is specified. A fragment can also be assigned * to an existing node hierarchy using `add()` or `this += inlineFragment {}`, or you can specify the behavior inside it using `Platform.runLater {}` before * you return the root node for the builder fragment. */ fun builderFragment(title: String = "", scope: Scope = [email protected], rootBuilder: UIComponent.() -> Parent) = BuilderFragment(scope, title, rootBuilder) fun builderWindow(title: String = "", modality: Modality = Modality.APPLICATION_MODAL, stageStyle: StageStyle = StageStyle.DECORATED, scope: Scope = [email protected], owner: Window? = currentWindow, rootBuilder: UIComponent.() -> Parent) = builderFragment(title, scope, rootBuilder).apply { openWindow(modality = modality, stageStyle = stageStyle, owner = owner) } fun dialog(title: String = "", modality: Modality = Modality.APPLICATION_MODAL, stageStyle: StageStyle = StageStyle.DECORATED, scope: Scope = [email protected], owner: Window? = currentWindow, labelPosition: Orientation = Orientation.HORIZONTAL, builder: StageAwareFieldset.() -> Unit): Stage? { val fragment = builderFragment(title, scope, { form() }) val fieldset = StageAwareFieldset(title, labelPosition) fragment.root.add(fieldset) fieldset.stage = fragment.openWindow(modality = modality, stageStyle = stageStyle, owner = owner)!! builder(fieldset) fieldset.stage.sizeToScene() return fieldset.stage } inline fun <reified T: UIComponent> replaceWith(transition: ViewTransition? = null, sizeToScene: Boolean = false, centerOnScreen: Boolean = false) = replaceWith(T::class, transition, sizeToScene, centerOnScreen) fun <T : UIComponent> replaceWith(component: KClass<T>, transition: ViewTransition? = null, sizeToScene: Boolean = false, centerOnScreen: Boolean = false) = replaceWith(find(component, scope), transition, sizeToScene, centerOnScreen) /** * Replace this component with another, optionally using a transition animation. * * @param replacement The component that will replace this one * @param transition The [ViewTransition] used to animate the transition * @return Whether or not the transition will run */ fun replaceWith(replacement: UIComponent, transition: ViewTransition? = null, sizeToScene: Boolean = false, centerOnScreen: Boolean = false): Boolean { return root.replaceWith(replacement.root, transition, sizeToScene, centerOnScreen) { if (root == root.scene?.root) (root.scene.window as? Stage)?.titleProperty()?.cleanBind(replacement.titleProperty) } } private fun undockFromParent(replacement: UIComponent) { (replacement.root.parent as? Pane)?.children?.remove(replacement.root) } } @Suppress("UNCHECKED_CAST") fun <U : UIComponent> U.whenDocked(listener: (U) -> Unit) { if (onDockListeners == null) onDockListeners = mutableListOf() onDockListeners!!.add(listener as (UIComponent) -> Unit) } @Suppress("UNCHECKED_CAST") fun <U : UIComponent> U.whenUndocked(listener: (U) -> Unit) { if (onUndockListeners == null) onUndockListeners = mutableListOf() onUndockListeners!!.add(listener as (UIComponent) -> Unit) } abstract class Fragment @JvmOverloads constructor(title: String? = null, icon: Node? = null) : UIComponent(title, icon) abstract class View @JvmOverloads constructor(title: String? = null, icon: Node? = null) : UIComponent(title, icon), ScopedInstance class ResourceLookup(val component: Any) { operator fun get(resource: String): String = component.javaClass.getResource(resource).toExternalForm() fun url(resource: String): URL = component.javaClass.getResource(resource) fun stream(resource: String): InputStream = component.javaClass.getResourceAsStream(resource) fun image(resource: String): Image = Image(stream(resource)) fun imageview(resource: String, lazyload: Boolean = false): ImageView = ImageView(Image(url(resource).toExternalForm(), lazyload)) fun json(resource: String) = stream(resource).toJSON() fun jsonArray(resource: String) = stream(resource).toJSONArray() fun text(resource: String): String = stream(resource).use { it.bufferedReader().readText() } } class BuilderFragment(overrideScope: Scope, title: String, rootBuilder: Fragment.() -> Parent) : Fragment(title) { override val scope = overrideScope override val root = rootBuilder(this) }
apache-2.0
52757760a3d0041021d7e9a712efc632
44.43428
304
0.655689
4.45765
false
false
false
false
nextcloud/android
app/src/main/java/com/nextcloud/client/logger/ui/LogsActivity.kt
1
4000
/* * Nextcloud Android client application * * @author Chris Narkiewicz * Copyright (C) 2019 Chris Narkiewicz <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.nextcloud.client.logger.ui import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.widget.ProgressBar import androidx.appcompat.widget.SearchView import androidx.databinding.DataBindingUtil import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.nextcloud.client.di.ViewModelFactory import com.owncloud.android.R import com.owncloud.android.databinding.LogsActivityBinding import com.owncloud.android.ui.activity.ToolbarActivity import com.owncloud.android.utils.theme.ViewThemeUtils import javax.inject.Inject class LogsActivity : ToolbarActivity() { @Inject protected lateinit var viewModelFactory: ViewModelFactory @Inject lateinit var viewThemeUtils: ViewThemeUtils private lateinit var vm: LogsViewModel private lateinit var binding: LogsActivityBinding private lateinit var logsAdapter: LogsAdapter private val searchBoxListener = object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String): Boolean { return false } override fun onQueryTextChange(newText: String): Boolean { vm.filter(newText) return false } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) vm = ViewModelProvider(this, viewModelFactory).get(LogsViewModel::class.java) binding = DataBindingUtil.setContentView<LogsActivityBinding>(this, R.layout.logs_activity).apply { lifecycleOwner = this@LogsActivity vm = [email protected] } findViewById<ProgressBar>(R.id.logs_loading_progress).apply { viewThemeUtils.platform.themeHorizontalProgressBar(this) } logsAdapter = LogsAdapter(this) findViewById<RecyclerView>(R.id.logsList).apply { layoutManager = LinearLayoutManager(this@LogsActivity) adapter = logsAdapter } vm.entries.observe(this, Observer { logsAdapter.entries = it }) vm.load() setupToolbar() supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.let { viewThemeUtils.files.themeActionBar(this, it, R.string.logs_title) } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.activity_logs, menu) (menu.findItem(R.id.action_search).actionView as SearchView).apply { setOnQueryTextListener(searchBoxListener) viewThemeUtils.androidx.themeToolbarSearchView(this) } return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { var retval = true when (item.itemId) { android.R.id.home -> finish() R.id.action_delete_logs -> vm.deleteAll() R.id.action_send_logs -> vm.send() R.id.action_refresh_logs -> vm.load() else -> retval = super.onOptionsItemSelected(item) } return retval } }
gpl-2.0
78a45d29b9b866deddec44ba97fd5869
34.714286
107
0.711
4.813478
false
false
false
false
HedvigInsurance/bot-service
src/main/java/com/hedvig/botService/chat/house/HouseConversationConstants.kt
1
15593
package com.hedvig.botService.chat.house import com.hedvig.botService.enteties.message.KeyboardType import com.hedvig.botService.enteties.message.TextContentType import com.hedvig.botService.enteties.userContextHelpers.UserData object HouseConversationConstants { const val HOUSE_CONVERSATION_DONE = "conversation.done" const val CONVERSATION_RENT_DONE = "conversation.rent.done" const val CONVERSATION_APARTMENT_DONE = "conversation.apartment.done" const val SPLIT = "\u000C" val SELECT_OWN = SingleSelectOption("message.house.own", "Jag äger huset") val SELECT_RENT = SingleSelectOption("message.house.rent", "Jag hyr huset") val HOUSE_FIRST = SingleSelectMessage( "message.house.first", "\uD83D\uDC4D${SPLIT}Hyr du eller äger du huset?", listOf( SELECT_OWN, SELECT_RENT ) ) val ASK_SSN = NumberInputMessage( "message.house.ask.ssn", "Vad är ditt personnummer? Jag behöver det så jag kan hämta din adress", "ååmmddxxxx" ) val ASK_LAST_NAME = TextInputMessage( "message.house.ask.last.name", "Konstigt, just nu kan jag inte hitta din adress. Så jag behöver ställa några extra frågor \uD83D\uDE0A${SPLIT}Vad heter du i efternamn?", TextContentType.FAMILY_NAME, KeyboardType.DEFAULT, "Efternamn" ) val ASK_STREET_ADDRESS = TextInputMessage( "message.house.street.address", "Vilken gatuadress bor du på?", TextContentType.STREET_ADDRESS_LINE1, KeyboardType.DEFAULT, "Kungsgatan 1" ) val ASK_STREET_ADDRESS_FAILED_LOOKUP = TextInputMessage( "message.house.street.address.failed.lookup", "Inga problem!${SPLIT}Vilken gatuadress bor du på?", TextContentType.STREET_ADDRESS_LINE1, KeyboardType.DEFAULT, "Kungsgatan 1" ) val ASK_ZIP_CODE = NumberInputMessage( "message.house.zip.code", "Vad är ditt postnummer?", "123 45" ) val ASK_SQUARE_METERS = NumberInputMessage( "message.house.square.meters", "Vad är husets boyta?${SPLIT}I boytan ingår exempelvis inte förråd, ihopsittande garage, kallvind, pannrum", "" ) val ASK_SQUARE_METERS_FAILED_LOOKUP = NumberInputMessage( "message.house.square.meters.failed.lookup", "Typiskt \uD83D\uDE48, då behöver jag ställa lite fler frågor till dig${SPLIT}Vad är husets boyta?${SPLIT}I boytan ingår inte förråd, ihopsittande garage, kallvind, pannrum och liknande", "" ) val ASK_ANCILLARY_AREA = NumberInputMessage( "message.house.ancillary.area", "Hur stor är biytan på huset?${SPLIT}Exempel på utrymmen som räknas som biytor är förråd, kallvind, pannrum och garage som sitter ihop med huset", "" ) val ASK_YEAR_OF_CONSTRUCTION = NumberInputMessage( "message.house.year.of.cunstruction", "Vilket år byggdes huset?", "åååå" ) val ASK_NUMBER_OF_BATHROOMS = NumberInputMessage( "message.house.number.of.bathrooms", "Hur många badrum finns i huset?${SPLIT}Badrum inkluderar inte mindre gästtoaletter utan dusch/bad", "" ) val ASK_NUMBER_OF_BATHROOMS_FROM_SUCCESS_LOOKUP = NumberInputMessage( "message.house.number.of.from.success.lookup", "Perfekt!${SPLIT}\uD83D\uDE0AHur många badrum finns i huset?${SPLIT}Badrum inkluderar inte mindre gästtoaletter utan dusch/bad", "" ) val ASK_HOUSE_HOUSEHOLD_MEMBERS = NumberInputMessage( "message.house.household.members", "Okej! Hur många bor där?", "" ) val SELECT_EXTRA_BUILDING_YES = SingleSelectOption("message.house.extra.buildings.yes", "Ja, det har jag") val SELECT_EXTRA_BUILDING_NO = SingleSelectOption("message.house.extra.buildings.no", "Nej, gå vidare") val ASK_HAS_EXTRA_BUILDINGS = SingleSelectMessage( "message.house.extra.buildings", "Har du några övriga byggnader på tomten? T.ex. garage eller gäststuga \uD83C\uDFD8", listOf( SELECT_EXTRA_BUILDING_YES, SELECT_EXTRA_BUILDING_NO ) ) val SELECT_REAL_ESTATE_LOOKUP_CORRECT_YES = SingleSelectOption("message.real.estate.lookup.yes", "Ja, allting stämmer") val SELECT_REAL_ESTATE_LOOKUP_CORRECT_NO = SingleSelectOption("message.real.estate.lookup.no", "Nej, en eller flera saker stämmer inte") val ASK_REAL_ESTATE_LOOKUP_CORRECT = SingleSelectMessage( "message.real.estate.lookup", "Toppen! Vi har hämtat lite information om ditt hus som vi behöver${SPLIT}" + "Stämmer det att:\n" + "\uD83D\uDC49 Boytan är {KVM} kvadratmeter\n" + "\uD83D\uDC49 Biytan är {HOUSE_ANCILLARY_AREA_KVM} kvadratmeter\n" + "\uD83D\uDC49 Och att huset är byggt {HOUSE_YEAR_OF_CUNSTRUCTION}?", listOf( SELECT_REAL_ESTATE_LOOKUP_CORRECT_YES, SELECT_REAL_ESTATE_LOOKUP_CORRECT_NO ) ) val ASK_NUMBER_OF_EXTRA_BUILDINGS = NumberInputMessage( "message.house.number.of.extra.buildings", "Hur många extra byggnader har du?", "" ) val SELECT_EXTRA_BUILDING_GARAGE = SingleSelectOption("message.house.extra.building.garage", "Garage") val SELECT_EXTRA_BUILDING_CARPORT = SingleSelectOption("message.house.extra.building.car.port", "Carport") val SELECT_EXTRA_BUILDING_SHED = SingleSelectOption("message.house.extra.building.shed", "Skjul") val SELECT_EXTRA_BUILDING_STORAGE = SingleSelectOption("message.house.extra.building.storage", "Förråd") val SELECT_EXTRA_BUILDING_FRIGGEBO = SingleSelectOption("message.house.extra.building.friggebod", "Friggebod") val SELECT_EXTRA_BUILDING_ATTEFALL = SingleSelectOption("message.house.extra.building.attefalls", "Attefallshus") val SELECT_EXTRA_BUILDING_OUTHOUSE = SingleSelectOption("message.house.extra.building.outhouse", "Uthus") val SELECT_EXTRA_BUILDING_GUESTHOUSE = SingleSelectOption("message.house.extra.building.guest.house", "Gästhus") val SELECT_EXTRA_BUILDING_GAZEBO = SingleSelectOption("message.house.extra.building.gazebo", "Lusthus") val SELECT_EXTRA_BUILDING_GREENHOUSE = SingleSelectOption("message.house.extra.building.green.house", "Växthus") val SELECT_EXTRA_BUILDING_SAUNA = SingleSelectOption("message.house.extra.building.sauna", "Bastu") val SELECT_EXTRA_BUILDING_BARN = SingleSelectOption("message.house.extra.building.barn", "Lada") val SELECT_EXTRA_BUILDING_BOATHOUSE = SingleSelectOption("message.house.extra.building.boathouse", "Båthus") val SELECT_EXTRA_BUILDING_OTHER = SingleSelectOption("message.house.extra.building.other", "Ingen av dessa") val SELECT_EXTRA_BUILDING_MORE_OTHER = SingleSelectOption("message.house.extra.building.more.other", "Annat") val ASK_EXTRA_BUILDING_TYPE_MORE_THAN_ONE = SingleSelectMessage( "message.house.extra.building.type.more.than.one", "Super! Jag behöver veta hur stora varje byggnad är och om de har indraget vatten \uD83D\uDE42${SPLIT}Vi börjar med den första byggnaden${SPLIT}Vad är det för typ av byggnad?", listOf( SELECT_EXTRA_BUILDING_GARAGE, SELECT_EXTRA_BUILDING_FRIGGEBO, SELECT_EXTRA_BUILDING_ATTEFALL, SELECT_EXTRA_BUILDING_OTHER ) ) val ASK_EXTRA_BUILDING_TYPE_ONE = SingleSelectMessage( "message.house.extra.building.type.one", "Super! Jag behöver veta hur stora varje byggnad är och om de har indraget vatten \uD83D\uDE42${SPLIT}Vad är det för typ av byggnad?", listOf( SELECT_EXTRA_BUILDING_GARAGE, SELECT_EXTRA_BUILDING_FRIGGEBO, SELECT_EXTRA_BUILDING_ATTEFALL, SELECT_EXTRA_BUILDING_OTHER ) ) val ASK_MORE_EXTRA_BUILDING_TYPE = SingleSelectMessage( "message.house.more.extra.building.type", "Är det någon av dessa typer?", listOf( SELECT_EXTRA_BUILDING_GUESTHOUSE, SELECT_EXTRA_BUILDING_CARPORT, SELECT_EXTRA_BUILDING_SAUNA, SELECT_EXTRA_BUILDING_BOATHOUSE, SELECT_EXTRA_BUILDING_MORE_OTHER ) ) val IN_LOOP_ASK_EXTRA_BUILDING_TYPE = SingleSelectMessage( "message.in.loop.house.extra.building.type", "Sådär ja, då har vi lagt till {HOUSE_EXTRA_BUILDINGS_TYPE_TEXT}. Vi går vidare till nästa byggnad${SPLIT}Vad är det för typ av byggnad?", listOf( SELECT_EXTRA_BUILDING_GARAGE, SELECT_EXTRA_BUILDING_FRIGGEBO, SELECT_EXTRA_BUILDING_ATTEFALL, SELECT_EXTRA_BUILDING_OTHER ) ) val ASK_SQUARE_METERS_EXTRA_BUILDING = NumberInputMessage( "message.house.square.meters.building", "Hur många kvadratmeter är ${UserData.HOUSE_EXTRA_BUILDINGS_TYPE_TEXT}?", "" ) val SELECT_EXTRA_BUILDING_HAS_WATER_YES = SingleSelectOption("message.house.extra.building.has.water.yes", "Ja") val SELECT_EXTRA_BUILDING_HAS_WATER_NO = SingleSelectOption("message.house.extra.building.has.water.no", "Nej") val ASK_HAS_WATER_EXTRA_BUILDING = SingleSelectMessage( "message.house.has.water.building", "Finns det indraget vatten till ${UserData.HOUSE_EXTRA_BUILDINGS_TYPE_TEXT}?", listOf( SELECT_EXTRA_BUILDING_HAS_WATER_YES, SELECT_EXTRA_BUILDING_HAS_WATER_NO ) ) val SELECT_SUBLETTING_HOUSE_YES = SingleSelectOption("message.house.sublet.yes", "Ja") val SELECT_SUBLETTING_HOUSE_NO = SingleSelectOption("message.house.sublet.no", "Nej") val ASK_SUBLETTING_HOUSE = SingleSelectMessage( "message.house.supletting.house", "Hyr du ut en del av ditt hus till någon?", listOf( SELECT_SUBLETTING_HOUSE_YES, SELECT_SUBLETTING_HOUSE_NO ) ) val SELECT_ADDRESS_LOOK_UP_SUCCESS_YES = SingleSelectOption("message.house.look.up.success.yes", "Ja, det stämmer") val SELECT_ADDRESS_LOOK_UP_SUCCESS_NO = SingleSelectOption("message.house.look.up.success.no", "Nej") val ASK_ADDRESS_LOOK_UP_SUCCESS = SingleSelectMessage( "message.house.look.up.success", "Tack {NAME}! Är det huset på {ADDRESS} jag ska ta fram ett förslag för?", listOf( SELECT_ADDRESS_LOOK_UP_SUCCESS_YES, SELECT_ADDRESS_LOOK_UP_SUCCESS_NO ) ) val SELECT_MORE_THAN_FOUR_FLOORS = SingleSelectOption("message.house.above.four.floors.yes", "Ja") val SELECT_LESS_THAN_FIVE_FLOORS = SingleSelectOption("message.house.above.four.floors.no", "Nej") val ASK_HOUSE_HAS_MORE_THAN_FOUR_FLOORS_FROM_YES = SingleSelectMessage( "message.house.below.four.floors.from.yes", "Bra, då har vi koll på det \uD83D\uDE42${SPLIT}Har huset mer än 4 våningar? Bara så du vet så räknas källaren som en våning", listOf( SELECT_MORE_THAN_FOUR_FLOORS, SELECT_LESS_THAN_FIVE_FLOORS ) ) val ASK_HOUSE_HAS_MORE_THAN_FOUR_FLOORS_FROM_NO = SingleSelectMessage( "message.house.below.four.floors.from.no", "\uD83D\uDC4D${SPLIT}Har huset mer än 4 våningar? Bara så du vet så räknas källaren som en våning", listOf( SELECT_MORE_THAN_FOUR_FLOORS, SELECT_LESS_THAN_FIVE_FLOORS ) ) val ASK_SSN_UNDER_EIGHTEEN = NumberInputMessage( "message.house.ask.ssn.under.eighteen", "Hoppsan! \uD83D\uDE4A För att skaffa en försäkring hos mig behöver du tyvärr ha fyllt 18 år" + "Om du råkade skriva fel personnummer så kan du testa att skriva igen \uD83D\uDE42${SPLIT}" + "Vad är ditt personnummer?", "ååmmddxxxx" ) val MORE_SQM_QUESTIONS_CALL = NumberInputMessage( "message.house.more.questions.call.sqm", "Tack! Jag behöver ställa några frågor på telefon till dig eftersom vi för tillfället inte har stöd för villor större än 250 kvadratmeter \uD83D\uDE42${SPLIT}Vilket telefonnummer kan jag nå dig på?", "070 123 45 67" ) val MORE_HOUSEHOLD_MEMBERS_QUESTIONS_CALL = NumberInputMessage( "message.house.more.questions.call.house.hold.members", "Tack! Jag behöver ställa några frågor på telefon till dig eftersom vi för tillfället inte har stöd för villor med fler än 6 personer som bor på samma adress \uD83D\uDE42${SPLIT}Vilket telefonnummer kan jag nå dig på?", "070 123 45 67" ) val MORE_TOTAL_SQM_QUESTIONS_CALL = NumberInputMessage( "message.house.more.questions.call.total.sqm", "Tack! Jag behöver ställa några frågor på telefon till dig eftersom vi för tillfället inte har stöd för villor större än 300 kvadratmeter sammanlagt \uD83D\uDE42${SPLIT}Vilket telefonnummer kan jag nå dig på?", "070 123 45 67" ) val MORE_YEAR_OF_CONSTRUCTION_QUESTIONS_CALL = NumberInputMessage( "message.house.more.questions.call.year.of.construction", "Tack! Jag behöver ställa några frågor på telefon till dig eftersom vi för tillfället inte har stöd för villor byggda tidigare än 1925 \uD83D\uDE42${SPLIT}Vilket telefonnummer kan jag nå dig på?", "070 123 45 67" ) val MORE_FLOORS_QUESTIONS_CALL = NumberInputMessage( "message.house.more.questions.call.floors", "Tack! Jag behöver ställa några frågor på telefon till dig eftersom vi för tillfället inte har stöd för villor med fler än 4 våningar inkl. källare \uD83D\uDE42${SPLIT}Vilket telefonnummer kan jag nå dig på?", "070 123 45 67" ) val MORE_BATHROOMS_QUESTIONS_CALL = NumberInputMessage( "message.house.more.questions.call.bathrooms", "Tack! Jag behöver ställa några frågor på telefon till dig eftersom vi för tillfället inte har stöd för villor med fler än 2 badrum \uD83D\uDE42${SPLIT}Vilket telefonnummer kan jag nå dig på?", "070 123 45 67" ) val MORE_EXTRA_BUILDINGS_QUESTIONS_CALL = NumberInputMessage( "message.house.more.questions.call.extra.buildings", "Tack! Jag behöver ställa några frågor på telefon till dig eftersom vi för tillfället inte har stöd för villor med fler än 4 extra byggnader \uD83D\uDE42${SPLIT}Vilket telefonnummer kan jag nå dig på?", "070 123 45 67" ) val MORE_EXTRA_BUILDING_SQM_QUESTIONS_CALL = NumberInputMessage( "message.house.more.questions.call.extra.building.sqm", "Tack! Jag behöver ställa några frågor på telefon till dig eftersom vi för tillfället inte har stöd för extra byggnader som är större än 75 kvadratmeter \uD83D\uDE42${SPLIT}Vilket telefonnummer kan jag nå dig på?", "070 123 45 67" ) // This is just because the user can edit this message val SELECT_APARTMENT = SingleSelectOption("message.lagenhet.pre", "Lägenhet") val SELECT_HOUSE = SingleSelectOption("message.hus", "Hus") val ASK_HOUSE_OR_APARTMENT = SingleSelectMessage( "message.forslagstart", "Tack! Bor du i lägenhet eller eget hus?", listOf( SELECT_APARTMENT, SELECT_HOUSE ) ) }
agpl-3.0
9340e1272db24cede72e0e1e1fd90d2f
42.538244
227
0.670506
3.165602
false
false
false
false
apixandru/intellij-community
platform/script-debugger/debugger-ui/src/VmConnection.kt
6
3845
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.debugger.connection import com.intellij.ide.browsers.WebBrowser import com.intellij.openapi.Disposable import com.intellij.openapi.util.Disposer import com.intellij.util.EventDispatcher import com.intellij.util.containers.ContainerUtil import com.intellij.util.io.socketConnection.ConnectionState import com.intellij.util.io.socketConnection.ConnectionStatus import com.intellij.util.io.socketConnection.SocketConnectionListener import org.jetbrains.annotations.TestOnly import org.jetbrains.concurrency.* import org.jetbrains.debugger.DebugEventListener import org.jetbrains.debugger.Vm import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicReference import javax.swing.event.HyperlinkListener abstract class VmConnection<T : Vm> : Disposable { open val browser: WebBrowser? = null private val stateRef = AtomicReference(ConnectionState(ConnectionStatus.NOT_CONNECTED)) open protected val dispatcher: EventDispatcher<DebugEventListener> = EventDispatcher.create( DebugEventListener::class.java) private val connectionDispatcher = ContainerUtil.createLockFreeCopyOnWriteList<(ConnectionState) -> Unit>() @Volatile var vm: T? = null protected set private val opened = AsyncPromise<Any?>() private val closed = AtomicBoolean() val state: ConnectionState get() = stateRef.get() fun addDebugListener(listener: DebugEventListener) { dispatcher.addListener(listener) } @TestOnly fun opened(): Promise<*> = opened fun executeOnStart(runnable: Runnable) { opened.done { runnable.run() } } protected fun setState(status: ConnectionStatus, message: String? = null, messageLinkListener: HyperlinkListener? = null) { val newState = ConnectionState(status, message, messageLinkListener) val oldState = stateRef.getAndSet(newState) if (oldState == null || oldState.status != status) { if (status == ConnectionStatus.CONNECTION_FAILED) { opened.setError(newState.message) } for (listener in connectionDispatcher) { listener(newState) } } } fun stateChanged(listener: (ConnectionState) -> Unit) { connectionDispatcher.add(listener) } // backward compatibility, go debugger fun addListener(listener: SocketConnectionListener) { stateChanged { listener.statusChanged(it.status) } } protected val debugEventListener: DebugEventListener get() = dispatcher.multicaster protected open fun startProcessing() { opened.setResult(null) } fun close(message: String?, status: ConnectionStatus) { if (!closed.compareAndSet(false, true)) { return } if (opened.isPending) { opened.setError("closed") } setState(status, message) Disposer.dispose(this, false) } override fun dispose() { vm = null } open fun detachAndClose(): Promise<*> { if (opened.isPending) { opened.setError(createError("detached and closed")) } val currentVm = vm val callback: Promise<*> if (currentVm == null) { callback = nullPromise() } else { vm = null callback = currentVm.attachStateManager.detach() } close(null, ConnectionStatus.DISCONNECTED) return callback } }
apache-2.0
ed819ae497ab0c43c3ec38b399de96e4
29.768
125
0.735761
4.599282
false
false
false
false
konfko/konfko
konfko-core/src/main/kotlin/com/github/konfko/core/source/SettingsResource.kt
1
2444
package com.github.konfko.core.source import java.io.IOException import java.io.InputStream import java.io.InputStreamReader import java.io.Reader import java.nio.charset.Charset import java.nio.charset.StandardCharsets import java.nio.file.Files import java.nio.file.Path import java.time.Instant /** * @author markopi */ /** * Provides input streams for [ResourceSettingsSource] */ interface SettingsResource { /** * If this resource represents an existing file on the filesystem, this value should point to it. * Read by [FilesystemWatcherService][com.github.konfko.core.watcher.FilesystemWatcherService] to watch * for configuration changes. * * Otherwise, it should be null. */ val path: Path? /** * When was this resource last modified. If modification is not supported, it should return null */ val lastModified: Instant? /** * Name of the resource. DefaultSettingsParser tries to extract an extension from this name to determine how to * parse the resource. */ val name: String /** * Opens a new input stream for this resource. */ fun openInputStream(): InputStream /** * Opens a new reader for this resource. Normally this is just a wrapper around [openInputStream] */ fun openReader(charset: Charset = StandardCharsets.UTF_8): Reader = InputStreamReader(openInputStream(), charset) } /** * A resource pointing to a particular file on the filesystem */ class PathResource(override val path: Path) : SettingsResource { override val name = path.toString() override val lastModified: Instant? = Files.getLastModifiedTime(path)?.toInstant() override fun openInputStream(): InputStream = Files.newInputStream(path) override fun toString(): String = "${javaClass.simpleName}[$name]" } /** * A resource pointing to a particular classpath resource */ class ClassPathResource(private val classPath: String, private val classLoader: ClassLoader = ClassLoader.getSystemClassLoader()) : SettingsResource { override val name = classPath override val path: Path? = null override val lastModified: Instant? = null override fun openInputStream(): InputStream = classLoader.getResourceAsStream(classPath) ?: throw IOException("No such classpath resource: [$classPath]") override fun toString(): String = "${javaClass.simpleName}[$name]" }
apache-2.0
d3e71ebe1be158d7078a52bb1921a47a
31.171053
117
0.71072
4.736434
false
false
false
false
vlad1m1r990/KotlinSample
app/src/main/java/com/vlad1m1r/kotlintest/presentation/base/BaseAdapter.kt
1
1678
/* * Copyright 2017 Vladimir Jovanovic * * 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.vlad1m1r.kotlintest.presentation.base import android.content.Context import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup abstract class BaseAdapter<T : RecyclerView.ViewHolder, H> : RecyclerView.Adapter<T>() { private val listOfData: ArrayList<H> = ArrayList() override fun getItemCount(): Int = listOfData.size var list: List<H> get() = this.listOfData set(list) { this.listOfData.clear() this.listOfData.addAll(list) notifyDataSetChanged() } fun addList(list: List<H>) { val oldSize: Int = this.listOfData.size this.listOfData.addAll(list) notifyItemRangeChanged(oldSize, this.listOfData.size) } fun getLayoutInflater(context: Context): LayoutInflater = LayoutInflater.from(context) fun inflate(resId: Int, parent: ViewGroup, attachToRoot: Boolean): View = LayoutInflater.from(parent.context).inflate(resId, parent, attachToRoot) }
apache-2.0
1f3147d71ad33e4f931c9b71a16c9962
32.56
88
0.710369
4.26972
false
false
false
false
openstreetview/android
app/src/main/java/com/telenav/osv/data/collector/obddata/sensors/type/EngineTorqueObdSensor.kt
1
1656
package com.telenav.osv.data.collector.obddata.sensors.type import timber.log.Timber /** * Created by ovidiuc2 on 11/10/16. */ /** * class used for extracting the engine torque sensor value from OBD */ class EngineTorqueObdSensor : CarObdSensor<Int?> { override fun convertValue(hexResponse: String): Int? { return if (hexResponse.length < RESPONSE_LENGTH) { null } else getEngineTorque(hexResponse.substring(PREFIX_LENGTH)) } companion object { private val TAG = EngineTorqueObdSensor::class.java.simpleName /** * the required response length */ private const val RESPONSE_LENGTH = 8 /** * Prefix that comes with the hexadecimal response */ private const val PREFIX_LENGTH = 4 /** * Returns engine torque in Nm using formula 256a*b (AABB - > a = AA, b = BB) * * @param engineTorque Value in hexadecimal that comes from OBD * @return Engine torque in Nm */ private fun getEngineTorque(engineTorque: String): Int? { var engineTorque = engineTorque engineTorque = engineTorque.replace("\r".toRegex(), " ").replace(" ".toRegex(), "") return try { val a = Integer.decode("0x" + engineTorque[0] + engineTorque[1]) val b = Integer.decode("0x" + engineTorque[2] + engineTorque[3]) 256 * a + b } catch (e: NumberFormatException) { Timber.tag(TAG).e("Engine torque response has invalid format: %s", engineTorque) null } } } }
lgpl-3.0
b7d50840594a1b01c28a3cc8ec42c711
32.14
96
0.584541
4.14
false
false
false
false
shlusiak/Freebloks-Android
game/src/main/java/de/saschahlusiak/freebloks/network/message/MessageStoneHint.kt
1
1647
package de.saschahlusiak.freebloks.network.message import de.saschahlusiak.freebloks.model.Orientation import de.saschahlusiak.freebloks.model.Rotation import de.saschahlusiak.freebloks.model.Shape import de.saschahlusiak.freebloks.model.Turn import de.saschahlusiak.freebloks.network.* import de.saschahlusiak.freebloks.utils.toUnsignedByte import java.nio.ByteBuffer /** * Basically identical to [MessageSetStone] other than the type */ data class MessageStoneHint( val player: Int, val shape: Int, val mirrored: Boolean, val rotation: Rotation, val x: Int, val y: Int ): Message(MessageType.StoneHint, 6) { init { assert(player in 0..3) { "Player $player must be between 0 and 3"} assert(shape in 0..Shape.COUNT) { "Invalid shape $shape" } } override fun write(buffer: ByteBuffer) { super.write(buffer) buffer.put(player.toByte()) buffer.put(shape.toByte()) buffer.put((if (mirrored) 1 else 0).toByte()) buffer.put(rotation.value.toByte()) buffer.put(x.toByte()) buffer.put(y.toByte()) } fun toTurn() = Turn(player, shape, y, x, Orientation(mirrored, rotation)) companion object { fun from(data: ByteBuffer): MessageStoneHint { val player = data.get().toInt() val shape = data.get().toUnsignedByte() val mirrored = data.get().toInt() == 1 val rotation = Rotation.from(data.get().toInt()) val x = data.get().toInt() val y = data.get().toInt() return MessageStoneHint(player, shape, mirrored, rotation, x, y) } } }
gpl-2.0
5f06621666003a02e8a2a0ee72b9aaf9
31.313725
77
0.648452
3.997573
false
false
false
false
mctoyama/PixelClient
src/main/kotlin/org/pixelndice/table/pixelclient/connection/lobby/server/State00Start.kt
1
1043
package org.pixelndice.table.pixelclient.connection.lobby.server import org.apache.logging.log4j.LogManager import org.pixelndice.table.pixelprotocol.ChannelCanceledException import org.pixelndice.table.pixelprotocol.Protobuf private val logger = LogManager.getLogger(State00Start::class.java) class State00Start : State { override fun process(ctx: Context) { val packet: Protobuf.Packet? = ctx.channel.peekPacket() if( packet != null){ when(packet.payloadCase){ Protobuf.Packet.PayloadCase.PING -> { ctx.state = State01WaitingPing() } Protobuf.Packet.PayloadCase.LOBBYAUTH -> { ctx.state = State02WaitingLobbyAuth() } else -> { val message = "Expecting ping or LobbyAuth, instead received: $packet. IP: ${ctx.channel.address}" logger.error(message) ctx.state = StateStop() } } } } }
bsd-2-clause
caa78982d587ad6d8d50bfc9aa455697
30.636364
118
0.589645
4.762557
false
false
false
false
SapuSeven/BetterUntis
weekview/src/main/java/com/sapuseven/untis/views/weekview/WeekViewData.kt
1
1201
package com.sapuseven.untis.views.weekview class WeekViewData<T> { var eventChips: MutableList<EventChip<T>> = mutableListOf() internal var previousPeriodEvents: List<WeekViewEvent<T>>? = null internal var currentPeriodEvents: List<WeekViewEvent<T>>? = null internal var nextPeriodEvents: List<WeekViewEvent<T>>? = null internal var fetchedPeriod = -1 // the middle period the calendar has fetched. internal fun clearEventChipsCache() { eventChips.forEach { it.rect = null } } internal fun clear() { eventChips.clear() previousPeriodEvents = null currentPeriodEvents = null nextPeriodEvents = null fetchedPeriod = -1 } /** * Shortcut for calling cacheEvent(WeekViewEvent<T>) on every list item. * * @param events The events to be cached. */ internal fun cacheEvents(events: List<WeekViewEvent<T>>) { for (event in events.sorted()) cacheEvent(event) } /** * Cache the event for smooth scrolling functionality. * * @param event The event to cache. */ private fun cacheEvent(event: WeekViewEvent<T>) { if (event.startTime >= event.endTime) return event.splitWeekViewEvents().forEach { eventChips.add(EventChip(it, event, null)) } } }
gpl-3.0
c2bd3ecc0980677cec4ebe9e9a1d966f
24.020833
79
0.718568
3.511696
false
false
false
false
lchli/MiNote
host/src/main/java/com/lch/menote/user/vm/RegisterVM.kt
1
1964
package com.lch.menote.user.vm import android.text.TextUtils import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.lch.menote.file.FileModuleInjector import com.lch.menote.note.NoteApiManager import com.lch.menote.user.UserModuleInjector import com.lch.menote.user.domain.RegisterUseCase import com.lch.menote.user.route.User import com.lchli.arch.clean.ControllerCallback class RegisterVM: ViewModel() { private val mRegisterUseCase = RegisterUseCase(UserModuleInjector.getINS().provideRemoteUserDataSource(), UserModuleInjector.getINS().provideLocalUserDataSource(), FileModuleInjector.getINS().provideRemoteFileSource()) private val account= MutableLiveData<String>() private val pwd=MutableLiveData<String>() private val nick=MutableLiveData<String>() private val fail=MutableLiveData<String>() val launchDestination=MutableLiveData<String>() private val loading=MutableLiveData<Boolean>() fun register(): Unit { if (TextUtils.isEmpty(account.value) || TextUtils.isEmpty(pwd.value)) { fail.postValue("empty.") return } val p = RegisterUseCase.RegisterParams() p.userName = account.value p.userPwd = pwd.value p.userHeadPath = "" loading.postValue(true) mRegisterUseCase.invokeAsync(p, object : ControllerCallback<User> { override fun onSuccess(user: User?) { loading.postValue(false) if (user == null) { fail.postValue("user is null.") return } NoteApiManager.getINS().onUserLogin() launchDestination.postValue("user_center") // view.toUserCenter() } override fun onError(i: Int, s: String) { fail.postValue(s) loading.postValue(false) } }) } }
gpl-3.0
81e6b051f87487afc91263e88fb0d690
32.87931
124
0.648676
4.567442
false
false
false
false
gmariotti/intro-big-data
05_movies-example/src/main/kotlin/FilterMapper.kt
1
1673
import common.hadoop.extensions.split import org.apache.hadoop.io.LongWritable import org.apache.hadoop.io.NullWritable import org.apache.hadoop.io.Text import org.apache.hadoop.mapreduce.Mapper import org.apache.hadoop.mapreduce.lib.output.MultipleOutputs import java.io.BufferedReader import java.io.File import java.io.FileReader import java.util.stream.Collectors.toConcurrentMap class FilterMapper : Mapper<LongWritable, Text, NullWritable, Text>() { lateinit var multipleOutputs: MultipleOutputs<NullWritable, Text> var threshold: Int = 0 var categoriesByID = hashMapOf<Int, String>() override fun setup(context: Context) { multipleOutputs = MultipleOutputs(context) val cachedFiles = context.cacheFiles val file = BufferedReader(FileReader(File(cachedFiles[0]))) categoriesByID = file.use { it.lines() .map { it.split("\t") } .map { it[0].toInt() to it[1] } .collect(toConcurrentMap( { pair: Pair<Int, String> -> pair.first } ) { (_, second) -> second }) .toMap(categoriesByID) } threshold = context.configuration.getInt(THRESHOLD, 0) } override fun map(key: LongWritable, value: Text, context: Context) { val values = value.split(",") val film = values[0] val duration = values[1].toInt() val categories = values.subList(2, values.size) .map { categoriesByID[it.toInt()] } .toList() .joinToString(",") if (duration <= threshold) { multipleOutputs.write(LOW_DURATION, NullWritable.get(), "$film,$categories") } else { multipleOutputs.write(HIGH_DURATION, NullWritable.get(), "$film,$categories") } } override fun cleanup(context: Context?) { multipleOutputs.close() } }
mit
fa4bb5fdd31a5f91e437d33e9e577831
30
80
0.716677
3.456612
false
false
false
false
AndroidX/androidx
wear/wear-phone-interactions/src/main/java/androidx/wear/phone/interactions/authentication/RemoteAuthService.kt
3
7326
/* * 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.wear.phone.interactions.authentication import android.annotation.SuppressLint import android.app.Service import android.content.Context import android.content.Intent import android.net.Uri import android.os.Binder import android.os.Bundle import android.os.IBinder import android.os.RemoteException import android.support.wearable.authentication.IAuthenticationRequestCallback import android.support.wearable.authentication.IAuthenticationRequestService import androidx.wear.phone.interactions.authentication.RemoteAuthClient.Companion.KEY_ERROR_CODE import androidx.wear.phone.interactions.authentication.RemoteAuthClient.Companion.KEY_PACKAGE_NAME import androidx.wear.phone.interactions.authentication.RemoteAuthClient.Companion.KEY_RESPONSE_URL import java.security.SecureRandom /** * Interface for specifying how the service handles the remote auth requests. */ public interface RemoteAuthRequestHandler { /** * Whether the auth service is enabled, return false would give an early out by sending the * 3p app a response with error code of ERROR_UNSUPPORTED */ public fun isAuthSupported(): Boolean /** * Handle the auth request by sending it to the phone. * Typically, if the paired phone is not connected, send a response with error code of * [RemoteAuthClient.ERROR_PHONE_UNAVAILABLE]; otherwise listening for the response from the * phone and send it back to the 3p app. * * [RemoteAuthService.sendResponseToCallback] is provided for sending response back to the * callback provided by the 3p app. * */ public fun sendAuthRequest( request: OAuthRequest, packageNameAndRequestId: Pair<String, Int> ) } /* * Extend this service class to trigger the handling of the remote auth requests, the * RemoteAuthRequestHandler is specified when the service is bound, typically: * * class AuthenticationService : RemoteAuthService { * override fun onBind(intent: Intent): IBinder { * return onBind( * intent, * object : RemoteAuthRequestHandler { * override fun isAuthSupported(): Boolean {...} * override fun sendAuthRequest(...) { * ... * sendResponseToCallback(...) * } * }) * } * } */ public abstract class RemoteAuthService : Service() { public companion object { @JvmStatic private val callbacksByPackageNameAndRequestID: MutableMap<Pair<String, Int>, IAuthenticationRequestCallback> = HashMap() /** * To be called by the child class to invoke the callback with Response */ @SuppressLint("DocumentExceptions") @JvmStatic public fun sendResponseToCallback( response: OAuthResponse, packageNameAndRequestId: Pair<String, Int> ) { try { callbacksByPackageNameAndRequestID[packageNameAndRequestId]?.onResult( buildBundleFromResponse(response, packageNameAndRequestId.first) ) callbacksByPackageNameAndRequestID.remove(packageNameAndRequestId) } catch (e: RemoteException) { throw e.cause!! } } internal fun getCallback(packageNameAndRequestId: Pair<String, Int>): IAuthenticationRequestCallback? = callbacksByPackageNameAndRequestID[packageNameAndRequestId] internal fun buildBundleFromResponse(response: OAuthResponse, packageName: String): Bundle = Bundle().apply { putParcelable(KEY_RESPONSE_URL, response.responseUrl) putInt(KEY_ERROR_CODE, response.errorCode) putString(KEY_PACKAGE_NAME, packageName) } } private val secureRandom: SecureRandom = SecureRandom() /** * To be called by child class when implementing the [Service.onBind], provide the * RemoteAuthRequestHandler and return the IBinder. */ protected fun onBind( @Suppress("UNUSED_PARAMETER") intent: Intent, remoteAuthRequestHandler: RemoteAuthRequestHandler ): IBinder = RemoteAuthServiceBinder(this, remoteAuthRequestHandler) /** * Implementation of [Service.onUnbind] */ public override fun onUnbind(intent: Intent): Boolean { callbacksByPackageNameAndRequestID.clear() return super.onUnbind(intent) } /** * Allow the child class to override the default behavior of the package name verification. * * By default, we check the request's package name belongs to the requester's UID. */ protected open fun verifyPackageName(context: Context, requestPackageName: String?): Boolean { val packagesForUID: Array<String>? = context.packageManager.getPackagesForUid(Binder.getCallingUid()) return !( requestPackageName.isNullOrEmpty() || packagesForUID.isNullOrEmpty() || !(packagesForUID.contains(requestPackageName)) ) } internal inner class RemoteAuthServiceBinder( private val context: Context, private val remoteAuthRequestHandler: RemoteAuthRequestHandler ) : IAuthenticationRequestService.Stub() { override fun getApiVersion(): Int = IAuthenticationRequestService.API_VERSION /** * @throws SecurityException */ @Suppress("DEPRECATION") override fun openUrl( request: Bundle, authenticationRequestCallback: IAuthenticationRequestCallback ) { val packageName = request.getString(RemoteAuthClient.KEY_PACKAGE_NAME) if (remoteAuthRequestHandler.isAuthSupported()) { if (!verifyPackageName(context, packageName)) { throw SecurityException("Failed to verify the Requester's package name") } val packageNameAndRequestId = Pair(packageName!!, secureRandom.nextInt()) callbacksByPackageNameAndRequestID[packageNameAndRequestId] = authenticationRequestCallback val requestUrl: Uri? = request.getParcelable(RemoteAuthClient.KEY_REQUEST_URL) remoteAuthRequestHandler.sendAuthRequest( OAuthRequest(packageName, requestUrl!!), packageNameAndRequestId ) } else { authenticationRequestCallback.onResult( Bundle().apply { putInt(KEY_ERROR_CODE, RemoteAuthClient.ERROR_UNSUPPORTED) } ) } } } }
apache-2.0
cddcabdb998b2e7d70631ead3b37e126
37.767196
100
0.668168
5.184713
false
false
false
false
pyamsoft/padlock
padlock/src/main/java/com/pyamsoft/padlock/main/MainFragment.kt
1
3281
/* * Copyright 2019 Peter Kenji Yamanaka * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.pyamsoft.padlock.main import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.annotation.CheckResult import androidx.fragment.app.Fragment import com.pyamsoft.padlock.Injector import com.pyamsoft.padlock.PadLockComponent import com.pyamsoft.padlock.R import com.pyamsoft.padlock.list.LockListFragment import com.pyamsoft.padlock.purge.PurgeFragment import com.pyamsoft.padlock.settings.SettingsFragment import com.pyamsoft.pydroid.ui.app.requireToolbarActivity import com.pyamsoft.pydroid.ui.util.commit import com.pyamsoft.pydroid.ui.util.setUpEnabled import javax.inject.Inject class MainFragment : Fragment() { @field:Inject internal lateinit var mainView: MainFragmentView override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { Injector.obtain<PadLockComponent>(requireActivity().applicationContext) .plusMainFragmentComponent() .owner(viewLifecycleOwner) .inflater(inflater) .container(container) .savedInstanceState(savedInstanceState) .build() .inject(this) mainView.create() return mainView.root() } override fun onViewCreated( view: View, savedInstanceState: Bundle? ) { super.onViewCreated(view, savedInstanceState) mainView.onBottomNavigationClicked { return@onBottomNavigationClicked when (it) { R.id.menu_locklist -> replaceFragment(LockListFragment(), LockListFragment.TAG) R.id.menu_settings -> replaceFragment(SettingsFragment(), SettingsFragment.TAG) R.id.menu_purge -> replaceFragment(PurgeFragment(), PurgeFragment.TAG) else -> false } } if (childFragmentManager.findFragmentById(R.id.main_view_container) == null) { mainView.loadDefaultPage() } } @CheckResult private fun replaceFragment( fragment: Fragment, tag: String ): Boolean { val containerId = R.id.main_view_container val fragmentManager = childFragmentManager val currentFragment: Fragment? = fragmentManager.findFragmentById(containerId) // Do nothing on same fragment if (currentFragment != null && currentFragment.tag == tag) { return false } fragmentManager.beginTransaction() .replace(containerId, fragment, tag) .commit(viewLifecycleOwner) return true } override fun onResume() { super.onResume() requireToolbarActivity().withToolbar { it.setTitle(R.string.app_name) it.setUpEnabled(false) } } companion object { const val TAG = "MainFragment" } }
apache-2.0
38efc71f32a9144b7fadf5119f8693b5
28.558559
87
0.729656
4.506868
false
false
false
false
adam-arold/hexameter
mixite.core/core/src/main/kotlin/org/hexworks/mixite/core/internal/impl/HexagonalGridCalculatorImpl.kt
1
4648
package org.hexworks.mixite.core.internal.impl import org.hexworks.cobalt.datatypes.Maybe import org.hexworks.mixite.core.api.* import org.hexworks.mixite.core.api.contract.SatelliteData import kotlin.math.abs import kotlin.math.max import kotlin.math.min import kotlin.math.round class HexagonalGridCalculatorImpl<T : SatelliteData>(private val hexagonalGrid: HexagonalGrid<T>) : HexagonalGridCalculator<T> { override fun calculateDistanceBetween(hex0: Hexagon<T>, hex1: Hexagon<T>): Int { val absX = abs(hex0.gridX - hex1.gridX) val absY = abs(hex0.gridY - hex1.gridY) val absZ = abs(hex0.gridZ - hex1.gridZ) return max(max(absX, absY), absZ) } override fun calculateMovementRangeFrom(hexagon: Hexagon<T>, distance: Int): Set<Hexagon<T>> { val ret = HashSet<Hexagon<T>>() for (x in -distance..distance) { for (y in max(-distance, -x - distance)..min(distance, -x + distance)) { val z = -x - y val tmpX = hexagon.gridX + x val tmpZ = hexagon.gridZ + z val tempCoordinate = CubeCoordinate.fromCoordinates(tmpX, tmpZ) if (hexagonalGrid.containsCubeCoordinate(tempCoordinate)) { val hex = hexagonalGrid.getByCubeCoordinate(tempCoordinate).get() ret.add(hex) } } } return ret } override fun rotateHexagon(originalHex: Hexagon<T>, targetHex: Hexagon<T>, rotationDirection: RotationDirection): Maybe<Hexagon<T>> { val diffX = targetHex.gridX - originalHex.gridX val diffZ = targetHex.gridZ - originalHex.gridZ val diffCoord = CubeCoordinate.fromCoordinates(diffX, diffZ) val rotatedCoord = rotationDirection.calculateRotation(diffCoord) val resultCoord = CubeCoordinate.fromCoordinates( originalHex.gridX + rotatedCoord.gridX, originalHex.gridZ + rotatedCoord.gridZ) // 0, x, return hexagonalGrid.getByCubeCoordinate(resultCoord) } override fun calculateRingFrom(centerHexagon: Hexagon<T>, radius: Int): Set<Hexagon<T>> { val result = HashSet<Hexagon<T>>() val neighborIndex = 0 var currentHexagon = centerHexagon for (i in 0 until radius) { val neighbor = hexagonalGrid.getNeighborByIndex(currentHexagon, neighborIndex) if (neighbor.isPresent) { currentHexagon = neighbor.get() } else { return result } } return result } override fun drawLine(from: Hexagon<T>, to: Hexagon<T>): List<Hexagon<T>> { val distance = calculateDistanceBetween(from, to) val results = mutableListOf<Hexagon<T>>() if (distance == 0) { return results } for (i in 0..distance) { val interpolatedCoordinate = cubeLinearInterpolate(from.cubeCoordinate, to.cubeCoordinate, 1.0 / distance * i) results.add(hexagonalGrid.getByCubeCoordinate(interpolatedCoordinate).get()) } return results } override fun isVisible(from: Hexagon<T>, to: Hexagon<T>): Boolean { val traversePath = drawLine(from, to) for (pathHexagon in traversePath) { if (pathHexagon.equals(from) || pathHexagon.equals(to)) { continue } if (pathHexagon.satelliteData.isPresent && pathHexagon.satelliteData.get().opaque) { return false } } return true } private fun cubeLinearInterpolate(from: CubeCoordinate, to: CubeCoordinate, sample: Double): CubeCoordinate { return roundToCubeCoordinate(linearInterpolate(from.gridX, to.gridX, sample), linearInterpolate(from.gridY, to.gridY, sample), linearInterpolate(from.gridZ, to.gridZ, sample)) } private fun linearInterpolate(from: Int, to: Int, sample: Double): Double { return from + (to - from) * sample } private fun roundToCubeCoordinate(gridX: Double, gridY: Double, gridZ: Double): CubeCoordinate { var rx = round(gridX).toInt() val ry = round(gridY).toInt() var rz = round(gridZ).toInt() val differenceX = abs(rx - gridX) val differenceY = abs(ry - gridY) val differenceZ = abs(rz - gridZ) if (differenceX > differenceY && differenceX > differenceZ) { rx = -ry - rz } else if (differenceY <= differenceZ) { rz = -rx - ry } return CubeCoordinate.fromCoordinates(rx, rz) } }
mit
b5aef670f6044a3e3523fe3bb7a22f08
39.068966
137
0.619621
4.283871
false
false
false
false
HabitRPG/habitrpg-android
Habitica/src/main/java/com/habitrpg/android/habitica/models/social/UserParty.kt
2
606
package com.habitrpg.android.habitica.models.social import com.google.gson.annotations.SerializedName import com.habitrpg.android.habitica.models.BaseObject import com.habitrpg.android.habitica.models.inventory.Quest import io.realm.RealmObject import io.realm.annotations.RealmClass @RealmClass(embedded = true) open class UserParty : RealmObject(), BaseObject { @SerializedName("_id") var id: String = "" var quest: Quest? = null @SerializedName("order") var partyOrder: String? = null // Order to display ppl var orderAscending: String? = null // Order type }
gpl-3.0
cd373d36a29b72dfe68d6734d3ce6f3c
33.647059
59
0.737624
4.04
false
false
false
false
yzbzz/beautifullife
icore/src/main/java/com/ddu/icore/dialog/AlertDialogFragment.kt
2
2633
package com.ddu.icore.dialog import android.content.DialogInterface import android.os.Bundle import android.text.method.LinkMovementMethod import android.util.Log import android.view.* import com.ddu.icore.R import kotlinx.android.synthetic.main.i_fragment_dialog_default.* class AlertDialogFragment : androidx.fragment.app.DialogFragment(), View.OnClickListener { var title = "" var msg = "" var special: CharSequence = "" var leftText = "" var rightText = "" var msgGravity = Gravity.CENTER var leftColor = R.color.c_4897fa var rightColor = R.color.c_272727 var mLeftClickListener: ((View, androidx.fragment.app.DialogFragment) -> Unit)? = null var mRightClickListener: ((View, androidx.fragment.app.DialogFragment) -> Unit)? = null var size = 17f override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { dialog?.window?.requestFeature(Window.FEATURE_NO_TITLE) dialog?.window?.setBackgroundDrawableResource(android.R.color.transparent) return inflater.inflate(R.layout.i_fragment_dialog_default, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) if (title.isNotEmpty()) { tv_dialog_title.text = title tv_dialog_title.visibility = View.VISIBLE view_line.visibility = View.VISIBLE } tv_dialog_msg.gravity = msgGravity tv_dialog_msg.textSize = size tv_dialog_msg.text = special tv_dialog_msg.movementMethod = LinkMovementMethod() tv_dialog_btn_left.text = leftText var color = resources.getColor(leftColor) tv_dialog_btn_left.setTextColor(color) if (!rightText.isNullOrEmpty()) { color = resources.getColor(rightColor) tv_dialog_btn_right.visibility = View.VISIBLE tv_dialog_btn_right.text = rightText tv_dialog_btn_right.setTextColor(color) } tv_dialog_btn_left.setOnClickListener(this) tv_dialog_btn_right.setOnClickListener(this) } override fun onClick(v: View) { val id = v.id if (id == R.id.tv_dialog_btn_left && null != mLeftClickListener) { mLeftClickListener?.invoke(v, this) } else if (id == R.id.tv_dialog_btn_right && null != mRightClickListener) { mRightClickListener?.invoke(v, this) } } override fun onDismiss(dialog: DialogInterface) { super.onDismiss(dialog) Log.v("lhz", "onDismiss") } }
apache-2.0
39b3e45d4d45f355fefa5c3710a092ef
31.9125
116
0.664641
4.172742
false
false
false
false
arcuri82/testing_security_development_enterprise_systems
advanced/exercise-solutions/card-game/part-10/scores/src/main/kotlin/org/tsdes/advanced/exercises/cardgame/scores/RestApi.kt
3
3124
package org.tsdes.advanced.exercises.cardgame.scores import io.swagger.annotations.Api import io.swagger.annotations.ApiOperation import io.swagger.annotations.ApiParam import org.springframework.http.CacheControl import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.* import org.tsdes.advanced.exercises.cardgame.scores.db.UserStatsRepository import org.tsdes.advanced.exercises.cardgame.scores.db.UserStatsService import org.tsdes.advanced.exercises.cardgame.scores.dto.UserStatsDto import org.tsdes.advanced.rest.dto.PageDto import org.tsdes.advanced.rest.dto.RestResponseFactory import org.tsdes.advanced.rest.dto.WrappedResponse import java.util.concurrent.TimeUnit @Api(value = "/api/scores", description = "Scores and ranks of the players, based on their victories and defeats") @RequestMapping( path = ["/api/scores"], produces = [(MediaType.APPLICATION_JSON_VALUE)] ) @RestController class RestApi( private val statsRepository: UserStatsRepository, private val statsService: UserStatsService ) { @ApiOperation("Retrieve the current score statistics for the given player") @GetMapping(path = ["/{userId}"]) fun getUserStatsInfo( @PathVariable("userId") userId: String ): ResponseEntity<WrappedResponse<UserStatsDto>> { val user = statsRepository.findById(userId).orElse(null) if (user == null) { return RestResponseFactory.notFound("User $userId not found") } return RestResponseFactory.payload(200, DtoConverter.transform(user)) } @ApiOperation("Create default info for a new player") @PutMapping(path = ["/{userId}"]) fun createUser( @PathVariable("userId") userId: String ): ResponseEntity<WrappedResponse<Void>> { val ok = statsService.registerNewUser(userId) return if (!ok) RestResponseFactory.userFailure("User $userId already exist") else RestResponseFactory.noPayload(201) } @ApiOperation("Return an iterable page of leaderboard results, starting from the top player") @GetMapping fun getAll( @ApiParam("Id of player in the previous page") @RequestParam("keysetId", required = false) keysetId: String?, // @ApiParam("Score of the player in the previous page") @RequestParam("keysetScore", required = false) keysetScore: Int?): ResponseEntity<WrappedResponse<PageDto<UserStatsDto>>> { val page = PageDto<UserStatsDto>() val n = 10 val scores = DtoConverter.transform(statsService.getNextPage(n, keysetId, keysetScore)) page.list = scores if (scores.size == n) { val last = scores.last() page.next = "/api/scores?keysetId=${last.userId}&keysetScore=${last.score}" } return ResponseEntity .status(200) .cacheControl(CacheControl.maxAge(1, TimeUnit.MINUTES).cachePublic()) .body(WrappedResponse(200, page).validated()) } }
lgpl-3.0
765f0a711d15a19b94ebf17104a15235
36.650602
114
0.693342
4.507937
false
false
false
false
android/identity-samples
Fido2/app/src/main/java/com/google/android/gms/identity/sample/fido2/ui/username/UsernameViewModel.kt
1
1978
/* * Copyright 2021 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gms.identity.sample.fido2.ui.username import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.google.android.gms.identity.sample.fido2.repository.AuthRepository import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class UsernameViewModel @Inject constructor( private val repository: AuthRepository ) : ViewModel() { private val _sending = MutableStateFlow(false) val sending = _sending.asStateFlow() val username = MutableStateFlow("") val nextEnabled = combine(sending, username) { isSending, username -> !isSending && username.isNotBlank() }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(), false) fun sendUsername() { val username = username.value if (username.isNotBlank()) { viewModelScope.launch { _sending.value = true try { repository.username(username) } finally { _sending.value = false } } } } }
apache-2.0
e7e9ed985dac27b5114aff625bc16eb4
33.103448
77
0.710313
4.665094
false
false
false
false
androidx/androidx
fragment/fragment/src/androidTest/java/androidx/fragment/app/MockitoUtils.kt
3
2848
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.fragment.app import android.os.SystemClock import org.mockito.exceptions.base.MockitoAssertionError import org.mockito.internal.verification.VerificationModeFactory import org.mockito.internal.verification.api.VerificationData import org.mockito.verification.VerificationMode private const val TIME_SLICE: Long = 50 fun within(timeout: Long): VerificationMode { return object : VerificationMode { override fun verify(data: VerificationData) { var remainingTime = timeout var errorToRethrow: MockitoAssertionError? = null // Loop in the same way we do in PollingCheck, sleeping and then testing for the target // invocation while (remainingTime > 0) { SystemClock.sleep(TIME_SLICE) try { val actualInvocations = data.allInvocations // Iterate over all invocations so far to see if we have a match for (invocation in actualInvocations) { if (data.target.matches(invocation)) { // Found our match within our timeout. Mark all invocations as verified markAllInvocationsAsVerified(data) // and return return } } } catch (assertionError: MockitoAssertionError) { errorToRethrow = assertionError } remainingTime -= TIME_SLICE } if (errorToRethrow != null) { throw errorToRethrow } throw MockitoAssertionError( "Timed out while waiting ${remainingTime}ms for ${data.target}" ) } override fun description(description: String): VerificationMode { return VerificationModeFactory.description(this, description) } private fun markAllInvocationsAsVerified(data: VerificationData) { for (invocation in data.allInvocations) { invocation.markVerified() data.target.captureArgumentsFrom(invocation) } } } }
apache-2.0
2b86a531259ff008d1d0dace90d0d409
36.973333
99
0.616573
5.313433
false
false
false
false
attila-kiss-it/querydsl
querydsl-kotlin-codegen/src/main/kotlin/com/querydsl/kotlin/codegen/KotlinEntitySerializer.kt
1
16488
/* * Copyright 2021, The Querydsl Team (http://www.querydsl.com/team) * * 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.querydsl.kotlin.codegen import com.querydsl.codegen.CodegenModule import com.querydsl.codegen.EntitySerializer import com.querydsl.codegen.EntityType import com.querydsl.codegen.GeneratedAnnotationResolver import com.querydsl.codegen.Property import com.querydsl.codegen.SerializerConfig import com.querydsl.codegen.TypeMappings import com.querydsl.codegen.utils.CodeWriter import com.querydsl.codegen.utils.model.SimpleType import com.querydsl.codegen.utils.model.Type import com.querydsl.codegen.utils.model.TypeCategory import com.querydsl.core.types.Path import com.querydsl.core.types.PathMetadata import com.querydsl.core.types.PathMetadataFactory import com.querydsl.core.types.dsl.ArrayPath import com.querydsl.core.types.dsl.BooleanPath import com.querydsl.core.types.dsl.CollectionPath import com.querydsl.core.types.dsl.CollectionPathBase import com.querydsl.core.types.dsl.ComparablePath import com.querydsl.core.types.dsl.DatePath import com.querydsl.core.types.dsl.DateTimePath import com.querydsl.core.types.dsl.EntityPathBase import com.querydsl.core.types.dsl.EnumPath import com.querydsl.core.types.dsl.ListPath import com.querydsl.core.types.dsl.MapPath import com.querydsl.core.types.dsl.NumberPath import com.querydsl.core.types.dsl.SetPath import com.querydsl.core.types.dsl.StringPath import com.querydsl.core.types.dsl.TimePath import com.squareup.kotlinpoet.AnnotationSpec import com.squareup.kotlinpoet.CodeBlock import com.squareup.kotlinpoet.FileSpec import com.squareup.kotlinpoet.FunSpec import com.squareup.kotlinpoet.KModifier import com.squareup.kotlinpoet.ParameterSpec import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy import com.squareup.kotlinpoet.PropertySpec import com.squareup.kotlinpoet.TypeName import com.squareup.kotlinpoet.TypeSpec import com.squareup.kotlinpoet.WildcardTypeName import com.squareup.kotlinpoet.asTypeName import com.squareup.kotlinpoet.buildCodeBlock import javax.inject.Inject import javax.inject.Named import kotlin.reflect.KClass open class KotlinEntitySerializer @Inject constructor( private val mappings: TypeMappings, @Named(CodegenModule.KEYWORDS) protected val keywords: Collection<String>, @Named(CodegenModule.GENERATED_ANNOTATION_CLASS) private val generatedAnnotationClass: Class<out Annotation> = GeneratedAnnotationResolver.resolveDefault() ) : EntitySerializer { override fun serialize(model: EntityType, config: SerializerConfig, writer: CodeWriter) { val queryType: Type = mappings.getPathType(model, model, false) FileSpec.builder(queryType.packageName, queryType.simpleName) .addImport(PathMetadataFactory::class, "forVariable", "forProperty") .addType( intro(model, config) .serializeProperties(model, config) .constructors(model, config) .build() ) .build() .writeTo(writer) } protected open fun intro(model: EntityType, config: SerializerConfig): TypeSpec.Builder { return introClassHeader(model, config) .introJavadoc(model, config) .introSuper(model) } protected open fun introClassHeader(model: EntityType, config: SerializerConfig): TypeSpec.Builder { val pathType = if (model.properties.isEmpty()) { when (model.originalCategory) { TypeCategory.COMPARABLE -> ComparablePath::class TypeCategory.ENUM -> EnumPath::class TypeCategory.DATE -> DatePath::class TypeCategory.DATETIME -> DateTimePath::class TypeCategory.TIME -> TimePath::class TypeCategory.NUMERIC -> NumberPath::class TypeCategory.STRING -> StringPath::class TypeCategory.BOOLEAN -> BooleanPath::class else -> defaultSuperType() } } else { defaultSuperType() } val superType = when (model.originalCategory) { TypeCategory.BOOLEAN, TypeCategory.STRING -> pathType.asTypeName() else -> pathType.parameterizedBy(model) } return TypeSpec.classBuilder(mappings.getPathClassName(model, model)) .addAnnotations(model.annotations.map { AnnotationSpec.get(it) }) .addAnnotation(AnnotationSpec.builder(generatedAnnotationClass).addMember("%S", javaClass.name).build()) .superclass(superType) .addType(introCompanion(model, config)) } protected open fun defaultSuperType(): KClass<out Path<*>> = EntityPathBase::class protected open fun introCompanion(model: EntityType, config: SerializerConfig): TypeSpec { return TypeSpec.companionObjectBuilder() .addProperty(PropertySpec.builder("serialVersionUID", Long::class, KModifier.CONST, KModifier.PRIVATE).initializer("%L", model.fullName.hashCode()).build()) .let { if (config.createDefaultVariable()) it.introDefaultInstance(model, config.defaultVariableName()) else it } .build() } protected open fun TypeSpec.Builder.introJavadoc(model: EntityType, config: SerializerConfig): TypeSpec.Builder = apply { addKdoc("%L is a Querydsl query type for %L", mappings.getPathType(model, model, true).simpleName, model.simpleName) } protected open fun TypeSpec.Builder.introDefaultInstance(model: EntityType, defaultName: String): TypeSpec.Builder = apply { val simpleName = if (defaultName.isNotEmpty()) defaultName else model.modifiedSimpleName val queryType = mappings.getPathClassName(model, model) val alias = if (keywords.contains(simpleName.toUpperCase())) "${simpleName}1" else simpleName addProperty(PropertySpec.builder(simpleName, queryType, KModifier.PUBLIC).initializer("%T(%S)", queryType, alias).build()) } protected open fun TypeSpec.Builder.introSuper(model: EntityType): TypeSpec.Builder = apply { val superType = model.superType?.entityType if (superType != null) { val superQueryType = mappings.getPathTypeName(superType, model) addProperty( PropertySpec.builder("_super", superQueryType, KModifier.PUBLIC) .delegate(buildCodeBlock { beginControlFlow("lazy") addStatement("%T(this)", superQueryType) endControlFlow() }).build() ) } } protected open fun TypeSpec.Builder.serializeProperties(model: EntityType, config: SerializerConfig): TypeSpec.Builder = apply { model.properties.forEach { property -> // FIXME : the custom types should have the custom type category if (mappings.isRegistered(property.type) && property.type.category != TypeCategory.CUSTOM && property.type.category != TypeCategory.ENTITY) { customField(model, property, config) } else { // strips of "? extends " etc val queryType = mappings.getPathTypeName(SimpleType(property.type, property.type.parameters), model) val classStatement = property.type.asClassNameStatement() when (property.type.category ?: TypeCategory.ENTITY) { TypeCategory.STRING -> serialize(model, property, queryType, "createString") TypeCategory.BOOLEAN -> serialize(model, property, queryType, "createBoolean") TypeCategory.SIMPLE -> serialize(model, property, queryType, "createSimple", classStatement) TypeCategory.COMPARABLE -> serialize(model, property, queryType, "createComparable", classStatement) TypeCategory.ENUM -> serialize(model, property, queryType, "createEnum", classStatement) TypeCategory.DATE -> serialize(model, property, queryType, "createDate", classStatement) TypeCategory.DATETIME -> serialize(model, property, queryType, "createDateTime", classStatement) TypeCategory.TIME -> serialize(model, property, queryType, "createTime", classStatement) TypeCategory.NUMERIC -> serialize(model, property, queryType, "createNumber", classStatement) TypeCategory.CUSTOM -> customField(model, property, config) TypeCategory.ARRAY -> serialize(model, property, ArrayPath::class.parameterizedBy(property.type, property.type.componentType), "createArray", classStatement) TypeCategory.COLLECTION -> collectionField(model, property, "createCollection", CollectionPath::class) TypeCategory.SET -> collectionField(model, property, "createSet", SetPath::class) TypeCategory.LIST -> collectionField(model, property, "createList", ListPath::class) TypeCategory.MAP -> { val genericQueryType = mappings.getPathType(getRaw(property.getParameter(1)), model, false) val qType = mappings.getPathClassName(property.getParameter(1), model) serialize( model, property, MapPath::class.parameterizedBy(getRaw(property.getParameter(0)), getRaw(property.getParameter(1)), genericQueryType), CodeBlock.of("this.createMap<%T, %T, %T>", property.getParameter(0).asTypeName(), property.getParameter(1).asTypeName(), genericQueryType.asTypeName()), property.getParameter(0).asClassNameStatement(), property.getParameter(1).asClassNameStatement(), qType.asClassStatement() ) } TypeCategory.ENTITY -> entityField(model, property, config) } } } } private fun TypeSpec.Builder.collectionField(model: EntityType, property: Property, factoryMethod: String, pathClass: KClass<out CollectionPathBase<*, *, *>>) { val genericQueryType = mappings.getPathType(getRaw(property.getParameter(0)), model, false) val qType = mappings.getPathClassName(property.getParameter(0), model) serialize( model, property, pathClass.parameterizedBy(getRaw(property.getParameter(0)), genericQueryType), CodeBlock.of("this.%L<%T, %T>", factoryMethod, property.getParameter(0).asTypeName(), genericQueryType.asTypeName()), property.getParameter(0).asClassNameStatement(), qType.asClassStatement(), "null".asCodeBlock() ) } protected open fun TypeSpec.Builder.customField(model: EntityType, field: Property, config: SerializerConfig) { val queryType = mappings.getPathTypeName(field.type, model) val builder = PropertySpec.builder(field.escapedName, queryType, KModifier.PUBLIC).addKdoc("custom") if (field.isInherited) { builder.addKdoc("inherited") builder.delegate(buildCodeBlock { beginControlFlow("lazy") addStatement("%T(_super.%L)", queryType, field.escapedName) endControlFlow() }) } else { builder.initializer("%T(forProperty(%S))", queryType, field.name) } addProperty(builder.build()) } protected open fun TypeSpec.Builder.serialize(model: EntityType, field: Property, type: TypeName, factoryMethod: Any, vararg args: CodeBlock) { val superType = model.superType val builder = PropertySpec.builder(field.escapedName, type, KModifier.PUBLIC) if (field.isInherited && superType != null) { builder.delegate(buildCodeBlock { beginControlFlow("lazy") addStatement("_super.%L", field.escapedName) endControlFlow() }) } else { builder.initializer("%L(%S${", %L".repeat(args.size)})", factoryMethod, field.name, *args) } if (field.isInherited) { builder.addKdoc("inherited") } addProperty(builder.build()) } private fun getRaw(type: Type): Type { return if (type is EntityType && type.getPackageName().startsWith("ext.java")) { type } else { SimpleType(type, type.parameters) } } protected open fun TypeSpec.Builder.entityField(model: EntityType, field: Property, config: SerializerConfig) { val fieldType = mappings.getPathTypeName(field.type, model) val builder = PropertySpec.builder(field.escapedName, fieldType) if (field.isInherited) { builder.addKdoc("inherited") } builder.addModifiers(if (config.useEntityAccessors()) KModifier.PROTECTED else KModifier.PUBLIC) builder.delegate(buildCodeBlock { beginControlFlow("lazy") addStatement("%T(forProperty(%S))", fieldType, field.name) endControlFlow() }) addProperty(builder.build()) } protected open fun TypeSpec.Builder.constructors(model: EntityType, config: SerializerConfig): TypeSpec.Builder { val stringOrBoolean = (model.originalCategory == TypeCategory.STRING || model.originalCategory == TypeCategory.BOOLEAN) // String constructorsForVariables(model) // Path val path = ParameterSpec.builder("path", if (model.isFinal) Path::class.parameterizedBy(model) else Path::class.parameterizedBy(model.asOutTypeName())).build() val pathConstructor = FunSpec.constructorBuilder().addParameter(path) if (stringOrBoolean) { pathConstructor.callSuperConstructor(CodeBlock.of("%N.metadata", path)) } else { pathConstructor.callSuperConstructor(CodeBlock.of("%N.type", path), CodeBlock.of("%N.metadata", path)) } pathConstructor.addCode(constructorContent(model)) addFunction(pathConstructor.build()) // PathMetadata val metadata = ParameterSpec.builder("metadata", PathMetadata::class).build() val pathMetadataConstructor = FunSpec.constructorBuilder().addParameter(metadata) if (stringOrBoolean) { pathMetadataConstructor.callSuperConstructor(metadata.asCodeBlock()) } else { pathMetadataConstructor.callSuperConstructor(model.asClassNameStatement(), metadata.asCodeBlock()) } pathConstructor.addCode(constructorContent(model)) addFunction(pathMetadataConstructor.build()) // Class, PathMetadata val type = ParameterSpec.builder("type", Class::class.asTypeName().parameterizedBy(WildcardTypeName.producerOf(model.asTypeName()))).build() addFunction( FunSpec.constructorBuilder() .addParameter(type) .addParameter(metadata) .callSuperConstructor(type.asCodeBlock(), metadata.asCodeBlock()) .addCode(constructorContent(model)).build() ) return this } protected open fun constructorContent(model: EntityType): CodeBlock { // override in subclasses return CodeBlock.builder().build() } protected open fun TypeSpec.Builder.constructorsForVariables(model: EntityType) { val stringOrBoolean = (model.originalCategory == TypeCategory.STRING || model.originalCategory == TypeCategory.BOOLEAN) val variable = ParameterSpec.builder("variable", String::class).build() val builder = FunSpec.constructorBuilder().addParameter(variable) if (stringOrBoolean) { builder.callSuperConstructor(CodeBlock.of("forVariable(%N)", variable)) } else { builder.callSuperConstructor(model.asClassNameStatement(), CodeBlock.of("forVariable(%N)", variable)) } builder.addCode(constructorContent(model)) addFunction(builder.build()) } }
apache-2.0
f1627213b69dfdabb438b658947b00d3
51.012618
180
0.678069
4.855124
false
true
false
false
pedroSG94/rtmp-rtsp-stream-client-java
rtmp/src/main/java/com/pedro/rtmp/rtmp/message/BasicHeader.kt
2
2975
/* * Copyright (C) 2021 pedroSG94. * * 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.pedro.rtmp.rtmp.message import com.pedro.rtmp.rtmp.chunk.ChunkType import java.io.IOException import java.io.InputStream import kotlin.experimental.and /** * Created by pedro on 21/04/21. * * cs id (6 bits) * fmt (2 bits) * cs id - 64 (8 or 16 bits) * * 0 1 2 3 4 5 6 7 * +-+-+-+-+-+-+-+-+ * |fmt| cs id | * +-+-+-+-+-+-+-+-+ * Chunk basic header 1 * * * Chunk stream IDs 64-319 can be encoded in the 2-byte form of the * header. ID is computed as (the second byte + 64). * * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * |fmt| 0 | cs id - 64 | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * Chunk basic header 2 * * * Chunk stream IDs 64-65599 can be encoded in the 3-byte version of * this field. ID is computed as ((the third byte)*256 + (the second * byte) + 64). * * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * |fmt| 1 | cs id - 64 | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * * Chunk basic header 3 */ class BasicHeader(val chunkType: ChunkType, val chunkStreamId: Int) { companion object { fun parseBasicHeader(input: InputStream): BasicHeader { val byte = input.read().toByte() val chunkTypeValue = 0xff and byte.toInt() ushr 6 val chunkType = ChunkType.values().find { it.mark.toInt() == chunkTypeValue } ?: throw IOException("Unknown chunk type value: $chunkTypeValue") var chunkStreamIdValue = (byte and 0x3F).toInt() if (chunkStreamIdValue > 63) throw IOException("Unknown chunk stream id value: $chunkStreamIdValue") if (chunkStreamIdValue == 0) { //Basic header 2 bytes chunkStreamIdValue = input.read() - 64 } else if (chunkStreamIdValue == 1) { //Basic header 3 bytes val a = input.read() val b = input.read() val value = b and 0xff shl 8 and a chunkStreamIdValue = value - 64 } return BasicHeader(chunkType, chunkStreamIdValue) } } fun getHeaderSize(timestamp: Int): Int { var size = when (chunkType) { ChunkType.TYPE_0 -> 12 ChunkType.TYPE_1 -> 8 ChunkType.TYPE_2 -> 4 ChunkType.TYPE_3 -> 0 } if (timestamp >= 0xffffff) { size += 4 } return size } override fun toString(): String { return "BasicHeader chunkType: $chunkType, chunkStreamId: $chunkStreamId" } }
apache-2.0
fc68f539534a62c7c48b144c2e7fcc2e
30
149
0.608403
3.751576
false
false
false
false
willjgriff/android-ethereum-wallet
app/src/main/kotlin/com/github/willjgriff/ethereumwallet/ui/screens/receive/ReceiveController.kt
1
2486
package com.github.willjgriff.ethereumwallet.ui.screens.receive import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.github.willjgriff.ethereumwallet.R import com.github.willjgriff.ethereumwallet.mvp.BaseMvpControllerKotlin import com.github.willjgriff.ethereumwallet.ui.navigation.NavigationToolbarListener import com.github.willjgriff.ethereumwallet.ui.screens.receive.di.injectNewReceivePresenter import com.github.willjgriff.ethereumwallet.ui.screens.receive.mvp.ReceivePresenter import com.github.willjgriff.ethereumwallet.ui.screens.receive.mvp.ReceiveView import com.github.willjgriff.ethereumwallet.ui.utils.inflate import kotlinx.android.synthetic.main.controller_receive.view.* import javax.inject.Inject /** * Created by williamgriffiths on 18/04/2017. */ class ReceiveController : BaseMvpControllerKotlin<ReceiveView, ReceivePresenter>(), ReceiveView { override val mvpView: ReceiveView get() = this @Inject lateinit override var presenter: ReceivePresenter lateinit var navigationToolbarListener: NavigationToolbarListener init { injectNewReceivePresenter() } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup): View { val view = container.inflate(R.layout.controller_receive) setNavigationToolbarListener() setupToolbarTitle() return view } private fun setNavigationToolbarListener() { if (targetController is NavigationToolbarListener) { navigationToolbarListener = targetController as NavigationToolbarListener } } private fun setupToolbarTitle() { navigationToolbarListener.setToolbarTitle(applicationContext?.getString(R.string.controller_receive_title) ?: "") } override fun setReceiveAddress(address: String) { view?.controller_receive_ethereum_address?.text = address } override fun setPendingBalance(pendingBalance: String) { val ethBalance = applicationContext?.getString(R.string.controller_receive_eth_balance, pendingBalance) view?.controller_receive_pending_balance?.text = ethBalance } override fun setConfirmedBalance(confirmedBalance: String) { val ethBalance = applicationContext?.getString(R.string.controller_receive_eth_balance, confirmedBalance) view?.controller_receive_confirmed_balance?.text = ethBalance navigationToolbarListener.setBalance(ethBalance ?: "") } }
apache-2.0
2bb35c027316f6ba8eb8f7cf0e93b1f2
39.096774
121
0.771521
4.922772
false
false
false
false
InfiniteSoul/ProxerAndroid
src/main/kotlin/me/proxer/app/profile/settings/ProfileSettingsViewModel.kt
1
2742
package me.proxer.app.profile.settings import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.Disposable import io.reactivex.schedulers.Schedulers import me.proxer.app.util.ErrorUtils import me.proxer.app.util.data.ResettingMutableLiveData import me.proxer.app.util.data.StorageHelper import me.proxer.app.util.extension.buildOptionalSingle import me.proxer.app.util.extension.buildSingle import me.proxer.app.util.extension.safeInject import me.proxer.app.util.extension.subscribeAndLogErrors import me.proxer.app.util.extension.toLocalSettings import me.proxer.library.ProxerApi import org.koin.core.KoinComponent /** * @author Ruben Gees */ class ProfileSettingsViewModel : ViewModel(), KoinComponent { val data = MutableLiveData<LocalProfileSettings>() val error = ResettingMutableLiveData<ErrorUtils.ErrorAction>() val updateError = ResettingMutableLiveData<ErrorUtils.ErrorAction>() private val api by safeInject<ProxerApi>() private val storageHelper by safeInject<StorageHelper>() private var disposable: Disposable? = null init { data.value = storageHelper.profileSettings refresh() } override fun onCleared() { disposable?.dispose() disposable = null super.onCleared() } fun refresh() { disposable?.dispose() disposable = api.ucp.settings() .buildSingle() .map { it.toLocalSettings() } .doOnSuccess { storageHelper.profileSettings = it } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnSubscribe { error.value = null updateError.value = null } .subscribeAndLogErrors({ data.value = it }, { error.value = ErrorUtils.handle(it) }) } fun update(newData: LocalProfileSettings) { data.value = newData disposable?.dispose() disposable = api.ucp.setSettings(newData.toNonLocalSettings()) .buildOptionalSingle() .doOnSuccess { storageHelper.profileSettings = newData } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnSubscribe { error.value = null updateError.value = null } .subscribeAndLogErrors({}, { updateError.value = ErrorUtils.handle(it) }) } fun retryUpdate() { val safeData = data.value if (safeData != null) { update(safeData) } } }
gpl-3.0
f4a039a9bc42868da89f4ae70d8ba213
29.466667
72
0.649161
4.976407
false
false
false
false
EddieVanHalen98/vision-kt
main/out/production/core/com/evh98/vision/util/Graphics.kt
2
5824
package com.evh98.vision.util import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator import com.badlogic.gdx.Gdx import com.evh98.vision.Vision import com.badlogic.gdx.graphics.Texture.TextureFilter import com.badlogic.gdx.files.FileHandle import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.graphics.Texture import com.badlogic.gdx.graphics.g2d.* import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator.FreeTypeFontParameter import com.badlogic.gdx.graphics.glutils.ShapeRenderer import com.badlogic.gdx.graphics.g2d.Sprite import com.badlogic.gdx.graphics.g2d.SpriteBatch object Graphics { val Vision = Vision() var font_roboto_thin = FreeTypeFontGenerator(Gdx.files.internal("fonts/roboto-thin.ttf")) var font_roboto_light = FreeTypeFontGenerator(Gdx.files.internal("fonts/roboto-light.ttf")) var font_roboto_bold = FreeTypeFontGenerator(Gdx.files.internal("fonts/roboto-bold.ttf")) var font_product_sans = FreeTypeFontGenerator(Gdx.files.internal("fonts/productsans.ttf")) var splash: Sprite? = null var lockscreen: Sprite? = null var default_movie: Sprite? = null var default_game: Sprite? = null var default_manage: Sprite? = null var default_add: Sprite? = null var particles = ParticleEffect() var glyph_layout = GlyphLayout() /* * Load all graphics */ fun loadAll() { loadSprites() loadParticles() } /** * Internal textures loading method */ private fun loadSprites() { Icons.loadAll() } /** * Internal particles loading method */ private fun loadParticles() { particles = ParticleEffect() particles.load(Gdx.files.internal("particles/particles.p"), Gdx.files.internal("particles/")) particles.setPosition(1920 * Vision.SCALE, 1080 * Vision.SCALE) particles.scaleEffect(Vision.SCALE) } /** * Changes the emitter of the particles to the specified color */ fun setParticles(color: Color) { val colors = FloatArray(3) if (color === Palette.WHITE) { particles.load(Gdx.files.internal("particles/particles.p"), Gdx.files.internal("particles/")) particles.setPosition(1920 * Vision.SCALE, 1080 * Vision.SCALE) particles.scaleEffect(Vision.SCALE) } else { colors[0] = color.r colors[1] = color.g colors[2] = color.b for (i in 0..3) { particles.emitters.get(i).tint.colors = colors } } } /** * Creates a BitmapFont from a FreeTypeFont with a specified size */ fun createFont(type: FreeTypeFontGenerator, size: Int): BitmapFont { val param = FreeTypeFontParameter() param.size = (size * Vision.SCALE).toInt() param.color = Palette.LIGHT_GRAY param.flip = true val font = type.generateFont(param) font.region.texture.setFilter(TextureFilter.Linear, TextureFilter.Linear) return font } /** * Creates a sprite with custom properties */ fun createSprite(path: FileHandle): Sprite { val t = Texture(path) t.setFilter(TextureFilter.Linear, TextureFilter.Linear) val s = Sprite(t) s.flip(false, true) return s } /** * Responsible for drawing the splash sprite */ fun drawSplash(sprite_batch: SpriteBatch) { sprite_batch.begin() sprite_batch.draw(splash, 0.0F, 0.0F, Vision.WIDTH, Vision.HEIGHT) sprite_batch.end() } /** * Draws a rectangle under Vision scaling relative to the global anchor point */ fun drawRect(shape_renderer: ShapeRenderer, x: Float, y: Float, width: Float, height: Float) { shape_renderer.rect(x * Vision.SCALE, y * Vision.SCALE, width * Vision.SCALE, height * Vision.SCALE) } /** * Draws text using relative to the global anchor point */ fun drawText(sprite_batch: SpriteBatch, font: BitmapFont, text: String, x: Float, y: Float) { glyph_layout.setText(font, text) val cx = x - glyph_layout.width / Vision.SCALE / 2 val cy = y - glyph_layout.height / Vision.SCALE / 2 font.draw(sprite_batch, glyph_layout, cx * Vision.SCALE, cy * Vision.SCALE) } /** * Draws a sprite under Vision scaling */ fun drawSprite(sprite_batch: SpriteBatch, sprite: Sprite, x: Float, y: Float) { sprite_batch.draw(sprite, x * Vision.SCALE, y * Vision.SCALE) } /** * Draws a sprite under Vision scaling with a specified color */ fun drawSprite(sprite_batch: SpriteBatch, sprite: Sprite, x: Float, y: Float, color: Color) { val original = sprite_batch.color sprite_batch.color = color sprite_batch.draw(sprite, (x - (sprite.width / 2)) * Vision.SCALE, (y - (sprite.height / 2)) * Vision.SCALE, sprite.width * Vision.SCALE, sprite.height * Vision.SCALE) sprite_batch.color = original } /** * Draws a sprite with a specified size under Vision scaling with a specified color */ fun drawSprite(sprite_batch: SpriteBatch, sprite: Sprite, x: Float, y: Float, width: Float, height: Float, color: Color) { val original = sprite_batch.color sprite_batch.color = color sprite_batch.draw(sprite, x * Vision.SCALE, y * Vision.SCALE, width * Vision.SCALE, height * Vision.SCALE) sprite_batch.color = original } /** * Draws a sprite with a specified size under Vision scaling */ fun drawSprite(sprite_batch: SpriteBatch, sprite: Sprite, x: Float, y: Float, width: Float, height: Float) { sprite_batch.draw(sprite, x * Vision.SCALE, y * Vision.SCALE, width * Vision.SCALE, height * Vision.SCALE) } }
mit
870299245f90395f44d85244f2c0e262
34.090361
126
0.648695
4.019324
false
false
false
false
Bios-Marcel/ServerBrowser
src/main/kotlin/com/msc/serverbrowser/gui/views/MainView.kt
1
8901
package com.msc.serverbrowser.gui.views import com.msc.serverbrowser.Client import com.msc.serverbrowser.gui.View import com.msc.serverbrowser.util.windows.OSUtility import javafx.beans.property.DoubleProperty import javafx.event.ActionEvent import javafx.event.EventHandler import javafx.scene.Node import javafx.scene.control.Hyperlink import javafx.scene.control.Label import javafx.scene.control.ProgressBar import javafx.scene.control.ScrollPane import javafx.scene.control.ToggleButton import javafx.scene.control.ToggleGroup import javafx.scene.control.Tooltip import javafx.scene.layout.HBox import javafx.scene.layout.Priority import javafx.scene.layout.VBox /** * Class containing the component hierarchy for the main view. * * * It contains the menu bar, the active view and the bottom bar. * * * @author Marcel * @since 10.01.2018 */ class MainView { val rootPane: HBox = HBox() private val menuItemServers: ToggleButton private val menuItemUser: ToggleButton private val menuItemVersion: ToggleButton private val menuItemFiles: ToggleButton private val menuItemSettings: ToggleButton private val menuItemKeyBinder: ToggleButton private val contentScrollPane: ScrollPane private val githubLink: Hyperlink private val helpLink: Hyperlink private val donateLink: Hyperlink private val bottomBarCustom: HBox private val globalProgressLabel: Label private val globalProgressBar: ProgressBar /** * Initializes the whole view. */ init { rootPane.setPrefSize(800.0, 500.0) rootPane.styleClass.add("root-pane") val menuContainer = VBox() menuContainer.styleClass.add("tabPane") val menuItemToggleGroup = ToggleGroup() val menuItemStyleClass = "MenuItem" menuItemServers = ToggleButton("\uf0c9") menuItemServers.styleClass.add(menuItemStyleClass) menuItemUser = ToggleButton("\uf007") menuItemUser.styleClass.add(menuItemStyleClass) menuItemVersion = ToggleButton("\uf0ed") menuItemVersion.styleClass.add(menuItemStyleClass) menuItemFiles = ToggleButton("\uf07b") menuItemFiles.styleClass.add(menuItemStyleClass) menuItemSettings = ToggleButton("\uf013") menuItemSettings.styleClass.add(menuItemStyleClass) menuItemKeyBinder = ToggleButton("\uf11c") menuItemKeyBinder.styleClass.add(menuItemStyleClass) menuItemToggleGroup.toggles.addAll(menuItemServers, menuItemUser, menuItemVersion, menuItemFiles, menuItemSettings, menuItemKeyBinder) menuContainer.children.addAll(menuItemServers, menuItemUser, menuItemVersion, menuItemFiles, menuItemSettings/*, menuItemKeyBinder*/) val menuScrollPane = ScrollPane(menuContainer) menuScrollPane.isFitToHeight = true menuScrollPane.isFitToWidth = true menuScrollPane.styleClass.add("tabScrollPane") val mainContentPane = VBox() HBox.setHgrow(mainContentPane, Priority.ALWAYS) contentScrollPane = ScrollPane() contentScrollPane.isFitToHeight = true contentScrollPane.isFitToWidth = true contentScrollPane.styleClass.add("viewContent") VBox.setVgrow(contentScrollPane, Priority.ALWAYS) val bottomBar = HBox() bottomBar.styleClass.add("bottom-bar") githubLink = Hyperlink("\uf09b") githubLink.styleClass.add("info-icon") githubLink.tooltip = Tooltip(Client.getString("openGithubTooltip")) githubLink.isFocusTraversable = false helpLink = Hyperlink("\uf059") helpLink.styleClass.add("info-icon") helpLink.tooltip = Tooltip(Client.getString("openGithubWikiTooltip")) helpLink.isFocusTraversable = false donateLink = Hyperlink(Client.getString("donate") + " \uf0d6") donateLink.styleClass.add("donate-button") donateLink.tooltip = Tooltip(Client.getString("openDonationPageTooltip")) donateLink.maxHeight = java.lang.Double.MAX_VALUE donateLink.isFocusTraversable = false bottomBarCustom = HBox() bottomBarCustom.styleClass.add("bottom-bar-isCustom") HBox.setHgrow(bottomBarCustom, Priority.ALWAYS) val progressBarContainer = HBox() progressBarContainer.styleClass.add("global-progress-bar-container") globalProgressLabel = Label() globalProgressBar = ProgressBar(0.0) progressBarContainer.children.addAll(globalProgressLabel, globalProgressBar) bottomBar.children.addAll(githubLink, helpLink, donateLink, bottomBarCustom, progressBarContainer) mainContentPane.children.add(contentScrollPane) mainContentPane.children.add(bottomBar) rootPane.children.add(menuScrollPane) rootPane.children.add(mainContentPane) } /** * Inserts the [Node] into the [.contentScrollPane]. * * @param node the [Node] to be inserted into the [.contentScrollPane] */ fun setActiveViewNode(node: Node) { contentScrollPane.content = node } /** * Adds [Node]s to the isCustom part of the BottomBar * * @param nodes the [Node]s to be added */ fun addToBottomBar(vararg nodes: Node) { bottomBarCustom.children.addAll(*nodes) } /** * Removes all [Node]s that have been added to the [.bottomBarCustom]. */ fun removeNodesFromBottomBar() { bottomBarCustom.children.clear() } /** * Sets the text for the global [ProgressBar]. * * @param text the text to be set */ fun setGlobalProgressBarText(text: String) { globalProgressLabel.text = text } /** * @return the [ProgressProperty][DoubleProperty] for the [.globalProgressBar] */ fun globalProgressProperty(): DoubleProperty { return globalProgressBar.progressProperty() } /** * Selects the proper menu item, depending on which [View] was given. * * @param view the [View] to select the menu item for */ fun selectMenuItemForView(view: View) { when (view) { View.SERVERS -> menuItemServers.isSelected = true View.USERNAME_CHANGER -> menuItemUser.isSelected = true View.VERSION_CHANGER -> menuItemVersion.isSelected = true View.FILES -> menuItemFiles.isSelected = true View.SETTINGS -> menuItemSettings.isSelected = true } } /** * Sets the [EventHandler] to handle all [ActionEvent]s on the * [.menuItemServers]. * * @param handler [EventHandler] to be set */ fun setMenuItemAllAction(handler: EventHandler<ActionEvent>) { menuItemServers.onAction = handler } /** * Sets the [EventHandler] to handle all [ActionEvent]s on the * [.menuItemUser]. * * @param handler [EventHandler] to be set */ fun setMenuItemUsernameAction(handler: EventHandler<ActionEvent>) { menuItemUser.onAction = handler } /** * Sets the [EventHandler] to handle all [ActionEvent]s on the * [.menuItemVersion]. * * @param handler [EventHandler] to be set */ fun setMenuItemVersionAction(handler: EventHandler<ActionEvent>) { menuItemVersion.onAction = handler } /** * Sets the [EventHandler] to handle all [ActionEvent]s on the * [.menuItemFiles]. * * @param handler [EventHandler] to be set */ fun setMenuItemFilesAction(handler: EventHandler<ActionEvent>) { menuItemFiles.onAction = handler } /** * Sets the [EventHandler] to handle all [ActionEvent]s on the * [.menuItemSettings]. * * @param handler [EventHandler] to be set */ fun setMenuItemSettingsAction(handler: EventHandler<ActionEvent>) { menuItemSettings.onAction = handler } /** * Sets the [EventHandler] to handle all [ActionEvent]s on the * [.menuItemKeyBinder]. * * @param handler [EventHandler] to be set */ fun setMenuItemKeyBinderAction(handler: EventHandler<ActionEvent>) { menuItemKeyBinder.onAction = handler } /** * Sets a browse action for the [.githubLink] using the given [String] as the URL. * * @param string the URL */ fun setGitHubHyperlink(string: String) { githubLink.setOnAction { OSUtility.browse(string) } } /** * Sets a browse action for the [.helpLink] using the given [String] as the URL. * * @param string the URL */ fun setHelpHyperlink(string: String) { helpLink.setOnAction { OSUtility.browse(string) } } /** * Sets a browse action for the [.donateLink] using the given [String] as the URL. * * @param string the URL */ fun setDonateHyperlink(string: String) { donateLink.setOnAction { OSUtility.browse(string) } } }
mpl-2.0
eef5998e1e2b2214cbf389a6788fa3ab
31.724265
142
0.680598
4.539011
false
false
false
false
apollostack/apollo-android
apollo-compiler/src/main/kotlin/com/apollographql/apollo3/compiler/codegen/CgLayout.kt
1
7215
package com.apollographql.apollo3.compiler.codegen import com.apollographql.apollo3.compiler.PackageNameProvider import com.apollographql.apollo3.compiler.escapeKotlinReservedWord import com.apollographql.apollo3.compiler.singularize import com.apollographql.apollo3.compiler.unified.ir.IrFieldInfo import com.apollographql.apollo3.compiler.unified.ir.IrListType import com.apollographql.apollo3.compiler.unified.ir.IrNonNullType import com.apollographql.apollo3.compiler.unified.ir.IrOperation import com.apollographql.apollo3.compiler.unified.ir.IrType import com.apollographql.apollo3.compiler.unified.ir.TypeSet /** * The central place where the names/packages of the different classes are decided and escape rules done. * * Inputs should always be GraphQL identifiers and outputs are valid Kotlin identifiers. * * By default, the layout is like: * * - com.example.TestQuery <- the query * - com.example.TestQuery.Data <- the data for the query * - com.example.TestQuery.Data.Hero <- nested compound fields as required * - com.example.adapter.TestQuery_ResponseAdapter <- a wrapper object to namespace the adapters * - com.example.adapter.TestQuery_ResponseAdapter.Data <- the response adapter for TestQuery * - com.example.adapter.TestQuery_VariablesAdapter <- the variables adapter for TestQuery * - com.example.responsefields.TestQuery_ResponseFields <- the response fields for TestQuery * * - com.example.fragment.HeroDetails <- the fragment interface * - com.example.fragment.HeroDetailsImpl <- the fragment implementation * - com.example.fragment.HeroDetailsImpl.Data <- the data for the fragment implementation * - com.example.fragment.adapter.HeroDetailsImpl <- a wrapper object to name space the adapters * - com.example.fragment.adapter.HeroDetailsImpl.Data <- the response adapter for the fragment * * - com.example.type.CustomScalars <- all the custom scalars * - com.example.type.ReviewInput <- an input type * - com.example.type.Episode <- an enum */ class CgLayout( private val packageNameProvider: PackageNameProvider, private val typePackageName: String, private val useSemanticNaming: Boolean, ) { // ------------------------ FileNames --------------------------------- internal fun fragmentInterfaceFileName(name: String) = capitalizedIdentifier(name) // ------------------------ PackageNames --------------------------------- fun typePackageName() = typePackageName fun typeAdapterPackageName() = "$typePackageName.adapter".stripDots() fun operationPackageName(filePath: String) = packageNameProvider.operationPackageName(filePath) fun operationAdapterPackageName(filePath: String) = "${packageNameProvider.operationPackageName(filePath)}.adapter".stripDots() fun operationResponseFieldsPackageName(filePath: String) = "${packageNameProvider.operationPackageName(filePath)}.responsefields".stripDots() fun fragmentPackageName(filePath: String?): String { return packageNameProvider.fragmentPackageName(filePath) } fun fragmentAdapterPackageName(filePath: String?) = "${fragmentPackageName(filePath)}.adapter".stripDots() fun fragmentResponseFieldsPackageName(filePath: String?) = "${fragmentPackageName(filePath)}.responsefields".stripDots() private fun String.stripDots() = this.removePrefix(".").removeSuffix(".") // ------------------------ Names --------------------------------- internal fun customScalarName(name: String) = capitalizedIdentifier(name) internal fun objectName(name: String) = capitalizedIdentifier(name) internal fun interfaceName(name: String) = capitalizedIdentifier(name) internal fun unionName(name: String) = capitalizedIdentifier(name) internal fun enumName(name: String) = regularIdentifier(name) // We used to write upper case enum values but the server can define different values with different cases // See https://github.com/apollographql/apollo-android/issues/3035 internal fun enumValueName(name: String) = regularIdentifier(name) internal fun enumResponseAdapterName(name: String) = enumName(name) + "_ResponseAdapter" internal fun operationName(operation: IrOperation): String { val str = capitalizedIdentifier(operation.name) if (!useSemanticNaming) { return str } return if (str.endsWith(operation.operationType.name)) { str } else { "$str${operation.operationType.name}" } } fun operationResponseAdapterWrapperName(operation: IrOperation) = operationName(operation) + "_ResponseAdapter" fun operationVariablesAdapterName(operation: IrOperation) = operationName(operation) + "_VariablesAdapter" fun operationResponseFieldsName(operation: IrOperation) = operationName(operation) + "_ResponseFields" internal fun fragmentName(name: String) = capitalizedIdentifier(name) + "Impl" internal fun fragmentResponseAdapterWrapperName(name: String) = fragmentName(name) + "_ResponseAdapter" internal fun fragmentVariablesAdapterName(name: String) = fragmentName(name) + "_VariablesAdapter" internal fun fragmentResponseFieldsName(name: String) = fragmentName(name) + "_ResponseFields" internal fun inputObjectName(name: String) = capitalizedIdentifier(name) internal fun inputObjectAdapterName(name: String) = capitalizedIdentifier(name) + "_InputAdapter" // variables keep the same case as their declared name internal fun variableName(name: String) = regularIdentifier(name) internal fun propertyName(name: String) = regularIdentifier(name) internal fun typesName() = "Types" // ------------------------ Helpers --------------------------------- private fun regularIdentifier(name: String) = name.escapeKotlinReservedWord() private fun upperCaseIdentifier(name: String) = name.toUpperCase().escapeKotlinReservedWord() private fun capitalizedIdentifier(name: String): String { return capitalizeFirstLetter(name).escapeKotlinReservedWord() } /** * A variation of [String.capitalize] that skips initial underscore, especially found in introspection queries * * There can still be name clashes if a property starts with an upper case letter */ private fun capitalizeFirstLetter(name: String): String { val builder = StringBuilder(name.length) var isCapitalized = false name.forEach { builder.append(if (!isCapitalized && it.isLetter()) { isCapitalized = true it.toUpperCase() } else { it }) } return builder.toString() } companion object { fun upperCamelCaseIgnoringNonLetters(strings: Collection<String>): String { return strings.map { capitalizeFirstLetter(it) }.joinToString("") } private fun IrType.isList(): Boolean { return when (this) { is IrListType -> true is IrNonNullType -> ofType.isList() else -> false } } fun modelName(info: IrFieldInfo, typeSet: TypeSet, isOther: Boolean): String { val responseName = if (info.type.isList()) { info.responseName.singularize() } else { info.responseName } val name = upperCamelCaseIgnoringNonLetters((typeSet - info.rawTypeName).sorted() + responseName) return (if (isOther) "Other" else "") + name } } }
mit
8cb4fce530da60eb2abf35c1b48244da
43
143
0.730977
4.625
false
true
false
false
zlyne0/colonization
core/src/promitech/colonization/orders/diplomacy/TradeController.kt
1
11497
package promitech.colonization.orders.diplomacy import com.badlogic.gdx.scenes.scene2d.ui.HorizontalGroup import com.badlogic.gdx.scenes.scene2d.ui.Image import com.badlogic.gdx.scenes.scene2d.ui.Label import com.badlogic.gdx.scenes.scene2d.ui.Table import com.badlogic.gdx.scenes.scene2d.ui.TextButton import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable import com.badlogic.gdx.utils.Align import com.badlogic.gdx.utils.Scaling import net.sf.freecol.common.model.Specification import net.sf.freecol.common.model.Map import promitech.colonization.GameResources import promitech.colonization.orders.move.MoveContext import promitech.colonization.screen.map.hud.GUIGameController import promitech.colonization.ui.ClosableDialog import promitech.colonization.ui.ModalDialogSize import promitech.colonization.ui.addListener import promitech.colonization.ui.resources.Messages import promitech.colonization.ui.resources.StringTemplate import net.sf.freecol.common.model.specification.GoodsType import net.sf.freecol.common.model.specification.AbstractGoods class TradeDialog(val tradeSession : TradeSession) : ClosableDialog<TradeDialog>(ModalDialogSize.width50(), ModalDialogSize.def()) { val layout = Table() val messages = mutableListOf<String>() init { getContentTable().add(layout).expandX().fillX().row() } fun sellGoods(goodsTypeId : String, amount : Int) { layout.clear() welcomeLabel() val tradeGoodsType = Specification.instance.goodsTypes.getById(goodsTypeId) var goodsOfferPrice = tradeSession.sellOffer(tradeGoodsType, amount) if (goodsOfferPrice <= 0) { tradeSession.markNoSell() addHaggleResultMessage(goodsOfferPrice) showTradeChoices() return } val sellLabel = Label(sellGoodsLabelStr(tradeGoodsType, amount, goodsOfferPrice), skin) val acceptSellOffer = TextButton(Messages.msg("sell.takeOffer"), skin) acceptSellOffer.addListener { -> tradeSession.acceptSellOfferToIndianSettlement(tradeGoodsType, amount, goodsOfferPrice) showTradeChoices() } val askForMoreGold = TextButton(Messages.msg("sell.moreGold"), skin) askForMoreGold.addListener { -> goodsOfferPrice = tradeSession.haggleSellOffer(tradeGoodsType, amount, goodsOfferPrice) if (goodsOfferPrice <= 0) { addHaggleResultMessage(goodsOfferPrice) showTradeChoices() } else { sellLabel.setText(sellGoodsLabelStr(tradeGoodsType, amount, goodsOfferPrice)) } } val offerGift = TextButton( StringTemplate.template("sell.gift") .addName("%goods%", tradeGoodsType) .eval(), skin ).addListener { -> deliverGoodsToIndianSettlement(tradeGoodsType, amount) } val cancel = TextButton(Messages.msg("tradeProposition.cancel"), skin) cancel.addListener( ::showTradeChoices ) layout.add(sellLabel).fillX().padTop(10f).row() layout.add(acceptSellOffer).fillX().padTop(10f).row() layout.add(askForMoreGold).fillX().padTop(10f).row() layout.add(offerGift).fillX().padTop(10f).row() layout.add(cancel).fillX().padTop(10f).row() dialog.pack() } private fun deliverGoodsToIndianSettlement(goodsType : GoodsType, amount : Int) { tradeSession.deliverGoodsToIndianSettlement(goodsType, amount); val msg = StringTemplate.template("model.unit.gift") .addStringTemplate("%player%", tradeSession.traderNationName()) .addAmount("%amount%", amount) .addName("%type%", goodsType) .add("%settlement%", tradeSession.indianSettlement.getName()) .eval() messages.add(msg) showTradeChoices() } private fun addHaggleResultMessage(price : Int) { val str = when (price) { TradeSession.NO_TRADE -> StringTemplate.template("trade.noTrade") .add("%settlement%", tradeSession.indianSettlement.getName()) .eval() TradeSession.NO_TRADE_HAGGLE -> Messages.msg("trade.noTradeHaggle") TradeSession.NO_TRADE_HOSTILE -> Messages.msg("trade.noTradeHostile") else -> "" } if (str.isNotBlank()) { messages.add(str) } } fun sellGoodsLabelStr(tradeGoodsType : GoodsType, amount : Int, price : Int) : String { val goodsAmountStrLabel = StringTemplate.template("model.goods.goodsAmount") .addAmount("%amount%", amount) .addName("%goods%", tradeGoodsType) return StringTemplate.template("sell.text") .addStringTemplate("%nation%", tradeSession.indianSettlement.getOwner().getNationName()) .addStringTemplate("%goods%", goodsAmountStrLabel) .addAmount("%gold%", price) .eval() } private fun showSellChoices() { layout.clear() welcomeLabel() val sellLabel = Label(Messages.msg("sellProposition.text"), skin) layout.add(sellLabel).fillX().padTop(10f).row() for (goods in tradeSession.goodsToSell()) { if (goods.value == 0) { continue } val goodsStrLabel = StringTemplate.template("model.goods.goodsAmount") .addAmount("%amount%", goods.value) .addName("%goods%", goods.key) .eval() val goodsButton = TextButton(goodsStrLabel, skin) var ag = AbstractGoods(goods.key, goods.value) goodsButton.addListener { -> sellGoods(ag.typeId, ag.quantity) } layout.add(goodsButton).fillX().padTop(10f).row() } val nothingButton = TextButton(Messages.msg("sellProposition.nothing"), skin) nothingButton.addListener { -> showTradeChoices() } layout.add(nothingButton).fillX().padTop(10f).row() dialog.pack() } fun showDeliverGift() { layout.clear() welcomeLabel() val sellLabel = Label(Messages.msg("gift.text"), skin) layout.add(sellLabel).fillX().padTop(10f).row() for (goods in tradeSession.goodsToSell()) { if (goods.value == 0) { continue } val goodsStrLabel = StringTemplate.template("model.goods.goodsAmount") .addAmount("%amount%", goods.value) .addName("%goods%", goods.key) .eval() val goodsButton = TextButton(goodsStrLabel, skin) var ag = AbstractGoods(goods.key, goods.value) goodsButton.addListener { -> val goodsType = Specification.instance.goodsTypes.getById(ag.typeId) deliverGoodsToIndianSettlement(goodsType, ag.quantity) } layout.add(goodsButton).fillX().padTop(10f).row() } val cancel = TextButton(Messages.msg("tradeProposition.cancel"), skin) cancel.addListener( ::showTradeChoices ) layout.add(cancel).fillX().padTop(10f).row() dialog.pack() } private fun showBuyChoices() { layout.clear() welcomeLabel() val sellLabel = Label(Messages.msg("buyProposition.text"), skin) layout.add(sellLabel).fillX().padTop(10f).row() for (goods in tradeSession.goodsToBuy()) { if (goods.getQuantity() == 0) { continue } val goodsStrLabel = StringTemplate.template("model.goods.goodsAmount") .addAmount("%amount%", goods.getQuantity()) .addName("%goods%", goods.getTypeId()) .eval() val goodsButton = TextButton(goodsStrLabel, skin) goodsButton.addListener { -> val goodsType = Specification.instance.goodsTypes.getById(goods.getTypeId()) buyGoodsFromSettlement(goodsType, goods.getQuantity()) } layout.add(goodsButton).fillX().padTop(10f).row() } val cancel = TextButton(Messages.msg("buyProposition.nothing"), skin) cancel.addListener( ::showTradeChoices ) layout.add(cancel).fillX().padTop(10f).row() dialog.pack() } private fun buyGoodsFromSettlement(goodsType : GoodsType, amount : Int) { layout.clear() welcomeLabel() var buyOfferPrice = tradeSession.buyOfferPrice(goodsType, amount) if (buyOfferPrice <= 0) { tradeSession.markNoBuy() addHaggleResultMessage(buyOfferPrice) showTradeChoices() return } val buyPriceLabel = Label(buyOfferPriceLabelStr(goodsType, amount, buyOfferPrice), skin) layout.add(buyPriceLabel).fillX().padTop(10f).row() val acceptSellOffer = TextButton(Messages.msg("buy.takeOffer"), skin) acceptSellOffer.setDisabled(tradeSession.tradeUnitHasNotGold(buyOfferPrice)) acceptSellOffer.addListener { -> tradeSession.acceptBuyOffer(goodsType, amount, buyOfferPrice) showTradeChoices() } layout.add(acceptSellOffer).fillX().padTop(10f).row() val askForLowerPrice = TextButton(Messages.msg("buy.moreGold"), skin) askForLowerPrice.addListener { -> buyOfferPrice = tradeSession.haggleBuyOfferPrice(goodsType, amount, buyOfferPrice) if (buyOfferPrice <= 0) { addHaggleResultMessage(buyOfferPrice) showTradeChoices() } else { acceptSellOffer.setDisabled(tradeSession.tradeUnitHasNotGold(buyOfferPrice)) buyPriceLabel.setText(buyOfferPriceLabelStr(goodsType, amount, buyOfferPrice)) } } layout.add(askForLowerPrice).fillX().padTop(10f).row() val cancel = TextButton(Messages.msg("tradeProposition.cancel"), skin) cancel.addListener( ::showTradeChoices ) layout.add(cancel).fillX().padTop(10f).row() dialog.pack() } private fun buyOfferPriceLabelStr(goodsType : GoodsType, amount : Int, price : Int) : String { val goodsAmountStrLabel = StringTemplate.template("model.goods.goodsAmount") .addAmount("%amount%", amount) .addName("%goods%", goodsType) val buyPriceLabelStr = StringTemplate.template("buy.text") .addStringTemplate("%nation%", tradeSession.indianSettlement.getOwner().getNationName()) .addStringTemplate("%goods%", goodsAmountStrLabel) .addAmount("%gold%", price) .eval() return buyPriceLabelStr } fun showTradeChoices() { tradeSession.updateSettlementProduction() layout.clear() welcomeLabel() if (tradeSession.canBuy()) { val buyButton = TextButton(Messages.msg("tradeProposition.toBuy"), skin) buyButton.addListener { -> showBuyChoices() } layout.add(buyButton).fillX().padTop(10f).row() } if (tradeSession.canSell()) { val sellButton = TextButton(Messages.msg("tradeProposition.toSell"), skin) sellButton.addListener { -> showSellChoices() } layout.add(sellButton).fillX().padTop(10f).row() } if (tradeSession.canGift()) { val giftButton = TextButton(Messages.msg("tradeProposition.toGift"), skin) giftButton.addListener { -> showDeliverGift() } layout.add(giftButton).fillX().padTop(10f).row() } val cancelButton = TextButton(Messages.msg("tradeProposition.cancel"), skin) cancelButton.addListener { -> hideWithFade() } layout.add(cancelButton).fillX().padTop(10f).row() for (msg in messages) { layout.add(Label(msg, skin)).fillX().padTop(10f).row() } messages.clear() dialog.pack() } private fun welcomeLabel() { val img = Image(TextureRegionDrawable( GameResources.instance.getCenterAdjustFrameTexture(tradeSession.indianSettlement.getImageKey()).texture ), Scaling.none, Align.center) val welcomeLabel = StringTemplate.template("tradeProposition.welcome") .addStringTemplate("%nation%", tradeSession.indianSettlement.getOwner().getNationName()) .add("%settlement%", tradeSession.indianSettlement.getName()) .eval() var l1 = HorizontalGroup() l1.addActor(img) l1.addActor(Label(welcomeLabel, skin)) layout.add(l1).row() } } class TradeController(val map : Map, val guiGameController : GUIGameController, val moveContext : MoveContext) { fun trade() { val tradeSession = TradeSession(map, moveContext.destTile.settlement.asIndianSettlement(), moveContext.unit) val tradeDialog = TradeDialog(tradeSession) tradeDialog.showTradeChoices() tradeDialog.addOnCloseListener { -> guiGameController.nextActiveUnitWhenNoMovePointsAsGdxPostRunnable() } guiGameController.showDialog(tradeDialog) } }
gpl-2.0
be9c449eb76cce82bb05fac9e027e8f9
32.424419
112
0.729234
3.427847
false
false
false
false
jdiazcano/modulartd
editor/core/src/main/kotlin/com/jdiazcano/modulartd/utils/SpriteLoader.kt
1
3136
package com.jdiazcano.modulartd.utils import com.badlogic.gdx.assets.AssetDescriptor import com.badlogic.gdx.assets.AssetLoaderParameters import com.badlogic.gdx.assets.AssetManager import com.badlogic.gdx.assets.loaders.AsynchronousAssetLoader import com.badlogic.gdx.assets.loaders.FileHandleResolver import com.badlogic.gdx.files.FileHandle import com.badlogic.gdx.graphics.Pixmap import com.badlogic.gdx.graphics.Texture import com.badlogic.gdx.graphics.TextureData import com.badlogic.gdx.graphics.g2d.Sprite import com.badlogic.gdx.utils.Array class SpriteLoader(resolver: FileHandleResolver?) : AsynchronousAssetLoader<Sprite, SpriteLoader.TextureParameter>(resolver) { class SpriteLoaderInfo { internal var filename: String? = null internal var data: TextureData? = null internal var texture: Texture? = null } internal var info: SpriteLoaderInfo = SpriteLoaderInfo() override fun loadAsync(manager: AssetManager, fileName: String, file: FileHandle, parameter: TextureParameter?) { info.filename = fileName if (parameter == null || parameter.textureData == null) { var format: Pixmap.Format? = null var genMipMaps = false info.texture = null if (parameter != null) { format = parameter.format genMipMaps = parameter.genMipMaps info.texture = parameter.texture } info.data = TextureData.Factory.loadFromFile(file, format, genMipMaps) } else { info.data = parameter.textureData info.texture = parameter.texture } if (!info.data!!.isPrepared) info.data!!.prepare() } override fun loadSync(manager: AssetManager, fileName: String, file: FileHandle, parameter: TextureParameter?): Sprite? { var texture = info.texture if (texture != null) { texture.load(info.data!!) } else { texture = Texture(info.data!!) } if (parameter != null) { texture.setFilter(parameter.minFilter, parameter.magFilter) texture.setWrap(parameter.wrapU, parameter.wrapV) } return Sprite(texture) } override fun getDependencies(fileName: String, file: FileHandle, parameter: TextureParameter?): Array<AssetDescriptor<*>>? { return null } class TextureParameter : AssetLoaderParameters<Sprite>() { /** the format of the final Texture. Uses the source images format if null */ var format: Pixmap.Format? = null /** whether to generate mipmaps */ var genMipMaps = false /** The sprite to put the [TextureData] in, optional. */ var texture: Texture? = null /** TextureData for textures created on the fly, optional. When set, all format and genMipMaps are ignored */ var textureData: TextureData? = null var minFilter = Texture.TextureFilter.Nearest var magFilter = Texture.TextureFilter.Nearest var wrapU = Texture.TextureWrap.ClampToEdge var wrapV = Texture.TextureWrap.ClampToEdge } }
apache-2.0
bf840a96948b791bc316413ec98aec76
38.708861
128
0.670281
4.773212
false
false
false
false
CarlosEsco/tachiyomi
app/src/main/java/eu/kanade/presentation/more/settings/screen/SettingsMainScreen.kt
1
10762
package eu.kanade.presentation.more.settings.screen import androidx.annotation.StringRes import androidx.compose.foundation.background import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.outlined.ChromeReaderMode import androidx.compose.material.icons.outlined.Code import androidx.compose.material.icons.outlined.CollectionsBookmark import androidx.compose.material.icons.outlined.Explore import androidx.compose.material.icons.outlined.GetApp import androidx.compose.material.icons.outlined.Info import androidx.compose.material.icons.outlined.Palette import androidx.compose.material.icons.outlined.Search import androidx.compose.material.icons.outlined.Security import androidx.compose.material.icons.outlined.SettingsBackupRestore import androidx.compose.material.icons.outlined.Sync import androidx.compose.material.icons.outlined.Tune import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.LocalContentColor import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.material3.rememberTopAppBarState import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.core.graphics.ColorUtils import cafe.adriel.voyager.core.screen.Screen import cafe.adriel.voyager.navigator.LocalNavigator import cafe.adriel.voyager.navigator.Navigator import cafe.adriel.voyager.navigator.currentOrThrow import eu.kanade.presentation.components.AppBar import eu.kanade.presentation.components.AppBarActions import eu.kanade.presentation.components.LazyColumn import eu.kanade.presentation.components.Scaffold import eu.kanade.presentation.more.settings.widget.TextPreferenceWidget import eu.kanade.presentation.util.LocalBackPress import eu.kanade.tachiyomi.R object SettingsMainScreen : Screen { @Composable override fun Content() { Content(twoPane = false) } @Composable private fun getPalerSurface(): Color { val surface = MaterialTheme.colorScheme.surface val dark = isSystemInDarkTheme() return remember(surface, dark) { val arr = FloatArray(3) ColorUtils.colorToHSL(surface.toArgb(), arr) arr[2] = if (dark) { arr[2] - 0.05f } else { arr[2] + 0.02f }.coerceIn(0f, 1f) Color.hsl(arr[0], arr[1], arr[2]) } } @Composable fun Content(twoPane: Boolean) { val navigator = LocalNavigator.currentOrThrow val backPress = LocalBackPress.currentOrThrow val containerColor = if (twoPane) getPalerSurface() else MaterialTheme.colorScheme.surface val topBarState = rememberTopAppBarState() Scaffold( topBarScrollBehavior = TopAppBarDefaults.pinnedScrollBehavior(topBarState), topBar = { scrollBehavior -> // https://issuetracker.google.com/issues/249688556 MaterialTheme( colorScheme = MaterialTheme.colorScheme.copy(surface = containerColor), ) { TopAppBar( title = { Text( text = stringResource(R.string.label_settings), modifier = Modifier.padding(start = 8.dp), ) }, navigationIcon = { IconButton(onClick = backPress::invoke) { Icon( imageVector = Icons.Default.ArrowBack, contentDescription = stringResource(R.string.abc_action_bar_up_description), ) } }, actions = { AppBarActions( listOf( AppBar.Action( title = stringResource(R.string.action_search), icon = Icons.Outlined.Search, onClick = { navigator.navigate(SettingsSearchScreen(), twoPane) }, ), ), ) }, scrollBehavior = scrollBehavior, ) } }, containerColor = containerColor, content = { contentPadding -> val state = rememberLazyListState() val indexSelected = if (twoPane) { items.indexOfFirst { it.screen::class == navigator.items.first()::class } .also { LaunchedEffect(Unit) { state.animateScrollToItem(it) if (it > 0) { // Lift scroll topBarState.contentOffset = topBarState.heightOffsetLimit } } } } else { null } LazyColumn( state = state, contentPadding = contentPadding, ) { itemsIndexed( items = items, key = { _, item -> item.hashCode() }, ) { index, item -> val selected = indexSelected == index var modifier: Modifier = Modifier var contentColor = LocalContentColor.current if (twoPane) { modifier = Modifier .padding(horizontal = 8.dp) .clip(RoundedCornerShape(24.dp)) .then( if (selected) { Modifier.background(MaterialTheme.colorScheme.surfaceVariant) } else { Modifier }, ) if (selected) { contentColor = MaterialTheme.colorScheme.onSurfaceVariant } } CompositionLocalProvider(LocalContentColor provides contentColor) { TextPreferenceWidget( modifier = modifier, title = stringResource(item.titleRes), subtitle = item.formatSubtitle(), icon = item.icon, onPreferenceClick = { navigator.navigate(item.screen, twoPane) }, ) } } } }, ) } private fun Navigator.navigate(screen: Screen, twoPane: Boolean) { if (twoPane) replaceAll(screen) else push(screen) } } private data class Item( @StringRes val titleRes: Int, @StringRes val subtitleRes: Int, val formatSubtitle: @Composable () -> String = { stringResource(subtitleRes) }, val icon: ImageVector, val screen: Screen, ) private val items = listOf( Item( titleRes = R.string.pref_category_general, subtitleRes = R.string.pref_general_summary, icon = Icons.Outlined.Tune, screen = SettingsGeneralScreen(), ), Item( titleRes = R.string.pref_category_appearance, subtitleRes = R.string.pref_appearance_summary, icon = Icons.Outlined.Palette, screen = SettingsAppearanceScreen(), ), Item( titleRes = R.string.pref_category_library, subtitleRes = R.string.pref_library_summary, icon = Icons.Outlined.CollectionsBookmark, screen = SettingsLibraryScreen(), ), Item( titleRes = R.string.pref_category_reader, subtitleRes = R.string.pref_reader_summary, icon = Icons.Outlined.ChromeReaderMode, screen = SettingsReaderScreen(), ), Item( titleRes = R.string.pref_category_downloads, subtitleRes = R.string.pref_downloads_summary, icon = Icons.Outlined.GetApp, screen = SettingsDownloadScreen(), ), Item( titleRes = R.string.pref_category_tracking, subtitleRes = R.string.pref_tracking_summary, icon = Icons.Outlined.Sync, screen = SettingsTrackingScreen(), ), Item( titleRes = R.string.browse, subtitleRes = R.string.pref_browse_summary, icon = Icons.Outlined.Explore, screen = SettingsBrowseScreen(), ), Item( titleRes = R.string.label_backup, subtitleRes = R.string.pref_backup_summary, icon = Icons.Outlined.SettingsBackupRestore, screen = SettingsBackupScreen(), ), Item( titleRes = R.string.pref_category_security, subtitleRes = R.string.pref_security_summary, icon = Icons.Outlined.Security, screen = SettingsSecurityScreen(), ), Item( titleRes = R.string.pref_category_advanced, subtitleRes = R.string.pref_advanced_summary, icon = Icons.Outlined.Code, screen = SettingsAdvancedScreen(), ), Item( titleRes = R.string.pref_category_about, subtitleRes = 0, formatSubtitle = { "${stringResource(R.string.app_name)} ${AboutScreen.getVersionName(withBuildDate = false)}" }, icon = Icons.Outlined.Info, screen = AboutScreen(), ), )
apache-2.0
ea18819bf6d2c04011adde920b10b567
39.920152
112
0.570154
5.389084
false
false
false
false
Heiner1/AndroidAPS
medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/util/MedtronicConst.kt
1
1351
package info.nightscout.androidaps.plugins.pump.medtronic.util import info.nightscout.androidaps.plugins.pump.medtronic.R /** * Created by andy on 5/12/18. */ object MedtronicConst { const val Prefix = "AAPS.Medtronic." object Prefs { val PumpSerial = R.string.key_medtronic_serial val PumpType = R.string.key_medtronic_pump_type val PumpFrequency = R.string.key_medtronic_frequency val MaxBolus = R.string.key_medtronic_max_bolus val MaxBasal = R.string.key_medtronic_max_basal val BolusDelay = R.string.key_medtronic_bolus_delay val Encoding = R.string.key_medtronic_encoding val BatteryType = R.string.key_medtronic_battery_type } object Statistics { private const val StatsPrefix = "medtronic_" const val FirstPumpStart = Prefix + "first_pump_use" const val LastGoodPumpCommunicationTime = Prefix + "lastGoodPumpCommunicationTime" const val TBRsSet = StatsPrefix + "tbrs_set" const val StandardBoluses = StatsPrefix + "std_boluses_delivered" const val SMBBoluses = StatsPrefix + "smb_boluses_delivered" const val LastPumpHistoryEntry = StatsPrefix + "pump_history_entry" const val LastPrime = StatsPrefix + "last_sent_prime" const val LastRewind = StatsPrefix + "last_sent_rewind" } }
agpl-3.0
2723114134150c8958dea09dd573591c
38.764706
90
0.695781
4.008902
false
false
false
false
PolymerLabs/arcs
javatests/arcs/sdk/HandleUtilsTest.kt
1
13566
/* * Copyright 2020 Google LLC. * * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * * Code distributed by Google as part of this project is also subject to an additional IP rights * grant found at * http://polymer.github.io/PATENTS.txt */ package arcs.sdk import arcs.core.data.CollectionType import arcs.core.data.EntityType import arcs.core.data.SingletonType import arcs.core.entity.ForeignReferenceCheckerImpl import arcs.core.entity.HandleSpec import arcs.core.entity.ReadWriteSingletonHandle import arcs.core.entity.awaitReady import arcs.core.host.HandleManagerImpl import arcs.core.host.HandleMode import arcs.core.storage.StorageKey import arcs.core.storage.api.DriverAndKeyConfigurator import arcs.core.storage.driver.RamDisk import arcs.core.storage.keys.RamDiskStorageKey import arcs.core.storage.referencemode.ReferenceModeStorageKey import arcs.core.storage.testutil.testStorageEndpointManager import arcs.core.testutil.handles.dispatchStore import arcs.core.util.Scheduler import arcs.core.util.testutil.LogRule import arcs.jvm.util.testutil.FakeTime import com.google.common.truth.Truth.assertWithMessage import java.util.concurrent.Executors import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.Job import kotlinx.coroutines.asCoroutineDispatcher import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import org.junit.After import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 private typealias Person = ReadSdkPerson_Person private typealias PersonSlice = ReadSdkPerson_Person_Slice @OptIn(ExperimentalCoroutinesApi::class) @RunWith(JUnit4::class) @Suppress("UNCHECKED_CAST", "UNUSED_PARAMETER") class HandleUtilsTest { @get:Rule val log = LogRule() private lateinit var scheduler: Scheduler private lateinit var managerImpl: HandleManagerImpl @Before fun setUp() = runBlocking { RamDisk.clear() DriverAndKeyConfigurator.configure(null) scheduler = Scheduler(Executors.newSingleThreadExecutor().asCoroutineDispatcher() + Job()) managerImpl = HandleManagerImpl( arcId = "testArc", hostId = "testHost", time = FakeTime(), scheduler = scheduler, storageEndpointManager = testStorageEndpointManager(), foreignReferenceChecker = ForeignReferenceCheckerImpl(emptyMap()) ) } @After fun tearDown() = runBlocking { scheduler.waitForIdle() managerImpl.close() scheduler.cancel() } @Test fun handleUtils_combineTwoUpdatesTest() = runBlocking { val collection = createCollectionHandle(STORAGE_KEY_ONE) val singleton = createSingletonHandle(STORAGE_KEY_TWO) log("Handles ready") var x = 0 var y = 0 val signalChannel = Channel<Unit>() combineUpdates(collection, singleton) { people, e2 -> log("Heard update: $people") if (people.elementAtOrNull(0)?.name == "George") { x += 1 } if (e2?.name == "Martha") { y += 1 } launch { signalChannel.send(Unit) } } collection.dispatchStore(Person("George")) signalChannel.receive() assertWithMessage("Expected Collection to include George").that(x).isEqualTo(1) assertWithMessage("Expected Singleton to not Equal Martha").that(y).isEqualTo(0) singleton.dispatchStore(Person("Martha")) signalChannel.receive() assertWithMessage("Expected Collection to include George").that(x).isEqualTo(2) assertWithMessage("Expected Singleton to include Martha").that(y).isEqualTo(1) } @Test fun handleUtils_combineThreeUpdatesTest() = runBlocking { val handle1 = createCollectionHandle(STORAGE_KEY_ONE) val handle2 = createSingletonHandle(STORAGE_KEY_TWO) val handle3 = createCollectionHandle(STORAGE_KEY_THREE) log("Handles ready") var handle1Tracking = 0 var handle2Tracking = 0 var handle3Tracking = 0 val signalChannel = Channel<Unit>() combineUpdates(handle1, handle2, handle3) { e1, e2, e3 -> log("Heard update: $e1, $e2, $e3") if (e1.elementAtOrNull(0)?.name == "A") { handle1Tracking += 1 } if (e2?.name == "B") { handle2Tracking += 1 } if (e3.elementAtOrNull(0)?.name == "C") { handle3Tracking += 1 } launch { signalChannel.send(Unit) } } handle1.dispatchStore(Person("A")) signalChannel.receive() assertWithMessage("Expected handle1 to include A").that(handle1Tracking).isEqualTo(1) assertWithMessage("Expected handle2 to not equal B").that(handle2Tracking).isEqualTo(0) assertWithMessage("Expected handle3 to not include C").that(handle3Tracking).isEqualTo(0) handle2.dispatchStore(Person("B")) signalChannel.receive() assertWithMessage("Expected handle1 to include A").that(handle1Tracking).isEqualTo(2) assertWithMessage("Expected handle2 to equal B").that(handle2Tracking).isEqualTo(1) assertWithMessage("Expected handle3 to not include C").that(handle3Tracking).isEqualTo(0) handle3.dispatchStore(Person("C")) signalChannel.receive() assertWithMessage("Expected handle1 to include A").that(handle1Tracking).isEqualTo(3) assertWithMessage("Expected handle2 to equal B").that(handle2Tracking).isEqualTo(2) assertWithMessage("Expected handle3 to include C").that(handle3Tracking).isEqualTo(1) } @Test fun handleUtils_combineFourUpdatesTest() = runBlocking { val handle1 = createCollectionHandle(STORAGE_KEY_ONE) val handle2 = createSingletonHandle(STORAGE_KEY_TWO) val handle3 = createCollectionHandle(STORAGE_KEY_THREE) val handle4 = createSingletonHandle(STORAGE_KEY_FOUR) log("Handles ready") var handle1Tracking = 0 var handle2Tracking = 0 var handle3Tracking = 0 var handle4Tracking = 0 val signalChannel = Channel<Unit>() combineUpdates(handle1, handle2, handle3, handle4) { e1, e2, e3, e4 -> if (e1.elementAtOrNull(0)?.name == "A") { handle1Tracking += 1 } if (e2?.name == "B") { handle2Tracking += 1 } if (e3.elementAtOrNull(0)?.name == "C") { handle3Tracking += 1 } if (e4?.name == "D") { handle4Tracking += 1 } launch { signalChannel.send(Unit) } } handle1.dispatchStore(Person("A")) signalChannel.receive() assertWithMessage("Expected handle1 to include A").that(handle1Tracking).isEqualTo(1) assertWithMessage("Expected handle2 to not equal B").that(handle2Tracking).isEqualTo(0) assertWithMessage("Expected handle3 to not include C").that(handle3Tracking).isEqualTo(0) assertWithMessage("Expected handle4 to not equal D").that(handle4Tracking).isEqualTo(0) handle2.dispatchStore(Person("B")) signalChannel.receive() assertWithMessage("Expected handle1 to include A").that(handle1Tracking).isEqualTo(2) assertWithMessage("Expected handle2 to equal B").that(handle2Tracking).isEqualTo(1) assertWithMessage("Expected handle3 to not include C").that(handle3Tracking).isEqualTo(0) assertWithMessage("Expected handle4 to not equal D").that(handle4Tracking).isEqualTo(0) handle3.dispatchStore(Person("C")) signalChannel.receive() assertWithMessage("Expected handle1 to include A").that(handle1Tracking).isEqualTo(3) assertWithMessage("Expected handle2 to equal B").that(handle2Tracking).isEqualTo(2) assertWithMessage("Expected handle3 to include C").that(handle3Tracking).isEqualTo(1) assertWithMessage("Expected handle4 to not equal D").that(handle4Tracking).isEqualTo(0) handle4.dispatchStore(Person("D")) signalChannel.receive() assertWithMessage("Expected handle1 to include A").that(handle1Tracking).isEqualTo(4) assertWithMessage("Expected handle2 to equal B").that(handle2Tracking).isEqualTo(3) assertWithMessage("Expected handle3 to include C").that(handle3Tracking).isEqualTo(2) assertWithMessage("Expected handle4 to equal D").that(handle4Tracking).isEqualTo(1) } @Test fun handleUtils_combineTenUpdatesTest() = runBlocking { val handle1 = createCollectionHandle(STORAGE_KEY_ONE) val handle2 = createSingletonHandle(STORAGE_KEY_TWO) val handle3 = createCollectionHandle(STORAGE_KEY_THREE) val handle4 = createSingletonHandle(STORAGE_KEY_FOUR) val handle5 = createCollectionHandle(STORAGE_KEY_FIVE) val handle6 = createSingletonHandle(STORAGE_KEY_SIX) val handle7 = createCollectionHandle(STORAGE_KEY_SEVEN) val handle8 = createSingletonHandle(STORAGE_KEY_EIGHT) val handle9 = createCollectionHandle(STORAGE_KEY_NINE) val handle10 = createSingletonHandle(STORAGE_KEY_TEN) log("Handles ready") var tracking5 = 0 var tracking6 = 0 var tracking7 = 0 var tracking8 = 0 var tracking9 = 0 var tracking10 = 0 val doneYet = Job() combineUpdates( handle1, handle2, handle3, handle4, handle5 ) { _, _, _, _, _ -> tracking5 += 1 } combineUpdates( handle1, handle2, handle3, handle4, handle5, handle6 ) { _, _, _, _, _, _ -> tracking6 += 1 } combineUpdates( handle1, handle2, handle3, handle4, handle5, handle6, handle7 ) { _, _, _, _, _, _, _ -> tracking7 += 1 } combineUpdates( handle1, handle2, handle3, handle4, handle5, handle6, handle7, handle8 ) { _, _, _, _, _, _, _, _ -> tracking8 += 1 } combineUpdates( handle1, handle2, handle3, handle4, handle5, handle6, handle7, handle8, handle9 ) { _, _, _, _, _, _, _, _, _ -> tracking9 += 1 } combineUpdates( handle1, handle2, handle3, handle4, handle5, handle6, handle7, handle8, handle9, handle10 ) { _, _, _, _, _, _, _, _, _, _ -> tracking10 += 1 if (tracking10 == 10) doneYet.complete() } handle1.dispatchStore(Person("A")) handle2.dispatchStore(Person("B")) handle3.dispatchStore(Person("C")) handle4.dispatchStore(Person("D")) handle5.dispatchStore(Person("E")) handle6.dispatchStore(Person("F")) handle7.dispatchStore(Person("G")) handle8.dispatchStore(Person("H")) handle9.dispatchStore(Person("I")) handle10.dispatchStore(Person("J")) doneYet.join() assertWithMessage("Expected 5 combineUpdates to be called.") .that(tracking5).isEqualTo(5) assertWithMessage("Expected 6 combineUpdates to be called.") .that(tracking6).isEqualTo(6) assertWithMessage("Expected 7 combineUpdates to be called.") .that(tracking7).isEqualTo(7) assertWithMessage("Expected 8 combineUpdates to be called.") .that(tracking8).isEqualTo(8) assertWithMessage("Expected 9 combineUpdates to be called.") .that(tracking9).isEqualTo(9) assertWithMessage("Expected 10 combineUpdates to be called.") .that(tracking10).isEqualTo(10) } private suspend fun createCollectionHandle( storageKey: StorageKey ) = managerImpl.createHandle( HandleSpec( READ_WRITE_HANDLE, HandleMode.ReadWriteQuery, CollectionType(EntityType(Person.SCHEMA)), Person ), storageKey ).awaitReady() as ReadWriteQueryCollectionHandle<Person, PersonSlice, *> private suspend fun createSingletonHandle( storageKey: StorageKey ) = managerImpl.createHandle( HandleSpec( READ_WRITE_HANDLE, HandleMode.ReadWrite, SingletonType(EntityType(Person.SCHEMA)), Person ), storageKey ).awaitReady() as ReadWriteSingletonHandle<Person, PersonSlice> private companion object { private const val READ_WRITE_HANDLE = "readWriteHandle" private val STORAGE_KEY_ONE = ReferenceModeStorageKey( backingKey = RamDiskStorageKey("backing"), storageKey = RamDiskStorageKey("entity") ) private val STORAGE_KEY_TWO = ReferenceModeStorageKey( backingKey = RamDiskStorageKey("backing2"), storageKey = RamDiskStorageKey("entity2") ) private val STORAGE_KEY_THREE = ReferenceModeStorageKey( backingKey = RamDiskStorageKey("backing3"), storageKey = RamDiskStorageKey("entity3") ) private val STORAGE_KEY_FOUR = ReferenceModeStorageKey( backingKey = RamDiskStorageKey("backing4"), storageKey = RamDiskStorageKey("entity4") ) private val STORAGE_KEY_FIVE = ReferenceModeStorageKey( backingKey = RamDiskStorageKey("backing5"), storageKey = RamDiskStorageKey("entity5") ) private val STORAGE_KEY_SIX = ReferenceModeStorageKey( backingKey = RamDiskStorageKey("backing6"), storageKey = RamDiskStorageKey("entity6") ) private val STORAGE_KEY_SEVEN = ReferenceModeStorageKey( backingKey = RamDiskStorageKey("backing7"), storageKey = RamDiskStorageKey("entity7") ) private val STORAGE_KEY_EIGHT = ReferenceModeStorageKey( backingKey = RamDiskStorageKey("backing8"), storageKey = RamDiskStorageKey("entity8") ) private val STORAGE_KEY_NINE = ReferenceModeStorageKey( backingKey = RamDiskStorageKey("backing9"), storageKey = RamDiskStorageKey("entity9") ) private val STORAGE_KEY_TEN = ReferenceModeStorageKey( backingKey = RamDiskStorageKey("backing10"), storageKey = RamDiskStorageKey("entity10") ) } }
bsd-3-clause
85853959877b425a937785aff1dea24f
31.454545
96
0.6977
4.330035
false
false
false
false
TomsUsername/Phoenix
src/main/kotlin/phoenix/bot/pogo/nRnMK9r/tasks/DropUselessItems.kt
1
4812
/** * Pokemon Go Bot Copyright (C) 2016 PokemonGoBot-authors (see authors.md for more information) * This program comes with ABSOLUTELY NO WARRANTY; * This is free software, and you are welcome to redistribute it under certain conditions. * * For more information, refer to the LICENSE file in this repositories root directory */ package phoenix.bot.pogo.nRnMK9r.tasks import POGOProtos.Inventory.Item.ItemIdOuterClass.ItemId import POGOProtos.Networking.Responses.RecycleInventoryItemResponseOuterClass import phoenix.bot.pogo.api.request.RecycleInventoryItem import phoenix.bot.pogo.nRnMK9r.Bot import phoenix.bot.pogo.nRnMK9r.Context import phoenix.bot.pogo.nRnMK9r.Settings import phoenix.bot.pogo.nRnMK9r.Task import phoenix.bot.pogo.nRnMK9r.util.Log import java.util.concurrent.atomic.AtomicInteger class DropUselessItems : Task { override fun run(bot: Bot, ctx: Context, settings: Settings) { // ignores the items that have -1 val itemsToDrop = settings.uselessItems.filter { it.value != -1 } if (settings.groupItemsByType) dropGroupedItems(ctx, itemsToDrop, settings) else dropItems(ctx, itemsToDrop, settings) } /** * Drops the excess items by group */ fun dropGroupedItems(ctx: Context, items: Map<ItemId, Int>, settings: Settings) { // map with what items to keep in what amounts val itemsToDrop = mutableMapOf<ItemId, Int>() // adds not groupable items on map itemsToDrop.putAll(items.filter { singlesFilter.contains(it.key) }) // groups items val groupedItems = groupItems(items) // adds new items to the map val itemBag = ctx.api.inventory.items groupedItems.forEach groupedItems@ { var groupCount = 0 it.key.forEach { groupCount += itemBag.getOrPut(it, { AtomicInteger(0) }).get() } var neededToDrop = groupCount - it.value if (neededToDrop > 0) it.key.forEach { val item = itemBag.getOrPut(it, { AtomicInteger(0) }) if (neededToDrop <= item.get()) { itemsToDrop.put(it, item.get() - neededToDrop) return@groupedItems } else { neededToDrop -= item.get() itemsToDrop.put(it, 0) } } } // drops excess items dropItems(ctx, itemsToDrop, settings) } /** * Groups the items using the groupFilters * Each group contains the list of itemIds of the group and sum of all its number */ fun groupItems(items: Map<ItemId, Int>): Map<Array<ItemId>, Int> { val groupedItems = mutableMapOf<Array<ItemId>, Int>() groupFilters.forEach { val filter = it val filteredItems = items.filter { filter.contains(it.key) } groupedItems.put(filteredItems.keys.toTypedArray(), filteredItems.values.sum()) } return groupedItems } // Items that can be grouped val groupFilters = arrayOf( arrayOf(ItemId.ITEM_REVIVE, ItemId.ITEM_MAX_REVIVE), arrayOf(ItemId.ITEM_POTION, ItemId.ITEM_SUPER_POTION, ItemId.ITEM_HYPER_POTION, ItemId.ITEM_MAX_POTION), arrayOf(ItemId.ITEM_POKE_BALL, ItemId.ITEM_GREAT_BALL, ItemId.ITEM_ULTRA_BALL, ItemId.ITEM_MASTER_BALL) ) // Items that cant be grouped val singlesFilter = arrayOf(ItemId.ITEM_RAZZ_BERRY, ItemId.ITEM_LUCKY_EGG, ItemId.ITEM_INCENSE_ORDINARY, ItemId.ITEM_TROY_DISK) /** * Drops the excess items by item */ fun dropItems(ctx: Context, items: Map<ItemId, Int>, settings: Settings) { val itemBag = ctx.api.inventory.items items.forEach { val item = itemBag.getOrPut(it.key, { AtomicInteger(0) }) val count = item.get() - it.value if (count > 0) { val dropItem = it.key val drop = RecycleInventoryItem().withCount(count).withItemId(dropItem) val result = ctx.api.queueRequest(drop).toBlocking().first().response if (result.result == RecycleInventoryItemResponseOuterClass.RecycleInventoryItemResponse.Result.SUCCESS) { ctx.itemStats.second.getAndAdd(count) Log.yellow("Dropped ${count}x ${dropItem.name}") ctx.server.sendProfile() } else { Log.red("Failed to drop ${count}x ${dropItem.name}: $result") } } if (settings.itemDropDelay != (-1).toLong()) { val itemDropDelay = settings.itemDropDelay / 2 + (Math.random() * settings.itemDropDelay).toLong() Thread.sleep(itemDropDelay) } } } }
gpl-3.0
a80bdac43c355d175bb5bba6a60e4087
42.351351
131
0.623234
4.300268
false
false
false
false
kelsos/mbrc
app/src/main/kotlin/com/kelsos/mbrc/constants/Const.kt
1
337
package com.kelsos.mbrc.constants object Const { val EMPTY = "" val PLUGIN = "plugin" val VERSIONS = "versions" val SUB = "sub" val LYRICS_NEWLINE = "\r\n|\n" val DATA = "data" val TOGGLE = "toggle" val PLAYING = "playing" val PAUSED = "paused" val STOPPED = "stopped" val NEWLINE = "\r\n" val UTF_8 = "UTF-8" }
gpl-3.0
bc465cdf9703ded1fde3099de46706fc
20.0625
33
0.617211
2.930435
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/coroutines/RedundantRunCatchingInspection.kt
1
2090
// 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.coroutines import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.inspections.collections.AbstractCallChainChecker import org.jetbrains.kotlin.idea.inspections.collections.SimplifyCallChainFix import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.psi.qualifiedExpressionVisitor /** * Test - [org.jetbrains.kotlin.idea.inspections.LocalInspectionTestGenerated.Coroutines.RedundantRunCatching] */ class RedundantRunCatchingInspection : AbstractCallChainChecker() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = qualifiedExpressionVisitor(fun(expression) { val conversion = findQualifiedConversion(expression, conversionGroups) { _, _, _, _ -> true } ?: return val replacement = conversion.replacement val descriptor = holder.manager.createProblemDescriptor( expression, expression.firstCalleeExpression()!!.textRange.shiftRight(-expression.startOffset), KotlinBundle.message("redundant.runcatching.call.may.be.reduced.to.0", replacement), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, isOnTheFly, SimplifyCallChainFix(conversion) ) holder.registerProblem(descriptor) }) private val conversionGroups = conversions.group() companion object { private val conversions = listOf( Conversion( "kotlin.runCatching", // FQNs are hardcoded instead of specifying their names via reflection because "kotlin.getOrThrow", // referencing function which has generics isn't yet supported in Kotlin KT-12140 "run" ) ) } }
apache-2.0
79b4c9a4de691c6afd6c2633692aac38
46.522727
158
0.715789
5.225
false
false
false
false
mdaniel/intellij-community
platform/platform-impl/src/com/intellij/ide/gdpr/ui/Styles.kt
12
2511
// 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.gdpr.ui import com.intellij.ui.JBColor import com.intellij.ui.scale.JBUIScale import com.intellij.util.ui.StartupUiUtil import java.awt.Color import javax.swing.text.SimpleAttributeSet import javax.swing.text.StyleConstants object Styles { private val foregroundColor: Color = JBColor.BLACK private val hintColor: Color = JBColor.GRAY private val headerColor: Color = JBColor.BLACK private val linkColor = Color(74, 120, 194) private val lineSpacing = 0.1f private val fontSize = StartupUiUtil.getLabelFont().size private val h1FontSize = JBUIScale.scale(24) private val h2FontSize = JBUIScale.scale(18) val H1 = SimpleAttributeSet().apply { StyleConstants.setForeground(this, headerColor) StyleConstants.setFontSize(this, h1FontSize) StyleConstants.setBold(this, true) StyleConstants.setSpaceBelow(this, h1FontSize * 0.6f) } val H2 = SimpleAttributeSet().apply { StyleConstants.setForeground(this, headerColor) StyleConstants.setFontSize(this, h2FontSize) StyleConstants.setBold(this, true) StyleConstants.setSpaceAbove(this, h2FontSize * 0.8f) } val REGULAR = SimpleAttributeSet().apply { StyleConstants.setForeground(this, foregroundColor) StyleConstants.setFontSize(this, fontSize) StyleConstants.setBold(this, false) } val BOLD = SimpleAttributeSet().apply { StyleConstants.setForeground(this, foregroundColor) StyleConstants.setBold(this, true) } val SUP = SimpleAttributeSet().apply { StyleConstants.setForeground(this, foregroundColor) StyleConstants.setSuperscript(this, true) } val LINK = SimpleAttributeSet().apply { StyleConstants.setForeground(this, linkColor) } val PARAGRAPH = SimpleAttributeSet().apply { StyleConstants.setForeground(this, foregroundColor) StyleConstants.setLineSpacing(this, lineSpacing) StyleConstants.setFontSize(this, fontSize) StyleConstants.setSpaceAbove(this, fontSize * 0.6f) } val HINT = SimpleAttributeSet().apply { StyleConstants.setForeground(this, hintColor) StyleConstants.setLineSpacing(this, lineSpacing) StyleConstants.setFontSize(this, fontSize) StyleConstants.setSpaceAbove(this, fontSize * 0.6f) } }
apache-2.0
9e7a2311fa9090f33237c3cba342ffa2
39.516129
140
0.722023
4.557169
false
false
false
false
johnjohndoe/Umweltzone
Umweltzone/src/main/java/de/avpptr/umweltzone/prefs/CameraPositionPreference.kt
1
2200
/* * Copyright (C) 2019 Tobias Preuss * * 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.avpptr.umweltzone.prefs import android.content.SharedPreferences import com.google.android.gms.maps.model.CameraPosition import com.google.android.gms.maps.model.LatLng import de.avpptr.umweltzone.utils.GeoPoint import info.metadude.android.typedpreferences.FloatPreference class CameraPositionPreference( sharedPreferences: SharedPreferences, key: String ) { private val targetPreference = GeoPointPreference(sharedPreferences, "$key.TARGET") private val zoomPreference = FloatPreference(sharedPreferences, "$key.ZOOM") private val tiltPreference = FloatPreference(sharedPreferences, "$key.TILT") private val bearingPreference = FloatPreference(sharedPreferences, "$key.BEARING") fun get(): CameraPosition { val geoPoint = targetPreference.get() val target = LatLng(geoPoint.latitude, geoPoint.longitude) val zoom = zoomPreference.get() val tilt = tiltPreference.get() val bearing = bearingPreference.get() return CameraPosition(target, zoom, tilt, bearing) } fun set(cameraPosition: CameraPosition) { targetPreference.set(GeoPoint(cameraPosition.target)) zoomPreference.set(cameraPosition.zoom) tiltPreference.set(cameraPosition.tilt) bearingPreference.set(cameraPosition.bearing) } fun delete() { targetPreference.delete() zoomPreference.delete() tiltPreference.delete() bearingPreference.delete() } }
gpl-3.0
0ae437d24924f563e5a41059b7d42989
33.920635
87
0.727273
4.453441
false
false
false
false
PKRoma/PocketHub
app/src/main/java/com/github/pockethub/android/ui/NewsFragment.kt
5
8839
/* * Copyright (c) 2015 PocketHub * * 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.pockethub.android.ui import android.content.Intent import android.content.Intent.ACTION_VIEW import android.content.Intent.CATEGORY_BROWSABLE import android.net.Uri import android.os.Bundle import android.text.TextUtils import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.github.pockethub.android.R import com.github.pockethub.android.core.gist.GistEventMatcher import com.github.pockethub.android.core.issue.IssueEventMatcher import com.github.pockethub.android.core.repo.RepositoryEventMatcher import com.github.pockethub.android.core.user.UserEventMatcher import com.github.pockethub.android.core.user.UserEventMatcher.UserPair import com.github.pockethub.android.ui.base.BaseFragment import com.github.pockethub.android.ui.commit.CommitCompareViewActivity import com.github.pockethub.android.ui.commit.CommitViewActivity import com.github.pockethub.android.ui.gist.GistsViewActivity import com.github.pockethub.android.ui.helpers.ItemListHandler import com.github.pockethub.android.ui.helpers.PagedListFetcher import com.github.pockethub.android.ui.helpers.PagedScrollListener import com.github.pockethub.android.ui.issue.IssuesViewActivity import com.github.pockethub.android.ui.item.news.NewsItem import com.github.pockethub.android.ui.repo.RepositoryViewActivity import com.github.pockethub.android.util.AvatarLoader import com.github.pockethub.android.util.ConvertUtils import com.github.pockethub.android.util.InfoUtils import com.github.pockethub.android.util.ToastUtils import com.meisolsson.githubsdk.model.GitHubEvent import com.meisolsson.githubsdk.model.GitHubEventType.CommitCommentEvent import com.meisolsson.githubsdk.model.GitHubEventType.DownloadEvent import com.meisolsson.githubsdk.model.GitHubEventType.PushEvent import com.meisolsson.githubsdk.model.Issue import com.meisolsson.githubsdk.model.Page import com.meisolsson.githubsdk.model.Repository import com.meisolsson.githubsdk.model.User import com.meisolsson.githubsdk.model.payload.CommitCommentPayload import com.meisolsson.githubsdk.model.payload.PushPayload import com.meisolsson.githubsdk.model.payload.ReleasePayload import com.xwray.groupie.Item import com.xwray.groupie.OnItemClickListener import io.reactivex.Single import kotlinx.android.synthetic.main.fragment_item_list.view.* import retrofit2.Response import javax.inject.Inject /** * Base news fragment class with utilities for subclasses to built on */ abstract class NewsFragment : BaseFragment() { @Inject protected lateinit var avatars: AvatarLoader protected lateinit var pagedListFetcher: PagedListFetcher<GitHubEvent> private lateinit var itemListHandler: ItemListHandler protected val errorMessage: Int get() = R.string.error_news_load override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_item_list, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) itemListHandler = ItemListHandler( view.list, view.empty, lifecycle, activity, OnItemClickListener(this::onItemClick) ) pagedListFetcher = PagedListFetcher( view.swipe_item, lifecycle, itemListHandler, { t -> ToastUtils.show(activity, errorMessage) }, this::loadData, this::createItem ) view.list.addOnScrollListener( PagedScrollListener(itemListHandler.mainSection, pagedListFetcher) ) itemListHandler.setEmptyText(R.string.no_news) } protected abstract fun loadData(page: Int): Single<Response<Page<GitHubEvent>>> fun onItemClick(item: Item<*>, view: View) { if (item !is NewsItem) { return } val event = item.gitHubEvent if (DownloadEvent == event.type()) { openDownload(event) return } if (PushEvent == event.type()) { openPush(event) return } if (CommitCommentEvent == event.type()) { openCommitComment(event) return } val issue = IssueEventMatcher.getIssue(event) if (issue != null) { val repo = ConvertUtils.eventRepoToRepo(event.repo()!!) viewIssue(issue, repo) return } val gist = GistEventMatcher.getGist(event) if (gist != null) { startActivity(GistsViewActivity.createIntent(gist)) return } val repo = RepositoryEventMatcher.getRepository(event) if (repo != null) { viewRepository(repo) } val users = UserEventMatcher.getUsers(event) if (users != null) { viewUser(users) } } // https://developer.github.com/v3/repos/downloads/#downloads-api-is-deprecated private fun openDownload(event: GitHubEvent) { val release = (event.payload() as ReleasePayload).release() ?: return val url = release.htmlUrl() if (TextUtils.isEmpty(url)) { return } val intent = Intent(ACTION_VIEW, Uri.parse(url)) intent.addCategory(CATEGORY_BROWSABLE) startActivity(intent) } private fun openCommitComment(event: GitHubEvent) { var repo: Repository? = ConvertUtils.eventRepoToRepo(event.repo()!!) ?: return if (repo!!.name()!!.contains("/")) { val repoId = repo.name()!! .split("/".toRegex()) .dropLastWhile { it.isEmpty() } .toTypedArray() repo = InfoUtils.createRepoFromData(repoId[0], repoId[1]) } val payload = event.payload() as CommitCommentPayload? ?: return val comment = payload.comment() ?: return val sha = comment.commitId() if (!TextUtils.isEmpty(sha)) { startActivity(CommitViewActivity.createIntent(repo!!, sha!!)) } } private fun openPush(event: GitHubEvent) { val repo = ConvertUtils.eventRepoToRepo(event.repo()!!) ?: return val payload = event.payload() as PushPayload? ?: return val commits = payload.commits() if (commits.isEmpty()) { return } if (commits.size > 1) { val base = payload.before() val head = payload.head() if (!TextUtils.isEmpty(base) && !TextUtils.isEmpty(head)) { startActivity(CommitCompareViewActivity.createIntent(repo, base, head)) } } else { val commit = commits[0] val sha = commit?.sha() if (!TextUtils.isEmpty(sha)) { startActivity(CommitViewActivity.createIntent(repo, sha!!)) } } } /** * Start an activity to view the given repository * * @param repository */ protected open fun viewRepository(repository: Repository?) { startActivity(RepositoryViewActivity.createIntent(repository!!)) } /** * Start an activity to view the given [UserPair] * * * This method does nothing by default, subclasses should override * * @param users */ protected open fun viewUser(users: UserPair) {} /** * Start an activity to view the given [User] * * @param user * @return true if new activity started, false otherwise */ protected open fun viewUser(user: User?): Boolean { return false } /** * Start an activity to view the given [Issue] * * @param issue * @param repository */ protected open fun viewIssue(issue: Issue, repository: Repository?) { if (repository != null) { startActivity(IssuesViewActivity.createIntent(issue, repository)) } else { startActivity(IssuesViewActivity.createIntent(issue)) } } protected fun createItem(item: GitHubEvent): Item<*> { return NewsItem.createNewsItem(avatars, item)!! } }
apache-2.0
1d8f0f4dc554a77456a225ed0ccf1b43
32.104869
87
0.670664
4.570321
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeCallableReturnTypeFix.kt
1
13095
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.quickfix import com.intellij.codeInsight.intention.FileModifier.SafeFieldForPreview import com.intellij.codeInsight.intention.HighPriorityAction import com.intellij.codeInsight.intention.IntentionAction import com.intellij.codeInsight.intention.preview.IntentionPreviewInfo import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiFile import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.findParentOfType import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.Errors.COMPONENT_FUNCTION_RETURN_TYPE_MISMATCH import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.project.builtIns import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DataClassDescriptorResolver import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.checker.KotlinTypeChecker import org.jetbrains.kotlin.types.error.ErrorUtils import org.jetbrains.kotlin.types.typeUtil.isUnit import java.util.* abstract class ChangeCallableReturnTypeFix( element: KtCallableDeclaration, type: KotlinType ) : KotlinQuickFixAction<KtCallableDeclaration>(element) { // Not actually safe but handled especially inside invokeForPreview @SafeFieldForPreview private val changeFunctionLiteralReturnTypeFix: ChangeFunctionLiteralReturnTypeFix? private val typeContainsError = ErrorUtils.containsErrorType(type) private val typePresentation = IdeDescriptorRenderers.SOURCE_CODE_TYPES_WITH_SHORT_NAMES.renderType(type) private val typeSourceCode = IdeDescriptorRenderers.SOURCE_CODE_TYPES.renderType(type) private val isUnitType = type.isUnit() init { changeFunctionLiteralReturnTypeFix = if (element is KtFunctionLiteral) { val functionLiteralExpression = PsiTreeUtil.getParentOfType(element, KtLambdaExpression::class.java) ?: error("FunctionLiteral outside any FunctionLiteralExpression: " + element.getElementTextWithContext()) ChangeFunctionLiteralReturnTypeFix(functionLiteralExpression, type) } else { null } } open fun functionPresentation(): String? { val element = element!! if (element.name == null) return null val container = element.unsafeResolveToDescriptor().containingDeclaration as? ClassDescriptor val containerName = container?.name?.takeUnless { it.isSpecial }?.asString() return ChangeTypeFixUtils.functionOrConstructorParameterPresentation(element, containerName) } class OnType(element: KtFunction, type: KotlinType) : ChangeCallableReturnTypeFix(element, type), HighPriorityAction { override fun functionPresentation() = null } class ForEnclosing(element: KtFunction, type: KotlinType) : ChangeCallableReturnTypeFix(element, type), HighPriorityAction { override fun functionPresentation(): String { val presentation = super.functionPresentation() ?: return KotlinBundle.message("fix.change.return.type.presentation.enclosing.function") return KotlinBundle.message("fix.change.return.type.presentation.enclosing", presentation) } } class ForCalled(element: KtCallableDeclaration, type: KotlinType) : ChangeCallableReturnTypeFix(element, type) { override fun functionPresentation(): String { val presentation = super.functionPresentation() ?: return KotlinBundle.message("fix.change.return.type.presentation.called.function") return when (element) { is KtParameter -> KotlinBundle.message("fix.change.return.type.presentation.accessed", presentation) else -> KotlinBundle.message("fix.change.return.type.presentation.called", presentation) } } } class ForOverridden(element: KtFunction, type: KotlinType) : ChangeCallableReturnTypeFix(element, type) { override fun functionPresentation(): String? { val presentation = super.functionPresentation() ?: return null return ChangeTypeFixUtils.baseFunctionOrConstructorParameterPresentation(presentation) } } override fun getText(): String { val element = element ?: return "" if (changeFunctionLiteralReturnTypeFix != null) { return changeFunctionLiteralReturnTypeFix.text } return ChangeTypeFixUtils.getTextForQuickFix(element, functionPresentation(), isUnitType, typePresentation) } override fun getFamilyName(): String = ChangeTypeFixUtils.familyName() override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean { return !typeContainsError && element !is KtConstructor<*> } override fun invoke(project: Project, editor: Editor?, file: KtFile) { val element = element ?: return if (changeFunctionLiteralReturnTypeFix != null) { changeFunctionLiteralReturnTypeFix.invoke(project, editor!!, file) } else { if (!(isUnitType && element is KtFunction && element.hasBlockBody())) { var newTypeRef = KtPsiFactory(project).createType(typeSourceCode) newTypeRef = element.setTypeReference(newTypeRef)!! ShortenReferences.DEFAULT.process(newTypeRef) } else { element.typeReference = null } } } override fun generatePreview(project: Project, editor: Editor, file: PsiFile): IntentionPreviewInfo { if (changeFunctionLiteralReturnTypeFix != null) { return changeFunctionLiteralReturnTypeFix.generatePreview(project, editor, file) } return super.generatePreview(project, editor, file) } object ComponentFunctionReturnTypeMismatchFactory : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val entry = getDestructuringDeclarationEntryThatTypeMismatchComponentFunction(diagnostic) val context = entry.analyze(BodyResolveMode.PARTIAL) val resolvedCall = context.get(BindingContext.COMPONENT_RESOLVED_CALL, entry) ?: return null val componentFunction = DescriptorToSourceUtils.descriptorToDeclaration(resolvedCall.candidateDescriptor) as? KtCallableDeclaration ?: return null val expectedType = context[BindingContext.TYPE, entry.typeReference!!] ?: return null return ForCalled(componentFunction, expectedType) } } object HasNextFunctionTypeMismatchFactory : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val expression = diagnostic.psiElement.findParentOfType<KtExpression>(strict = false) ?: error("HAS_NEXT_FUNCTION_TYPE_MISMATCH reported on element that is not within any expression") val context = expression.analyze(BodyResolveMode.PARTIAL) val resolvedCall = context[BindingContext.LOOP_RANGE_HAS_NEXT_RESOLVED_CALL, expression] ?: return null val hasNextDescriptor = resolvedCall.candidateDescriptor val hasNextFunction = DescriptorToSourceUtils.descriptorToDeclaration(hasNextDescriptor) as KtFunction? ?: return null return ForCalled(hasNextFunction, hasNextDescriptor.builtIns.booleanType) } } object CompareToTypeMismatchFactory : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val expression = diagnostic.psiElement.findParentOfType<KtBinaryExpression>(strict = false) ?: error("COMPARE_TO_TYPE_MISMATCH reported on element that is not within any expression") val resolvedCall = expression.resolveToCall() ?: return null val compareToDescriptor = resolvedCall.candidateDescriptor val compareTo = DescriptorToSourceUtils.descriptorToDeclaration(compareToDescriptor) as? KtFunction ?: return null return ForCalled(compareTo, compareToDescriptor.builtIns.intType) } } object ReturnTypeMismatchOnOverrideFactory : KotlinIntentionActionsFactory() { override fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction> { val function = diagnostic.psiElement.findParentOfType<KtFunction>(strict = false) ?: return emptyList() val actions = LinkedList<IntentionAction>() val descriptor = function.resolveToDescriptorIfAny(BodyResolveMode.FULL) as? FunctionDescriptor ?: return emptyList() val matchingReturnType = findLowerBoundOfOverriddenCallablesReturnTypes(descriptor) if (matchingReturnType != null) { actions.add(OnType(function, matchingReturnType)) } val functionType = descriptor.returnType ?: return actions val overriddenMismatchingFunctions = LinkedList<FunctionDescriptor>() for (overriddenFunction in descriptor.overriddenDescriptors) { val overriddenFunctionType = overriddenFunction.returnType ?: continue if (!KotlinTypeChecker.DEFAULT.isSubtypeOf(functionType, overriddenFunctionType)) { overriddenMismatchingFunctions.add(overriddenFunction) } } if (overriddenMismatchingFunctions.size == 1) { val overriddenFunction = DescriptorToSourceUtils.descriptorToDeclaration(overriddenMismatchingFunctions[0]) if (overriddenFunction is KtFunction) { actions.add(ForOverridden(overriddenFunction, functionType)) } } return actions } } object ChangingReturnTypeToUnitFactory : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val function = diagnostic.psiElement.findParentOfType<KtFunction>(strict = false) ?: return null return ForEnclosing(function, function.builtIns.unitType) } } object ChangingReturnTypeToNothingFactory : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val function = diagnostic.psiElement.findParentOfType<KtFunction>(strict = false) ?: return null return ForEnclosing(function, function.builtIns.nothingType) } } companion object { fun getDestructuringDeclarationEntryThatTypeMismatchComponentFunction(diagnostic: Diagnostic): KtDestructuringDeclarationEntry { val componentName = COMPONENT_FUNCTION_RETURN_TYPE_MISMATCH.cast(diagnostic).a val componentIndex = DataClassDescriptorResolver.getComponentIndex(componentName.asString()) val multiDeclaration = diagnostic.psiElement.findParentOfType<KtDestructuringDeclaration>(strict = false) ?: error("COMPONENT_FUNCTION_RETURN_TYPE_MISMATCH reported on expression that is not within any multi declaration") return multiDeclaration.entries[componentIndex - 1] } fun findLowerBoundOfOverriddenCallablesReturnTypes(descriptor: CallableDescriptor): KotlinType? { var matchingReturnType: KotlinType? = null for (overriddenDescriptor in descriptor.overriddenDescriptors) { val overriddenReturnType = overriddenDescriptor.returnType ?: return null if (matchingReturnType == null || KotlinTypeChecker.DEFAULT.isSubtypeOf(overriddenReturnType, matchingReturnType)) { matchingReturnType = overriddenReturnType } else if (!KotlinTypeChecker.DEFAULT.isSubtypeOf(matchingReturnType, overriddenReturnType)) { return null } } return matchingReturnType } } }
apache-2.0
14d248e98d776f10c3fb2bad7086840d
51.38
136
0.727835
5.794248
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/checker/kt32189returnTypeWithTypealiasSubtitution.kt
10
527
// FIR_IDENTICAL class B { class Builder } typealias ApplyRestrictions = B.Builder.() -> B.Builder fun applyRestrictions1(): ApplyRestrictions = { this } fun applyRestrictions2() = applyRestrictions1() fun <K> applyRestrictions3(<warning descr="[UNUSED_PARAMETER] Parameter 'e' is never used">e</warning>: K) = applyRestrictions1() fun buildB() { val a1 = applyRestrictions1() val a2 = applyRestrictions2() val a3 = applyRestrictions3("foo") B.Builder().a1() B.Builder().a2() B.Builder().a3() }
apache-2.0
555418871b12a6e9705d2970d2473410
25.35
129
0.685009
3.536913
false
false
false
false
jk1/intellij-community
python/tools/src/com/jetbrains/python/tools/PyPrebuiltIndicesGenerator.kt
4
2999
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.tools import com.intellij.ide.BootstrapClassLoaderUtil import com.intellij.idea.IdeaTestApplication import com.intellij.index.PrebuiltIndexAwareIdIndexer import com.intellij.openapi.application.PathManager import com.intellij.openapi.application.WriteAction import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.psi.stubs.PrebuiltStubsProviderBase import com.intellij.testFramework.PlatformTestCase import com.intellij.util.ReflectionUtil import com.intellij.util.io.ZipUtil import com.intellij.util.ui.UIUtil import com.jetbrains.python.psi.impl.stubs.PyPrebuiltStubsProvider import org.jetbrains.index.id.IdIndexGenerator import java.io.File import java.util.* fun main(args: Array<String>) { buildIndices(args[0], "${args[1]}/${PyPrebuiltStubsProvider.NAME}") } fun buildIndices(root: String, outputPath: String) { val app = createApp() try { FileUtil.delete(File(outputPath)) val roots = unzipArchivesToRoots(root) val rootFiles = ArrayList(roots.map { it -> LocalFileSystem.getInstance().findFileByIoFile(it)!! }) PyStubsGenerator("$outputPath/${PrebuiltStubsProviderBase.SDK_STUBS_STORAGE_NAME}").buildStubsForRoots(rootFiles) IdIndexGenerator("$outputPath/${PrebuiltIndexAwareIdIndexer.ID_INDEX_FILE_NAME}").buildIdIndexForRoots(rootFiles) } catch (e: Throwable) { e.printStackTrace() } finally { UIUtil.invokeAndWaitIfNeeded(Runnable { WriteAction.run<Throwable> { app.dispose() } }) FileUtil.delete(File(System.getProperty(PathManager.PROPERTY_PLUGINS_PATH))) FileUtil.delete(File(System.getProperty(PathManager.PROPERTY_SYSTEM_PATH))) System.exit(0) } } fun unzipArchivesToRoots(root: String): List<File> { val dir = File(root) if (!dir.exists() || !dir.isDirectory) { throw IllegalStateException("$root doesn't exist or isn't a directory") } return dir.listFiles { _, name -> name.endsWith(".zip") }.map { zip -> val unzipRoot = File(root, zip.nameWithoutExtension) println("Extracting $zip") ZipUtil.extract(zip, unzipRoot, null) unzipRoot } } private fun createApp(): IdeaTestApplication { val candidates = ReflectionUtil.getField(PlatformTestCase::class.java, null, Array<String>::class.java, "PREFIX_CANDIDATES") candidates[0] = "PyCharm" System.setProperty(PathManager.PROPERTY_PLUGINS_PATH, FileUtil.createTempDirectory("pystubs", "plugins").absolutePath) System.setProperty(PathManager.PROPERTY_SYSTEM_PATH, FileUtil.createTempDirectory("pystubs", "system").absolutePath) System.setProperty(PathManager.PROPERTY_CONFIG_PATH, FileUtil.createTempDirectory("pystubs", "config").absolutePath) Thread.currentThread().contextClassLoader = BootstrapClassLoaderUtil.initClassLoader() return IdeaTestApplication.getInstance() }
apache-2.0
2c08138e7acaeee1c61ec21431349a66
39.527027
140
0.771591
4.108219
false
true
false
false
ktorio/ktor
ktor-client/ktor-client-winhttp/windows/src/io/ktor/client/engine/winhttp/internal/WinHttpCoroutine.kt
1
1354
/* * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.engine.winhttp.internal import io.ktor.utils.io.core.* import kotlinx.cinterop.* import kotlinx.coroutines.* import ktor.cinterop.winhttp.* import kotlin.coroutines.* internal suspend inline fun <T> Closeable.closeableCoroutine( state: WinHttpConnect, errorMessage: String, crossinline block: (CancellableContinuation<T>) -> Unit ): T = suspendCancellableCoroutine { continuation -> if (!continuation.isActive) { close() return@suspendCancellableCoroutine } continuation.invokeOnCancellation { close() } state.handlers[WinHttpCallbackStatus.RequestError.value] = { statusInfo, _ -> val result = statusInfo!!.reinterpret<WINHTTP_ASYNC_RESULT>().pointed continuation.resumeWithException(getWinHttpException(errorMessage, result.dwError)) } state.handlers[WinHttpCallbackStatus.SecureFailure.value] = { statusInfo, _ -> val securityCode = statusInfo!!.reinterpret<UIntVar>().pointed.value continuation.resumeWithException(getWinHttpException(errorMessage, securityCode)) } try { block(continuation) } catch (cause: Throwable) { continuation.resumeWithException(cause) } }
apache-2.0
1c85dc9ae8c60b1f7fcc2286c0da3f83
31.238095
119
0.71935
4.528428
false
false
false
false
ktorio/ktor
ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-xml/jvm/src/io/ktor/serialization/kotlinx/xml/XmlSupport.kt
1
1465
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.serialization.kotlinx.xml import io.ktor.http.* import io.ktor.serialization.* import io.ktor.serialization.kotlinx.* import kotlinx.serialization.* import nl.adaptivity.xmlutil.* import nl.adaptivity.xmlutil.serialization.* /** * The default XML configuration. The settings are: * - Every declaration without a namespace is automatically wrapped in the namespace. * See also [XMLOutputFactory.IS_REPAIRING_NAMESPACES]. * - The XML declaration is not generated. * - The indent is empty. * - Polymorphic serialization is disabled. * * See [XML] for more details. */ public val DefaultXml: XML = XML { repairNamespaces = true xmlDeclMode = XmlDeclMode.None indentString = "" autoPolymorphic = false this.xmlDeclMode } /** * Registers the `application/xml` (or another specified [contentType]) content type * to the [ContentNegotiation] plugin using kotlinx.serialization. * * You can learn more from [Content negotiation and serialization](https://ktor.io/docs/serialization.html). * * @param format instance. [DefaultXml] is used by default * @param contentType to register with, `application/xml` by default */ public fun Configuration.xml( format: XML = DefaultXml, contentType: ContentType = ContentType.Application.Xml ) { serialization(contentType, format) }
apache-2.0
3566b136d11f4b51b3c46f8aa9619b47
30.847826
119
0.741297
4.08078
false
false
false
false
RayBa82/DVBViewerController
dvbViewerController/src/main/java/org/dvbviewer/controller/data/epg/ChannelEpgViewModel.kt
1
1396
package org.dvbviewer.controller.data.epg import android.util.Log import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.launch import org.dvbviewer.controller.data.entities.EpgEntry import java.util.* class ChannelEpgViewModel(private val repository: EPGRepository) : ViewModel() { private val data: MutableLiveData<List<EpgEntry>> = MutableLiveData() fun getChannelEPG(channel: Long, start: Date, end: Date, force: Boolean = false): MutableLiveData<List<EpgEntry>> { if (data.value == null || force) { fetchChannelEPG(channel, start, end) } return data } private fun fetchChannelEPG(channel: Long, start: Date, end: Date) { viewModelScope.launch(Dispatchers.Main, CoroutineStart.DEFAULT) { val groupList: MutableList<EpgEntry> = mutableListOf() async(Dispatchers.IO) { try { repository.getChannelEPG(channel, start, end)?.let { groupList.addAll(it) } } catch (e: Exception) { Log.e(javaClass.simpleName, "Error getting EPG Entry", e) } }.await() data.value = groupList } } }
apache-2.0
20e840a142b50eb73afa2184757bf63d
30.75
119
0.669771
4.607261
false
false
false
false
jimandreas/UIandOpenGLthreading
app/src/main/java/com/jimandreas/handlerstudy/uithread/MainActivity.kt
1
8267
/* * Copyright (C) 2011 The Android Open Source Project * Copyright (c) 2018 Jim Andreas * * 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.jimandreas.handlerstudy.uithread import android.app.Activity import android.content.Intent import android.graphics.Color import android.graphics.PorterDuff import android.net.Uri import android.os.Bundle import android.os.Handler import android.os.Looper import android.os.Message import android.support.design.widget.FloatingActionButton import android.support.design.widget.Snackbar import android.widget.SeekBar import com.jimandreas.handlerstudy.customview.SpeedometerGauge import com.jimandreas.handlerstudy.opengl.MyGLRenderer import com.jimandreas.handlerstudy.opengl.MyGLSurfaceView import com.jimandreas.handlerstudy.opengl.R import kotlinx.coroutines.experimental.android.HandlerContext import kotlinx.coroutines.experimental.android.UI import kotlinx.coroutines.experimental.launch import kotlinx.coroutines.experimental.runBlocking data class SliderColor(var red: Int = 0, var green: Int = 0, var blue: Int = 0) class MainActivity : Activity(), SeekBar.OnSeekBarChangeListener, Handler.Callback { private lateinit var sliderRed: SeekBar private lateinit var sliderGreen: SeekBar private lateinit var sliderBlue: SeekBar private lateinit var surfaceView: MyGLSurfaceView private lateinit var speedometer: SpeedometerGauge private lateinit var fab: FloatingActionButton private lateinit var renderer: MyGLRenderer private val sliderColor = SliderColor(50, 75, 50) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.main) sliderRed = findViewById(R.id.slider_red) sliderGreen = findViewById(R.id.slider_green) sliderBlue = findViewById(R.id.slider_blue) surfaceView = findViewById(R.id.surface_view) speedometer = findViewById(R.id.rpm_value) fab = findViewById(R.id.info_fab) val handler = Handler(Looper.getMainLooper(), this) /* * set up the OpenGL system */ // Request an OpenGL ES 2.0 compatible context. surfaceView.setEGLContextClientVersion(2) renderer = MyGLRenderer(surfaceView, handler) surfaceView.setRenderer(renderer) // http://stackoverflow.com/a/19265149/3853712 val sliderList = arrayListOf(sliderRed, sliderGreen, sliderBlue) val colorList = arrayListOf(-0x10000, -0x00ff0100, -0xffff01) sliderList.forEachIndexed { index, it -> it.progressDrawable.setColorFilter(colorList[index], PorterDuff.Mode.SRC_IN) it.thumb.setColorFilter(colorList[index], PorterDuff.Mode.SRC_IN) it.setOnSeekBarChangeListener(this) } /* * if this is a rotation (have old state), then don't init sliders - they are preserved */ // if (savedInstanceState == null) { // sliderRed.progress = 50 // sliderGreen.progress = 75 // greenish initially, better than grey! // sliderBlue.progress = 50 // } // set up the speedometer custom view initSpeedometer() sliderRed.progress = sliderColor.red sliderGreen.progress = sliderColor.green sliderBlue.progress = sliderColor.blue /* * FAB button (floating action button = FAB) to get more information * Vector to the website for more info */ fab.setOnClickListener { view -> val snackbar = Snackbar.make(view, "website", Snackbar.LENGTH_LONG) snackbar.setAction("View website") { val intent = Intent(Intent.ACTION_VIEW) intent.data = Uri.parse( "https://github.com/jimandreas/UIandOpenGLthreading") startActivity(intent) } snackbar.show() } } /** * SeekBar override methods - feed adjustments to the triangle color * by calling into the Renderer on the OpenGL thread * * @param seekBar The SeekBar whose progress has changed * @param progress how far we are - using default 0..100 * @param fromUser True if the progress change was initiated by the user. */ override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) { when { seekBar === sliderRed -> sliderColor.red = progress seekBar === sliderGreen -> sliderColor.green = progress else -> sliderColor.blue = progress } surfaceView.queueEvent { renderer.updateColor2(sliderColor) } } override fun onStartTrackingTouch(seekBar: SeekBar) { } override fun onStopTrackingTouch(seekBar: SeekBar) { } override fun onPause() { super.onPause() // The following call pauses the rendering thread. // If your OpenGL application is memory intensive, // you should consider de-allocating objects that // consume significant memory here. // mGLView.onPause(); } override fun onResume() { super.onResume() // The following call resumes a paused rendering thread. // If you de-allocated graphic objects for onPause() // this is a good place to re-allocate them. // mGLView.onResume(); } /* private fun resetSlider( @MyGLRenderer.RenderSetColor which_color: Int, progress: Int) { surfaceView.queueEvent { renderer.updateColor(which_color, progress) } }*/ private fun initSpeedometer() { // configure value range and ticks speedometer.maxSpeed = 300.0 speedometer.majorTickStep = 30.0 speedometer.minorTicks = 2 // Configure value range colors speedometer.addColoredRange(30.0, 140.0, Color.GREEN) speedometer.addColoredRange(140.0, 180.0, Color.YELLOW) speedometer.addColoredRange(180.0, 400.0, Color.RED) } /** * receive messages from the renderer * Currently: * GL_READY - the GL components are created - instance state can * now be set (like for device rotation) * UPDATE_RPM - RPM indicator - to be implemented * @param msg message sent from renderer * @return true */ override fun handleMessage(msg: Message): Boolean { when (msg.what) { UI_MESSAGE_GL_READY -> { renderer.updateColor2(sliderColor) } UI_MESSAGE_UPDATE_RPM -> { var rpm = msg.arg1 if (rpm < 0) { rpm *= -1 } speedometer.speed = rpm.toDouble() } } return true } fun signalingUIFunction() = runBlocking<Unit> { launch(UI) { // will get dispatched to ForkJoinPool.commonPool (or equivalent) println(" 'CommonPool': I'm working in thread ${Thread.currentThread().name}") } } fun signalingOpenGLFunction() = runBlocking<Unit> { val UI = HandlerContext(Handler(Looper.getMainLooper()), "UI") launch(UI) { // will get dispatched to ForkJoinPool.commonPool (or equivalent) println(" 'CommonPool': I'm working in thread ${Thread.currentThread().name}") } } companion object { /** * Handler messages * for more information on the IntDef in the Studio annotation library: * * https://noobcoderblog.wordpress.com/2015/04/12/java-enum-and-android-intdefstringdef-annotation/ */ const val UI_MESSAGE_GL_READY = 1 const val UI_MESSAGE_UPDATE_RPM = 2 } }
apache-2.0
6dc6ecb5b25cfe866e05092cd201d5ba
34.947826
107
0.652595
4.527382
false
false
false
false
airbnb/lottie-android
sample/src/main/kotlin/com/airbnb/lottie/samples/views/ListingCard.kt
1
1449
package com.airbnb.lottie.samples.views import android.content.Context import android.util.AttributeSet import android.widget.FrameLayout import com.airbnb.epoxy.CallbackProp import com.airbnb.epoxy.ModelProp import com.airbnb.epoxy.ModelView import com.airbnb.epoxy.OnViewRecycled import com.airbnb.lottie.samples.databinding.ListingCardBinding import com.airbnb.lottie.samples.utils.viewBinding @ModelView(autoLayout = ModelView.Size.MATCH_WIDTH_WRAP_HEIGHT) class ListingCard @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : FrameLayout(context, attrs, defStyleAttr) { private val binding: ListingCardBinding by viewBinding() @CallbackProp fun onToggled(listener: ((isWishListed: Boolean) -> Unit)?) { binding.wishListIcon.setOnClickListener(when (listener) { null -> null else -> { _ -> listener(binding.wishListIcon.progress == 0f) } }) } @ModelProp fun isWishListed(isWishListed: Boolean) { val targetProgress = if (isWishListed) 1f else 0f binding.wishListIcon.speed = if (isWishListed) 1f else -1f if (binding.wishListIcon.progress != targetProgress) { binding.wishListIcon.playAnimation() } } @OnViewRecycled fun onRecycled() { binding.wishListIcon.pauseAnimation() binding.wishListIcon.progress = 0f } }
apache-2.0
91ecbbb939a1f93c8020e23e8c506a6e
31.222222
66
0.700483
4.116477
false
false
false
false
MiniMineCraft/MiniBus
src/main/kotlin/me/camdenorrb/minibus/MiniBus.kt
1
2354
@file:Suppress("UNCHECKED_CAST") package me.camdenorrb.minibus import me.camdenorrb.minibus.event.EventWatcher import me.camdenorrb.minibus.listener.ListenerAction import me.camdenorrb.minibus.listener.ListenerAction.Lambda import me.camdenorrb.minibus.listener.ListenerPriority import me.camdenorrb.minibus.listener.ListenerPriority.NORMAL import me.camdenorrb.minibus.listener.MiniListener import me.camdenorrb.minibus.listener.table.ListenerTable import kotlin.reflect.KCallable import kotlin.reflect.KFunction import kotlin.reflect.full.declaredFunctions import kotlin.reflect.full.findAnnotation import kotlin.reflect.jvm.isAccessible // TODO: Use star projection more often class MiniBus { val listenerTable = ListenerTable() fun cleanUp() { listenerTable.map.clear() } inline operator fun <reified T : Any> invoke(event: T): T { listenerTable.call<T>(event) return event } fun unregister(callable: KCallable<*>) = listenerTable.remove(callable) fun unregister(action: ListenerAction<*>) = listenerTable.remove(action) fun unregister(lambda: Any.() -> Unit) = listenerTable.remove(lambda::invoke) fun unregister(listener: MiniListener) { listener::class.declaredFunctions.forEach { if (it.findAnnotation<EventWatcher>() == null) return@forEach unregister(it) } } fun register(vararg listeners: MiniListener) = listeners.forEach { register(it) } inline fun <reified T : Any> register(action: ListenerAction<T>, priority: ListenerPriority = NORMAL) = listenerTable.add(action, priority) inline fun <reified T : Any> register(priority: ListenerPriority = NORMAL, noinline block: Lambda<T>.(T) -> Unit) = listenerTable.add(priority, block) fun register(listener: MiniListener) = listener::class.declaredFunctions.forEach { //if (it.visibility != PUBLIC) return@forEach if (!it.isAccessible) it.isAccessible = true val priority = it.findAnnotation<EventWatcher>()?.priority ?: return@forEach //it.parameters[1]::type::returnType //val event = it.parameters[1].type.jvmErasure as? KClass<Any> ?: error("Unable to register event!") val event = it.parameters[1].type //println("${listener::class.simpleName} $it") listenerTable.add(event, listener, it as KFunction<Any>, priority) //println(listenerTable[event]?.joinToString { it.action.callable.toString() }) } }
apache-2.0
939f0b32b73996a796ddc0c448fc088e
26.705882
114
0.759558
3.8527
false
false
false
false
code-disaster/lwjgl3
modules/generator/src/main/kotlin/org/lwjgl/generator/ModifiersFunction.kt
4
8174
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package org.lwjgl.generator class DependsOn(override val reference: String, val postfix: String? = null) : FunctionModifier, ReferenceModifier { override val isSpecial = false } /** * Can be used to mark a function as optional. FunctionProviders should ignore such functions if they're missing. * This is useful for functions that have been added long after the initial release of a particular extension, or * as a workaround for buggy drivers. */ object IgnoreMissing : FunctionModifier { override val isSpecial = false } /** Defines an expression that should be passed to the getInstance() method. */ class Capabilities( /** The expression to pass to the getInstance() method. */ val expression: String, /** If true, getInstance() will not be called and the expression will be assigned to the FUNCTION_ADDRESS variable directly. */ val override: Boolean = false ) : FunctionModifier { override val isSpecial = true } enum class ApplyTo( private val alternative: Boolean?, private val array: Boolean? ) { NORMAL(false, null), ALTERNATIVE(true, null), ARRAY_ONLY(null, true), BOTH(null, null); fun filter(alternative: Boolean, arrays: Boolean): Boolean { if (this.alternative != null) { if (this.alternative != alternative) return false } if (this.array != null) { if (this.array != arrays) return false } return true } } class Code( val javaInit: List<Statement> = NO_STATEMENTS, val javaBeforeNative: List<Statement> = NO_STATEMENTS, val javaAfterNative: List<Statement> = NO_STATEMENTS, val javaFinally: List<Statement> = NO_STATEMENTS, val nativeBeforeCall: String? = null, val nativeCall: String? = null, val nativeAfterCall: String? = null ) : FunctionModifier { companion object { // Used to avoid null checks private val NO_STATEMENTS = ArrayList<Statement>(0) internal val NO_CODE = Code() } data class Statement( val code: String, val applyTo: ApplyTo = ApplyTo.BOTH ) override val isSpecial get() = NO_STATEMENTS !== javaInit || NO_STATEMENTS !== javaBeforeNative || NO_STATEMENTS !== javaAfterNative || NO_STATEMENTS !== javaFinally internal fun hasStatements(statements: List<Statement>, alternative: Boolean, arrays: Boolean) = if (statements === NO_STATEMENTS) false else statements.any { it.applyTo.filter(alternative, arrays) } internal fun getStatements(statements: List<Statement>, alternative: Boolean, arrays: Boolean) = if (statements === NO_STATEMENTS) statements else statements.filter { it.applyTo.filter(alternative, arrays) } private fun List<Statement>.append(other: List<Statement>) = if (this === NO_STATEMENTS && other === NO_STATEMENTS) NO_STATEMENTS else this + other private fun String?.append(other: String?) = when { this == null -> other other == null -> this else -> "$this\n$other" } internal fun append( javaInit: List<Statement> = NO_STATEMENTS, javaBeforeNative: List<Statement> = NO_STATEMENTS, javaAfterNative: List<Statement> = NO_STATEMENTS, javaFinally: List<Statement> = NO_STATEMENTS, nativeBeforeCall: String? = null, nativeCall: String? = null, nativeAfterCall: String? = null ) = Code( this.javaInit.append(javaInit), this.javaBeforeNative.append(javaBeforeNative), this.javaAfterNative.append(javaAfterNative), this.javaFinally.append(javaFinally), this.nativeBeforeCall.append(nativeBeforeCall), this.nativeCall.append(nativeCall), this.nativeAfterCall.append(nativeAfterCall) ) } val SaveErrno = Code(nativeAfterCall = "${t}saveErrno();") fun statement(code: String, applyTo: ApplyTo = ApplyTo.BOTH): List<Code.Statement> = arrayListOf(Code.Statement(code, applyTo)) /** Marks a function without arguments as a macro. */ class Macro internal constructor(val function: Boolean, val constant: Boolean, val expression: String? = null) : FunctionModifier { companion object { internal val CONSTANT = Macro(function = false, constant = true) internal val VARIABLE = Macro(function = false, constant = false) internal val FUNCTION = Macro(function = true, constant = false) } override val isSpecial = false override fun validate(func: Func) { require(!constant || func.parameters.isEmpty()) { "The constant macro modifier can only be applied to functions with no arguments." } } } val macro = Macro.CONSTANT fun macro(variable: Boolean = false) = if (variable) Macro.VARIABLE else Macro.FUNCTION fun macro(expression: String) = Macro(function = true, constant = false, expression = expression) class AccessModifier(val access: Access) : FunctionModifier { override val isSpecial = false } /** Makes the generated methods private. */ val private = AccessModifier(Access.PRIVATE) /** Makes the generated methods package private. */ val internal = AccessModifier(Access.INTERNAL) /** Overrides the native function name. This is useful for functions like Windows functions that have both a Unicode (W suffix) and ANSI version (A suffix). */ class NativeName(val nativeName: String) : FunctionModifier, StructMemberModifier { companion object { private val EXPRESSION_REGEX = "[ (]".toRegex() } internal val name get() = if (nativeName.contains(EXPRESSION_REGEX)) nativeName else "\"$nativeName\"" override val isSpecial = false } /** Marks reused functions. */ class Reuse(val source: NativeClass) : FunctionModifier { override val isSpecial = false } /** Disables creation of Java array overloads. */ object OffHeapOnly : FunctionModifier { override val isSpecial = false } /** Marks a return value as a pointer that should be mapped (wrapped in a buffer of some capacity). */ class MapPointer( /** An expression that defines the buffer capacity. */ val sizeExpression: String, /** If true, overloads with an old_buffer parameter will be generated. */ val oldBufferOverloads: Boolean = false // TODO: remove in LWJGL 4 ) : FunctionModifier { override val isSpecial = true override fun validate(func: Func) { require(func.returns.nativeType is PointerType<*>) { "The MapPointer modifier can only be applied to functions with pointer return types." } } } class Construct( val firstArg: String, // Makes the user specify at least one, else the modifier is pointless vararg val otherArgs: String ) : FunctionModifier { override val isSpecial = true override fun validate(func: Func) { require(func.returns.nativeType is WrappedPointerType) { "The Construct modifier can only be applied to functions with object return types." } } } /** Returns the address of the return value, instead of the return value itself. Implies Nonnull. */ object Address : FunctionModifier { override val isSpecial = false } /** Marks a pointer or Java instance return type as non-nullable. */ object Nonnull : FunctionModifier { override val isSpecial = false override fun validate(func: Func) { require(func.returns.nativeType is PointerType<*> || func.returns.nativeType is JObjectType) { "The Nonnull modifier can only be applied to functions with pointer or Java instance return types." } } } /** Forces a character sequence return type to be mapped to ByteBuffer instead of String, so that it can be disposed after use. */ object MustBeDisposed/*tentative name*/ : FunctionModifier { override val isSpecial = false override fun validate(func: Func) { require(func.returns.nativeType is CharSequenceType) { "The MustBeDisposed modifier can only be applied to functions with character sequence return types." } } }
bsd-3-clause
f4b0dff9c3b52aad53a00c1abbbe3481
35.172566
159
0.68412
4.516022
false
false
false
false
AshishKayastha/Movie-Guide
app/src/main/kotlin/com/ashish/movieguide/ui/season/SeasonDetailActivity.kt
1
4671
package com.ashish.movieguide.ui.season import android.content.Context import android.content.Intent import android.os.Bundle import android.view.View import android.view.ViewStub import com.ashish.movieguide.R import com.ashish.movieguide.data.models.Episode import com.ashish.movieguide.data.models.Season import com.ashish.movieguide.data.models.SeasonDetail import com.ashish.movieguide.di.modules.ActivityModule import com.ashish.movieguide.di.multibindings.activity.ActivityComponentBuilderHost import com.ashish.movieguide.ui.base.detail.fulldetail.FullDetailContentActivity import com.ashish.movieguide.ui.common.adapter.OnItemClickListener import com.ashish.movieguide.ui.common.adapter.RecyclerViewAdapter import com.ashish.movieguide.ui.episode.EpisodeDetailActivity import com.ashish.movieguide.utils.Constants.ADAPTER_TYPE_EPISODE import com.ashish.movieguide.utils.Constants.ADAPTER_TYPE_SEASON import com.ashish.movieguide.utils.Constants.TMDB_URL import com.ashish.movieguide.utils.extensions.bindView import com.ashish.movieguide.utils.extensions.getOriginalImageUrl import com.ashish.movieguide.utils.extensions.getPosterUrl import com.ashish.movieguide.utils.extensions.setTitleAndYear import icepick.State /** * Created by Ashish on Jan 07. */ class SeasonDetailActivity : FullDetailContentActivity<SeasonDetail, SeasonDetailView, SeasonDetailPresenter>(), SeasonDetailView { companion object { private const val EXTRA_SEASON = "season" private const val EXTRA_TV_SHOW_ID = "tv_show_id" @JvmStatic fun createIntent(context: Context, tvShowId: Long?, season: Season?): Intent { return Intent(context, SeasonDetailActivity::class.java) .putExtra(EXTRA_TV_SHOW_ID, tvShowId) .putExtra(EXTRA_SEASON, season) } } @JvmField @State var tvShowId: Long? = null @JvmField @State var season: Season? = null private val episodesViewStub: ViewStub by bindView(R.id.episodes_view_stub) private var episodesAdapter: RecyclerViewAdapter<Episode>? = null private val onEpisodeItemClickLitener = object : OnItemClickListener { override fun onItemClick(position: Int, view: View) { val episode = episodesAdapter?.getItem<Episode>(position) val intent = EpisodeDetailActivity.createIntent(this@SeasonDetailActivity, tvShowId, episode) startNewActivityWithTransition(view, R.string.transition_episode_image, intent) } } override fun injectDependencies(builderHost: ActivityComponentBuilderHost) { builderHost.getActivityComponentBuilder(SeasonDetailActivity::class.java, SeasonDetailComponent.Builder::class.java) .withModule(ActivityModule(this)) .build() .inject(this) } override fun getLayoutId() = R.layout.activity_detail_season override fun getIntentExtras(extras: Bundle?) { tvShowId = extras?.getLong(EXTRA_TV_SHOW_ID) season = extras?.getParcelable(EXTRA_SEASON) } override fun getTransitionNameId() = R.string.transition_season_poster override fun loadDetailContent() { presenter?.setSeasonNumber(season?.seasonNumber!!) presenter?.loadDetailContent(tvShowId) } override fun getBackdropPath() = season?.posterPath.getOriginalImageUrl() override fun getPosterPath() = season?.posterPath.getPosterUrl() override fun showDetailContent(detailContent: SeasonDetail) { detailContent.apply { titleText.setTitleAndYear(name, airDate) imdbId = detailContent.externalIds?.imdbId } super.showDetailContent(detailContent) } override fun getItemTitle(): String { val seasonNumber = season?.seasonNumber ?: 0 return if (seasonNumber > 0) { String.format(getString(R.string.season_number_format), seasonNumber) } else { return getString(R.string.season_specials) } } override fun getDetailContentType() = ADAPTER_TYPE_SEASON override fun showEpisodeList(episodeList: List<Episode>) { episodesAdapter = RecyclerViewAdapter(R.layout.list_item_content_alt, ADAPTER_TYPE_EPISODE, onEpisodeItemClickLitener) inflateViewStubRecyclerView(episodesViewStub, R.id.episodes_recycler_view, episodesAdapter!!, episodeList) } override fun getShareText(): CharSequence { return TMDB_URL + "tv/" + tvShowId + "season/" + season!!.seasonNumber } override fun performCleanup() { episodesAdapter?.removeListener() super.performCleanup() } }
apache-2.0
5a2bd9f721548840e3f8f25fa1028011
37.933333
114
0.726183
4.583906
false
false
false
false
iSoron/uhabits
uhabits-core-legacy/src/test/common/org/isoron/uhabits/components/CalendarChartTest.kt
1
1886
/* * Copyright (C) 2016-2019 Álinson Santos Xavier <[email protected]> * * This file is part of Loop Habit Tracker. * * Loop Habit Tracker 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. * * Loop Habit Tracker is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.isoron.uhabits.components import org.isoron.* import org.isoron.platform.time.* import org.isoron.uhabits.* import kotlin.test.* class CalendarChartTest : BaseViewTest() { val base = "components/CalendarChart" @Test fun testDraw() = asyncTest { val fmt = DependencyResolver.getDateFormatter(Locale.US) val component = CalendarChart(LocalDate(2015, 1, 25), theme.color(4), theme, fmt) component.series = listOf(1.0, // today 0.2, 0.5, 0.7, 0.0, 0.3, 0.4, 0.6, 0.6, 0.0, 0.3, 0.6, 0.5, 0.8, 0.0, 0.0, 0.0, 0.0, 0.6, 0.5, 0.7, 0.7, 0.5, 0.5, 0.8, 0.9, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.5, 0.2) assertRenders(400, 200, "$base/base.png", component) component.scrollPosition = 2 assertRenders(400, 200, "$base/scroll.png", component) } }
gpl-3.0
5fbd491e1bc8e73eb03f3847f4ccee14
38.291667
78
0.578249
3.75498
false
true
false
false
McMoonLakeDev/MoonLake
Core/src/main/kotlin/com/mcmoonlake/impl/depend/DependWorldEditImpl.kt
1
3414
/* * Copyright (C) 2016-Present The MoonLake ([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.mcmoonlake.impl.depend import com.mcmoonlake.api.depend.DependPluginAbstract import com.mcmoonlake.api.depend.DependWorldEdit import com.mcmoonlake.api.getPlugin import com.mcmoonlake.api.region.* import com.sk89q.worldedit.BlockVector2D import com.sk89q.worldedit.Vector import com.sk89q.worldedit.Vector2D import com.sk89q.worldedit.bukkit.WorldEditPlugin import com.sk89q.worldedit.bukkit.selections.CuboidSelection import com.sk89q.worldedit.bukkit.selections.CylinderSelection import com.sk89q.worldedit.bukkit.selections.Selection import com.sk89q.worldedit.regions.selector.CuboidRegionSelector import com.sk89q.worldedit.regions.selector.CylinderRegionSelector import org.bukkit.entity.Player class DependWorldEditImpl : DependPluginAbstract<WorldEditPlugin>(getPlugin(DependWorldEdit.NAME)), DependWorldEdit { private fun Vector.toRegionVectorBlock(): RegionVectorBlock = RegionVectorBlock(x, y, z) private fun Vector.toRegionVector2D(): RegionVector2D = RegionVector2D(x, z) private fun Vector2D.toRegionVector2D(): RegionVector2D = RegionVector2D(x, z) private fun RegionVector.toVector(): Vector = Vector(x, y, z) private fun RegionVector.toVector2D(): BlockVector2D = BlockVector2D(x, z) override fun getSelection(player: Player): Region? { val selection = plugin.getSelection(player) ?: return null val world = selection.world ?: return null return when(selection) { is CuboidSelection -> { val region0 = (selection.regionSelector as CuboidRegionSelector).incompleteRegion RegionCuboid(world, region0.pos1.toRegionVectorBlock(), region0.pos2.toRegionVectorBlock()) } is CylinderSelection -> { val region0 = (selection.regionSelector as CylinderRegionSelector).incompleteRegion RegionCylinder(world, region0.center.toRegionVector2D(), region0.radius.toRegionVector2D(), region0.minimumY, region0.maximumY) } else -> null } } override fun setSelection(player: Player, region: Region) { val world = region.world val selection: Selection = when(region) { is RegionCuboid -> CuboidSelection(world, region.pos1.toVector(), region.pos2.toVector()) is RegionCylinder -> CylinderSelection(world, region.center.toVector2D(), region.center.toVector2D(), region.minimumY, region.maximumY) else -> throw IllegalArgumentException("不支持的区域类型, WorldEdit 仅支持矩形和圆柱.") } plugin.setSelection(player, selection) } }
gpl-3.0
032717baa4370cc7267b07e2b4086d33
44.093333
147
0.722649
3.941725
false
false
false
false
dahlstrom-g/intellij-community
plugins/evaluation-plugin/core/src/com/intellij/cce/workspace/Config.kt
4
6052
package com.intellij.cce.workspace import com.intellij.cce.actions.* import com.intellij.cce.filter.EvaluationFilter import com.intellij.cce.workspace.filter.CompareSessionsFilter import com.intellij.cce.workspace.filter.NamedFilter import com.intellij.cce.workspace.filter.SessionsFilter import java.nio.file.Paths data class Config internal constructor( val projectPath: String, val language: String, val outputDir: String, val actions: ActionsGeneration, val interpret: ActionsInterpretation, val reorder: ReorderElements, val reports: ReportGeneration ) { companion object { fun build(projectPath: String, language: String, init: Builder.() -> Unit): Config { val builder = Builder(projectPath, language) builder.init() return builder.build() } fun buildFromConfig(config: Config, update: Builder.() -> Unit): Config { val builder = Builder(config) builder.update() return builder.build() } } data class ActionsGeneration internal constructor( val evaluationRoots: List<String>, val strategy: CompletionStrategy) data class ActionsInterpretation internal constructor( val completionType: CompletionType, val experimentGroup: Int?, val sessionsLimit: Int?, val completeTokenProbability: Double, val completeTokenSeed: Long?, val emulationSettings: UserEmulator.Settings?, val codeGolfSettings: CodeGolfEmulation.Settings?, val saveLogs: Boolean, val saveFeatures: Boolean, val saveContent: Boolean, val logLocationAndItemText: Boolean, val trainTestSplit: Int) data class ReorderElements internal constructor( val useReordering: Boolean, val title: String, val features: List<String> ) data class ReportGeneration internal constructor( val evaluationTitle: String, val sessionsFilters: List<SessionsFilter>, val comparisonFilters: List<CompareSessionsFilter>) class Builder internal constructor(private val projectPath: String, private val language: String) { var evaluationRoots = mutableListOf<String>() var outputDir: String = Paths.get(projectPath, "completion-evaluation").toAbsolutePath().toString() var saveLogs = false var saveFeatures = true var saveContent = false var logLocationAndItemText = false var trainTestSplit: Int = 70 var completionType: CompletionType = CompletionType.BASIC var evaluationTitle: String = completionType.name var prefixStrategy: CompletionPrefix = CompletionPrefix.NoPrefix var contextStrategy: CompletionContext = CompletionContext.ALL var experimentGroup: Int? = null var sessionsLimit: Int? = null var emulateUser: Boolean = false var codeGolf: Boolean = false var emulationSettings: UserEmulator.Settings? = null var codeGolfSettings: CodeGolfEmulation.Settings? = null var completeTokenProbability: Double = 1.0 var completeTokenSeed: Long? = null var useReordering: Boolean = false var reorderingTitle: String = evaluationTitle var featuresForReordering = mutableListOf<String>() val filters: MutableMap<String, EvaluationFilter> = mutableMapOf() private val sessionsFilters: MutableList<SessionsFilter> = mutableListOf() private val comparisonFilters: MutableList<CompareSessionsFilter> = mutableListOf() constructor(config: Config) : this(config.projectPath, config.language) { outputDir = config.outputDir evaluationRoots.addAll(config.actions.evaluationRoots) prefixStrategy = config.actions.strategy.prefix contextStrategy = config.actions.strategy.context emulateUser = config.actions.strategy.emulateUser filters.putAll(config.actions.strategy.filters) saveLogs = config.interpret.saveLogs saveFeatures = config.interpret.saveFeatures saveContent = config.interpret.saveContent logLocationAndItemText = config.interpret.logLocationAndItemText trainTestSplit = config.interpret.trainTestSplit completionType = config.interpret.completionType experimentGroup = config.interpret.experimentGroup sessionsLimit = config.interpret.sessionsLimit emulationSettings = config.interpret.emulationSettings completeTokenProbability = config.interpret.completeTokenProbability completeTokenSeed = config.interpret.completeTokenSeed useReordering = config.reorder.useReordering reorderingTitle = config.reorder.title featuresForReordering.addAll(config.reorder.features) evaluationTitle = config.reports.evaluationTitle mergeFilters(config.reports.sessionsFilters) mergeComparisonFilters(config.reports.comparisonFilters) } fun mergeFilters(filters: List<SessionsFilter>) = merge(filters, sessionsFilters as MutableList<NamedFilter>) fun mergeComparisonFilters(filters: List<CompareSessionsFilter>) = merge(filters, comparisonFilters as MutableList<NamedFilter>) private fun merge(filters: List<NamedFilter>, existedFilters: MutableList<NamedFilter>) { for (filter in filters) { if (existedFilters.all { it.name != filter.name }) existedFilters.add(filter) else println("More than one filter has name ${filter.name}") } } fun build(): Config = Config( projectPath, language, outputDir, ActionsGeneration( evaluationRoots, CompletionStrategy(prefixStrategy, contextStrategy, emulateUser, codeGolf, filters) ), ActionsInterpretation( completionType, experimentGroup, sessionsLimit, completeTokenProbability, completeTokenSeed, emulationSettings, codeGolfSettings, saveLogs, saveFeatures, saveContent, logLocationAndItemText, trainTestSplit ), ReorderElements( useReordering, reorderingTitle, featuresForReordering ), ReportGeneration( evaluationTitle, sessionsFilters, comparisonFilters ) ) } }
apache-2.0
fe8434748f5e23e04883c7c35229106e
36.590062
132
0.732981
4.845476
false
true
false
false
dahlstrom-g/intellij-community
plugins/devkit/devkit-core/src/inspections/RegistryPropertiesAnnotator.kt
4
5941
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.idea.devkit.inspections import com.intellij.codeInsight.intention.IntentionAction import com.intellij.lang.annotation.AnnotationHolder import com.intellij.lang.annotation.Annotator import com.intellij.lang.annotation.HighlightSeverity import com.intellij.lang.properties.psi.PropertiesFile import com.intellij.lang.properties.psi.impl.PropertyImpl import com.intellij.lang.properties.psi.impl.PropertyKeyImpl import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.util.IncorrectOperationException import com.intellij.util.PsiNavigateUtil import org.jetbrains.annotations.Nls import org.jetbrains.annotations.NonNls import org.jetbrains.idea.devkit.DevKitBundle import org.jetbrains.idea.devkit.util.PsiUtil /** * Highlights key in `registry.properties` without matching `key.description` entry + corresponding quickfix. */ class RegistryPropertiesAnnotator : Annotator { override fun annotate(element: PsiElement, holder: AnnotationHolder) { if (element !is PropertyKeyImpl) return val file = holder.currentAnnotationSession.file if (!isRegistryPropertiesFile(file)) { return } val propertyName = element.text if (isImplicitUsageKey(propertyName)) { return } val groupName = propertyName.substringBefore('.').toLowerCase() if (PLUGIN_GROUP_NAMES.contains(groupName) || propertyName.startsWith("editor.config.")) { holder.newAnnotation(HighlightSeverity.ERROR, DevKitBundle.message("registry.properties.annotator.plugin.keys.use.ep")) .withFix(ShowEPDeclarationIntention(propertyName)).create() } val propertiesFile = file as PropertiesFile val descriptionProperty = propertiesFile.findPropertyByKey(propertyName + DESCRIPTION_SUFFIX) if (descriptionProperty == null) { holder.newAnnotation(HighlightSeverity.WARNING, DevKitBundle.message("registry.properties.annotator.key.no.description.key", propertyName)) .withFix(AddDescriptionKeyIntention(propertyName)).create() } } private class ShowEPDeclarationIntention(private val propertyName: String) : IntentionAction { override fun startInWriteAction(): Boolean = false override fun getFamilyName(): String = DevKitBundle.message("registry.properties.annotator.show.ep.family.name") override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?): Boolean = true override fun getText(): String = DevKitBundle.message("registry.properties.annotator.show.ep.name", propertyName) override fun invoke(project: Project, editor: Editor?, file: PsiFile?) { val propertiesFile = file as PropertiesFile val defaultValue = propertiesFile.findPropertyByKey(propertyName)!!.value val description = propertiesFile.findPropertyByKey(propertyName + DESCRIPTION_SUFFIX)?.value @NonNls var restartRequiredText = "" if (propertiesFile.findPropertyByKey(propertyName + RESTART_REQUIRED_SUFFIX) != null) { restartRequiredText = "restartRequired=\"true\"" } val epText = """ <registryKey key="${propertyName}" defaultValue="${defaultValue}" ${restartRequiredText} description="${description}"/> """.trimIndent() Messages.showMultilineInputDialog(project, DevKitBundle.message("registry.properties.annotator.show.ep.message"), DevKitBundle.message("registry.properties.annotator.show.ep.title"), epText, null, null) } } private class AddDescriptionKeyIntention(private val myPropertyName: String) : IntentionAction { @Nls override fun getText(): String = DevKitBundle.message("registry.properties.annotator.add.description.text", myPropertyName) @Nls override fun getFamilyName(): String = DevKitBundle.message("registry.properties.annotator.add.description.family.name") override fun isAvailable(project: Project, editor: Editor, file: PsiFile): Boolean = true @Throws(IncorrectOperationException::class) override fun invoke(project: Project, editor: Editor, file: PsiFile) { val propertiesFile = file as PropertiesFile val originalProperty = propertiesFile.findPropertyByKey(myPropertyName) as PropertyImpl? val descriptionProperty = propertiesFile.addPropertyAfter(myPropertyName + DESCRIPTION_SUFFIX, "Description", originalProperty) val valueNode = (descriptionProperty.psiElement as PropertyImpl).valueNode!! PsiNavigateUtil.navigate(valueNode.psi) } override fun startInWriteAction(): Boolean = true } companion object { @NonNls private val PLUGIN_GROUP_NAMES = setOf( "appcode", "cidr", "clion", "cvs", "git", "github", "svn", "hg4idea", "tfs", "dart", "markdown", "java", "javac", "uast", "junit4", "dsm", "js", "javascript", "typescript", "nodejs", "eslint", "jest", "ruby", "rubymine", "groovy", "grails", "python", "php", "kotlin" ) @NonNls private const val REGISTRY_PROPERTIES_FILENAME = "registry.properties" @NonNls const val DESCRIPTION_SUFFIX = ".description" @NonNls const val RESTART_REQUIRED_SUFFIX = ".restartRequired" @JvmStatic fun isImplicitUsageKey(keyName: String): Boolean = StringUtil.endsWith(keyName, DESCRIPTION_SUFFIX) || StringUtil.endsWith(keyName, RESTART_REQUIRED_SUFFIX) @JvmStatic fun isRegistryPropertiesFile(psiFile: PsiFile): Boolean = PsiUtil.isIdeaProject(psiFile.project) && psiFile.name == REGISTRY_PROPERTIES_FILENAME } }
apache-2.0
8dff43b64b8e7ee28cc3effb5228cb86
41.141844
133
0.727655
4.791129
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/gradle/gradle-tooling/src/org/jetbrains/kotlin/idea/gradleTooling/arguments/CompilerArgumentsCacheHolder.kt
5
2130
// 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.gradleTooling.arguments import org.jetbrains.kotlin.idea.projectModel.CacheOriginIdentifierAware import org.jetbrains.kotlin.idea.projectModel.CompilerArgumentsCacheAware import java.io.Serializable import java.util.* class CompilerArgumentsCacheHolder : Serializable { private val cacheAwareWithMergeByIdentifier: HashMap<Long, CompilerArgumentsCacheAwareWithMerge> = hashMapOf() fun getCacheAware(originIdentifier: Long): CompilerArgumentsCacheAware? = cacheAwareWithMergeByIdentifier[originIdentifier] fun mergeCacheAware(cacheAware: CompilerArgumentsCacheAware) { val cacheAwareWithMerge = cacheAwareWithMergeByIdentifier.getOrPut(cacheAware.cacheOriginIdentifier) { CompilerArgumentsCacheAwareWithMerge(cacheAware.cacheOriginIdentifier) } cacheAwareWithMerge.mergeCacheAware(cacheAware) } companion object { private class CompilerArgumentsCacheAwareWithMerge(override val cacheOriginIdentifier: Long) : AbstractCompilerArgumentsCacheAware() { override val cacheByValueMap: HashMap<Int, String> = hashMapOf() fun mergeCacheAware(cacheAware: CompilerArgumentsCacheAware) { val cacheAwareMap = cacheAware.distributeCacheIds().associateWith { cacheAware.getCached(it)!! } check(cacheByValueMap.keys.intersect(cacheAwareMap.keys).all { cacheByValueMap[it] == cacheAwareMap[it] }) { "Compiler arguments caching failure! Trying to merge cache with existing ID but different value!" } val cacheAwareMapReversed = cacheAwareMap.entries.associate { it.value to it.key } check(cacheAwareMap.size == cacheAwareMapReversed.size) { "Compiler arguments caching failure! Cache with non unique cached values detected!" } cacheByValueMap.putAll(cacheAwareMap) } } } }
apache-2.0
614f7d050a7d78a39bda6bf0bb8c6f86
53.615385
158
0.730047
5.461538
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/JavaMapForEachInspection.kt
1
2931
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.CleanupLocalInspectionTool import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import org.jetbrains.kotlin.builtins.DefaultBuiltIns import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.core.getLastLambdaExpression import org.jetbrains.kotlin.idea.inspections.collections.isMap import org.jetbrains.kotlin.idea.util.textRangeIn import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.psi.KtLambdaExpression import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.synthetic.isResolvedWithSamConversions class JavaMapForEachInspection : AbstractApplicabilityBasedInspection<KtCallExpression>( KtCallExpression::class.java ), CleanupLocalInspectionTool { override fun isApplicable(element: KtCallExpression): Boolean { val calleeExpression = element.calleeExpression ?: return false if (calleeExpression.text != "forEach") return false if (element.valueArguments.size != 1) return false val lambda = element.lambda() ?: return false val lambdaParameters = lambda.valueParameters if (lambdaParameters.size != 2 || lambdaParameters.any { it.destructuringDeclaration != null }) return false val context = element.analyze(BodyResolveMode.PARTIAL) val resolvedCall = element.getResolvedCall(context) ?: return false return resolvedCall.dispatchReceiver?.type?.isMap(DefaultBuiltIns.Instance) == true && resolvedCall.isResolvedWithSamConversions() } override fun inspectionHighlightRangeInElement(element: KtCallExpression): TextRange? = element.calleeExpression?.textRangeIn(element) override fun inspectionText(element: KtCallExpression) = KotlinBundle.message("java.map.foreach.method.call.should.be.replaced.with.kotlin.s.foreach") override val defaultFixText get() = KotlinBundle.message("replace.with.kotlin.s.foreach") override fun applyTo(element: KtCallExpression, project: Project, editor: Editor?) { val lambda = element.lambda() ?: return val valueParameters = lambda.valueParameters lambda.functionLiteral.valueParameterList?.replace( KtPsiFactory(element).createLambdaParameterList("(${valueParameters[0].text}, ${valueParameters[1].text})") ) } private fun KtCallExpression.lambda(): KtLambdaExpression? { return lambdaArguments.singleOrNull()?.getArgumentExpression() as? KtLambdaExpression ?: getLastLambdaExpression() } }
apache-2.0
47e51b44d7f09f83888699bd569dc8ea
50.421053
138
0.781644
5.062176
false
false
false
false
laviua/komock
komock-core/src/main/kotlin/ua/com/lavi/komock/registrar/proxy/YamlRouteWriter.kt
1
1119
package ua.com.lavi.komock.registrar.proxy import com.google.gson.Gson import ua.com.lavi.komock.model.config.http.RouteProperties import java.io.File class YamlRouteWriter { private val gson = Gson() fun write(routeMap: Map<String, MutableMap<String, RouteProperties>>, targetFile: File) { //check that possible to write targetFile.writeText("") val routes: List<RouteProperties> = routeMap.flatMap { it.value.values } for (route in routes) { val url = "url: ${route.url}" val headers = "responseHeaders: ${gson.toJson(route.responseHeaders)}" val httpMethod = "httpMethod: ${route.httpMethod}" val httpCode = "code: ${route.code}" val responseBody = "responseBody: ${route.responseBody.replace("\n", "")}" val template = "-\r\n" + " $httpMethod \r\n" + " $url \r\n" + " $headers \r\n" + " $httpCode \r\n" + " $responseBody \r\n" targetFile.appendText(template) } } }
apache-2.0
c6193d7923c8a2f0309cf749f2de89f7
30.111111
93
0.559428
4.098901
false
false
false
false
JuliaSoboleva/SmartReceiptsLibrary
app/src/test/java/co/smartreceipts/android/versioning/AppVersionManagerTest.kt
2
4653
package co.smartreceipts.android.versioning import android.content.Context import android.content.pm.PackageInfo import android.content.pm.PackageManager import android.os.Build import androidx.test.core.app.ApplicationProvider import co.smartreceipts.android.settings.UserPreferenceManager import co.smartreceipts.android.settings.catalog.UserPreference import com.nhaarman.mockitokotlin2.* import io.reactivex.Observable import io.reactivex.schedulers.Schedulers import org.junit.Before import org.junit.Ignore import org.junit.Test import org.junit.runner.RunWith import org.mockito.ArgumentMatchers.anyString import org.mockito.Mock import org.mockito.MockitoAnnotations import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config import java.util.* @RunWith(RobolectricTestRunner::class) class AppVersionManagerTest { companion object { private const val OLD_VERSION = 1 } private lateinit var appVersionManager: AppVersionManager @Mock private lateinit var context: Context @Mock private lateinit var packageManager: PackageManager @Mock private lateinit var userPreferenceManager: UserPreferenceManager @Mock private lateinit var appVersionUpgradesList: AppVersionUpgradesList @Mock private lateinit var versionUpgradedListener1: VersionUpgradedListener @Mock private lateinit var versionUpgradedListener2: VersionUpgradedListener private val packageInfo = PackageInfo() @Before fun setUp() { MockitoAnnotations.initMocks(this) whenever(userPreferenceManager.getObservable(UserPreference.Internal.ApplicationVersionCode)).thenReturn(Observable.just(OLD_VERSION)) whenever(context.packageManager).thenReturn(packageManager) whenever(context.packageName).thenReturn(ApplicationProvider.getApplicationContext<Context>().packageName) whenever(packageManager.getPackageInfo(anyString(), any())).thenReturn(packageInfo) whenever(appVersionUpgradesList.getUpgradeListeners()).thenReturn(Arrays.asList(versionUpgradedListener1, versionUpgradedListener2)) appVersionManager = AppVersionManager(context, userPreferenceManager, appVersionUpgradesList, Schedulers.trampoline()) } @Test fun onLaunchWithNewVersionThatIsTheSameAsTheOld() { val newVersion = OLD_VERSION packageInfo.versionCode = newVersion appVersionManager.onLaunch() verifyZeroInteractions(versionUpgradedListener1, versionUpgradedListener2) verify(userPreferenceManager, never())[UserPreference.Internal.ApplicationVersionCode] = newVersion } @Test fun onLaunchWithNewVersionThatIsAboveTheOld() { val newVersion = OLD_VERSION + 1 packageInfo.versionCode = newVersion appVersionManager.onLaunch() verify(versionUpgradedListener1).onVersionUpgrade(OLD_VERSION, newVersion) verify(versionUpgradedListener2).onVersionUpgrade(OLD_VERSION, newVersion) verify(userPreferenceManager)[UserPreference.Internal.ApplicationVersionCode] = newVersion } @Test @Config(sdk = [Build.VERSION_CODES.P]) @Ignore("Ignoring until we upgrade to Robolectric 4.x") fun onLaunchWithNewVersionThatIsTheSameAsTheOldUsingSdk28() { val newVersion = OLD_VERSION packageInfo.longVersionCode = newVersion.toLong() appVersionManager.onLaunch() verifyZeroInteractions(versionUpgradedListener1, versionUpgradedListener2) verify(userPreferenceManager, never())[UserPreference.Internal.ApplicationVersionCode] = newVersion } @Test @Config(sdk = [Build.VERSION_CODES.P]) @Ignore("Ignoring until we upgrade to Robolectric 4.x") fun onLaunchWithNewVersionThatIsAboveTheOldUsingSdk28() { val newVersion = OLD_VERSION + 1 packageInfo.longVersionCode = newVersion.toLong() appVersionManager.onLaunch() verify(versionUpgradedListener1).onVersionUpgrade(OLD_VERSION, newVersion) verify(versionUpgradedListener2).onVersionUpgrade(OLD_VERSION, newVersion) verify(userPreferenceManager)[UserPreference.Internal.ApplicationVersionCode] = newVersion } @Test fun onLaunchWithNewVersionThatThrowsException() { val newVersion = OLD_VERSION whenever(packageManager.getPackageInfo(anyString(), any())).thenThrow(PackageManager.NameNotFoundException("test")) appVersionManager.onLaunch() verifyZeroInteractions(versionUpgradedListener1, versionUpgradedListener2) verify(userPreferenceManager, never())[UserPreference.Internal.ApplicationVersionCode] = newVersion } }
agpl-3.0
e7b255cd30dbf4faa28e70911f1b9bd7
37.46281
142
0.773909
5.09081
false
true
false
false
flesire/ontrack
ontrack-model/src/main/java/net/nemerosa/ontrack/model/structure/AbstractValidationDataType.kt
1
1008
package net.nemerosa.ontrack.model.structure import net.nemerosa.ontrack.model.exceptions.ValidationRunDataInputException import net.nemerosa.ontrack.model.extension.ExtensionFeature abstract class AbstractValidationDataType<C, T>( private val extensionFeature: ExtensionFeature ) : ValidationDataType<C, T> { override fun getFeature() = extensionFeature protected fun validateNotNull(data: T?): T { if (data == null) { throw ValidationRunDataInputException("Data must not be null") } else { return data } } protected fun validateNotNull(data: T?, validation: T.() -> Unit): T { if (data == null) { throw ValidationRunDataInputException("Data must not be null") } else { validation(data) return data } } protected fun validate(check: Boolean, message: String) { if (!check) { throw ValidationRunDataInputException(message) } } }
mit
27b5e1b655478dc403eabd49b094b610
27.8
76
0.641865
4.777251
false
false
false
false
DemonWav/MinecraftDevIntelliJ
src/main/kotlin/com/demonwav/mcdev/platform/bukkit/PaperModuleType.kt
1
1561
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2020 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.bukkit import com.demonwav.mcdev.asset.PlatformAssets import com.demonwav.mcdev.facet.MinecraftFacet import com.demonwav.mcdev.platform.AbstractModuleType import com.demonwav.mcdev.platform.PlatformType import com.demonwav.mcdev.platform.bukkit.generation.BukkitEventGenerationPanel import com.demonwav.mcdev.platform.bukkit.util.BukkitConstants import com.demonwav.mcdev.platform.bungeecord.util.BungeeCordConstants import com.demonwav.mcdev.util.CommonColors import com.intellij.psi.PsiClass object PaperModuleType : AbstractModuleType<BukkitModule<PaperModuleType>>("com.destroystokyo.paper", "paper-api") { private const val ID = "PAPER_MODULE_TYPE" init { CommonColors.applyStandardColors(colorMap, BukkitConstants.CHAT_COLOR_CLASS) CommonColors.applyStandardColors(colorMap, BungeeCordConstants.CHAT_COLOR_CLASS) } override val platformType = PlatformType.PAPER override val icon = PlatformAssets.PAPER_ICON override val id = ID override val ignoredAnnotations = BukkitModuleType.IGNORED_ANNOTATIONS override val listenerAnnotations = BukkitModuleType.LISTENER_ANNOTATIONS override val isEventGenAvailable = true override fun generateModule(facet: MinecraftFacet): BukkitModule<PaperModuleType> = BukkitModule(facet, this) override fun getEventGenerationPanel(chosenClass: PsiClass) = BukkitEventGenerationPanel(chosenClass) }
mit
a5fc560c12cc46d392207dc4821e6cdf
37.073171
116
0.80205
4.397183
false
false
false
false
DemonWav/MinecraftDevIntelliJ
src/main/kotlin/com/demonwav/mcdev/platform/mcp/gradle/datahandler/McpModelFG3Handler.kt
1
3183
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2020 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mcp.gradle.datahandler import com.demonwav.mcdev.buildsystem.gradle.runGradleTask import com.demonwav.mcdev.platform.mcp.McpModuleSettings import com.demonwav.mcdev.platform.mcp.gradle.McpModelData import com.demonwav.mcdev.platform.mcp.gradle.tooling.McpModelFG3 import com.demonwav.mcdev.platform.mcp.srg.SrgType import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.externalSystem.model.project.ModuleData import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.ProjectManager import org.gradle.tooling.model.idea.IdeaModule import org.jetbrains.plugins.gradle.service.project.ProjectResolverContext object McpModelFG3Handler : McpModelDataHandler { override fun build( gradleModule: IdeaModule, module: ModuleData, resolverCtx: ProjectResolverContext ): McpModelData? { val data = resolverCtx.getExtraProject(gradleModule, McpModelFG3::class.java) ?: return null var version: String? = null for (minecraftDepVersion in data.minecraftDepVersions) { val index = minecraftDepVersion.indexOf('-') if (index == -1) { continue } version = minecraftDepVersion.substring(0, minecraftDepVersion.indexOf('-')) break } val state = McpModuleSettings.State( version, data.mcpVersion, data.taskOutputLocation.absolutePath, SrgType.TSRG ) ApplicationManager.getApplication().executeOnPooledThread { // Wait until indexing is done, to try and not interfere with current gradle process for (openProject in ProjectManager.getInstance().openProjects) { DumbService.getInstance(openProject).waitForSmartMode() } val project = ProjectManager.getInstance().openProjects.firstOrNull { it.name == gradleModule.project.name } var gradleProject = gradleModule.gradleProject val task = StringBuilder(data.taskName) if (gradleProject.parent != null) { task.insert(0, ':') } while (gradleProject.parent != null) { gradleProject = gradleProject.parent task.insert(0, gradleProject.name) task.insert(0, ':') } ProgressManager.getInstance().run(object : Task.Backgroundable(project, "Generating SRG map", false) { override fun run(indicator: ProgressIndicator) { indicator.isIndeterminate = true runGradleTask(project, gradleProject.projectDirectory, indicator) { launcher -> launcher.forTasks(data.taskName) } } }) } return McpModelData(module, state) } }
mit
7341d5231f80a19734038eda1067f4ed
36.892857
120
0.662897
4.965679
false
false
false
false
Jire/Overwatcheat
src/main/kotlin/org/jire/overwatcheat/overlay/transparency/AccentPolicy.kt
1
1331
/* * Free, open-source undetected color cheat for Overwatch! * Copyright (C) 2017 Thomas G. Nappo * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.jire.overwatcheat.overlay.transparency import com.sun.jna.Structure @Structure.FieldOrder(value = ["AccentState", "AccentFlags", "GradientColor", "AnimationId"]) class AccentPolicy : Structure(), Structure.ByReference { @JvmField internal var AccentState: Int = 0 var accentState get() = AccentStates[AccentState] set(value) { AccentState = value.ordinal } @JvmField var AccentFlags: Int = 0 @JvmField var GradientColor: Int = 0 @JvmField var AnimationId: Int = 0 }
agpl-3.0
c3518b8a84f586f01cbb02ab06ff290c
30.714286
93
0.710744
4.082822
false
false
false
false
auricgoldfinger/Memento-Namedays
android_mobile/src/main/java/com/alexstyl/specialdates/ui/base/MementoActivity.kt
3
2337
package com.alexstyl.specialdates.ui.base import android.app.Activity import android.content.Context import android.content.Intent import android.os.Bundle import android.support.v4.app.NavUtils import android.support.v4.app.TaskStackBuilder import android.support.v7.app.AppCompatActivity import android.view.KeyEvent import android.view.MenuItem import com.alexstyl.android.Version open class MementoActivity : AppCompatActivity() { private fun shouldUseHomeAsUp(): Boolean = parentActivityIntent != null override fun onPostCreate(savedInstanceState: Bundle?) { super.onPostCreate(savedInstanceState) if (shouldUseHomeAsUp()) { val bar = supportActionBar if (bar != null) { bar.setHomeButtonEnabled(true) bar.setDisplayHomeAsUpEnabled(true) } } } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { navigateUpToParent() return true } return super.onOptionsItemSelected(item) } fun navigateUpToParent() { val upIntent = NavUtils.getParentActivityIntent(this) ?: return if (NavUtils.shouldUpRecreateTask(this, upIntent) || isTaskRoot) { TaskStackBuilder.create(this) .addNextIntentWithParentStack(upIntent) .startActivities() } else { NavUtils.navigateUpTo(this, upIntent) } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) val fragments = supportFragmentManager.fragments if (fragments != null) { for (fragment in fragments) { fragment?.onActivityResult(requestCode, resultCode, data) } } } protected fun context(): Context = this protected fun supportsTransitions(): Boolean = Version.hasKitKat() protected fun thisActivity(): Activity = this override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean { return if (keyCode == KeyEvent.KEYCODE_MENU) { onKeyMenuPressed() } else { super.onKeyDown(keyCode, event) } } open fun onKeyMenuPressed(): Boolean = false }
mit
53b0b5bf3734344a60fe157895111fec
30.16
85
0.652118
5.036638
false
false
false
false
DemonWav/MinecraftDevIntelliJ
src/main/kotlin/com/demonwav/mcdev/translations/lang/psi/mixins/LangEntryImplMixin.kt
1
2117
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2020 minecraft-dev * * MIT License */ package com.demonwav.mcdev.translations.lang.psi.mixins import com.demonwav.mcdev.asset.PlatformAssets import com.demonwav.mcdev.translations.lang.LangFile import com.demonwav.mcdev.translations.lang.LangFileType import com.demonwav.mcdev.translations.lang.gen.psi.LangEntry import com.demonwav.mcdev.translations.lang.gen.psi.LangTypes import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.lang.ASTNode import com.intellij.navigation.ItemPresentation import com.intellij.psi.PsiElement import com.intellij.psi.PsiFileFactory abstract class LangEntryImplMixin(node: ASTNode) : ASTWrapperPsiElement(node), LangEntryMixin { override val key: String get() = node.findChildByType(LangTypes.KEY)?.text ?: "" override val value: String get() = node.findChildByType(LangTypes.VALUE)?.text ?: "" override fun getNameIdentifier() = node.findChildByType(LangTypes.KEY)?.psi override fun getName() = key override fun setName(name: String): PsiElement { val keyElement = node.findChildByType(LangTypes.KEY) val tmpFile = PsiFileFactory.getInstance(project).createFileFromText("name", LangFileType, "name=") as LangFile val renamed = tmpFile.firstChild as LangEntry val newKey = renamed.node.findChildByType(LangTypes.KEY) if (newKey != null) { if (keyElement != null) { this.node.replaceChild(keyElement, newKey) } else { this.node.addChild(newKey, node.findChildByType(LangTypes.EQUALS)) } } else if (keyElement != null) { this.node.removeChild(keyElement) } return this } override fun getPresentation() = object : ItemPresentation { override fun getPresentableText() = key override fun getLocationString() = containingFile.name override fun getIcon(unused: Boolean) = PlatformAssets.MINECRAFT_ICON } override fun toString() = "LangEntry($key=$value)" }
mit
5f2656d13068a6185d59740ef022302f
33.704918
119
0.705716
4.42887
false
false
false
false
BenDoan/playground
i-before-e-except-after-c/src/main/kotlin/me/bendoan/grammar/IBeforeEExceptAfterC.kt
1
1415
package me.bendoan.grammar import java.io.File; data class NumOccurrences(var numIe: Int, var numEi: Int, var numIeIncorrect: Int, var numEiIncorrect: Int) fun main(args: Array<String>) { val words = File("/usr/share/dict/american-english") .readLines() .map({ it.trim() }) .filter({ !it.endsWith("'s") }) val numOccurrences = calcNumOccurrences(words) println(""" |#IE: ${numOccurrences.numIe} |#IE after c: ${numOccurrences.numIeIncorrect} | |#EI: ${numOccurrences.numEi} |#EI not after c: ${numOccurrences.numEiIncorrect}""".trimMargin()) } fun calcNumOccurrences(words: List<String>): NumOccurrences { var counter = NumOccurrences(0, 0, 0, 0) for (word in words) { for (i in 0 until word.length) { val prevChar = if (i == 0) '0' else word.get(i-1) val firstChar = word.get(i) val secondChar = if (i == word.length-1) '0' else word.get(i+1) val combined = charArrayOf(firstChar, secondChar).joinToString(separator="") if (combined == "ei") { counter.numEi++ if (prevChar != 'c') counter.numEiIncorrect++ } else if (combined == "ie") { counter.numIe++ if (prevChar == 'c') counter.numIeIncorrect++ } } } return counter }
mit
5a36bf668a53dc1eaf1f369521711f89
31.906977
107
0.557597
3.675325
false
false
false
false
Atsky/haskell-idea-plugin
plugin/src/org/jetbrains/haskell/external/GhcMod.kt
1
3613
package org.jetbrains.haskell.external import org.jetbrains.haskell.util.ProcessRunner import java.io.IOException import com.intellij.util.messages.MessageBus import com.intellij.util.MessageBusUtil import com.intellij.notification.Notifications import com.intellij.notification.Notification import com.intellij.notification.NotificationType import java.io.File import org.jetbrains.haskell.util.OSUtil import org.jetbrains.haskell.config.HaskellSettings import java.util.Collections import java.util.HashMap /** * Created by atsky on 3/29/14. */ object GhcMod { var errorReported : Boolean = false fun getPath() : String { return HaskellSettings.getInstance().state.ghcModPath!! } fun getModuleContent(module : String) : List<Pair<String, String?>> { try { val path = getPath() val text = ProcessRunner(null).executeOrFail(path, "browse", "-d", module) if (!text.contains(":Error:")) { val f: (String) -> Pair<String, String?> = { if (it.contains("::")) { val t = it.split("::".toRegex()).toTypedArray() Pair(t[0].trim(), t[1].trim()) } else { Pair(it, null) } } return text.split('\n').map(f).toList() } else { return listOf() } } catch(e : Exception) { reportError() return listOf() } } fun debug(basePath : String, file: String) : Map<String, String> { try { val path = getPath() val text = ProcessRunner(basePath).executeOrFail(path, "debug", file) if (!text.contains(":Error:")) { val map = HashMap<String, String>() for (line in text.split('\n')) { val index = line.indexOf(":") map.put(line.substring(0, index), line.substring(index).trim()) } return map } else { return Collections.emptyMap() } } catch(e : Exception) { reportError() return Collections.emptyMap() } } fun check(basePath : String, file: String) : List<String> { try { val path = getPath() val text = ProcessRunner(basePath).executeOrFail(path, "check", file) if (!text.contains(":Error:")) { return text.split('\n').toList() } else { return listOf() } } catch(e : Exception) { reportError() return listOf() } } fun reportError() { if (!errorReported) { Notifications.Bus.notify(Notification("ghc-mod error", "ghc-mod", "Can't find ghc-mod executable. "+ "Please correct ghc-mod path in settings.", NotificationType.ERROR)) errorReported = true } } fun сheck() : Boolean { try { ProcessRunner(null).executeOrFail(getPath()) return true } catch(e : IOException) { return false } } fun getModulesList() : List<String> { try { val text = ProcessRunner(null).executeOrFail(getPath(), "list") if (!text.contains(":Error:")) { return text.split('\n').toList() } else { return listOf() } } catch(e : Exception) { reportError() return listOf() } } }
apache-2.0
c3677f813f2d700a52e75df1f9afb713
29.108333
112
0.518272
4.601274
false
false
false
false
tiarebalbi/okhttp
okhttp/src/test/java/okhttp3/SocketChannelTest.kt
1
7877
/* * Copyright (C) 2021 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okhttp3 import mockwebserver3.MockResponse import mockwebserver3.MockWebServer import okhttp3.Protocol.HTTP_1_1 import okhttp3.Protocol.HTTP_2 import okhttp3.Provider.CONSCRYPT import okhttp3.Provider.JSSE import okhttp3.TlsExtensionMode.DISABLED import okhttp3.TlsExtensionMode.STANDARD import okhttp3.TlsVersion.TLS_1_2 import okhttp3.TlsVersion.TLS_1_3 import okhttp3.internal.platform.ConscryptPlatform import okhttp3.internal.platform.Platform import okhttp3.testing.Flaky import okhttp3.testing.PlatformRule import okhttp3.tls.HandshakeCertificates import okhttp3.tls.HeldCertificate import org.assertj.core.api.Assertions.assertThat import org.conscrypt.Conscrypt import org.junit.After import org.junit.jupiter.api.Assumptions.assumeFalse import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Timeout import org.junit.jupiter.api.extension.RegisterExtension import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.MethodSource import java.io.IOException import java.net.InetAddress import java.security.Security import java.util.concurrent.CompletableFuture import java.util.concurrent.TimeUnit.SECONDS import javax.net.ssl.SNIHostName import javax.net.ssl.SNIMatcher import javax.net.ssl.SNIServerName import javax.net.ssl.SSLSocket import javax.net.ssl.StandardConstants @Suppress("UsePropertyAccessSyntax") @Timeout(6) @Tag("slow") class SocketChannelTest( val server: MockWebServer ) { @JvmField @RegisterExtension val platform = PlatformRule() @JvmField @RegisterExtension val clientTestRule = OkHttpClientTestRule().apply { recordFrames = true // recordSslDebug = true } @After fun cleanPlatform() { Security.removeProvider("Conscrypt") platform.resetPlatform() } // https://tools.ietf.org/html/rfc6066#page-6 specifies a FQDN is required. val hostname = "local.host" private val handshakeCertificates = run { // Generate a self-signed cert for the server to serve and the client to trust. val heldCertificate = HeldCertificate.Builder() .commonName(hostname) .addSubjectAlternativeName(hostname) .build() HandshakeCertificates.Builder() .heldCertificate(heldCertificate) .addTrustedCertificate(heldCertificate.certificate) .build() } private var acceptedHostName: String? = null @ParameterizedTest @MethodSource("connectionTypes") fun testConnection(socketMode: SocketMode) { // https://github.com/square/okhttp/pull/6554 assumeFalse( socketMode is TlsInstance && socketMode.socketMode == Channel && socketMode.protocol == HTTP_2 && socketMode.tlsExtensionMode == STANDARD, "failing for channel and h2" ) if (socketMode is TlsInstance && socketMode.provider == CONSCRYPT) { Security.insertProviderAt(Conscrypt.newProvider(), 1) Platform.resetForTests(ConscryptPlatform.buildIfSupported()!!) } val client = clientTestRule.newClientBuilder() .dns(object : Dns { override fun lookup(hostname: String): List<InetAddress> { return listOf(InetAddress.getByName("localhost")) } }) .callTimeout(4, SECONDS) .writeTimeout(2, SECONDS) .readTimeout(2, SECONDS) .apply { if (socketMode is TlsInstance) { if (socketMode.socketMode == Channel) { socketFactory(ChannelSocketFactory()) } connectionSpecs( listOf( ConnectionSpec.Builder(ConnectionSpec.COMPATIBLE_TLS) .tlsVersions(socketMode.tlsVersion) .supportsTlsExtensions(socketMode.tlsExtensionMode == STANDARD) .build() ) ) val sslSocketFactory = handshakeCertificates.sslSocketFactory() sslSocketFactory( sslSocketFactory, handshakeCertificates.trustManager ) when (socketMode.protocol) { HTTP_2 -> protocols(listOf(HTTP_2, HTTP_1_1)) HTTP_1_1 -> protocols(listOf(HTTP_1_1)) else -> TODO() } val serverSslSocketFactory = object: DelegatingSSLSocketFactory(sslSocketFactory) { override fun configureSocket(sslSocket: SSLSocket): SSLSocket { return sslSocket.apply { sslParameters = sslParameters.apply { sniMatchers = listOf(object : SNIMatcher(StandardConstants.SNI_HOST_NAME) { override fun matches(serverName: SNIServerName): Boolean { acceptedHostName = (serverName as SNIHostName).asciiName return true } }) } } } } server.useHttps(serverSslSocketFactory, false) } else if (socketMode == Channel) { socketFactory(ChannelSocketFactory()) } } .build() server.enqueue(MockResponse().setBody("abc")) @Suppress("HttpUrlsUsage") val url = if (socketMode is TlsInstance) "https://$hostname:${server.port}/get" else "http://$hostname:${server.port}/get" val request = Request.Builder() .url(url) .build() val promise = CompletableFuture<Response>() val call = client.newCall(request) call.enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { promise.completeExceptionally(e) } override fun onResponse(call: Call, response: Response) { promise.complete(response) } }) val response = promise.get(4, SECONDS) assertThat(response).isNotNull() assertThat(response.body!!.string()).isNotBlank() if (socketMode is TlsInstance) { assertThat(response.handshake!!.tlsVersion).isEqualTo(socketMode.tlsVersion) assertThat(acceptedHostName).isEqualTo(hostname) if (socketMode.tlsExtensionMode == STANDARD) { assertThat(response.protocol).isEqualTo(socketMode.protocol) } else { assertThat(response.protocol).isEqualTo(HTTP_1_1) } } } companion object { @Suppress("unused") @JvmStatic fun connectionTypes(): List<SocketMode> = listOf(CONSCRYPT, JSSE).flatMap { provider -> listOf(HTTP_1_1, HTTP_2).flatMap { protocol -> listOf(TLS_1_3, TLS_1_2).flatMap { tlsVersion -> listOf(Channel, Standard).flatMap { socketMode -> listOf(DISABLED, TlsExtensionMode.STANDARD).map { tlsExtensionMode -> TlsInstance(provider, protocol, tlsVersion, socketMode, tlsExtensionMode) } } } } } + Channel + Standard } } sealed class SocketMode object Channel : SocketMode() { override fun toString(): String = "Channel" } object Standard : SocketMode() { override fun toString(): String = "Standard" } data class TlsInstance( val provider: Provider, val protocol: Protocol, val tlsVersion: TlsVersion, val socketMode: SocketMode, val tlsExtensionMode: TlsExtensionMode ) : SocketMode() { override fun toString(): String = "$provider/$protocol/$tlsVersion/$socketMode/$tlsExtensionMode" } enum class Provider { JSSE, CONSCRYPT } enum class TlsExtensionMode { DISABLED, STANDARD }
apache-2.0
abb522aa4fc4f4d0280606b59a4c6e11
30.512
99
0.681224
4.437746
false
false
false
false
vvv1559/intellij-community
plugins/copyright/src/com/intellij/copyright/CopyrightManager.kt
1
10338
/* * 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.copyright import com.intellij.configurationStore.* import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.EditorFactory import com.intellij.openapi.editor.event.DocumentEvent import com.intellij.openapi.editor.event.DocumentListener import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.options.SchemeManagerFactory import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.startup.StartupActivity import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.InvalidDataException import com.intellij.openapi.util.WriteExternalException import com.intellij.openapi.util.text.StringUtil import com.intellij.packageDependencies.DependencyValidationManager import com.intellij.project.isDirectoryBased import com.intellij.psi.PsiFile import com.intellij.psi.PsiManager import com.intellij.util.attribute import com.intellij.util.element import com.maddyhome.idea.copyright.CopyrightProfile import com.maddyhome.idea.copyright.actions.UpdateCopyrightProcessor import com.maddyhome.idea.copyright.options.LanguageOptions import com.maddyhome.idea.copyright.options.Options import com.maddyhome.idea.copyright.util.FileTypeUtil import com.maddyhome.idea.copyright.util.NewFileTracker import org.jdom.Element import java.util.* import java.util.function.Function private const val DEFAULT = "default" private const val MODULE_TO_COPYRIGHT = "module2copyright" private const val COPYRIGHT = "copyright" private const val ELEMENT = "element" private const val MODULE = "module" private val LOG = Logger.getInstance(CopyrightManager::class.java) @State(name = "CopyrightManager", storages = arrayOf(Storage(value = "copyright/profiles_settings.xml", exclusive = true))) class CopyrightManager(private val project: Project, schemeManagerFactory: SchemeManagerFactory) : PersistentStateComponent<Element> { companion object { @JvmStatic fun getInstance(project: Project) = project.service<CopyrightManager>() } private var defaultCopyrightName: String? = null var defaultCopyright: CopyrightProfile? get() = defaultCopyrightName?.let { schemeManager.findSchemeByName(it)?.scheme } set(value) { defaultCopyrightName = value?.name } val scopeToCopyright = LinkedHashMap<String, String>() val options = Options() private val schemeWriter = { scheme: CopyrightProfile -> val element = scheme.writeScheme() if (project.isDirectoryBased) wrapScheme(element) else element } private val schemeManagerIprProvider = if (project.isDirectoryBased) null else SchemeManagerIprProvider("copyright") private val schemeManager = schemeManagerFactory.create("copyright", object : LazySchemeProcessor<SchemeWrapper<CopyrightProfile>, SchemeWrapper<CopyrightProfile>>("myName") { override fun createScheme(dataHolder: SchemeDataHolder<SchemeWrapper<CopyrightProfile>>, name: String, attributeProvider: Function<String, String?>, isBundled: Boolean): SchemeWrapper<CopyrightProfile> { return CopyrightLazySchemeWrapper(name, dataHolder, schemeWriter) } override fun isSchemeFile(name: CharSequence) = !StringUtil.equals(name, "profiles_settings.xml") }, schemeNameToFileName = OLD_NAME_CONVERTER, streamProvider = schemeManagerIprProvider) init { val app = ApplicationManager.getApplication() if (project.isDirectoryBased || !app.isUnitTestMode) { schemeManager.loadSchemes() } } fun mapCopyright(scopeName: String, copyrightProfileName: String) { scopeToCopyright.put(scopeName, copyrightProfileName) } fun unmapCopyright(scopeName: String) { scopeToCopyright.remove(scopeName) } fun hasAnyCopyrights(): Boolean { return defaultCopyrightName != null || !scopeToCopyright.isEmpty() } override fun getState(): Element? { val result = Element("settings") try { schemeManagerIprProvider?.writeState(result) if (!scopeToCopyright.isEmpty()) { val map = Element(MODULE_TO_COPYRIGHT) for ((scopeName, profileName) in scopeToCopyright) { map.element(ELEMENT) .attribute(MODULE, scopeName) .attribute(COPYRIGHT, profileName) } result.addContent(map) } options.writeExternal(result) } catch (e: WriteExternalException) { LOG.error(e) return null } defaultCopyrightName?.let { result.setAttribute(DEFAULT, it) } return wrapState(result, project) } override fun loadState(state: Element) { val data = unwrapState(state, project, schemeManagerIprProvider, schemeManager) ?: return data.getChild(MODULE_TO_COPYRIGHT)?.let { for (element in it.getChildren(ELEMENT)) { scopeToCopyright.put(element.getAttributeValue(MODULE), element.getAttributeValue(COPYRIGHT)) } } try { defaultCopyrightName = data.getAttributeValue(DEFAULT) options.readExternal(data) } catch (e: InvalidDataException) { LOG.error(e) } } private fun addCopyright(profile: CopyrightProfile) { schemeManager.addScheme(InitializedSchemeWrapper(profile, schemeWriter)) } fun getCopyrights(): Collection<CopyrightProfile> = schemeManager.allSchemes.map { it.scheme } fun clearMappings() { scopeToCopyright.clear() } fun removeCopyright(copyrightProfile: CopyrightProfile) { schemeManager.removeScheme(copyrightProfile.name) val it = scopeToCopyright.keys.iterator() while (it.hasNext()) { if (scopeToCopyright.get(it.next()) == copyrightProfile.name) { it.remove() } } } fun replaceCopyright(name: String, profile: CopyrightProfile) { val existingScheme = schemeManager.findSchemeByName(name) if (existingScheme == null) { addCopyright(profile) } else { existingScheme.scheme.copyFrom(profile) } } fun getCopyrightOptions(file: PsiFile): CopyrightProfile? { val virtualFile = file.virtualFile if (virtualFile == null || options.getOptions(virtualFile.fileType.name).getFileTypeOverride() == LanguageOptions.NO_COPYRIGHT) { return null } val validationManager = DependencyValidationManager.getInstance(project) for (scopeName in scopeToCopyright.keys) { val packageSet = validationManager.getScope(scopeName)?.value ?: continue if (packageSet.contains(file, validationManager)) { scopeToCopyright.get(scopeName)?.let { schemeManager.findSchemeByName(it) }?.let { return it.scheme } } } return defaultCopyright } } private class CopyrightManagerPostStartupActivity : StartupActivity { val newFileTracker = NewFileTracker() override fun runActivity(project: Project) { Disposer.register(project, Disposable { newFileTracker.clear() }) EditorFactory.getInstance().eventMulticaster.addDocumentListener(object : DocumentListener { override fun documentChanged(e: DocumentEvent) { val virtualFile = FileDocumentManager.getInstance().getFile(e.document) ?: return val module = ProjectRootManager.getInstance(project).fileIndex.getModuleForFile(virtualFile) ?: return if (!newFileTracker.poll(virtualFile) || !FileTypeUtil.getInstance().isSupportedFile(virtualFile) || PsiManager.getInstance(project).findFile(virtualFile) == null) { return } ApplicationManager.getApplication().invokeLater(Runnable { if (!virtualFile.isValid) { return@Runnable } val file = PsiManager.getInstance(project).findFile(virtualFile) if (file != null && file.isWritable) { CopyrightManager.getInstance(project).getCopyrightOptions(file)?.let { UpdateCopyrightProcessor(project, module, file).run() } } }, ModalityState.NON_MODAL, project.disposed) } }, project) } } private fun wrapScheme(element: Element): Element { val wrapper = Element("component") .attribute("name", "CopyrightManager") wrapper.addContent(element) return wrapper } private class CopyrightLazySchemeWrapper(name: String, dataHolder: SchemeDataHolder<SchemeWrapper<CopyrightProfile>>, writer: (scheme: CopyrightProfile) -> Element, private val subStateTagName: String = "copyright") : LazySchemeWrapper<CopyrightProfile>(name, dataHolder, writer) { override val lazyScheme = lazy { val scheme = CopyrightProfile() @Suppress("NAME_SHADOWING") val dataHolder = this.dataHolder.getAndSet(null) var element = dataHolder.read() if (element.name != subStateTagName) { element = element.getChild(subStateTagName) } element.deserializeInto(scheme) @Suppress("DEPRECATION") val allowReplaceKeyword = scheme.allowReplaceKeyword if (allowReplaceKeyword != null && scheme.allowReplaceRegexp == null) { scheme.allowReplaceRegexp = StringUtil.escapeToRegexp(allowReplaceKeyword) @Suppress("DEPRECATION") scheme.allowReplaceKeyword = null } scheme.resetModificationCount() dataHolder.updateDigest(writer(scheme)) scheme } }
apache-2.0
08f3f01774857a48a967e762d6d9e458
36.057348
177
0.728187
4.934606
false
false
false
false
ruslanys/vkmusic
src/main/kotlin/me/ruslanys/vkmusic/component/ScraperVkClient.kt
1
8107
package me.ruslanys.vkmusic.component import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import me.ruslanys.vkmusic.domain.Audio import me.ruslanys.vkmusic.exception.VkException import org.apache.commons.text.StringEscapeUtils import org.jsoup.Connection import org.jsoup.Jsoup import org.slf4j.LoggerFactory import org.springframework.stereotype.Component import java.io.BufferedReader import java.io.InputStreamReader import java.util.concurrent.ConcurrentHashMap import java.util.regex.Pattern import javax.script.Invocable import javax.script.ScriptEngineManager /** * @author Ruslan Molchanov ([email protected]) */ @Suppress("JoinDeclarationAndAssignment") @Component class ScraperVkClient : VkClient { companion object { private const val USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36" private const val PATH_BASE = "https://vk.com" private const val JSON_DELIMITER = "<!json>" private const val BLOCK_DELIMITER = "<!>" private const val SLEEP_INTERVAL = 5000L private const val CHUNK_SIZE = 5 private val SCRIPT_ENGINE = ScriptEngineManager().getEngineByName("JavaScript") private val log = LoggerFactory.getLogger(ScraperVkClient::class.java) } private val script: String private val cookies = ConcurrentHashMap<String, String>() init { script = BufferedReader(InputStreamReader(javaClass.classLoader.getResourceAsStream("decrypt.js"))) .use(BufferedReader::readText) } override fun addCookies(cookies: Map<String, String>) { this.cookies.putAll(cookies) } override fun setCookies(cookies: Map<String, String>) { clearCookies() addCookies(cookies) } override fun clearCookies() { this.cookies.clear() } override fun fetchUserId(): Long { val response = Jsoup.connect(PATH_BASE) .userAgent(USER_AGENT).cookies(cookies).method(Connection.Method.GET) .execute() val matcher = Pattern.compile("id: (\\d+)").matcher(response.body()) if (!matcher.find() || "0" == matcher.group(1).trim()) { throw VkException("Can not get user ID.") } val id = matcher.group(1).toLong() log.info("User ID: {}", id) return id } override fun getAudio(): List<Audio> { val userId = fetchUserId() return getAudio(userId) } override fun getAudio(ownerId: Long): List<Audio> { val list = mutableListOf<Audio>() var offset = 0 var audioDto: AudioPageDto do { audioDto = fetchAudioChunk(ownerId, offset) list.addAll(audioDto.audio) offset = audioDto.nextOffset } while (audioDto.hasMore()) log.debug("Total count: {}", audioDto.totalCount) log.debug("Fetched audio collection: {}", list.size) return list } private fun fetchAudioChunk(ownerId: Long, offset: Int): AudioPageDto { val response = Jsoup.connect("$PATH_BASE/al_audio.php") .userAgent(USER_AGENT).cookies(cookies).method(Connection.Method.POST) .data("access_hash", "") .data("act", "load_section") .data("al", "1") .data("claim", "0") .data("offset", offset.toString()) .data("owner_id", ownerId.toString()) .data("playlist_id", "-1") .data("type", "playlist") .execute() val body = response.body() val trimmed = body.substring(body.indexOf(JSON_DELIMITER) + JSON_DELIMITER.length) val json = trimmed.substring(0 until trimmed.indexOf(BLOCK_DELIMITER)) return jacksonObjectMapper().readValue(json, AudioPageDto::class.java) } override fun fetchUrls(audioList: List<Audio>) { val userId = fetchUserId() var sleepInterval = SLEEP_INTERVAL val chunks = audioList.chunked(CHUNK_SIZE) var chunkNumber = 0 while (chunkNumber < chunks.size) { val chunkContent = chunks[chunkNumber] log.debug("Fetching urls: ${chunkContent.size}") try { fetchUrlsChunk(userId, chunkContent) sleepInterval = SLEEP_INTERVAL } catch (e: VkException) { log.info("Sleeping {} sec...", sleepInterval / 1000) Thread.sleep(sleepInterval) sleepInterval += SLEEP_INTERVAL continue } chunkNumber++ Thread.sleep(200) } } private fun fetchUrlsChunk(userId: Long, audioList: List<Audio>) { val audioMap = audioList.associateBy { it.id }.toSortedMap() val ids = audioList.joinToString(",") { "${it.ownerId}_${it.id}_${it.hash}" } .plus(",${audioList.first().ownerId}_${audioList.first().id}") val response = Jsoup.connect("$PATH_BASE/al_audio.php") .userAgent(USER_AGENT).cookies(cookies).method(Connection.Method.POST) .data("act", "reload_audio") .data("al", "1") .data("ids", ids) .execute() val body = response.body() if (!body.contains(JSON_DELIMITER)) { throw VkException("Can not fetch audio urls.") } val trimmed = body.substring(body.indexOf(JSON_DELIMITER) + JSON_DELIMITER.length) val json = trimmed.substring(0 until trimmed.indexOf(BLOCK_DELIMITER)) val list = jacksonObjectMapper().readValue<List<*>>(json, List::class.java) list.forEach { it as List<*> val audio = audioMap[(it[0] as Number).toLong()] val url = decrypt(userId, it[2] as String) audio!!.url = if (url.contains(".m3u")) { fetchUrlFromM3u(url) } else { url } } } private fun fetchUrlFromM3u(url: String): String { val response = Jsoup.connect(url).ignoreContentType(true).execute() val body = response.body() val matcher = Pattern.compile("URI=\"(.*)\"").matcher(body) if (!matcher.find()) { throw VkException("Can not fetch audio url from M3U.") } val keyUrl = matcher.group(1) val mp3Url = keyUrl.replace(Regex("https://(?<domain>.*)/(.*)/(.*)/(.*)/key.pub(.*)"), "https://\${domain}/\$2/\$4.mp3\$5") return mp3Url } private fun decrypt(vkId: Long, url: String): String { val script = this.script.replace("\${vkId}", vkId.toString()) // TODO: replace with bindings SCRIPT_ENGINE.eval(script) return (SCRIPT_ENGINE as Invocable).invokeFunction("decode", url) as String } @JsonIgnoreProperties(ignoreUnknown = true) data class AudioPageDto( val type: String, val ownerId: Long, val title: String, val hasMore: Int, val nextOffset: Int, val totalCount: Int, val list: List<List<*>>, val audio: List<Audio> = list.map { Audio( (it[0] as Number).toLong(), (it[1] as Number).toLong(), StringEscapeUtils.unescapeHtml4(it[4] as String), StringEscapeUtils.unescapeHtml4(it[3] as String), it[5] as Int, (it[13] as String).split("/") // hash .reduceIndexed { index, acc, s -> when (index) { 2 -> s 5 -> acc + "_" + s else -> acc } } ) }.toList() ) { fun hasMore(): Boolean = hasMore == 1 } }
mit
b31dcb78ef60094163196bef8fee195a
34.713656
162
0.567781
4.417984
false
false
false
false
Kotlin/kotlinx.coroutines
kotlinx-coroutines-core/native/src/Dispatchers.kt
1
2808
/* * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines import kotlinx.coroutines.internal.multithreadingSupported import kotlin.coroutines.* public actual object Dispatchers { public actual val Default: CoroutineDispatcher = createDefaultDispatcherBasedOnMm() public actual val Main: MainCoroutineDispatcher get() = injectedMainDispatcher ?: mainDispatcher public actual val Unconfined: CoroutineDispatcher get() = kotlinx.coroutines.Unconfined // Avoid freezing private val mainDispatcher = createMainDispatcher(Default) private var injectedMainDispatcher: MainCoroutineDispatcher? = null @PublishedApi internal fun injectMain(dispatcher: MainCoroutineDispatcher) { if (!multithreadingSupported) { throw IllegalStateException("Dispatchers.setMain is not supported in Kotlin/Native when new memory model is disabled") } injectedMainDispatcher = dispatcher } @PublishedApi internal fun resetInjectedMain() { injectedMainDispatcher = null } } internal expect fun createMainDispatcher(default: CoroutineDispatcher): MainCoroutineDispatcher private fun createDefaultDispatcherBasedOnMm(): CoroutineDispatcher { return if (multithreadingSupported) createDefaultDispatcher() else OldDefaultExecutor } private fun takeEventLoop(): EventLoopImpl = ThreadLocalEventLoop.currentOrNull() as? EventLoopImpl ?: error("There is no event loop. Use runBlocking { ... } to start one.") internal object OldDefaultExecutor : CoroutineDispatcher(), Delay { override fun dispatch(context: CoroutineContext, block: Runnable) = takeEventLoop().dispatch(context, block) override fun scheduleResumeAfterDelay(timeMillis: Long, continuation: CancellableContinuation<Unit>) = takeEventLoop().scheduleResumeAfterDelay(timeMillis, continuation) override fun invokeOnTimeout(timeMillis: Long, block: Runnable, context: CoroutineContext): DisposableHandle = takeEventLoop().invokeOnTimeout(timeMillis, block, context) } internal class OldMainDispatcher(private val delegate: CoroutineDispatcher) : MainCoroutineDispatcher() { override val immediate: MainCoroutineDispatcher get() = throw UnsupportedOperationException("Immediate dispatching is not supported on Native") override fun dispatch(context: CoroutineContext, block: Runnable) = delegate.dispatch(context, block) override fun isDispatchNeeded(context: CoroutineContext): Boolean = delegate.isDispatchNeeded(context) override fun dispatchYield(context: CoroutineContext, block: Runnable) = delegate.dispatchYield(context, block) override fun toString(): String = toStringInternalImpl() ?: delegate.toString() }
apache-2.0
ae0701856509bf7215fb0b76b8a9c156
45.032787
130
0.773148
5.452427
false
false
false
false
zdary/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/ext/spock/dataTables.kt
12
3658
// 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 org.jetbrains.plugins.groovy.ext.spock import com.intellij.openapi.util.NlsSafe import com.intellij.psi.PsiElement import com.intellij.psi.util.siblings import com.intellij.psi.util.skipTokens import org.jetbrains.plugins.groovy.lang.lexer.TokenSets.WHITE_SPACES_OR_COMMENTS import org.jetbrains.plugins.groovy.lang.psi.GroovyElementTypes import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrLabeledStatement import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrBinaryExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression @NlsSafe private const val WHERE_LABEL = "where" @NlsSafe private const val AND_LABEL = "and" /** * @return `true` if [this] expression is a binary `|` or `||` expression which is a part of Spock data table, * otherwise `false` */ fun GrExpression.isTableColumnSeparator(): Boolean { if (this !is GrBinaryExpression || !isOr()) return false val maybeTableRow = findMaybeTableRow() ?: return false return maybeTableRow.isUnderTableHeader() || maybeTableRow.isTableRow() } /** * Skips table columns (`|` or `||` expression) up. * * @return topmost `|` or `||` expression */ private fun GrBinaryExpression.findMaybeTableRow(): GrBinaryExpression? { var current = this while (true) { val parent = current.parent if (parent == null) { return null } else if (parent is GrBinaryExpression && parent.isOr()) { current = parent } else { return current } } } /** * @return `true` if [this] expression has `where:` label */ private fun PsiElement.isUnderTableHeader(): Boolean { return parent?.isTableHeader() ?: false } private fun PsiElement.isTableHeader(): Boolean { return this is GrLabeledStatement && name == WHERE_LABEL } private fun GrExpression.isTableRow(): Boolean { val parent = parent if (parent is GrLabeledStatement && parent.name == AND_LABEL) { return parent.isTableRow() } else { return (this as GrStatement).isTableRow() } } /** * @return `true` if some previous sibling is a table header and there are only table rows between them, * otherwise `false` */ private fun GrStatement.isTableRow(): Boolean { for (sibling in siblings(false).drop(1).skipTokens(WHITE_SPACES_OR_COMMENTS)) { if (sibling.maybeTableColumnExpression()) { continue } if (sibling !is GrLabeledStatement) { return false } if (sibling.name == AND_LABEL && sibling.statement?.maybeTableColumnExpression() == true) { continue } return findWhereLabeledStatement(sibling) != null } return false } /** * foo: * bar: * where: * a << 1 * * Such structure is parsed as `(foo: (bar: (where: (a << 1)))`. * We have to go deep and find `a << 1` statement. */ fun findWhereLabeledStatement(top: GrLabeledStatement): GrStatement? { var current = top while (true) { val labeledStatement = current.statement when { WHERE_LABEL == current.name -> { return labeledStatement } labeledStatement is GrLabeledStatement -> { current = labeledStatement } else -> { return null } } } } private fun PsiElement.maybeTableColumnExpression() = this is GrBinaryExpression && isOr() fun GrBinaryExpression.isOr(): Boolean { val type = operationTokenType return type === GroovyElementTypes.T_BOR || type === GroovyElementTypes.T_LOR }
apache-2.0
fbc985e090a4a9082f935e12d250ee91
28.5
140
0.700929
3.937567
false
false
false
false
moko256/twicalico
app/src/main/java/com/github/moko256/twitlatte/viewmodel/TrendsViewModel.kt
1
3239
/* * Copyright 2015-2019 The twitlatte authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.moko256.twitlatte.viewmodel import android.location.Address import android.location.Geocoder import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.github.moko256.latte.client.base.ApiClient import com.github.moko256.latte.client.base.entity.Trend import com.github.moko256.twitlatte.database.CachedTrendsSQLiteOpenHelper import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers import java.util.* class TrendsViewModel : ViewModel() { private val disposables = CompositeDisposable() lateinit var database: CachedTrendsSQLiteOpenHelper lateinit var apiClient: ApiClient lateinit var geocoder: Geocoder val trends = MutableLiveData<List<Trend>>() val errors = MutableLiveData<Throwable>() fun load(withoutCache: Boolean) { disposables.add( Single.create<List<Trend>> { try { if (!withoutCache) { val fromDb = database.trends if (fromDb.isNotEmpty()) { it.onSuccess(fromDb) return@create } } it.onSuccess(getTrendsFromApi()) } catch (e: Throwable) { it.tryOnError(e) } }.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( //TODO: Consider to use whether post/setValues method in MutableLiveData. It is different about using thread { trends.value = it }, { errors.value = it } ) ) } private fun getTrendsFromApi(): List<Trend> { val address = getGeoLocation() val trends = apiClient.getClosestTrends(address.latitude, address.longitude) database.trends = trends return trends } private fun getGeoLocation(): Address { val locale = Locale.getDefault() val address = geocoder.getFromLocationName(locale.displayCountry, 1)[0] if (address != null) { return address } else { throw Exception("Cannot use trends") } } }
apache-2.0
bbae72650944714ea5f65fa347cf8f9a
34.217391
140
0.588762
5.362583
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/reflection/types/jvmErasureOfTypeParameter.kt
2
1831
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE // WITH_REFLECT import kotlin.reflect.jvm.jvmErasure import kotlin.reflect.KClass import kotlin.test.assertEquals open class O class A { fun <T> simple(): T = null!! fun <T : String> string(): T = null!! fun <T : String?> nullableString(): T = null!! fun <T : U, U> otherTypeParameter(): T = null!! fun <T : U, U : List<String>> otherTypeParameterWithBound(): T = null!! fun <T : Cloneable> twoInterfaces1(): T where T : Comparable<*> = null!! fun <T : Comparable<*>> twoInterfaces2(): T where T : Cloneable = null!! fun <T : Cloneable> interfaceAndClass1(): T where T : O = null!! fun <T : O> interfaceAndClass2(): T where T : Cloneable = null!! fun <T> arrayOfAny(): Array<T> = null!! fun <T : Number> arrayOfNumber(): Array<T> = null!! fun <T> arrayOfArrayOfCloneable(): Array<Array<T>> where T : Cloneable, T : Comparable<*> = null!! } fun get(name: String): KClass<*> = A::class.members.single { it.name == name }.returnType.jvmErasure fun box(): String { assertEquals(Any::class, get("simple")) assertEquals(String::class, get("string")) assertEquals(String::class, get("nullableString")) assertEquals(Any::class, get("otherTypeParameter")) assertEquals(List::class, get("otherTypeParameterWithBound")) assertEquals(Cloneable::class, get("twoInterfaces1")) assertEquals(Comparable::class, get("twoInterfaces2")) assertEquals(O::class, get("interfaceAndClass1")) assertEquals(O::class, get("interfaceAndClass2")) assertEquals(Array<Any>::class, get("arrayOfAny")) assertEquals(Array<Number>::class, get("arrayOfNumber")) assertEquals(Array<Array<Cloneable>>::class, get("arrayOfArrayOfCloneable")) return "OK" }
apache-2.0
7bc0d3ecfcf590ecf0a07e4a86d92fc6
37.145833
102
0.67231
3.830544
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/multiDecl/VarCapturedInLocalFunction.kt
5
222
class A { } operator fun A.component1() = 1 operator fun A.component2() = 2 fun box() : String { var (a, b) = A() fun local() { a = 3 } local() return if (a == 3 && b == 2) "OK" else "fail" }
apache-2.0
7d4d9b451af97f8943d74d41bab80126
13.866667
49
0.481982
2.810127
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/closures/captureOuterProperty/captureFunctionInProperty.kt
5
222
interface T { fun result(): String } class A(val x: String) { fun getx() = x fun foo() = object : T { val bar = getx() override fun result() = bar } } fun box() = A("OK").foo().result()
apache-2.0
71dc01c87eed15c9bf60a1093f26cebc
13.8
35
0.495495
3.171429
false
false
false
false
codeka/wwmmo
client/src/main/kotlin/au/com/codeka/warworlds/client/game/welcome/WelcomeScreen.kt
1
9532
package au.com.codeka.warworlds.client.game.welcome import android.app.ActivityManager import android.content.Context import android.content.Intent import android.net.Uri import android.view.ViewGroup import au.com.codeka.warworlds.client.App import au.com.codeka.warworlds.client.R import au.com.codeka.warworlds.client.concurrency.Threads import au.com.codeka.warworlds.client.game.starfield.StarfieldScreen import au.com.codeka.warworlds.client.game.world.EmpireManager import au.com.codeka.warworlds.client.net.ServerStateEvent import au.com.codeka.warworlds.client.net.auth.AuthAccountUpdate import au.com.codeka.warworlds.client.ui.Screen import au.com.codeka.warworlds.client.ui.ScreenContext import au.com.codeka.warworlds.client.ui.ShowInfo import au.com.codeka.warworlds.client.util.UrlFetcher.fetchStream import au.com.codeka.warworlds.client.util.Version.string import au.com.codeka.warworlds.client.util.eventbus.EventHandler import au.com.codeka.warworlds.common.Log import au.com.codeka.warworlds.common.proto.Empire import com.google.android.gms.auth.api.signin.GoogleSignInAccount import com.google.common.base.Preconditions import org.w3c.dom.Document import org.w3c.dom.Element import java.io.IOException import java.io.InputStream import java.text.DecimalFormat import java.text.ParseException import java.text.SimpleDateFormat import java.util.* import javax.xml.parsers.DocumentBuilderFactory /** * The "Welcome" screen is what you see when you first start the game, it has a view for showing * news, letting you change your empire and so on. */ class WelcomeScreen : Screen() { private lateinit var context: ScreenContext private lateinit var welcomeLayout: WelcomeLayout private var motd: String? = null override fun onCreate(context: ScreenContext, container: ViewGroup) { super.onCreate(context, container) this.context = context welcomeLayout = WelcomeLayout(context.activity, layoutCallbacks) App.eventBus.register(eventHandler) refreshWelcomeMessage() // TODO //optionsButton.setOnClickListener(v -> // getFragmentTransitionManager().replaceFragment(GameSettingsFragment.class)); } override fun onShow(): ShowInfo { welcomeLayout.setConnectionStatus(false, "") updateServerState(App.server.currState) if (EmpireManager.hasMyEmpire()) { welcomeLayout.refreshEmpireDetails(EmpireManager.getMyEmpire()) } if (motd != null) { welcomeLayout.updateWelcomeMessage(motd!!) } updateSignInButtonText(App.auth.account) /* String currAccountName = prefs.getString("AccountName", null); if (currAccountName != null && currAccountName.endsWith("@anon.war-worlds.com")) { Button reauthButton = (Button) findViewById(R.id.reauth_btn); reauthButton.setText("Sign in"); }*/maybeShowSignInPrompt() // } // } // }); return ShowInfo.builder().view(welcomeLayout).toolbarVisible(false).build() } override fun onDestroy() { App.eventBus.unregister(eventHandler) } private fun maybeShowSignInPrompt() { /*final SharedPreferences prefs = Util.getSharedPreferences(); int numStartsSinceSignInPrompt = prefs.getInt("NumStartsSinceSignInPrompt", 0); if (numStartsSinceSignInPrompt < 5) { prefs.edit().putInt("NumStartsSinceSignInPrompt", numStartsSinceSignInPrompt + 1).apply(); return; } // set the count to -95, which means they won't get prompted for another 100 starts... should // be plenty to not be annoying, yet still be a useful prompt. prefs.edit().putInt("NumStartsSinceSignInPrompt", -95).apply(); new StyledDialog.Builder(context) .setMessage(Html.fromHtml("<p>In order to ensure your empire is safe in the event you lose " + "your phone, it's recommended that you sign in. You must also sign in if you want to " + "access your empire from multiple devices.</p><p>Click \"Sign in\" below to sign in " + "with a Google account.</p>")) .setTitle("Sign in") .setNegativeButton("No, thanks", null) .setPositiveButton("Sign in", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { onReauthClick(); } }) .create().show();*/ } private fun parseDate(pubDate: String, format: SimpleDateFormat): Date? { return try { format.parse(pubDate) } catch (e: ParseException) { null } } private fun refreshWelcomeMessage() { App.taskRunner.runTask(Runnable { val ins: InputStream? = try { fetchStream(MOTD_RSS) } catch (e: IOException) { log.warning("Error loading MOTD: %s", MOTD_RSS, e) return@Runnable } val builderFactory = DocumentBuilderFactory.newInstance() builderFactory.isValidating = false val doc: Document = try { val builder = builderFactory.newDocumentBuilder() builder.parse(ins) } catch (e: Exception) { log.warning("Error parsing MOTD: %s", MOTD_RSS, e) return@Runnable } val inputFormat = SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US) val outputFormat = SimpleDateFormat("dd MMM yyyy h:mm a", Locale.US) val motd = StringBuilder() val itemNodes = doc.getElementsByTagName("item") for (i in 0 until itemNodes.length) { val itemElem = itemNodes.item(i) as Element val title = itemElem.getElementsByTagName("title").item(0).textContent val content = itemElem.getElementsByTagName("description").item(0).textContent val pubDate = itemElem.getElementsByTagName("pubDate").item(0).textContent val link = itemElem.getElementsByTagName("link").item(0).textContent val date = parseDate(pubDate, inputFormat) if (date != null) { motd.append("<h1>") motd.append(outputFormat.format(date)) motd.append("</h1>") } motd.append("<h2>") motd.append(title) motd.append("</h2>") motd.append(content) motd.append("<div style=\"text-align: right; border-bottom: dashed 1px #fff; " + "padding-bottom: 4px;\">") motd.append("<a href=\"") motd.append(link) motd.append("\">") motd.append("View forum post") motd.append("</a></div>") } App.taskRunner.runTask({ this.motd = motd.toString() welcomeLayout.updateWelcomeMessage(motd.toString()) }, Threads.UI) }, Threads.BACKGROUND) } private fun updateServerState(event: ServerStateEvent) { Preconditions.checkNotNull(welcomeLayout) if (event.state === ServerStateEvent.ConnectionState.CONNECTED) { val maxMemoryBytes = Runtime.getRuntime().maxMemory() val context = App.applicationContext val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager val memoryClass = activityManager.memoryClass val formatter = DecimalFormat("#,##0") val msg = String.format(Locale.ENGLISH, "Connected\r\nMemory Class: %d - Max bytes: %s\r\nVersion: %s", memoryClass, formatter.format(maxMemoryBytes), string()) welcomeLayout.setConnectionStatus(true, msg) } else { if (event.state === ServerStateEvent.ConnectionState.ERROR) { handleConnectionError(event) } val msg = String.format("%s - %s", event.url, event.state) welcomeLayout.setConnectionStatus(false, msg) } } /** * Called when get notified that there was some error connecting to the server. Sometimes we'll * be able to fix the error and try again. */ private fun handleConnectionError(event: ServerStateEvent) { if (event.loginStatus == null) { // Nothing we can do. log.debug("Got an error, but login status is null.") } } private fun updateSignInButtonText(account: GoogleSignInAccount?) { if (account == null) { welcomeLayout.setSignInText(R.string.signin) } else { welcomeLayout.setSignInText(R.string.switch_user) } } private val layoutCallbacks: WelcomeLayout.Callbacks = object : WelcomeLayout.Callbacks { override fun onStartClick() { context.home() context.pushScreen(StarfieldScreen()) } override fun onHelpClick() { val i = Intent(Intent.ACTION_VIEW) i.data = Uri.parse("http://www.war-worlds.com/doc/getting-started") context.startActivity(i) } override fun onWebsiteClick() { val i = Intent(Intent.ACTION_VIEW) i.data = Uri.parse("http://www.war-worlds.com/") context.startActivity(i) } override fun onSignInClick() { context.pushScreen(SignInScreen(false /* immediate */)) } } private val eventHandler: Any = object : Any() { @EventHandler fun onServerStateUpdated(event: ServerStateEvent) { updateServerState(event) } @EventHandler fun onEmpireUpdated(empire: Empire) { val myEmpire = EmpireManager.getMyEmpire() if (myEmpire.id == empire.id) { welcomeLayout.refreshEmpireDetails(empire) } } @EventHandler fun onAuthUpdated(auth: AuthAccountUpdate) { updateSignInButtonText(auth.account) } } companion object { private val log = Log("WelcomeScreen") /** URL of RSS content to fetch and display in the motd view. */ private const val MOTD_RSS = "https://www.war-worlds.com/forum/announcements/rss" } }
mit
083f87278a1003b399d6805857ff94ae
35.385496
100
0.68548
4.128194
false
false
false
false
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/internal/statistic/collectors/fus/os/SystemRuntimeCollector.kt
6
8515
// 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.internal.statistic.collectors.fus.os import com.intellij.diagnostic.VMOptions import com.intellij.internal.DebugAttachDetector import com.intellij.internal.statistic.beans.MetricEvent import com.intellij.internal.statistic.eventLog.EventLogGroup import com.intellij.internal.statistic.eventLog.events.EventFields import com.intellij.internal.statistic.eventLog.events.EventFields.Boolean import com.intellij.internal.statistic.eventLog.events.EventFields.Int import com.intellij.internal.statistic.eventLog.events.EventFields.Long import com.intellij.internal.statistic.eventLog.events.EventFields.String import com.intellij.internal.statistic.eventLog.events.EventId1 import com.intellij.internal.statistic.eventLog.events.EventId2 import com.intellij.internal.statistic.eventLog.events.EventId3 import com.intellij.internal.statistic.service.fus.collectors.ApplicationUsagesCollector import com.intellij.internal.statistic.service.fus.collectors.AllowedDuringStartupCollector import com.intellij.internal.statistic.utils.StatisticsUtil import com.intellij.openapi.application.PathManager import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.Version import com.intellij.util.lang.JavaVersion import com.intellij.util.system.CpuArch import com.sun.management.OperatingSystemMXBean import java.lang.management.ManagementFactory import java.nio.file.Files import java.util.* import kotlin.math.min import kotlin.math.roundToInt class SystemRuntimeCollector : ApplicationUsagesCollector(), AllowedDuringStartupCollector { private val COLLECTORS = listOf("Serial", "Parallel", "CMS", "G1", "Z", "Shenandoah", "Epsilon", "Other") private val ARCHITECTURES = listOf("x86", "x86_64", "arm64", "other", "unknown") private val VENDORS = listOf("JetBrains", "Apple", "Oracle", "Sun", "IBM", "Azul", "Other") private val VM_OPTIONS = listOf("Xmx", "Xms", "SoftRefLRUPolicyMSPerMB", "ReservedCodeCacheSize") private val SYSTEM_PROPERTIES = listOf("splash", "nosplash") private val RENDERING_PIPELINES = listOf("Metal", "OpenGL") private val GROUP: EventLogGroup = EventLogGroup("system.runtime", 16) private val CORES: EventId1<Int> = GROUP.registerEvent("cores", Int("value")) private val MEMORY_SIZE: EventId1<Int> = GROUP.registerEvent("memory.size", Int("gigabytes")) private val SWAP_SIZE: EventId1<Int> = GROUP.registerEvent("swap.size", Int("gigabytes")) private val DISK_SIZE: EventId2<Int, Int> = GROUP.registerEvent("disk.size", Int("index_partition_size"), Int("index_partition_free")) private val GC: EventId1<String?> = GROUP.registerEvent("garbage.collector", String("name", COLLECTORS)) private val JVM: EventId3<Version?, String?, String?> = GROUP.registerEvent("jvm", EventFields.VersionByObject, String("arch", ARCHITECTURES), String("vendor", VENDORS)) private val JVM_OPTION: EventId2<String?, Long> = GROUP.registerEvent("jvm.option", String("name", VM_OPTIONS), Long("value")) private val SYSTEM_PROPERTY: EventId2<String?, Boolean> = GROUP.registerEvent("jvm.client.properties", String("name", SYSTEM_PROPERTIES), Boolean("value")) private val DEBUG_AGENT: EventId1<Boolean> = GROUP.registerEvent("debug.agent", EventFields.Enabled) private val RENDERING: EventId1<String?> = GROUP.registerEvent("rendering.pipeline", String("name", RENDERING_PIPELINES)) override fun getGroup(): EventLogGroup = GROUP override fun getMetrics(): Set<MetricEvent> { val result = mutableSetOf<MetricEvent>() result += CORES.metric(getCpuCoreCount()) val (physicalMemory, swapSize) = getPhysicalMemoryAndSwapSize() result += MEMORY_SIZE.metric(physicalMemory) result += SWAP_SIZE.metric(swapSize) val indexVolumeData = getIndexVolumeSizeAndFreeSpace() if (indexVolumeData != null) { val (size, freeSpace) = indexVolumeData result += DISK_SIZE.metric(size, freeSpace) } result += GC.metric(getGcName()) // Proper detection implemented only for macOS if (SystemInfo.isMac) result += RENDERING.metric(getRenderingPipelineName()) result += JVM.metric( Version(1, JavaVersion.current().feature, 0), CpuArch.CURRENT.name.lowercase(Locale.ENGLISH), getJavaVendor()) for (option in collectJvmOptions()) { result += JVM_OPTION.metric(option.key, option.value) } for (property in collectSystemProperties()) { result += SYSTEM_PROPERTY.metric(property.key, property.value.toBoolean()) } result += DEBUG_AGENT.metric(DebugAttachDetector.isDebugEnabled()) return result } private fun getCpuCoreCount(): Int = StatisticsUtil.roundToUpperBound(Runtime.getRuntime().availableProcessors(), intArrayOf(1, 2, 4, 6, 8, 12, 16, 20, 24, 32, 64)) private fun getPhysicalMemoryAndSwapSize(): Pair<Int, Int> { @Suppress("FunctionName") fun GiB(bytes: Long) = (bytes.toDouble() / (1 shl 30)).roundToInt() val bean = ManagementFactory.getOperatingSystemMXBean() as OperatingSystemMXBean val physicalMemory = StatisticsUtil.roundToUpperBound(GiB(bean.totalPhysicalMemorySize), intArrayOf(1, 2, 4, 8, 12, 16, 24, 32, 48, 64, 128, 256)) val swapSize = StatisticsUtil.roundToPowerOfTwo(min(GiB(bean.totalSwapSpaceSize), physicalMemory)) return physicalMemory to swapSize } private fun getIndexVolumeSizeAndFreeSpace(): Pair<Int, Int>? { try { val fileStore = Files.getFileStore(PathManager.getIndexRoot()) val totalSpace = fileStore.totalSpace if (totalSpace > 0L) { val size = min(1 shl 14, StatisticsUtil.roundToPowerOfTwo((totalSpace shr 30).toInt())) // ATM, the biggest popular consumer HDDs are ~16 TB val freeSpace = (fileStore.usableSpace * 100.0 / totalSpace).toInt() return size to freeSpace } } catch (_: UnsupportedOperationException) { } // some non-standard FS catch (_: SecurityException) { } // security manager denies reading of FS attributes return null } private fun getGcName(): String { for (gc in ManagementFactory.getGarbageCollectorMXBeans()) { if (gc.name == "MarkSweepCompact" || gc.name == "Copy") return "Serial" // -XX:+UseSerialGC if (gc.name == "PS MarkSweep" || gc.name == "PS Scavenge") return "Parallel" // -XX:+UseParallelGC if (gc.name == "ConcurrentMarkSweep" || gc.name == "ParNew") return "CMS" // -XX:+UseConcMarkSweepGC if (gc.name.startsWith("G1 ")) return "G1" // -XX:+UseG1GC if (gc.name == "ZGC") return "Z" // -XX:+UseZGC if (gc.name.startsWith("Shenandoah ")) return "Shenandoah" // -XX:+UseShenandoahGC if (gc.name.startsWith("Epsilon ")) return "Epsilon" // -XX:+UseEpsilonGC } return "Other" } private fun getRenderingPipelineName() = if (SystemInfo.isMetalRendering) "Metal" else "OpenGL" private fun getJavaVendor(): String = when { SystemInfo.isJetBrainsJvm -> "JetBrains" SystemInfo.isOracleJvm -> "Oracle" SystemInfo.isIbmJvm -> "IBM" SystemInfo.isAzulJvm -> "Azul" else -> "Other" } private fun collectJvmOptions(): Map<String, Long> = ManagementFactory.getRuntimeMXBean().inputArguments.asSequence() .map { arg -> try { fun parse(arg: String, start: Int) = VMOptions.parseMemoryOption(arg.substring(start)) shr 20 fun roundDown(value: Long, vararg steps: Long) = steps.findLast { it <= value } ?: 0 when { arg.startsWith("-Xms") -> "Xms" to roundDown(parse(arg, 4), 64, 128, 256, 512) arg.startsWith("-Xmx") -> "Xmx" to roundDown(parse(arg, 4), 512, 750, 1000, 1024, 1500, 2000, 2048, 3000, 4000, 4096, 6000, 8000) arg.startsWith("-XX:SoftRefLRUPolicyMSPerMB=") -> "SoftRefLRUPolicyMSPerMB" to roundDown(parse(arg, 28), 50, 100) arg.startsWith("-XX:ReservedCodeCacheSize=") -> "ReservedCodeCacheSize" to roundDown(parse(arg, 26), 240, 300, 400, 500) else -> null } } catch (e: IllegalArgumentException) { null } } .filterNotNull() .toMap() private fun collectSystemProperties(): Map<String, String> = SYSTEM_PROPERTIES.asSequence() .map { it to System.getProperty(it) } .filter { it.second != null } .toMap() }
apache-2.0
4a1dde5d9747f52b4ea586a02f2395eb
49.384615
150
0.703934
4.0625
false
false
false
false