repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
allotria/intellij-community | plugins/git4idea/src/git4idea/stash/ui/GitStashUi.kt | 2 | 3230 | // 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 git4idea.stash.ui
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vcs.changes.EditorTabPreview
import com.intellij.openapi.vcs.changes.ui.ChangesTree
import com.intellij.openapi.vcs.changes.ui.TreeActionsToolbarPanel
import com.intellij.ui.OnePixelSplitter
import com.intellij.ui.PopupHandler
import com.intellij.ui.ScrollPaneFactory
import com.intellij.ui.SideBorder
import java.awt.BorderLayout
import javax.swing.JComponent
import javax.swing.JPanel
class GitStashUi(private val project: Project, isEditorDiffPreview: Boolean, disposable: Disposable) : Disposable {
val mainComponent: JPanel = JPanel(BorderLayout())
private val tree: ChangesTree
private val treeDiffSplitter: OnePixelSplitter
private val toolbar: JComponent
private var diffPreviewProcessor: GitStashDiffPreview? = null
private var editorTabPreview: EditorTabPreview? = null
init {
tree = GitStashTree(project, this)
PopupHandler.installPopupHandler(tree, "Git.Stash.ContextMenu", GIT_STASH_UI_PLACE)
toolbar = buildToolbar()
val treePanel = JPanel(BorderLayout())
treePanel.add(toolbar, BorderLayout.NORTH)
treePanel.add(ScrollPaneFactory.createScrollPane(tree, SideBorder.TOP), BorderLayout.CENTER)
treeDiffSplitter = OnePixelSplitter("git.stash.diff.splitter", 0.5f)
treeDiffSplitter.firstComponent = treePanel
setDiffPreviewInEditor(isEditorDiffPreview, force = true)
mainComponent.add(treeDiffSplitter, BorderLayout.CENTER)
Disposer.register(disposable, this)
}
private fun buildToolbar(): JComponent {
val toolbarGroup = DefaultActionGroup()
toolbarGroup.add(ActionManager.getInstance().getAction("Git.Stash.Toolbar"))
toolbarGroup.addSeparator()
toolbarGroup.add(ActionManager.getInstance().getAction(ChangesTree.GROUP_BY_ACTION_GROUP))
toolbarGroup.addSeparator()
toolbarGroup.addAll(TreeActionsToolbarPanel.createTreeActions(tree))
val toolbar = ActionManager.getInstance().createActionToolbar(GIT_STASH_UI_PLACE, toolbarGroup, true)
toolbar.setTargetComponent(tree)
return toolbar.component
}
fun setDiffPreviewInEditor(isInEditor: Boolean, force: Boolean = false) {
if (!force && (isInEditor == (editorTabPreview != null))) return
if (diffPreviewProcessor != null) Disposer.dispose(diffPreviewProcessor!!)
diffPreviewProcessor = GitStashDiffPreview(project, tree, this)
diffPreviewProcessor!!.toolbarWrapper.setVerticalSizeReferent(toolbar)
if (isInEditor) {
editorTabPreview = GitStashEditorDiffPreview(diffPreviewProcessor!!, tree, mainComponent)
treeDiffSplitter.secondComponent = null
}
else {
editorTabPreview = null
treeDiffSplitter.secondComponent = diffPreviewProcessor!!.component
}
}
override fun dispose() {
}
companion object {
const val GIT_STASH_UI_PLACE = "GitStashUiPlace"
}
} | apache-2.0 | 5699ce4ab403088550dd7c38f0e58437 | 37.927711 | 140 | 0.782972 | 4.708455 | false | false | false | false |
matrix-org/matrix-android-sdk | matrix-sdk-crypto/src/main/java/org/matrix/androidsdk/crypto/rest/model/crypto/KeyVerificationMac.kt | 1 | 2091 | /*
* Copyright 2019 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.matrix.androidsdk.crypto.rest.model.crypto
import com.google.gson.annotations.SerializedName
/**
* Sent by both devices to send the MAC of their device key to the other device.
*/
class KeyVerificationMac : SendToDeviceObject {
/**
* the ID of the transaction that the message is part of
*/
@SerializedName("transaction_id")
@JvmField
var transactionID: String? = null
/**
* A map of key ID to the MAC of the key, as an unpadded base64 string, calculated using the MAC key
*/
@JvmField
var mac: Map<String, String>? = null
/**
* The MAC of the comma-separated, sorted list of key IDs given in the mac property,
* as an unpadded base64 string, calculated using the MAC key.
* For example, if the mac property gives MACs for the keys ed25519:ABCDEFG and ed25519:HIJKLMN, then this property will
* give the MAC of the string “ed25519:ABCDEFG,ed25519:HIJKLMN”.
*/
@JvmField
var keys: String? = null
fun isValid(): Boolean {
if (transactionID.isNullOrBlank() || keys.isNullOrBlank() || mac.isNullOrEmpty()) {
return false
}
return true
}
companion object {
fun create(tid: String, mac: Map<String, String>, keys: String): KeyVerificationMac {
return KeyVerificationMac().apply {
this.transactionID = tid
this.mac = mac
this.keys = keys
}
}
}
} | apache-2.0 | ab6f2b8b7ab519ecf0115f61c67585ec | 31.625 | 125 | 0.659799 | 4.259184 | false | false | false | false |
ylemoigne/ReactKT | sampleprojects/demo-core/src/main/kotlin/fr/javatic/reactktSample/core/Utils.kt | 1 | 2008 | /*
* Copyright 2015 Yann Le Moigne
*
* 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 fr.javatic.reactktSample.core
import fr.javatic.reactktSample.core.interfaces.Todo
import kotlin.browser.localStorage
object Utils {
fun uuid(): String {
var uuid = "";
for (i in 0..32) {
val random = (Math.random() * 16).toInt().or(0)
if (i === 8 || i === 12 || i === 16 || i === 20) {
uuid += '-';
}
uuid += (if (i == 12) 4 else (if (i == 16) (random.and(3 or 8)) else random))
}
return uuid;
}
fun pluralize(count: Number, word: String): String {
return if (count == 1) word else word + "s"
}
fun store(namespace: String, dat: Any): Unit {
localStorage.setItem(namespace, JSON.stringify(dat));
}
fun store(namespace: String): List<Todo> {
val store = localStorage.getItem(namespace);
return if (store != null) {
val ar: Array<Todo> = JSON.parse(store)
ar.toList()
} else listOf();
}
// fun extend(...objs : any[]) : any {
// var newObj = {};
// for (var i = 0; i < objs.length; i++) {
// var obj = objs[i];
// for (var key in obj) {
// if (obj.hasOwnProperty(key)) {
// newObj[key] = obj[key];
// }
// }
// }
// return newObj;
// }
} | apache-2.0 | 2f921c79afe372ec7a3b64a82bf6dfe0 | 29.439394 | 89 | 0.539841 | 3.854127 | false | false | false | false |
Kotlin/kotlinx.coroutines | kotlinx-coroutines-core/jvm/test/exceptions/StackTraceRecoverySelectTest.kt | 1 | 1422 | /*
* Copyright 2016-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.exceptions
import kotlinx.coroutines.*
import kotlinx.coroutines.selects.*
import org.junit.*
import org.junit.rules.*
class StackTraceRecoverySelectTest : TestBase() {
@get:Rule
val name = TestName()
@Test
fun testSelectJoin() = runTest {
expect(1)
val result = runCatching { doSelect() }
expect(3)
verifyStackTrace("select/${name.methodName}", result.exceptionOrNull()!!)
finish(4)
}
private suspend fun doSelect(): Int {
val job = CompletableDeferred(Unit)
return select {
job.onJoin {
yield() // Hide the stackstrace
expect(2)
throw RecoverableTestException()
}
}
}
@Test
fun testSelectCompletedAwait() = runTest {
val deferred = CompletableDeferred<Unit>()
deferred.completeExceptionally(RecoverableTestException())
val result = runCatching { doSelectAwait(deferred) }
verifyStackTrace("select/${name.methodName}", result.exceptionOrNull()!!)
}
private suspend fun doSelectAwait(deferred: Deferred<Unit>): Int {
return select {
deferred.onAwait {
yield() // Hide the frame
42
}
}
}
}
| apache-2.0 | 24699cf5042a9d338033881051ca0b47 | 25.830189 | 102 | 0.600563 | 4.9375 | false | true | false | false |
NiuYongjie/coderepo | kotlin/src/basicType.kt | 1 | 4899 | package my.demo
/*
kotlin中,万物皆对象
*/
fun main(args: Array<String>) {
numbersExpression()
charactersExpression()
booleansExpression()
stringExpression()
}
/*
Numbers--数值型
与Java中数值型类似,但没有隐含的类型转换,
并且字符型在kotlin中不属于数值型,这点与Java不同
Type |Bit Width
Double| 64
Float| 32
Long| 64
Int| 32
Short| 16
Byte| 8
*/
fun numbersExpression() {
//数值型定义
val decimals = 1234
val longInt = 1234L
val hexaDecimals = 0x0F
val binaries = 0b000100101
val doublenum = 0.234 //default
val floatnum = 0.234F //0.234f
//使用下划线,增强数值型数据的可读性
val oneMillion = 1_000_000
val hexBytes = 0xFF_EC_DE_5E
val bytes = 0b11010010_01101001_10010100_10010010
/*
在Java中,数值型是原始类型,在使用过程能够自动装箱,拆箱(Box),而在kotlin中everything is object,即数值类型本身就是装箱的(Boxed)
*/
val a: Int = 1000
println(a === a)
val boxedA: Int? = a
val boxedB: Int? = a
println(boxedA === boxedB) //false
println(boxedA == boxedB) //true
/*
显示转换
kotlin中,小类型并不是大类型的特殊类型
*/
// val b:Byte = 1
// val a:Int = b 无法直接转换,只能采用显示转换,从小类型向大类型转换
val b: Byte = 1
val i: Int = b.toInt()
//在表达式中隐式转换
val l: Long = 1L + 3
/*
位运算符
operator | meaning
shl | shift left <<
shr | shift right >>
ushr | unsigned shift right >>>
and | bitwise and
or | bitwise or
xor | bitwise xor
inv | bitwise inversion
*/
val x = (1 shl 2) and 0x00_0F_F0_00 //shift left 左移
toPrintlnNumber(listOf(decimals, longInt, hexaDecimals, binaries, doublenum, floatnum, oneMillion, hexBytes, bytes,
x))
/*
浮点型
1. 是否相等: a == b a != b
2. 比较运算符: a < b a > b a <= b a >= b
3. 范围区间: a..b x in a..b x !in a..b
浮点运算遵循 IEEE 754
当浮点类型比较的对象不是静态类型时,应当实现equals和comparable接口,如:Any
通常约定:
NaN 和它自己相等
NaN 大于任何数值型数据
-0.0 比 0.0 小
*/
}
/**
* 输出数字集合
*/
fun toPrintlnNumber(list: List<Number>) {
for (item in list) {
println(item)
}
}
/**
* 字符型数据
*/
fun charactersExpression() {
/*
在kotlin中,字符型数据不能当做数字
*/
var c = 'a'
println(c)
// if (c == 1) { //错误:操作符不能作用与字符和数值型数据之间
//
// }
/*
字符类型用一对单引号括起来: '1'
Kotlin支持一下字符:\t , \b , \n , \r , \' , \" , \\ and \$
字符数字转数值型
fun decimalDigitValue(c: Char): Int{
if( c !in '0'..'9')
throw IllegalArgumentException("Out of Range");
return c.toInt() - '0'.toInt();
}
*/
}
/**
* 布尔型
*/
fun booleansExpression() {
/*
和其他数据类型一样,布尔型也是装箱的,其值为true false
*/
}
/**
* 数组演示
*/
fun arrayExpression() {
//1.创建数组
val array1 = arrayOf(1, 2, 3, 4, 5)
val array2 = arrayOfNulls<Int>(10)//创建大小为10的空数组
val array3 = Array(5, { i -> (i * i).toString() })//利用构造方法和小标创建数组
/*
在Kotlin中,数组是不可变的,也就是说不能讲Array<String> 指定给Array<Any>类型的数组
*/
val x: IntArray = intArrayOf(1, 2, 3, 4, 5, 6)
}
/**
* 字符串演示
*/
fun stringExpression() {
/*
字符串是不可变的,本质是一个字符数组,所以可以用下标的形式操作
*/
val str = "这是一个字符串示例"
for (c in str) {
println(c)
}
println("下标的形式操作字符串: " + str[3])
//转义字符串
val s = "HELLO WORLD!\n"
print(s)
//raw String
val text = """
fun (c in str)
println(c)
"""
print(text)
//通过"|"清楚掉行首的空格
val text2 = """
|Tell me and I forget.
| Teach me and I remember.
|Involve me and I learn.
|(Benjamin Franklin)
"""
println(text2)
println(text2.trimMargin("|"))
//字符串模板,通过$符号来替换掉模板中的值,甚至可以调用方法
val i = 10
val si = "i is $i"
println(si)
val ss = "abc"
val strs = "${ss.length} is $ss.length"
println(strs)
//输出$符号
println("""
${'$'} 9.99
""")
}
| gpl-3.0 | 30b1339d5bd3a2aa3feadc61053977a9 | 18.169903 | 119 | 0.521651 | 2.820714 | false | false | false | false |
Kotlin/kotlinx.coroutines | kotlinx-coroutines-core/common/test/CancellableContinuationTest.kt | 1 | 4198 | /*
* Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
@file:Suppress("NAMED_ARGUMENTS_NOT_ALLOWED") // KT-21913
package kotlinx.coroutines
import kotlin.coroutines.*
import kotlin.test.*
class CancellableContinuationTest : TestBase() {
@Test
fun testResumeWithExceptionAndResumeWithException() = runTest {
var continuation: Continuation<Unit>? = null
val job = launch {
try {
expect(2)
suspendCancellableCoroutine<Unit> { c ->
continuation = c
}
} catch (e: TestException) {
expect(3)
}
}
expect(1)
yield()
continuation!!.resumeWithException(TestException())
yield()
assertFailsWith<IllegalStateException> { continuation!!.resumeWithException(TestException()) }
job.join()
finish(4)
}
@Test
fun testResumeAndResumeWithException() = runTest {
var continuation: Continuation<Unit>? = null
val job = launch {
expect(2)
suspendCancellableCoroutine<Unit> { c ->
continuation = c
}
expect(3)
}
expect(1)
yield()
continuation!!.resume(Unit)
job.join()
assertFailsWith<IllegalStateException> { continuation!!.resumeWithException(TestException()) }
finish(4)
}
@Test
fun testResumeAndResume() = runTest {
var continuation: Continuation<Unit>? = null
val job = launch {
expect(2)
suspendCancellableCoroutine<Unit> { c ->
continuation = c
}
expect(3)
}
expect(1)
yield()
continuation!!.resume(Unit)
job.join()
assertFailsWith<IllegalStateException> { continuation!!.resume(Unit) }
finish(4)
}
/**
* Cancelling outer job may, in practise, race with attempt to resume continuation and resumes
* should be ignored. Here suspended coroutine is cancelled but then resumed with exception.
*/
@Test
fun testCancelAndResumeWithException() = runTest {
var continuation: Continuation<Unit>? = null
val job = launch {
try {
expect(2)
suspendCancellableCoroutine<Unit> { c ->
continuation = c
}
} catch (e: CancellationException) {
expect(3)
}
}
expect(1)
yield()
job.cancel() // Cancel job
yield()
continuation!!.resumeWithException(TestException()) // Should not fail
finish(4)
}
/**
* Cancelling outer job may, in practise, race with attempt to resume continuation and resumes
* should be ignored. Here suspended coroutine is cancelled but then resumed with exception.
*/
@Test
fun testCancelAndResume() = runTest {
var continuation: Continuation<Unit>? = null
val job = launch {
try {
expect(2)
suspendCancellableCoroutine<Unit> { c ->
continuation = c
}
} catch (e: CancellationException) {
expect(3)
}
}
expect(1)
yield()
job.cancel() // Cancel job
yield()
continuation!!.resume(Unit) // Should not fail
finish(4)
}
@Test
fun testCompleteJobWhileSuspended() = runTest {
expect(1)
val completableJob = Job()
val coroutineBlock = suspend {
assertFailsWith<CancellationException> {
suspendCancellableCoroutine<Unit> { cont ->
expect(2)
assertSame(completableJob, cont.context[Job])
completableJob.complete()
}
expectUnreached()
}
expect(3)
}
coroutineBlock.startCoroutine(Continuation(completableJob) {
assertEquals(Unit, it.getOrNull())
expect(4)
})
finish(5)
}
} | apache-2.0 | 170109ac8c1cbef739310609fc53a2f4 | 28.780142 | 102 | 0.540257 | 5.300505 | false | true | false | false |
leafclick/intellij-community | plugins/built-in-help/src/com/jetbrains/builtInHelp/search/HelpComplete.kt | 1 | 2467 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.builtInHelp.search
import com.google.gson.Gson
import com.intellij.openapi.diagnostic.Logger
import org.apache.commons.compress.utils.IOUtils
import org.apache.lucene.analysis.standard.StandardAnalyzer
import org.apache.lucene.index.DirectoryReader
import org.apache.lucene.search.spell.LuceneDictionary
import org.apache.lucene.search.suggest.analyzing.BlendedInfixSuggester
import org.apache.lucene.store.FSDirectory
import org.jetbrains.annotations.NotNull
import java.io.FileOutputStream
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
class HelpComplete {
companion object {
val resources = arrayOf("_0.cfe", "_0.cfs", "_0.si", "segments_1")
val PREFIX = "/search/"
val NOT_FOUND = "[]"
private val analyzer: StandardAnalyzer = StandardAnalyzer()
@NotNull
fun complete(query: String, maxHits: Int): String {
val indexDir: Path? = Files.createTempDirectory("search-index")
var indexDirectory: FSDirectory? = null
var reader: DirectoryReader? = null
var suggester: BlendedInfixSuggester? = null
if (indexDir != null)
try {
for (resourceName in resources) {
val input = HelpSearch::class.java.getResourceAsStream(
PREFIX + resourceName)
val fos: FileOutputStream = FileOutputStream(Paths.get(indexDir.toAbsolutePath().toString(), resourceName).toFile())
IOUtils.copy(input, fos)
fos.flush()
fos.close()
input.close()
}
indexDirectory = FSDirectory.open(indexDir)
reader = DirectoryReader.open(indexDirectory)
suggester = BlendedInfixSuggester(indexDirectory, analyzer)
suggester.build(LuceneDictionary(reader, "contents"))
val completionResults = suggester.lookup(query, maxHits, false, true)
return Gson().toJson(completionResults)
}
catch (e: Exception) {
Logger.getInstance(HelpComplete::class.java).error("Error searching help for $query", e)
}
finally {
suggester?.close()
indexDirectory?.close()
reader?.close()
for (f in indexDir.toFile().listFiles()) f.delete()
Files.delete(indexDir)
}
return NOT_FOUND
}
}
} | apache-2.0 | bd00bd5ed1f776ae444b798d11025533 | 34.257143 | 140 | 0.677746 | 4.358657 | false | false | false | false |
leafclick/intellij-community | platform/platform-tests/testSrc/com/intellij/internal/statistics/collector/SystemRuntimeCollectorTest.kt | 1 | 7404 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.internal.statistics.collector
import com.intellij.internal.statistic.collectors.fus.os.SystemRuntimeCollector
import com.intellij.internal.statistic.eventLog.FeatureUsageData
import com.intellij.testFramework.HeavyPlatformTestCase
import org.junit.Assert
import org.junit.Test
class SystemRuntimeCollectorTest : HeavyPlatformTestCase() {
@Test
fun `test round down method`() {
Assert.assertEquals(0, SystemRuntimeCollector.roundDown(0, 10, 30, 50, 100, 200))
Assert.assertEquals(0, SystemRuntimeCollector.roundDown(9, 10, 30, 50, 100, 200))
Assert.assertEquals(10, SystemRuntimeCollector.roundDown(10, 10, 30, 50, 100, 200))
Assert.assertEquals(10, SystemRuntimeCollector.roundDown(15, 10, 30, 50, 100, 200))
Assert.assertEquals(100, SystemRuntimeCollector.roundDown(100, 10, 30, 50, 100, 200))
Assert.assertEquals(100, SystemRuntimeCollector.roundDown(105, 10, 30, 50, 100, 200))
Assert.assertEquals(100, SystemRuntimeCollector.roundDown(150, 10, 30, 50, 100, 200))
Assert.assertEquals(50, SystemRuntimeCollector.roundDown(99, 10, 30, 50, 100, 200))
Assert.assertEquals(200, SystemRuntimeCollector.roundDown(200, 10, 30, 50, 100, 200))
Assert.assertEquals(200, SystemRuntimeCollector.roundDown(201, 10, 30, 50, 100, 200))
Assert.assertEquals(200, SystemRuntimeCollector.roundDown(2010, 10, 30, 50, 100, 200))
Assert.assertEquals(200, SystemRuntimeCollector.roundDown(Long.MAX_VALUE, 10, 30, 50, 100, 200))
Assert.assertEquals(0, SystemRuntimeCollector.roundDown(4, 0, 30, 50, 100, 200))
Assert.assertEquals(30, SystemRuntimeCollector.roundDown(30, 0, 30, 50, 100, 200))
Assert.assertEquals(30, SystemRuntimeCollector.roundDown(31, 0, 30, 50, 100, 200))
Assert.assertEquals(-1, SystemRuntimeCollector.roundDown(31, -1, 30, 50, 100, 200))
Assert.assertEquals(-1, SystemRuntimeCollector.roundDown(31, -10, 30, 50, 100, 200))
}
@Test
fun `test convert xmx option`() {
//512, 750, 1000, 1024, 1500, 2000, 2048, 3000, 4000, 4096, 6000, 8000
assertMb("Xmx", 0, SystemRuntimeCollector.convertOptionToData("-Xmx511m"))
assertMb("Xmx", 0, SystemRuntimeCollector.convertOptionToData("-Xmx10m"))
assertMb("Xmx", 512, SystemRuntimeCollector.convertOptionToData("-Xmx512m"))
assertMb("Xmx", 512, SystemRuntimeCollector.convertOptionToData("-Xmx550M"))
assertMb("Xmx", 512, SystemRuntimeCollector.convertOptionToData("-Xmx530"))
assertMb("Xmx", 512, SystemRuntimeCollector.convertOptionToData("-Xmx524288K"))
assertMb("Xmx", 512, SystemRuntimeCollector.convertOptionToData("-Xmx524289k"))
assertMb("Xmx", 512, SystemRuntimeCollector.convertOptionToData("-Xmx536870913B"))
assertMb("Xmx", 512, SystemRuntimeCollector.convertOptionToData("-Xmx536870923b"))
assertMb("Xmx", 750, SystemRuntimeCollector.convertOptionToData("-Xmx750m"))
assertMb("Xmx", 750, SystemRuntimeCollector.convertOptionToData("-Xmx750M"))
assertMb("Xmx", 750, SystemRuntimeCollector.convertOptionToData("-Xmx999m"))
assertMb("Xmx", 1024, SystemRuntimeCollector.convertOptionToData("-Xmx1024m"))
assertMb("Xmx", 1024, SystemRuntimeCollector.convertOptionToData("-Xmx1050M"))
assertMb("Xmx", 1024, SystemRuntimeCollector.convertOptionToData("-Xmx1073"))
assertMb("Xmx", 1024, SystemRuntimeCollector.convertOptionToData("-Xmx1048576k"))
assertMb("Xmx", 1024, SystemRuntimeCollector.convertOptionToData("-Xmx1048576K"))
assertMb("Xmx", 1024, SystemRuntimeCollector.convertOptionToData("-Xmx1048576K"))
assertMb("Xmx", 1024, SystemRuntimeCollector.convertOptionToData("-Xmx1073741824b"))
assertMb("Xmx", 1024, SystemRuntimeCollector.convertOptionToData("-Xmx1073741824B"))
assertMb("Xmx", 1024, SystemRuntimeCollector.convertOptionToData("-Xmx1G"))
assertMb("Xmx", 2048, SystemRuntimeCollector.convertOptionToData("-Xmx2g"))
assertMb("Xmx", 2048, SystemRuntimeCollector.convertOptionToData("-Xmx2G"))
assertMb("Xmx", 8000, SystemRuntimeCollector.convertOptionToData("-Xmx8000M"))
assertMb("Xmx", 8000, SystemRuntimeCollector.convertOptionToData("-Xmx8G"))
assertMb("Xmx", 8000, SystemRuntimeCollector.convertOptionToData("-Xmx9000m"))
assertMb("Xmx", 8000, SystemRuntimeCollector.convertOptionToData("-Xmx10G"))
assertMb("Xmx", 8000, SystemRuntimeCollector.convertOptionToData("-Xmx100G"))
}
@Test
fun `test convert xms option`() {
//64, 128, 256, 512
assertMb("Xms", 64, SystemRuntimeCollector.convertOptionToData("-Xms64m"))
assertMb("Xms", 128, SystemRuntimeCollector.convertOptionToData("-Xms129m"))
assertMb("Xms", 128, SystemRuntimeCollector.convertOptionToData("-Xms136"))
assertMb("Xms", 128, SystemRuntimeCollector.convertOptionToData("-Xms132096k"))
assertMb("Xms", 512, SystemRuntimeCollector.convertOptionToData("-Xms750m"))
assertMb("Xms", 512, SystemRuntimeCollector.convertOptionToData("-Xms750M"))
assertMb("Xms", 512, SystemRuntimeCollector.convertOptionToData("-Xms2G"))
}
@Test
fun `test convert SoftRefLRUPolicyMSPerMB option`() {
//50, 100
assertMb("SoftRefLRUPolicyMSPerMB", 0, SystemRuntimeCollector.convertOptionToData("-XX:SoftRefLRUPolicyMSPerMB=10m"))
assertMb("SoftRefLRUPolicyMSPerMB", 50, SystemRuntimeCollector.convertOptionToData("-XX:SoftRefLRUPolicyMSPerMB=50m"))
assertMb("SoftRefLRUPolicyMSPerMB", 50, SystemRuntimeCollector.convertOptionToData("-XX:SoftRefLRUPolicyMSPerMB=55M"))
assertMb("SoftRefLRUPolicyMSPerMB", 50, SystemRuntimeCollector.convertOptionToData("-XX:SoftRefLRUPolicyMSPerMB55M"))
assertMb("SoftRefLRUPolicyMSPerMB", 50, SystemRuntimeCollector.convertOptionToData("-XX:SoftRefLRUPolicyMSPerMB=101376k"))
assertMb("SoftRefLRUPolicyMSPerMB", 100, SystemRuntimeCollector.convertOptionToData("-XX:SoftRefLRUPolicyMSPerMB=104857600"))
assertMb("SoftRefLRUPolicyMSPerMB", 100, SystemRuntimeCollector.convertOptionToData("-XX:SoftRefLRUPolicyMSPerMB=104857600b"))
assertMb("SoftRefLRUPolicyMSPerMB", 100, SystemRuntimeCollector.convertOptionToData("-XX:SoftRefLRUPolicyMSPerMB=204857600b"))
assertMb("SoftRefLRUPolicyMSPerMB", 100, SystemRuntimeCollector.convertOptionToData("-XX:SoftRefLRUPolicyMSPerMB=200G"))
}
@Test
fun `test convert ReservedCodeCacheSize option`() {
//240, 300, 400, 500
assertMb("ReservedCodeCacheSize", 0, SystemRuntimeCollector.convertOptionToData("-XX:ReservedCodeCacheSize=10"))
assertMb("ReservedCodeCacheSize", 240, SystemRuntimeCollector.convertOptionToData("-XX:ReservedCodeCacheSize=250"))
assertMb("ReservedCodeCacheSize", 240, SystemRuntimeCollector.convertOptionToData("-XX:ReservedCodeCacheSize=250M"))
assertMb("ReservedCodeCacheSize", 500, SystemRuntimeCollector.convertOptionToData("-XX:ReservedCodeCacheSize=500m"))
assertMb("ReservedCodeCacheSize", 500, SystemRuntimeCollector.convertOptionToData("-XX:ReservedCodeCacheSize=1500m"))
assertMb("ReservedCodeCacheSize", 500, SystemRuntimeCollector.convertOptionToData("-XX:ReservedCodeCacheSize=1536000K"))
}
private fun assertMb(name: String, sizeMb: Long, actual: FeatureUsageData?) {
Assert.assertNotNull(actual)
Assert.assertEquals(FeatureUsageData().addData("name", name).addData("value", sizeMb), actual)
}
} | apache-2.0 | 12425eff393d689f56affb4c535d69a7 | 63.391304 | 140 | 0.7708 | 4.095133 | false | true | false | false |
moko256/twicalico | app/src/main/java/com/github/moko256/twitlatte/intent/IntentAppExcluder.kt | 1 | 3053 | /*
* 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.intent
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import com.github.moko256.twitlatte.R
/**
* Created by moko256 on 2018/12/14.
*
* @author moko256
*/
@SuppressLint("PrivateResource")
fun Intent.excludeOwnApp(context: Context, packageManager: PackageManager): Intent = run {
val intents = packageManager
.queryIntentActivities(
this,
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
PackageManager.MATCH_ALL
} else {
PackageManager.MATCH_DEFAULT_ONLY
}
)
.also {
if (it.size == 1) {
it.addAll(
packageManager
.queryIntentActivities(
Intent(Intent.ACTION_VIEW, Uri.parse("https://")),
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
PackageManager.MATCH_ALL
} else {
PackageManager.MATCH_DEFAULT_ONLY
}
)
)
}
}
.asSequence()
.map { it.activityInfo.packageName }
.distinct()
.filter {
it != context.packageName
}.map {
Intent(this).setPackage(it)
}.toMutableList()
val openWithText = context.getString(R.string.abc_activitychooserview_choose_application)
when {
intents.isEmpty() -> {
Intent.createChooser(Intent(), openWithText)
}
intents.size == 1 -> {
intents[0]
}
else -> {
Intent.createChooser(
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Intent()
} else {
intents.removeAt(0)
},
openWithText
).putExtra(Intent.EXTRA_INITIAL_INTENTS, intents.toTypedArray())
}
}
} | apache-2.0 | 27c520438a6060df5038e4d6d1ddd6ad | 33.704545 | 97 | 0.512611 | 5.218803 | false | false | false | false |
romannurik/muzei | wearable/src/main/java/com/google/android/apps/muzei/MuzeiProviderItem.kt | 1 | 6368 | /*
* Copyright 2020 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.muzei
import android.app.Application
import android.content.ComponentName
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStoreOwner
import androidx.lifecycle.get
import androidx.lifecycle.liveData
import androidx.lifecycle.switchMap
import androidx.lifecycle.viewModelScope
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import androidx.wear.widget.RoundedDrawable
import com.google.android.apps.muzei.datalayer.ActivateMuzeiReceiver
import com.google.android.apps.muzei.featuredart.BuildConfig
import com.google.android.apps.muzei.room.Provider
import com.google.android.apps.muzei.sync.ProviderManager
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.launch
import net.nurik.roman.muzei.R
import net.nurik.roman.muzei.databinding.MuzeiProviderItemBinding
data class ProviderData(
val provider: Provider,
val icon: Drawable,
val label: CharSequence,
val description: String,
val settingsActivity: ComponentName?
)
class MuzeiProviderViewModel(application: Application) : AndroidViewModel(application) {
val providerLiveData = ProviderManager.getInstance(getApplication()).switchMap { provider ->
liveData {
val app = getApplication<Application>()
if (provider != null) {
val pm = app.packageManager
@Suppress("DEPRECATION")
val providerInfo = pm.resolveContentProvider(provider.authority,
PackageManager.GET_META_DATA)
if (providerInfo != null) {
val icon = providerInfo.loadIcon(pm)
val label = providerInfo.loadLabel(pm)
val settingsActivity = providerInfo.metaData?.getString("settingsActivity")?.run {
ComponentName(providerInfo.packageName, this)
}
emit(ProviderData(provider, icon, label,
ProviderManager.getDescription(app, provider.authority),
settingsActivity))
}
} else {
viewModelScope.launch(NonCancellable) {
ProviderManager.select(app, BuildConfig.FEATURED_ART_AUTHORITY)
ActivateMuzeiReceiver.checkForPhoneApp(app)
}
}
}
}
}
class MuzeiProviderViewHolder(
private val binding: MuzeiProviderItemBinding
) : RecyclerView.ViewHolder(binding.root) {
private val context = binding.root.context
init {
binding.provider.setOnClickListener {
context.startActivity(Intent(context, ChooseProviderActivity::class.java))
}
binding.settings.setCompoundDrawablesRelative(RoundedDrawable().apply {
isClipEnabled = true
radius = context.resources.getDimensionPixelSize(R.dimen.art_detail_open_on_phone_radius)
backgroundColor = ContextCompat.getColor(context, R.color.theme_primary)
drawable = ContextCompat.getDrawable(context, R.drawable.ic_provider_settings)
bounds = Rect(0, 0, radius * 2, radius * 2)
}, null, null, null)
}
fun bind(providerData: ProviderData) = binding.run {
val context = root.context
val size = context.resources.getDimensionPixelSize(R.dimen.choose_provider_image_size)
providerData.icon.bounds = Rect(0, 0, size, size)
provider.setCompoundDrawablesRelative(providerData.icon,
null, null, null)
provider.text = providerData.label
providerDescription.isGone = providerData.description.isBlank()
providerDescription.text = providerData.description
settings.isVisible = providerData.settingsActivity != null
settings.setOnClickListener {
if (providerData.settingsActivity != null) {
context.startActivity(Intent().apply {
component = providerData.settingsActivity
})
}
}
}
}
class MuzeiProviderAdapter<O>(owner: O) : ListAdapter<ProviderData, MuzeiProviderViewHolder>(
object : DiffUtil.ItemCallback<ProviderData>() {
override fun areItemsTheSame(
providerData1: ProviderData,
providerData2: ProviderData
) = providerData1.provider.authority == providerData2.provider.authority
override fun areContentsTheSame(
providerData1: ProviderData,
providerData2: ProviderData
) = providerData1.provider == providerData2.provider
}
) where O : LifecycleOwner, O : ViewModelStoreOwner {
init {
val viewModel: MuzeiProviderViewModel = ViewModelProvider(owner).get()
viewModel.providerLiveData.observe(owner) { provider ->
submitList(listOf(provider))
}
}
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
) = MuzeiProviderViewHolder(MuzeiProviderItemBinding.inflate(
LayoutInflater.from(parent.context), parent, false))
override fun onBindViewHolder(holder: MuzeiProviderViewHolder, position: Int) {
holder.bind(getItem(position))
}
} | apache-2.0 | 48b46e00a072717d1d661ee7076dd58b | 40.090323 | 102 | 0.686715 | 5.057983 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/annotations/kt10136.kt | 2 | 578 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// WITH_RUNTIME
annotation class A
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
annotation class B(val items: Array<A> = arrayOf(A()))
@B
class C
fun box(): String {
val bClass = B::class.java
val cClass = C::class.java
val items = cClass.getAnnotation(bClass).items
assert(items.size == 1) { "Expected: [A()], got ${items.asList()}" }
assert(items[0] is A) { "Expected: [A()], got ${items.asList()}" }
return "OK"
}
| apache-2.0 | fa394284dd1c7a7f734aaed751b14029 | 23.083333 | 72 | 0.66436 | 3.4 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/llvm/IrToBitcode.kt | 1 | 111864 | /*
* 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.
*/
package org.jetbrains.kotlin.backend.konan.llvm
import kotlinx.cinterop.*
import llvm.*
import org.jetbrains.kotlin.backend.common.descriptors.allParameters
import org.jetbrains.kotlin.backend.common.descriptors.isSuspend
import org.jetbrains.kotlin.backend.common.ir.ir2string
import org.jetbrains.kotlin.backend.konan.*
import org.jetbrains.kotlin.backend.konan.descriptors.*
import org.jetbrains.kotlin.backend.konan.ir.*
import org.jetbrains.kotlin.backend.konan.objcexport.ObjCExport
import org.jetbrains.kotlin.backend.konan.optimizations.*
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.ir.IrElement
import org.jetbrains.kotlin.ir.IrStatement
import org.jetbrains.kotlin.ir.SourceManager
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.declarations.impl.IrValueParameterImpl
import org.jetbrains.kotlin.ir.descriptors.IrBuiltinOperatorDescriptorBase
import org.jetbrains.kotlin.ir.expressions.*
import org.jetbrains.kotlin.ir.expressions.impl.IrReturnableBlockImpl
import org.jetbrains.kotlin.ir.util.getArguments
import org.jetbrains.kotlin.ir.visitors.IrElementVisitorVoid
import org.jetbrains.kotlin.ir.visitors.acceptChildrenVoid
import org.jetbrains.kotlin.ir.visitors.acceptVoid
import org.jetbrains.kotlin.konan.target.KonanTarget
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.typeUtil.isNothing
import org.jetbrains.kotlin.types.typeUtil.isPrimitiveNumberType
import org.jetbrains.kotlin.types.typeUtil.isTypeParameter
import org.jetbrains.kotlin.types.typeUtil.isUnit
internal fun emitLLVM(context: Context) {
val irModule = context.irModule!!
// Note that we don't set module target explicitly.
// It is determined by the target of runtime.bc
// (see Llvm class in ContextUtils)
// Which in turn is determined by the clang flags
// used to compile runtime.bc.
val llvmModule = LLVMModuleCreateWithName("out")!! // TODO: dispose
context.llvmModule = llvmModule
context.debugInfo.builder = DICreateBuilder(llvmModule)
context.llvmDeclarations = createLlvmDeclarations(context)
val phaser = PhaseManager(context)
phaser.phase(KonanPhase.RTTI) {
irModule.acceptVoid(RTTIGeneratorVisitor(context))
}
generateDebugInfoHeader(context)
var moduleDFG: ModuleDFG? = null
phaser.phase(KonanPhase.BUILD_DFG) {
moduleDFG = ModuleDFGBuilder(context, irModule).build()
}
phaser.phase(KonanPhase.SERIALIZE_DFG) {
DFGSerializer.serialize(context, moduleDFG!!)
}
@Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
var externalModulesDFG: ExternalModulesDFG? = null
phaser.phase(KonanPhase.DESERIALIZE_DFG) {
externalModulesDFG = DFGSerializer.deserialize(context, moduleDFG!!.symbolTable.privateTypeIndex, moduleDFG!!.symbolTable.privateFunIndex)
}
val lifetimes = mutableMapOf<IrElement, Lifetime>()
val codegenVisitor = CodeGeneratorVisitor(context, lifetimes)
phaser.phase(KonanPhase.ESCAPE_ANALYSIS) {
val callGraph = CallGraphBuilder(context, moduleDFG!!, externalModulesDFG!!).build()
EscapeAnalysis.computeLifetimes(moduleDFG!!, externalModulesDFG!!, callGraph, lifetimes)
}
phaser.phase(KonanPhase.CODEGEN) {
irModule.acceptVoid(codegenVisitor)
}
if (context.shouldContainDebugInfo()) {
DIFinalize(context.debugInfo.builder)
}
}
internal fun verifyModule(llvmModule: LLVMModuleRef, current: String = "") {
memScoped {
val errorRef = allocPointerTo<ByteVar>()
// TODO: use LLVMDisposeMessage() on errorRef, once possible in interop.
if (LLVMVerifyModule(
llvmModule, LLVMVerifierFailureAction.LLVMPrintMessageAction, errorRef.ptr) == 1) {
if (current.isNotEmpty())
println("Error in $current")
LLVMDumpModule(llvmModule)
throw Error("Invalid module")
}
}
}
internal class RTTIGeneratorVisitor(context: Context) : IrElementVisitorVoid {
val generator = RTTIGenerator(context)
val kotlinObjCClassInfoGenerator = KotlinObjCClassInfoGenerator(context)
override fun visitElement(element: IrElement) {
element.acceptChildrenVoid(this)
}
override fun visitClass(declaration: IrClass) {
super.visitClass(declaration)
val descriptor = declaration.descriptor
if (descriptor.isIntrinsic) {
// do not generate any code for intrinsic classes as they require special handling
return
}
generator.generate(descriptor)
if (descriptor.isKotlinObjCClass()) {
kotlinObjCClassInfoGenerator.generate(declaration)
}
}
}
//-------------------------------------------------------------------------//
/**
* Defines how to generate context-dependent operations.
*/
internal interface CodeContext {
/**
* Generates `return` [value] operation.
*
* @param value may be null iff target type is `Unit`.
*/
fun genReturn(target: CallableDescriptor, value: LLVMValueRef?)
fun genBreak(destination: IrBreak)
fun genContinue(destination: IrContinue)
fun genCall(function: LLVMValueRef, args: List<LLVMValueRef>, resultLifetime: Lifetime): LLVMValueRef
fun genThrow(exception: LLVMValueRef)
/**
* Declares the variable.
* @return index of declared variable.
*/
fun genDeclareVariable(descriptor: VariableDescriptor, value: LLVMValueRef?, variableLocation: VariableDebugLocation?): Int
/**
* @return index of variable declared before, or -1 if no such variable has been declared yet.
*/
fun getDeclaredVariable(descriptor: VariableDescriptor): Int
/**
* Generates the code to obtain a value available in this context.
*
* @return the requested value
*/
fun genGetValue(descriptor: ValueDescriptor): LLVMValueRef
/**
* Returns owning function scope.
*
* @return the requested value
*/
fun functionScope(): CodeContext?
/**
* Returns owning file scope.
*
* @return the requested value if in the file scope or null.
*/
fun fileScope(): CodeContext?
/**
* Returns owning class scope [ClassScope].
*
* @returns the requested value if in the class scope or null.
*/
fun classScope(): CodeContext?
fun addResumePoint(bbLabel: LLVMBasicBlockRef): Int
}
//-------------------------------------------------------------------------//
internal class CodeGeneratorVisitor(val context: Context, val lifetimes: Map<IrElement, Lifetime>) : IrElementVisitorVoid {
val codegen = CodeGenerator(context)
//-------------------------------------------------------------------------//
// TODO: consider eliminating mutable state
private var currentCodeContext: CodeContext = TopLevelCodeContext
/**
* Fake [CodeContext] that doesn't support any operation.
*
* During function code generation [FunctionScope] should be set up.
*/
private object TopLevelCodeContext : CodeContext {
private fun unsupported(any: Any? = null): Nothing = throw UnsupportedOperationException(any?.toString() ?: "")
override fun genReturn(target: CallableDescriptor, value: LLVMValueRef?) = unsupported(target)
override fun genBreak(destination: IrBreak) = unsupported()
override fun genContinue(destination: IrContinue) = unsupported()
override fun genCall(function: LLVMValueRef, args: List<LLVMValueRef>, resultLifetime: Lifetime) = unsupported(function)
override fun genThrow(exception: LLVMValueRef) = unsupported()
override fun genDeclareVariable(descriptor: VariableDescriptor, value: LLVMValueRef?, variableLocation: VariableDebugLocation?) = unsupported(descriptor)
override fun getDeclaredVariable(descriptor: VariableDescriptor) = -1
override fun genGetValue(descriptor: ValueDescriptor) = unsupported(descriptor)
override fun functionScope(): CodeContext? = null
override fun fileScope(): CodeContext? = null
override fun classScope(): CodeContext? = null
override fun addResumePoint(bbLabel: LLVMBasicBlockRef) = unsupported(bbLabel)
}
/**
* The [CodeContext] which can define some operations and delegate other ones to [outerContext]
*/
private abstract class InnerScope(val outerContext: CodeContext) : CodeContext by outerContext
/**
* Convenient [InnerScope] implementation that is bound to the [currentCodeContext].
*/
private abstract inner class InnerScopeImpl : InnerScope(currentCodeContext)
/**
* Executes [block] with [codeContext] substituted as [currentCodeContext].
*/
private inline fun <R> using(codeContext: CodeContext?, block: () -> R): R {
val oldCodeContext = currentCodeContext
if (codeContext != null) {
currentCodeContext = codeContext
}
try {
return block()
} finally {
currentCodeContext = oldCodeContext
}
}
private fun appendCAdapters() {
CAdapterGenerator(context, codegen).generateBindings()
}
//-------------------------------------------------------------------------//
override fun visitElement(element: IrElement) {
TODO(ir2string(element))
}
//-------------------------------------------------------------------------//
override fun visitModuleFragment(declaration: IrModuleFragment) {
context.log{"visitModule : ${ir2string(declaration)}"}
declaration.acceptChildrenVoid(this)
// Note: it is here because it also generates some bitcode.
ObjCExport(context).produceObjCFramework()
appendLlvmUsed("llvm.used", context.llvm.usedFunctions + context.llvm.usedGlobals)
appendLlvmUsed("llvm.compiler.used", context.llvm.compilerUsedGlobals)
appendStaticInitializers(context.llvm.staticInitializers)
appendEntryPointSelector(findMainEntryPoint(context))
if (context.isDynamicLibrary) {
appendCAdapters()
}
}
//-------------------------------------------------------------------------//
val kVoidFuncType = LLVMFunctionType(LLVMVoidType(), null, 0, 0)
val kInitFuncType = LLVMFunctionType(LLVMVoidType(), cValuesOf(LLVMInt32Type()), 1, 0)
val kNodeInitType = LLVMGetTypeByName(context.llvmModule, "struct.InitNode")!!
//-------------------------------------------------------------------------//
private fun createInitBody(initName: String): LLVMValueRef {
val initFunction = LLVMAddFunction(context.llvmModule, initName, kInitFuncType)!! // create LLVM function
generateFunction(codegen, initFunction) {
using(FunctionScope(initFunction, it)) {
val bbInit = basicBlock("init", null)
val bbDeinit = basicBlock("deinit", null)
condBr(functionGenerationContext.icmpEq(LLVMGetParam(initFunction, 0)!!, kImmZero), bbDeinit, bbInit)
appendingTo(bbDeinit) {
context.llvm.fileInitializers.forEach {
val descriptor = it.descriptor
if (descriptor.type.isValueType())
return@forEach // Is not a subject for memory management.
val address = context.llvmDeclarations.forStaticField(descriptor).storage
storeAny(codegen.kNullObjHeaderPtr, address)
}
objects.forEach { storeAny(codegen.kNullObjHeaderPtr, it) }
ret(null)
}
appendingTo(bbInit) {
context.llvm.fileInitializers
.forEach {
if (it.initializer?.expression !is IrConst<*>?) {
val initialization = evaluateExpression(it.initializer!!.expression)
val address = context.llvmDeclarations.forStaticField(it.descriptor).storage
storeAny(initialization, address)
}
}
ret(null)
}
}
}
return initFunction
}
//-------------------------------------------------------------------------//
// Creates static struct InitNode $nodeName = {$initName, NULL};
private fun createInitNode(initFunction: LLVMValueRef, nodeName: String): LLVMValueRef {
val nextInitNode = LLVMConstNull(pointerType(kNodeInitType)) // Set InitNode.next = NULL.
val argList = cValuesOf(initFunction, nextInitNode) // Construct array of args.
val initNode = LLVMConstNamedStruct(kNodeInitType, argList, 2)!! // Create static object of class InitNode.
return context.llvm.staticData.placeGlobal(nodeName, constPointer(initNode)).llvmGlobal // Put the object in global var with name "nodeName".
}
//-------------------------------------------------------------------------//
private fun createInitCtor(ctorName: String, initNodePtr: LLVMValueRef) {
val ctorFunction = LLVMAddFunction(context.llvmModule, ctorName, kVoidFuncType)!! // Create constructor function.
generateFunction(codegen, ctorFunction) {
call(context.llvm.appendToInitalizersTail, listOf(initNodePtr)) // Add node to the tail of initializers list.
ret(null)
}
context.llvm.staticInitializers.add(ctorFunction) // Push newly created constructor in staticInitializers list.
}
//-------------------------------------------------------------------------//
override fun visitFile(declaration: IrFile) {
// TODO: collect those two in one place.
context.llvm.fileInitializers.clear()
objects.clear()
using(FileScope(declaration)) {
declaration.acceptChildrenVoid(this)
if (context.llvm.fileInitializers.isEmpty() && objects.isEmpty())
return
// Create global initialization records.
val fileName = declaration.name.takeLastWhile { it != '/' }.dropLastWhile { it != '.' }.dropLast(1)
val initName = "${fileName}_init_${context.llvm.globalInitIndex}"
val nodeName = "${fileName}_node_${context.llvm.globalInitIndex}"
// Make the name prefix easily parsable for the platforms lacking
// llvm.global_ctors mechanism (such as WASM).
val ctorName = "Konan_global_ctor_${fileName}_${context.llvm.globalInitIndex++}"
val initFunction = createInitBody(initName)
val initNode = createInitNode(initFunction, nodeName)
createInitCtor(ctorName, initNode)
}
}
//-------------------------------------------------------------------------//
private inner class LoopScope(val loop: IrLoop) : InnerScopeImpl() {
val loopExit = functionGenerationContext.basicBlock("loop_exit", loop.condition.startLocation)
val loopCheck = functionGenerationContext.basicBlock("loop_check", loop.condition.startLocation)
override fun genBreak(destination: IrBreak) {
if (destination.loop == loop)
functionGenerationContext.br(loopExit)
else
super.genBreak(destination)
}
override fun genContinue(destination: IrContinue) {
if (destination.loop == loop)
functionGenerationContext.br(loopCheck)
else
super.genContinue(destination)
}
}
//-------------------------------------------------------------------------//
fun evaluateBreak(destination: IrBreak): LLVMValueRef {
currentCodeContext.genBreak(destination)
return codegen.kNothingFakeValue
}
//-------------------------------------------------------------------------//
fun evaluateContinue(destination: IrContinue): LLVMValueRef {
currentCodeContext.genContinue(destination)
return codegen.kNothingFakeValue
}
//-------------------------------------------------------------------------//
override fun visitConstructor(declaration: IrConstructor) {
context.log{"visitConstructor : ${ir2string(declaration)}"}
if (declaration.descriptor.containingDeclaration.isIntrinsic) {
// Do not generate any ctors for intrinsic classes.
return
}
val constructorDescriptor = declaration.descriptor
val classDescriptor = constructorDescriptor.constructedClass
if (constructorDescriptor.isPrimary) {
if (DescriptorUtils.isObject(classDescriptor)) {
if (!classDescriptor.isUnit()) {
val objectPtr = getObjectInstanceStorage(classDescriptor)
LLVMSetInitializer(objectPtr, codegen.kNullObjHeaderPtr)
}
}
}
visitFunction(declaration)
}
//-------------------------------------------------------------------------//
override fun visitAnonymousInitializer(declaration: IrAnonymousInitializer) {
context.log{"visitAnonymousInitializer : ${ir2string(declaration)}"}
}
//-------------------------------------------------------------------------//
/**
* The scope of variable visibility.
*/
private inner class VariableScope : InnerScopeImpl() {
override fun genDeclareVariable(descriptor: VariableDescriptor, value: LLVMValueRef?, variableLocation: VariableDebugLocation?): Int {
return functionGenerationContext.vars.createVariable(descriptor, value, variableLocation)
}
override fun getDeclaredVariable(descriptor: VariableDescriptor): Int {
val index = functionGenerationContext.vars.indexOf(descriptor)
return if (index < 0) super.getDeclaredVariable(descriptor) else return index
}
override fun genGetValue(descriptor: ValueDescriptor): LLVMValueRef {
val index = functionGenerationContext.vars.indexOf(descriptor)
if (index < 0) {
return super.genGetValue(descriptor)
} else {
return functionGenerationContext.vars.load(index)
}
}
}
/**
* The scope of parameter visibility.
*/
private open inner class ParameterScope(
function: IrFunction?,
private val functionGenerationContext: FunctionGenerationContext): InnerScopeImpl() {
val parameters = bindParameters(function?.descriptor)
init {
if (function != null) {
parameters.forEach{
val descriptor = it.key
val ir = when {
descriptor is ValueParameterDescriptor -> function.getIrValueParameter(descriptor)
descriptor is ReceiverParameterDescriptor && function.extensionReceiverParameter?.descriptor == descriptor -> function.extensionReceiverParameter!!
descriptor is ReceiverParameterDescriptor && function.dispatchReceiverParameter?.descriptor == descriptor-> function.dispatchReceiverParameter!!
function.descriptor is ClassConstructorDescriptor && (function.descriptor as ClassConstructorDescriptor).constructedClass.thisAsReceiverParameter == descriptor-> IrValueParameterImpl(function.startOffset, function.startOffset, object: IrDeclarationOriginImpl("THIS"){}, descriptor)
else -> TODO()
}
val local = functionGenerationContext.vars.createParameter(descriptor,
debugInfoIfNeeded(function, ir))
functionGenerationContext.mapParameterForDebug(local, it.value)
}
}
}
override fun genGetValue(descriptor: ValueDescriptor): LLVMValueRef {
val index = functionGenerationContext.vars.indexOf(descriptor)
if (index < 0) {
return super.genGetValue(descriptor)
} else {
return functionGenerationContext.vars.load(index)
}
}
}
/**
* The [CodeContext] enclosing the entire function body.
*/
private inner class FunctionScope (val declaration: IrFunction?, val functionGenerationContext: FunctionGenerationContext) : InnerScopeImpl() {
constructor(llvmFunction:LLVMValueRef, functionGenerationContext: FunctionGenerationContext):this(null, functionGenerationContext) {
this.llvmFunction = llvmFunction
}
var llvmFunction:LLVMValueRef? = declaration?.let{
codegen.llvmFunction(declaration.descriptor)
}
override fun genReturn(target: CallableDescriptor, value: LLVMValueRef?) {
if (declaration == null || target == declaration.descriptor) {
if (target.returnsUnit()) {
assert (value == null)
functionGenerationContext.ret(null)
} else {
functionGenerationContext.ret(value!!)
}
} else {
super.genReturn(target, value)
}
}
override fun genCall(function: LLVMValueRef, args: List<LLVMValueRef>, resultLifetime: Lifetime) =
functionGenerationContext.callAtFunctionScope(function, args, resultLifetime)
override fun genThrow(exception: LLVMValueRef) {
val objHeaderPtr = functionGenerationContext.bitcast(codegen.kObjHeaderPtr, exception)
val args = listOf(objHeaderPtr)
this.genCall(context.llvm.throwExceptionFunction, args, Lifetime.IRRELEVANT)
functionGenerationContext.unreachable()
}
override fun functionScope(): CodeContext = this
}
private val functionGenerationContext
get() = (currentCodeContext.functionScope() as FunctionScope).functionGenerationContext
/**
* Binds LLVM function parameters to IR parameter descriptors.
*/
private fun bindParameters(descriptor: FunctionDescriptor?): Map<ParameterDescriptor, LLVMValueRef> {
if (descriptor == null) return emptyMap()
val parameterDescriptors = descriptor.allParameters
return parameterDescriptors.mapIndexed { i, parameterDescriptor ->
val parameter = codegen.param(descriptor, i)
assert(codegen.getLLVMType(parameterDescriptor.type) == parameter.type)
parameterDescriptor to parameter
}.toMap()
}
override fun visitFunction(declaration: IrFunction) {
context.log{"visitFunction : ${ir2string(declaration)}"}
val body = declaration.body
if (declaration.descriptor.modality == Modality.ABSTRACT) return
if (declaration.descriptor.isExternal) return
if (body == null) return
val scope = declaration.scope()
val startLine = declaration.startLine()
val startLocationInfo = LocationInfo(
scope = scope,
line = startLine,
column = declaration.startColumn())
val endLocationInfo = LocationInfo(
scope = scope,
line = declaration.endLine(),
column = declaration.endColumn())
generateFunction(codegen, declaration.descriptor, startLocationInfo, endLocationInfo) {
using(FunctionScope(declaration, it)) {
val parameterScope = ParameterScope(declaration, functionGenerationContext)
using(parameterScope) {
using(VariableScope()) {
when (body) {
is IrBlockBody -> body.statements.forEach { generateStatement(it) }
is IrExpressionBody -> generateStatement(body.expression)
is IrSyntheticBody -> throw AssertionError("Synthetic body ${body.kind} has not been lowered")
else -> TODO(ir2string(body))
}
}
}
}
}
if (declaration.descriptor.usedAnnotation) {
context.llvm.usedFunctions.add(codegen.llvmFunction(declaration.descriptor))
}
if (context.shouldVerifyBitCode())
verifyModule(context.llvmModule!!,
"${declaration.descriptor.containingDeclaration}::${ir2string(declaration)}")
}
//-------------------------------------------------------------------------//
override fun visitClass(declaration: IrClass) {
context.log{"visitClass : ${ir2string(declaration)}"}
if (declaration.descriptor.kind == ClassKind.ANNOTATION_CLASS) {
// do not generate any code for annotation classes as a workaround for NotImplementedError
return
}
using(ClassScope(declaration)) {
declaration.declarations.forEach {
it.acceptVoid(this)
}
}
}
//-------------------------------------------------------------------------//
override fun visitTypeAlias(declaration: IrTypeAlias) {
// Nothing to do.
}
//-------------------------------------------------------------------------//
override fun visitProperty(declaration: IrProperty) {
declaration.acceptChildrenVoid(this)
}
//-------------------------------------------------------------------------//
override fun visitField(declaration: IrField) {
context.log{"visitField : ${ir2string(declaration)}"}
debugFieldDeclaration(declaration)
val descriptor = declaration.descriptor
if (context.needGlobalInit(declaration)) {
val type = codegen.getLLVMType(descriptor.type)
val globalProperty = context.llvmDeclarations.forStaticField(descriptor).storage
val initializer = declaration.initializer?.expression as? IrConst<*>
if (initializer != null)
LLVMSetInitializer(globalProperty, evaluateExpression(initializer))
else
LLVMSetInitializer(globalProperty, LLVMConstNull(type))
context.llvm.fileInitializers.add(declaration)
// (Cannot do this before the global is initialized).
LLVMSetLinkage(globalProperty, LLVMLinkage.LLVMInternalLinkage)
}
}
//-------------------------------------------------------------------------//
private fun evaluateExpression(value: IrExpression): LLVMValueRef {
debugLocation(value)
when (value) {
is IrTypeOperatorCall -> return evaluateTypeOperator (value)
is IrCall -> return evaluateCall (value)
is IrDelegatingConstructorCall ->
return evaluateCall (value)
is IrInstanceInitializerCall ->
return evaluateInstanceInitializerCall(value)
is IrGetValue -> return evaluateGetValue (value)
is IrSetVariable -> return evaluateSetVariable (value)
is IrGetField -> return evaluateGetField (value)
is IrSetField -> return evaluateSetField (value)
is IrConst<*> -> return evaluateConst (value)
is IrReturn -> return evaluateReturn (value)
is IrWhen -> return evaluateWhen (value)
is IrThrow -> return evaluateThrow (value)
is IrTry -> return evaluateTry (value)
is IrReturnableBlockImpl -> return evaluateReturnableBlock (value)
is IrContainerExpression -> return evaluateContainerExpression (value)
is IrWhileLoop -> return evaluateWhileLoop (value)
is IrDoWhileLoop -> return evaluateDoWhileLoop (value)
is IrVararg -> return evaluateVararg (value)
is IrBreak -> return evaluateBreak (value)
is IrContinue -> return evaluateContinue (value)
is IrGetObjectValue -> return evaluateGetObjectValue (value)
is IrFunctionReference -> return evaluateFunctionReference (value)
is IrSuspendableExpression ->
return evaluateSuspendableExpression (value)
is IrSuspensionPoint -> return evaluateSuspensionPoint (value)
else -> {
TODO(ir2string(value))
}
}
}
private fun generateStatement(statement: IrStatement) {
when (statement) {
is IrExpression -> evaluateExpression(statement)
is IrVariable -> generateVariable(statement)
else -> TODO(ir2string(statement))
}
}
private fun IrStatement.generate() = generateStatement(this)
//-------------------------------------------------------------------------//
private fun evaluateGetObjectValue(value: IrGetObjectValue): LLVMValueRef {
if (value.descriptor.isUnit()) {
return codegen.theUnitInstanceRef.llvm
}
val objectPtr = getObjectInstanceStorage(value.descriptor)
val bbCurrent = functionGenerationContext.currentBlock
val bbInit = functionGenerationContext.basicBlock("label_init", value.startLocation)
val bbExit = functionGenerationContext.basicBlock("label_continue", value.startLocation)
val objectVal = functionGenerationContext.loadSlot(objectPtr, false)
val condition = functionGenerationContext.icmpNe(objectVal, codegen.kNullObjHeaderPtr)
functionGenerationContext.condBr(condition, bbExit, bbInit)
functionGenerationContext.positionAtEnd(bbInit)
val typeInfo = typeInfoForAllocation(value.descriptor)
val initFunction = value.descriptor.constructors.first { it.valueParameters.size == 0 }
val ctor = codegen.llvmFunction(initFunction)
val args = listOf(objectPtr, typeInfo, ctor)
val newValue = call(context.llvm.initInstanceFunction, args, Lifetime.GLOBAL)
val bbInitResult = functionGenerationContext.currentBlock
functionGenerationContext.br(bbExit)
functionGenerationContext.positionAtEnd(bbExit)
val valuePhi = functionGenerationContext.phi(codegen.getLLVMType(value.type))
functionGenerationContext.addPhiIncoming(valuePhi,
bbCurrent to objectVal, bbInitResult to newValue)
return valuePhi
}
//-------------------------------------------------------------------------//
private fun evaluateExpressionAndJump(expression: IrExpression, destination: ContinuationBlock) {
val result = evaluateExpression(expression)
// It is possible to check here whether the generated code has the normal continuation path
// and do not generate any jump if not;
// however such optimization can lead to phi functions with zero entries, which is not allowed by LLVM;
// TODO: find the better solution.
jump(destination, result)
}
//-------------------------------------------------------------------------//
/**
* Represents the basic block which may expect a value:
* when generating a [jump] to this block, one should provide the value.
* Inside the block that value is accessible as [valuePhi].
*
* This class is designed to be used to generate Kotlin expressions that have a value and require branching.
*
* [valuePhi] may be `null`, which would mean `Unit` value is passed.
*/
private data class ContinuationBlock(val block: LLVMBasicBlockRef, val valuePhi: LLVMValueRef?)
private val ContinuationBlock.value: LLVMValueRef
get() = this.valuePhi ?: codegen.theUnitInstanceRef.llvm
/**
* Jumps to [target] passing [value].
*/
private fun jump(target: ContinuationBlock, value: LLVMValueRef?) {
val entry = target.block
functionGenerationContext.br(entry)
if (target.valuePhi != null) {
functionGenerationContext.assignPhis(target.valuePhi to value!!)
}
}
/**
* Creates new [ContinuationBlock] that receives the value of given Kotlin type
* and generates [code] starting from its beginning.
*/
private fun continuationBlock(type: KotlinType,
locationInfo: LocationInfo?, code: (ContinuationBlock) -> Unit = {}): ContinuationBlock {
val entry = functionGenerationContext.basicBlock("continuation_block", locationInfo)
functionGenerationContext.appendingTo(entry) {
val valuePhi = if (type.isUnit()) {
null
} else {
functionGenerationContext.phi(codegen.getLLVMType(type))
}
val result = ContinuationBlock(entry, valuePhi)
code(result)
return result
}
}
//-------------------------------------------------------------------------//
private fun evaluateVararg(value: IrVararg): LLVMValueRef {
val elements = value.elements.map {
if (it is IrExpression) {
val mapped = evaluateExpression(it)
if (mapped.isConst) {
return@map mapped
}
}
throw IllegalStateException("IrVararg neither was lowered nor can be statically evaluated")
}
// Note: even if all elements are const, they aren't guaranteed to be statically initialized.
// E.g. an element may be a pointer to lazy-initialized object (aka singleton).
// However it is guaranteed that all elements are already initialized at this point.
return codegen.staticData.createKotlinArray(value.type, elements)
}
//-------------------------------------------------------------------------//
private fun evaluateThrow(expression: IrThrow): LLVMValueRef {
val exception = evaluateExpression(expression.value)
currentCodeContext.genThrow(exception)
return codegen.kNothingFakeValue
}
//-------------------------------------------------------------------------//
/**
* The [CodeContext] that catches exceptions.
*/
private inner abstract class CatchingScope : InnerScopeImpl() {
/**
* The LLVM `landingpad` such that if invoked function throws an exception,
* then this exception is passed to [handler].
*/
private val landingpad: LLVMBasicBlockRef by lazy {
using(outerContext) {
functionGenerationContext.basicBlock("landingpad", endLocationInfoFromScope()) {
genLandingpad()
}
}
}
/**
* The Kotlin exception handler, i.e. the [ContinuationBlock] which gets started
* when the exception is caught, receiving this exception as its value.
*/
private val handler by lazy {
using(outerContext) {
continuationBlock(context.builtIns.throwable.defaultType, endLocationInfoFromScope()) {
genHandler(it.value)
}
}
}
private inline fun endLocationInfoFromScope(): LocationInfo? {
val functionScope = currentCodeContext.functionScope()
val irFunction = functionScope?.let {
(functionScope as FunctionScope).declaration
}
val locationInfo = irFunction?.endLocation
return locationInfo
}
private fun jumpToHandler(exception: LLVMValueRef) {
jump(this.handler, exception)
}
/**
* Generates the LLVM `landingpad` that catches C++ exception with type `KotlinException`,
* unwraps the Kotlin exception object and jumps to [handler].
*
* This method generates nearly the same code as `clang++` does for the following:
* ```
* catch (KotlinException& e) {
* KRef exception = e.exception_;
* return exception;
* }
* ```
* except that our code doesn't check exception `typeid`.
*
* TODO: why does `clang++` check `typeid` even if there is only one catch clause?
*/
private fun genLandingpad() {
with(functionGenerationContext) {
val landingpadResult = gxxLandingpad(numClauses = 1, name = "lp")
LLVMAddClause(landingpadResult, LLVMConstNull(kInt8Ptr))
// FIXME: properly handle C++ exceptions: currently C++ exception can be thrown out from try-finally
// bypassing the finally block.
val exceptionRecord = extractValue(landingpadResult, 0, "er")
// __cxa_begin_catch returns pointer to C++ exception object.
val beginCatch = context.llvm.cxaBeginCatchFunction
val exceptionRawPtr = call(beginCatch, listOf(exceptionRecord))
// Pointer to KotlinException instance:
val exceptionPtrPtr = bitcast(codegen.kObjHeaderPtrPtr, exceptionRawPtr, "")
// Pointer to Kotlin exception object:
// We do need a slot here, as otherwise exception instance could be freed by _cxa_end_catch.
val exceptionPtr = functionGenerationContext.loadSlot(exceptionPtrPtr, true, "exception")
// __cxa_end_catch performs some C++ cleanup, including calling `KotlinException` class destructor.
val endCatch = context.llvm.cxaEndCatchFunction
call(endCatch, listOf())
jumpToHandler(exceptionPtr)
}
}
// The call inside [CatchingScope] must be configured to dispatch exception to the scope's handler.
override fun genCall(function: LLVMValueRef, args: List<LLVMValueRef>, resultLifetime: Lifetime): LLVMValueRef {
val res = functionGenerationContext.call(function, args, resultLifetime, this::landingpad)
return res
}
override fun genThrow(exception: LLVMValueRef) {
jumpToHandler(exception)
}
protected abstract fun genHandler(exception: LLVMValueRef)
}
/**
* The [CatchingScope] that handles exceptions using Kotlin `catch` clauses.
*
* @param success the block to be used when the exception is successfully handled;
* expects `catch` expression result as its value.
*/
private inner class CatchScope(private val catches: List<IrCatch>,
private val success: ContinuationBlock) : CatchingScope() {
override fun genHandler(exception: LLVMValueRef) {
for (catch in catches) {
fun genCatchBlock() {
using(VariableScope()) {
currentCodeContext.genDeclareVariable(catch.parameter, exception, null)
evaluateExpressionAndJump(catch.result, success)
}
}
if (catch.parameter.type == context.builtIns.throwable.defaultType) {
genCatchBlock()
return // Remaining catch clauses are unreachable.
} else {
val isInstance = genInstanceOf(exception, catch.parameter.type)
val body = functionGenerationContext.basicBlock("catch", catch.startLocation)
val nextCheck = functionGenerationContext.basicBlock("catchCheck", catch.endLocation)
functionGenerationContext.condBr(isInstance, body, nextCheck)
functionGenerationContext.appendingTo(body) {
genCatchBlock()
}
functionGenerationContext.positionAtEnd(nextCheck)
}
}
// rethrow the exception if no clause can handle it.
outerContext.genThrow(exception)
}
}
private fun evaluateTry(expression: IrTry): LLVMValueRef {
// TODO: does basic block order influence machine code order?
// If so, consider reordering blocks to reduce exception tables size.
assert (expression.finallyExpression == null, { "All finally blocks should've been lowered" })
val continuation = continuationBlock(expression.type, expression.endLocation)
val catchScope = if (expression.catches.isEmpty())
null
else
CatchScope(expression.catches, continuation)
using(catchScope) {
evaluateExpressionAndJump(expression.tryResult, continuation)
}
functionGenerationContext.positionAtEnd(continuation.block)
return continuation.value
}
//-------------------------------------------------------------------------//
/* FIXME. Fix "when" type in frontend.
* For the following code:
* fun foo(x: Int) {
* when (x) {
* 0 -> 0
* }
* }
* we cannot determine if the result of when is assigned or not.
*/
private fun evaluateWhen(expression: IrWhen): LLVMValueRef {
context.log{"evaluateWhen : ${ir2string(expression)}"}
var bbExit: LLVMBasicBlockRef? = null // By default "when" does not have "exit".
val isUnit = KotlinBuiltIns.isUnit(expression.type)
val isNothing = KotlinBuiltIns.isNothing(expression.type)
// We may not cover all cases if IrWhen is used as statement.
val coverAllCases = isUnconditional(expression.branches.last())
// "When" has exit block if:
// its type is not Nothing - we must place phi in the exit block
// or it doesn't cover all cases - we may fall through all of them and must create exit block to continue.
if (!isNothing || !coverAllCases) // If "when" has "exit".
bbExit = functionGenerationContext.basicBlock("when_exit", expression.startLocation) // Create basic block to process "exit".
val llvmType = codegen.getLLVMType(expression.type)
val resultPhi = if (isUnit || isNothing || !coverAllCases) null else
functionGenerationContext.appendingTo(bbExit!!) {
functionGenerationContext.phi(llvmType)
}
expression.branches.forEach { // Iterate through "when" branches (clauses).
var bbNext = bbExit // For last clause bbNext coincides with bbExit.
if (it != expression.branches.last()) // If it is not last clause.
bbNext = functionGenerationContext.basicBlock("when_next", it.startLocation) // Create new basic block for next clause.
generateWhenCase(resultPhi, it, bbNext, bbExit) // Generate code for current clause.
}
return when {
// FIXME: remove the hacks.
isUnit -> functionGenerationContext.theUnitInstanceRef.llvm
isNothing -> functionGenerationContext.kNothingFakeValue
!coverAllCases -> LLVMGetUndef(llvmType)!!
else -> resultPhi!!
}
}
//-------------------------------------------------------------------------//
private fun evaluateWhileLoop(loop: IrWhileLoop): LLVMValueRef {
val loopScope = LoopScope(loop)
using(loopScope) {
val loopBody = functionGenerationContext.basicBlock("while_loop", loop.startLocation)
functionGenerationContext.br(loopScope.loopCheck)
functionGenerationContext.positionAtEnd(loopScope.loopCheck)
val condition = evaluateExpression(loop.condition)
functionGenerationContext.condBr(condition, loopBody, loopScope.loopExit)
functionGenerationContext.positionAtEnd(loopBody)
loop.body?.generate()
functionGenerationContext.br(loopScope.loopCheck)
functionGenerationContext.positionAtEnd(loopScope.loopExit)
}
assert(loop.type.isUnit())
return functionGenerationContext.theUnitInstanceRef.llvm
}
//-------------------------------------------------------------------------//
private fun evaluateDoWhileLoop(loop: IrDoWhileLoop): LLVMValueRef {
val loopScope = LoopScope(loop)
using(loopScope) {
val loopBody = functionGenerationContext.basicBlock("do_while_loop", loop.body?.startLocation ?: loop.startLocation)
functionGenerationContext.br(loopBody)
functionGenerationContext.positionAtEnd(loopBody)
loop.body?.generate()
functionGenerationContext.br(loopScope.loopCheck)
functionGenerationContext.positionAtEnd(loopScope.loopCheck)
val condition = evaluateExpression(loop.condition)
functionGenerationContext.condBr(condition, loopBody, loopScope.loopExit)
functionGenerationContext.positionAtEnd(loopScope.loopExit)
}
assert(loop.type.isUnit())
return functionGenerationContext.theUnitInstanceRef.llvm
}
//-------------------------------------------------------------------------//
private fun evaluateGetValue(value: IrGetValue): LLVMValueRef {
context.log{"evaluateGetValue : ${ir2string(value)}"}
return currentCodeContext.genGetValue(value.descriptor)
}
//-------------------------------------------------------------------------//
private fun evaluateSetVariable(value: IrSetVariable): LLVMValueRef {
context.log{"evaluateSetVariable : ${ir2string(value)}"}
val result = evaluateExpression(value.value)
val variable = currentCodeContext.getDeclaredVariable(value.descriptor)
functionGenerationContext.vars.store(result, variable)
assert(value.type.isUnit())
return functionGenerationContext.theUnitInstanceRef.llvm
}
//-------------------------------------------------------------------------//
private fun debugInfoIfNeeded(function: IrFunction?, element: IrElement): VariableDebugLocation? {
if (function == null || !context.shouldContainDebugInfo()) return null
val functionScope = function.scope()
if (functionScope == null || !element.needDebugInfo(context)) return null
val location = debugLocation(element)
val file = (currentCodeContext.fileScope() as FileScope).file.file()
val line = element.startLine()
return when (element) {
is IrVariable -> debugInfoLocalVariableLocation(
builder = context.debugInfo.builder,
functionScope = functionScope,
diType = element.descriptor.type.diType(context, codegen.llvmTargetData),
name = element.descriptor.name,
file = file,
line = line,
location = location)
is IrValueParameter -> debugInfoParameterLocation(
builder = context.debugInfo.builder,
functionScope = functionScope,
diType = element.descriptor.type.diType(context, codegen.llvmTargetData),
name = element.descriptor.name,
argNo = (element.descriptor as? ValueParameterDescriptor)?.index ?: 0,
file = file,
line = line,
location = location)
else -> throw Error("Unsupported element type: ${ir2string(element)}")
}
}
private fun generateVariable(variable: IrVariable) {
context.log{"generateVariable : ${ir2string(variable)}"}
val value = variable.initializer?.let { evaluateExpression(it) }
currentCodeContext.genDeclareVariable(
variable.descriptor, value, debugInfoIfNeeded(
(currentCodeContext.functionScope() as FunctionScope).declaration, variable))
}
//-------------------------------------------------------------------------//
private fun evaluateTypeOperator(value: IrTypeOperatorCall): LLVMValueRef {
return when (value.operator) {
IrTypeOperator.CAST -> evaluateCast(value)
IrTypeOperator.IMPLICIT_INTEGER_COERCION -> evaluateIntegerCoercion(value)
IrTypeOperator.IMPLICIT_CAST -> evaluateExpression(value.argument)
IrTypeOperator.IMPLICIT_NOTNULL -> TODO(ir2string(value))
IrTypeOperator.IMPLICIT_COERCION_TO_UNIT -> {
evaluateExpression(value.argument)
functionGenerationContext.theUnitInstanceRef.llvm
}
IrTypeOperator.SAFE_CAST -> throw IllegalStateException("safe cast wasn't lowered")
IrTypeOperator.INSTANCEOF -> evaluateInstanceOf(value)
IrTypeOperator.NOT_INSTANCEOF -> evaluateNotInstanceOf(value)
}
}
//-------------------------------------------------------------------------//
private fun KotlinType.isPrimitiveInteger(): Boolean {
return isPrimitiveNumberType() &&
!KotlinBuiltIns.isFloat(this) &&
!KotlinBuiltIns.isDouble(this) &&
!KotlinBuiltIns.isChar(this)
}
private fun evaluateIntegerCoercion(value: IrTypeOperatorCall): LLVMValueRef {
context.log{"evaluateIntegerCoercion : ${ir2string(value)}"}
val type = value.typeOperand
assert(type.isPrimitiveInteger())
val result = evaluateExpression(value.argument)
val llvmSrcType = codegen.getLLVMType(value.argument.type)
val llvmDstType = codegen.getLLVMType(type)
val srcWidth = LLVMGetIntTypeWidth(llvmSrcType)
val dstWidth = LLVMGetIntTypeWidth(llvmDstType)
return when {
srcWidth == dstWidth -> result
srcWidth > dstWidth -> LLVMBuildTrunc(functionGenerationContext.builder, result, llvmDstType, "")!!
else /* srcWidth < dstWidth */ -> LLVMBuildSExt(functionGenerationContext.builder, result, llvmDstType, "")!!
}
}
//-------------------------------------------------------------------------//
// table of conversion with llvm for primitive types
// to be used in replacement fo primitive.toX() calls with
// translator intrinsics.
// | byte short int long float double
//------------|----------------------------------------------------
// byte | x sext sext sext sitofp sitofp
// short | trunc x sext sext sitofp sitofp
// int | trunc trunc x sext sitofp sitofp
// long | trunc trunc trunc x sitofp sitofp
// float | fptosi fptosi fptosi fptosi x fpext
// double | fptosi fptosi fptosi fptosi fptrunc x
private fun evaluateCast(value: IrTypeOperatorCall): LLVMValueRef {
context.log{"evaluateCast : ${ir2string(value)}"}
val type = value.typeOperand
assert(!KotlinBuiltIns.isPrimitiveType(type) && !KotlinBuiltIns.isPrimitiveType(value.argument.type))
assert(!type.isTypeParameter())
val dstDescriptor = TypeUtils.getClassDescriptor(type) // Get class descriptor for dst type.
val dstTypeInfo = codegen.typeInfoValue(dstDescriptor!!) // Get TypeInfo for dst type.
val srcArg = evaluateExpression(value.argument) // Evaluate src expression.
val srcObjInfoPtr = functionGenerationContext.bitcast(codegen.kObjHeaderPtr, srcArg) // Cast src to ObjInfoPtr.
val args = listOf(srcObjInfoPtr, dstTypeInfo) // Create arg list.
call(context.llvm.checkInstanceFunction, args) // Check if dst is subclass of src.
return srcArg
}
//-------------------------------------------------------------------------//
private fun evaluateInstanceOf(value: IrTypeOperatorCall): LLVMValueRef {
context.log{"evaluateInstanceOf : ${ir2string(value)}"}
val type = value.typeOperand
val srcArg = evaluateExpression(value.argument) // Evaluate src expression.
val bbExit = functionGenerationContext.basicBlock("instance_of_exit", value.startLocation)
val bbInstanceOf = functionGenerationContext.basicBlock("instance_of_notnull", value.startLocation)
val bbNull = functionGenerationContext.basicBlock("instance_of_null", value.startLocation)
val condition = functionGenerationContext.icmpEq(srcArg, codegen.kNullObjHeaderPtr)
functionGenerationContext.condBr(condition, bbNull, bbInstanceOf)
functionGenerationContext.positionAtEnd(bbNull)
val resultNull = if (TypeUtils.isNullableType(type)) kTrue else kFalse
functionGenerationContext.br(bbExit)
functionGenerationContext.positionAtEnd(bbInstanceOf)
val resultInstanceOf = genInstanceOf(srcArg, type)
functionGenerationContext.br(bbExit)
val bbInstanceOfResult = functionGenerationContext.currentBlock
functionGenerationContext.positionAtEnd(bbExit)
val result = functionGenerationContext.phi(kBoolean)
functionGenerationContext.addPhiIncoming(result, bbNull to resultNull, bbInstanceOfResult to resultInstanceOf)
return result
}
//-------------------------------------------------------------------------//
private fun genInstanceOf(obj: LLVMValueRef, type: KotlinType): LLVMValueRef {
val dstDescriptor = TypeUtils.getClassDescriptor(type) ?: return kTrue // Get class descriptor for dst type.
// Reified parameters are not yet supported.
// Workaround for reified parameters
val dstTypeInfo = codegen.typeInfoValue(dstDescriptor) // Get TypeInfo for dst type.
val srcObjInfoPtr = functionGenerationContext.bitcast(codegen.kObjHeaderPtr, obj) // Cast src to ObjInfoPtr.
val args = listOf(srcObjInfoPtr, dstTypeInfo) // Create arg list.
val result = call(context.llvm.isInstanceFunction, args) // Check if dst is subclass of src.
return LLVMBuildTrunc(functionGenerationContext.builder, result, kInt1, "")!! // Truncate result to boolean
}
//-------------------------------------------------------------------------//
private fun evaluateNotInstanceOf(value: IrTypeOperatorCall): LLVMValueRef {
val instanceOfResult = evaluateInstanceOf(value)
return LLVMBuildNot(functionGenerationContext.builder, instanceOfResult, "")!!
}
//-------------------------------------------------------------------------//
private fun evaluateGetField(value: IrGetField): LLVMValueRef {
context.log{"evaluateGetField : ${ir2string(value)}"}
if (value.descriptor.dispatchReceiverParameter != null) {
val thisPtr = evaluateExpression(value.receiver!!)
return functionGenerationContext.loadSlot(
fieldPtrOfClass(thisPtr, value.descriptor), value.descriptor.isVar())
}
else {
assert (value.receiver == null)
val ptr = context.llvmDeclarations.forStaticField(value.descriptor).storage
return functionGenerationContext.loadSlot(ptr, value.descriptor.isVar())
}
}
//-------------------------------------------------------------------------//
private val objects = mutableSetOf<LLVMValueRef>()
private fun getObjectInstanceStorage(descriptor: ClassDescriptor): LLVMValueRef {
assert (!descriptor.isUnit())
val llvmGlobal = if (!codegen.isExternal(descriptor)) {
context.llvmDeclarations.forSingleton(descriptor).instanceFieldRef
} else {
val llvmType = codegen.getLLVMType(descriptor.defaultType)
codegen.importGlobal(
descriptor.objectInstanceFieldSymbolName,
llvmType,
origin = descriptor.llvmSymbolOrigin,
threadLocal = true
)
}
objects += llvmGlobal
return llvmGlobal
}
//-------------------------------------------------------------------------//
private fun evaluateSetField(value: IrSetField): LLVMValueRef {
context.log{"evaluateSetField : ${ir2string(value)}"}
val valueToAssign = evaluateExpression(value.value)
if (value.descriptor.dispatchReceiverParameter != null) {
val thisPtr = evaluateExpression(value.receiver!!)
functionGenerationContext.storeAny(valueToAssign, fieldPtrOfClass(thisPtr, value.descriptor))
}
else {
assert (value.receiver == null)
val globalValue = context.llvmDeclarations.forStaticField(value.descriptor).storage
functionGenerationContext.storeAny(valueToAssign, globalValue)
}
assert (value.type.isUnit())
return codegen.theUnitInstanceRef.llvm
}
//-------------------------------------------------------------------------//
/*
in C:
struct ObjHeader *header = (struct ObjHeader *)ptr;
struct T* obj = (T*)&header[1];
return &obj->fieldX;
in llvm ir:
%struct.ObjHeader = type { i32, i32 }
%struct.Object = type { i32, i32 }
; Function Attrs: nounwind ssp uwtable
define i32 @fooField2(i8*) #0 {
%2 = alloca i8*, align 8
%3 = alloca %struct.ObjHeader*, align 8
%4 = alloca %struct.Object*, align 8
store i8* %0, i8** %2, align 8
%5 = load i8*, i8** %2, align 8
%6 = bitcast i8* %5 to %struct.ObjHeader*
store %struct.ObjHeader* %6, %struct.ObjHeader** %3, align 8
%7 = load %struct.ObjHeader*, %struct.ObjHeader** %3, align 8
%8 = getelementptr inbounds %struct.ObjHeader, %struct.ObjHeader* %7, i64 1; <- (T*)&header[1];
%9 = bitcast %struct.ObjHeader* %8 to %struct.Object*
store %struct.Object* %9, %struct.Object** %4, align 8
%10 = load %struct.Object*, %struct.Object** %4, align 8
%11 = getelementptr inbounds %struct.Object, %struct.Object* %10, i32 0, i32 0 <- &obj->fieldX
%12 = load i32, i32* %11, align 4
ret i32 %12
}
*/
private fun fieldPtrOfClass(thisPtr: LLVMValueRef, value: PropertyDescriptor): LLVMValueRef {
val fieldInfo = context.llvmDeclarations.forField(value)
val classDescriptor = value.containingDeclaration as ClassDescriptor
val typePtr = pointerType(fieldInfo.classBodyType)
val bodyPtr = getObjectBodyPtr(classDescriptor, thisPtr)
val typedBodyPtr = functionGenerationContext.bitcast(typePtr, bodyPtr)
val fieldPtr = LLVMBuildStructGEP(functionGenerationContext.builder, typedBodyPtr, fieldInfo.index, "")
return fieldPtr!!
}
private fun getObjectBodyPtr(classDescriptor: ClassDescriptor, objectPtr: LLVMValueRef): LLVMValueRef {
return if (classDescriptor.isObjCClass()) {
assert(classDescriptor.isKotlinObjCClass())
val objCPtr = callDirect(context.interopBuiltIns.objCPointerHolderValue.getter!!,
listOf(objectPtr), Lifetime.IRRELEVANT)
val objCDeclarations = context.llvmDeclarations.forClass(classDescriptor).objCDeclarations!!
val bodyOffset = functionGenerationContext.load(objCDeclarations.bodyOffsetGlobal.llvmGlobal)
functionGenerationContext.gep(objCPtr, bodyOffset)
} else {
LLVMBuildGEP(functionGenerationContext.builder, objectPtr, cValuesOf(kImmOne), 1, "")!!
}
}
//-------------------------------------------------------------------------//
private fun evaluateStringConst(value: IrConst<String>) =
context.llvm.staticData.kotlinStringLiteral(value.value).llvm
private fun evaluateConst(value: IrConst<*>): LLVMValueRef {
context.log{"evaluateConst : ${ir2string(value)}"}
when (value.kind) {
IrConstKind.Null -> return codegen.kNullObjHeaderPtr
IrConstKind.Boolean -> when (value.value) {
true -> return kTrue
false -> return kFalse
}
IrConstKind.Char -> return LLVMConstInt(LLVMInt16Type(), (value.value as Char).toLong(), 0)!!
IrConstKind.Byte -> return LLVMConstInt(LLVMInt8Type(), (value.value as Byte).toLong(), 1)!!
IrConstKind.Short -> return LLVMConstInt(LLVMInt16Type(), (value.value as Short).toLong(), 1)!!
IrConstKind.Int -> return LLVMConstInt(LLVMInt32Type(), (value.value as Int).toLong(), 1)!!
IrConstKind.Long -> return LLVMConstInt(LLVMInt64Type(), value.value as Long, 1)!!
IrConstKind.String -> return evaluateStringConst(@Suppress("UNCHECKED_CAST") value as IrConst<String>)
IrConstKind.Float -> return LLVMConstRealOfString(LLVMFloatType(), (value.value as Float).toString())!!
IrConstKind.Double -> return LLVMConstRealOfString(LLVMDoubleType(), (value.value as Double).toString())!!
}
TODO(ir2string(value))
}
//-------------------------------------------------------------------------//
private fun evaluateReturn(expression: IrReturn): LLVMValueRef {
context.log{"evaluateReturn : ${ir2string(expression)}"}
val value = expression.value
val evaluated = evaluateExpression(value)
val target = expression.returnTarget
val ret = if (target.returnsUnit()) {
null
} else {
evaluated
}
currentCodeContext.genReturn(target, ret)
return codegen.kNothingFakeValue
}
//-------------------------------------------------------------------------//
fun getFileEntry(sourceFileName: String): SourceManager.FileEntry =
// We must cache file entries, otherwise we reparse same file many times.
context.fileEntryCache.getOrPut(sourceFileName) {
NaiveSourceBasedFileEntryImpl(sourceFileName)
}
private inner class ReturnableBlockScope(val returnableBlock: IrReturnableBlockImpl) :
FileScope(IrFileImpl(getFileEntry(returnableBlock.sourceFileName))) {
var bbExit : LLVMBasicBlockRef? = null
var resultPhi : LLVMValueRef? = null
private fun getExit(): LLVMBasicBlockRef {
if (bbExit == null) bbExit = functionGenerationContext.basicBlock("returnable_block_exit", null)
return bbExit!!
}
private fun getResult(): LLVMValueRef {
if (resultPhi == null) {
val bbCurrent = functionGenerationContext.currentBlock
functionGenerationContext.positionAtEnd(getExit())
resultPhi = functionGenerationContext.phi(codegen.getLLVMType(returnableBlock.type))
functionGenerationContext.positionAtEnd(bbCurrent)
}
return resultPhi!!
}
override fun genReturn(target: CallableDescriptor, value: LLVMValueRef?) {
if (target != returnableBlock.descriptor) { // It is not our "local return".
super.genReturn(target, value)
return
}
// It is local return from current function.
functionGenerationContext.br(getExit()) // Generate branch on exit block.
if (!target.returnsUnit()) { // If function returns more then "unit"
functionGenerationContext.assignPhis(getResult() to value!!) // Assign return value to result PHI node.
}
}
}
//-------------------------------------------------------------------------//
private open inner class FileScope(val file:IrFile) : InnerScopeImpl() {
override fun fileScope(): CodeContext? = this
}
//-------------------------------------------------------------------------//
private inner class ClassScope(val clazz:IrClass) : InnerScopeImpl() {
val isExported
get() = clazz.descriptor.isExported()
var offsetInBits = 0L
val members = mutableListOf<DIDerivedTypeRef>()
@Suppress("UNCHECKED_CAST")
val scope = if (isExported && context.shouldContainDebugInfo())
DICreateReplaceableCompositeType(
tag = DwarfTag.DW_TAG_structure_type.value,
refBuilder = context.debugInfo.builder,
refScope = context.debugInfo.compilationModule as DIScopeOpaqueRef,
name = clazz.descriptor.typeInfoSymbolName,
refFile = file().file(),
line = clazz.startLine()) as DITypeOpaqueRef
else null
override fun classScope(): CodeContext? = this
}
//-------------------------------------------------------------------------//
private fun evaluateReturnableBlock(value: IrReturnableBlockImpl): LLVMValueRef {
context.log{"evaluateReturnableBlock : ${value.statements.forEach { ir2string(it) }}"}
val returnableBlockScope = ReturnableBlockScope(value)
using(returnableBlockScope) {
using(VariableScope()) {
value.statements.forEach {
generateStatement(it)
}
}
}
val bbExit = returnableBlockScope.bbExit
if (bbExit != null) {
if (!functionGenerationContext.isAfterTerminator()) { // TODO should we solve this problem once and for all
if (returnableBlockScope.resultPhi != null) {
functionGenerationContext.unreachable()
} else {
functionGenerationContext.br(bbExit)
}
}
functionGenerationContext.positionAtEnd(bbExit)
}
return returnableBlockScope.resultPhi ?: codegen.theUnitInstanceRef.llvm
}
//-------------------------------------------------------------------------//
private fun evaluateContainerExpression(value: IrContainerExpression): LLVMValueRef {
context.log{"evaluateContainerExpression : ${value.statements.forEach { ir2string(it) }}"}
val scope = if (value.isTransparentScope) {
null
} else {
VariableScope()
}
using(scope) {
value.statements.dropLast(1).forEach {
generateStatement(it)
}
value.statements.lastOrNull()?.let {
if (it is IrExpression) {
return evaluateExpression(it)
} else {
generateStatement(it)
}
}
assert(value.type.isUnit())
return codegen.theUnitInstanceRef.llvm
}
}
private fun evaluateInstanceInitializerCall(expression: IrInstanceInitializerCall): LLVMValueRef {
assert (expression.type.isUnit())
return codegen.theUnitInstanceRef.llvm
}
//-------------------------------------------------------------------------//
/**
* Tries to evaluate given expression with given (already evaluated) arguments in compile time.
* Returns `null` on failure.
*/
private fun compileTimeEvaluate(expression: IrMemberAccessExpression, args: List<LLVMValueRef>): LLVMValueRef? {
if (!args.all { it.isConst }) {
return null
}
val function = expression.descriptor
if (function.fqNameSafe.asString() == "kotlin.collections.listOf" && function.valueParameters.size == 1) {
val varargExpression = expression.getValueArgument(0) as? IrVararg
if (varargExpression != null) {
// The function is kotlin.collections.listOf<T>(vararg args: T).
// TODO: refer functions more reliably.
val vararg = args.single()
if (varargExpression.elements.any { it is IrSpreadElement }) {
return null // not supported yet, see `length` calculation below.
}
val length = varargExpression.elements.size
// TODO: store length in `vararg` itself when more abstract types will be used for values.
// `elementType` is type argument of function return type:
val elementType = function.returnType!!.arguments.single()
val array = constPointer(vararg)
// Note: dirty hack here: `vararg` has type `Array<out E>`, but `createArrayList` expects `Array<E>`;
// however `vararg` is immutable, and in current implementation it has type `Array<E>`,
// so let's ignore this mismatch currently for simplicity.
return context.llvm.staticData.createArrayList(elementType, array, length).llvm
}
}
return null
}
private fun evaluateSpecialIntrinsicCall(expression: IrFunctionAccessExpression): LLVMValueRef? {
if (expression.descriptor.isIntrinsic) {
when (expression.descriptor.original) {
context.interopBuiltIns.objCObjectInitBy -> {
val receiver = evaluateExpression(expression.extensionReceiver!!)
val irConstructorCall = expression.getValueArgument(0) as IrCall
val constructorDescriptor = irConstructorCall.descriptor as ClassConstructorDescriptor
val constructorArgs = evaluateExplicitArgs(irConstructorCall)
val args = listOf(receiver) + constructorArgs
callDirect(constructorDescriptor, args, Lifetime.IRRELEVANT)
return receiver
}
context.builtIns.immutableBinaryBlobOf -> {
@Suppress("UNCHECKED_CAST")
val arg = expression.getValueArgument(0) as IrConst<String>
return context.llvm.staticData.createImmutableBinaryBlob(arg)
}
context.ir.symbols.initInstance.descriptor -> {
val callee = expression as IrCall
val initializer = callee.getValueArgument(1) as IrCall
val thiz = evaluateExpression(callee.getValueArgument(0)!!)
evaluateSimpleFunctionCall(initializer.descriptor, listOf(thiz) + evaluateExplicitArgs(initializer), resultLifetime(initializer))
return codegen.theUnitInstanceRef.llvm
}
}
}
return null
}
//-------------------------------------------------------------------------//
private fun evaluateCall(value: IrFunctionAccessExpression): LLVMValueRef {
context.log{"evaluateCall : ${ir2string(value)}"}
evaluateSpecialIntrinsicCall(value)?.let { return it }
val args = evaluateExplicitArgs(value)
compileTimeEvaluate(value, args)?.let { return it }
debugLocation(value)
when {
value is IrDelegatingConstructorCall ->
return delegatingConstructorCall(value.descriptor, args)
else ->
return evaluateFunctionCall(value as IrCall, args, resultLifetime(value))
}
}
//-------------------------------------------------------------------------//
private fun file() = (currentCodeContext.fileScope() as FileScope).file
//-------------------------------------------------------------------------//
private fun debugLocation(element: IrElement?):DILocationRef? {
if (!context.shouldContainDebugInfo() || element == null) return null
@Suppress("UNCHECKED_CAST")
return element.startLocation?.let{functionGenerationContext.debugLocation(it)}
}
private val IrElement.startLocation: LocationInfo?
get() = location(startLine(), startColumn())
private val IrElement.endLocation: LocationInfo?
get() = location(endLine(), endColumn())
private inline fun location(line: Int, column: Int): LocationInfo? {
val functionScope = currentCodeContext.functionScope() as? FunctionScope ?: return null
val scope = functionScope.declaration ?: return null
val diScope = scope.scope() ?: return null
return LocationInfo(
line = line,
column = column,
scope = diScope)
}
//-------------------------------------------------------------------------//
private fun IrElement.startLine() = file().fileEntry.line(this.startOffset)
//-------------------------------------------------------------------------//
private fun IrElement.startColumn() = file().fileEntry.column(this.startOffset)
//-------------------------------------------------------------------------//
private fun IrElement.endLine() = file().fileEntry.line(this.endOffset)
//-------------------------------------------------------------------------//
private fun IrElement.endColumn() = file().fileEntry.column(this.endOffset)
//-------------------------------------------------------------------------//
private fun debugFieldDeclaration(expression: IrField) {
val scope = currentCodeContext.classScope() as? ClassScope ?: return
if (!scope.isExported || !context.shouldContainDebugInfo()) return
val irFile = (currentCodeContext.fileScope() as FileScope).file
val sizeInBits = expression.descriptor.type.size(context)
scope.offsetInBits += sizeInBits
val alignInBits = expression.descriptor.type.alignment(context)
scope.offsetInBits = alignTo(scope.offsetInBits, alignInBits)
@Suppress("UNCHECKED_CAST")
scope.members.add(DICreateMemberType(
refBuilder = context.debugInfo.builder,
refScope = scope.scope as DIScopeOpaqueRef,
name = expression.descriptor.symbolName,
file = irFile.file(),
lineNum = expression.startLine(),
sizeInBits = sizeInBits,
alignInBits = alignInBits,
offsetInBits = scope.offsetInBits,
flags = 0,
type = expression.descriptor.type.diType(context, codegen.llvmTargetData)
)!!)
}
//-------------------------------------------------------------------------//
private fun IrFile.file(): DIFileRef {
return context.debugInfo.files.getOrPut(this) {
val path = this.fileEntry.name.toFileAndFolder()
DICreateFile(context.debugInfo.builder, path.file, path.folder)!!
}
}
//-------------------------------------------------------------------------//
@Suppress("UNCHECKED_CAST")
private fun IrFunction.scope():DIScopeOpaqueRef? {
if (!context.shouldContainDebugInfo()) return null
return context.debugInfo.subprograms.getOrPut(descriptor) {
memScoped {
val subroutineType = descriptor.subroutineType(context, codegen.llvmTargetData)
val functionLlvmValue = codegen.functionLlvmValue(descriptor)
val linkageName = LLVMGetValueName(functionLlvmValue)!!.toKString()
val diFunction = DICreateFunction(
builder = context.debugInfo.builder,
scope = context.debugInfo.compilationModule as DIScopeOpaqueRef,
name = descriptor.name.asString(),
linkageName = linkageName,
file = file().file(),
lineNo = startLine(),
type = subroutineType,
//TODO: need more investigations.
isLocal = 0,
isDefinition = 1,
scopeLine = 0)
DIFunctionAddSubprogram(functionLlvmValue , diFunction)
diFunction!!
}
} as DIScopeOpaqueRef
}
//-------------------------------------------------------------------------//
private val coroutineImplDescriptor = context.getInternalClass("CoroutineImpl")
private val doResumeFunctionDescriptor = coroutineImplDescriptor.unsubstitutedMemberScope
.getContributedFunctions(Name.identifier("doResume"), NoLookupLocation.FROM_BACKEND).single()
private fun getContinuation(): LLVMValueRef {
val caller = functionGenerationContext.functionDescriptor!!
return if (caller.isSuspend)
codegen.param(caller, caller.allParameters.size) // The last argument.
else {
// Suspend call from non-suspend function - must be [CoroutineImpl].
assert (doResumeFunctionDescriptor in caller.overriddenDescriptors,
{ "Expected 'CoroutineImpl.doResume' but was '$caller'" })
currentCodeContext.genGetValue(caller.dispatchReceiverParameter!!) // Coroutine itself is a continuation.
}
}
private fun CallableDescriptor.returnsUnit() = returnType == context.builtIns.unitType && !isSuspend
/**
* Evaluates all arguments of [expression] that are explicitly represented in the IR.
* Returns results in the same order as LLVM function expects, assuming that all explicit arguments
* exactly correspond to a tail of LLVM parameters.
*/
private fun evaluateExplicitArgs(expression: IrMemberAccessExpression): List<LLVMValueRef> {
val evaluatedArgs = expression.getArguments().map { (param, argExpr) ->
param to evaluateExpression(argExpr)
}.toMap()
val allValueParameters = expression.descriptor.allParameters
return allValueParameters.dropWhile { it !in evaluatedArgs }.map {
evaluatedArgs[it]!!
}
}
//-------------------------------------------------------------------------//
private fun evaluateFunctionReference(expression: IrFunctionReference): LLVMValueRef {
// TODO: consider creating separate IR element for pointer to function.
assert (TypeUtils.getClassDescriptor(expression.type) == context.interopBuiltIns.cPointer)
assert (expression.getArguments().isEmpty())
val descriptor = expression.descriptor
assert (descriptor.dispatchReceiverParameter == null)
val entry = codegen.functionEntryPointAddress(descriptor)
return entry
}
//-------------------------------------------------------------------------//
private inner class SuspendableExpressionScope(val resumePoints: MutableList<LLVMBasicBlockRef>) : InnerScopeImpl() {
override fun addResumePoint(bbLabel: LLVMBasicBlockRef): Int {
val result = resumePoints.size
resumePoints.add(bbLabel)
return result
}
}
private fun evaluateSuspendableExpression(expression: IrSuspendableExpression): LLVMValueRef {
val suspensionPointId = evaluateExpression(expression.suspensionPointId)
val bbStart = functionGenerationContext.basicBlock("start", expression.result.startLocation)
val bbDispatch = functionGenerationContext.basicBlock("dispatch", expression.suspensionPointId.startLocation)
val resumePoints = mutableListOf<LLVMBasicBlockRef>()
using (SuspendableExpressionScope(resumePoints)) {
functionGenerationContext.condBr(functionGenerationContext.icmpEq(suspensionPointId, kNullInt8Ptr), bbStart, bbDispatch)
functionGenerationContext.positionAtEnd(bbStart)
val result = evaluateExpression(expression.result)
functionGenerationContext.appendingTo(bbDispatch) {
if (context.config.indirectBranchesAreAllowed)
functionGenerationContext.indirectBr(suspensionPointId, resumePoints)
else {
val bbElse = functionGenerationContext.basicBlock("else", null) {
functionGenerationContext.unreachable()
}
val cases = resumePoints.withIndex().map { Int32(it.index + 1).llvm to it.value }
functionGenerationContext.switch(functionGenerationContext.ptrToInt(suspensionPointId, int32Type), cases, bbElse)
}
}
return result
}
}
private inner class SuspensionPointScope(val suspensionPointId: VariableDescriptor,
val bbResume: LLVMBasicBlockRef,
val bbResumeId: Int): InnerScopeImpl() {
override fun genGetValue(descriptor: ValueDescriptor): LLVMValueRef {
if (descriptor == suspensionPointId) {
return if (context.config.indirectBranchesAreAllowed)
functionGenerationContext.blockAddress(bbResume)
else
functionGenerationContext.intToPtr(Int32(bbResumeId + 1).llvm, int8TypePtr)
}
return super.genGetValue(descriptor)
}
}
private fun evaluateSuspensionPoint(expression: IrSuspensionPoint): LLVMValueRef {
val bbResume = functionGenerationContext.basicBlock("resume", expression.resumeResult.startLocation)
val id = currentCodeContext.addResumePoint(bbResume)
using (SuspensionPointScope(expression.suspensionPointIdParameter.descriptor, bbResume, id)) {
continuationBlock(expression.type, expression.result.startLocation).run {
val normalResult = evaluateExpression(expression.result)
jump(this, normalResult)
functionGenerationContext.positionAtEnd(bbResume)
val resumeResult = evaluateExpression(expression.resumeResult)
jump(this, resumeResult)
functionGenerationContext.positionAtEnd(this.block)
return this.value
}
}
}
//-------------------------------------------------------------------------//
private fun evaluateFunctionCall(callee: IrCall, args: List<LLVMValueRef>,
resultLifetime: Lifetime): LLVMValueRef {
val descriptor = callee.descriptor
val argsWithContinuationIfNeeded = if (descriptor.isSuspend)
args + getContinuation()
else args
if (descriptor.isIntrinsic) {
return evaluateIntrinsicCall(callee, argsWithContinuationIfNeeded)
}
when (descriptor) {
is IrBuiltinOperatorDescriptorBase -> return evaluateOperatorCall (callee, argsWithContinuationIfNeeded)
is ConstructorDescriptor -> return evaluateConstructorCall (callee, argsWithContinuationIfNeeded)
else -> return evaluateSimpleFunctionCall(
descriptor, argsWithContinuationIfNeeded, resultLifetime, callee.superQualifier)
}
}
//-------------------------------------------------------------------------//
private fun evaluateSimpleFunctionCall(
descriptor: FunctionDescriptor, args: List<LLVMValueRef>,
resultLifetime: Lifetime, superClass: ClassDescriptor? = null): LLVMValueRef {
//context.log{"evaluateSimpleFunctionCall : $tmpVariableName = ${ir2string(value)}"}
if (descriptor.isOverridable && superClass == null)
return callVirtual(descriptor, args, resultLifetime)
else
return callDirect(descriptor, args, resultLifetime)
}
//-------------------------------------------------------------------------//
private fun resultLifetime(callee: IrElement): Lifetime {
return lifetimes.getOrElse(callee) { /* TODO: make IRRELEVANT */ Lifetime.GLOBAL }
}
private fun evaluateConstructorCall(callee: IrCall, args: List<LLVMValueRef>): LLVMValueRef {
context.log{"evaluateConstructorCall : ${ir2string(callee)}"}
return memScoped {
val constructedClass = (callee.descriptor as ConstructorDescriptor).constructedClass
val thisValue = if (constructedClass.isArray) {
assert(args.isNotEmpty() && args[0].type == int32Type)
functionGenerationContext.allocArray(codegen.typeInfoValue(constructedClass), args[0],
resultLifetime(callee))
} else if (constructedClass == context.builtIns.string) {
// TODO: consider returning the empty string literal instead.
assert(args.isEmpty())
functionGenerationContext.allocArray(codegen.typeInfoValue(constructedClass), count = kImmZero,
lifetime = resultLifetime(callee))
} else if (constructedClass.isKotlinObjCClass()) {
callDirect(context.interopBuiltIns.allocObjCObject, listOf(genGetObjCClass(constructedClass)),
resultLifetime(callee))
} else {
functionGenerationContext.allocInstance(typeInfoForAllocation(constructedClass), resultLifetime(callee))
}
evaluateSimpleFunctionCall(callee.descriptor,
listOf(thisValue) + args, Lifetime.IRRELEVANT /* constructor doesn't return anything */)
thisValue
}
}
private fun typeInfoForAllocation(constructedClass: ClassDescriptor): LLVMValueRef {
val descriptorForTypeInfo = if (constructedClass.isObjCClass()) {
context.interopBuiltIns.objCPointerHolder
} else {
constructedClass
}
return codegen.typeInfoValue(descriptorForTypeInfo)
}
//-------------------------------------------------------------------------//
private fun evaluateIntrinsicCall(callee: IrCall, args: List<LLVMValueRef>): LLVMValueRef {
val descriptor = callee.descriptor.original
val name = descriptor.fqNameUnsafe.asString()
when (name) {
"konan.internal.areEqualByValue" -> {
val arg0 = args[0]
val arg1 = args[1]
assert (arg0.type == arg1.type, { "Types are different: '${llvmtype2string(arg0.type)}' and '${llvmtype2string(arg1.type)}'" })
return when (LLVMGetTypeKind(arg0.type)) {
LLVMTypeKind.LLVMFloatTypeKind, LLVMTypeKind.LLVMDoubleTypeKind ->
functionGenerationContext.fcmpEq(arg0, arg1)
else ->
functionGenerationContext.icmpEq(arg0, arg1)
}
}
"konan.internal.getContinuation" -> return getContinuation()
}
val interop = context.interopBuiltIns
return when (descriptor) {
interop.interpretNullablePointed, interop.interpretCPointer,
interop.nativePointedGetRawPointer, interop.cPointerGetRawValue -> args.single()
in interop.readPrimitive -> {
val pointerType = pointerType(codegen.getLLVMType(descriptor.returnType!!))
val rawPointer = args.last()
val pointer = functionGenerationContext.bitcast(pointerType, rawPointer)
functionGenerationContext.load(pointer)
}
in interop.writePrimitive -> {
val pointerType = pointerType(codegen.getLLVMType(descriptor.valueParameters.last().type))
val rawPointer = args[1]
val pointer = functionGenerationContext.bitcast(pointerType, rawPointer)
functionGenerationContext.store(args[2], pointer)
codegen.theUnitInstanceRef.llvm
}
context.builtIns.nativePtrPlusLong -> functionGenerationContext.gep(args[0], args[1])
context.builtIns.getNativeNullPtr -> kNullInt8Ptr
interop.getPointerSize -> Int32(LLVMPointerSize(codegen.llvmTargetData)).llvm
context.builtIns.nativePtrToLong -> {
val intPtrValue = functionGenerationContext.ptrToInt(args.single(), codegen.intPtrType)
val resultType = functionGenerationContext.getLLVMType(descriptor.returnType!!)
if (resultType == intPtrValue.type) {
intPtrValue
} else {
LLVMBuildSExt(functionGenerationContext.builder, intPtrValue, resultType, "")!!
}
}
interop.objCObjectInitFromPtr -> {
genObjCObjectInitFromPtr(args)
}
interop.getObjCReceiverOrSuper -> {
genGetObjCReceiverOrSuper(args)
}
interop.getObjCClass -> {
val typeArgument = callee.getTypeArgument(descriptor.typeParameters.single())
val classDescriptor = TypeUtils.getClassDescriptor(typeArgument!!)!!
genGetObjCClass(classDescriptor)
}
interop.getObjCMessenger -> {
genGetObjCMessenger(args, isLU = false)
}
interop.getObjCMessengerLU -> {
genGetObjCMessenger(args, isLU = true)
}
interop.readBits -> genReadBits(args)
interop.writeBits -> genWriteBits(args)
context.ir.symbols.getClassTypeInfo.descriptor -> {
val typeArgument = callee.getTypeArgumentOrDefault(descriptor.typeParameters.single())
val typeArgumentClass = TypeUtils.getClassDescriptor(typeArgument)
if (typeArgumentClass == null) {
// E.g. for `T::class` in a body of an inline function itself.
functionGenerationContext.unreachable()
kNullInt8Ptr
} else {
val classDescriptor = context.ir.symbols.valueClassToBox[typeArgumentClass]?.descriptor
?: typeArgumentClass
val typeInfo = codegen.typeInfoValue(classDescriptor)
LLVMConstBitCast(typeInfo, kInt8Ptr)!!
}
}
context.ir.symbols.createUninitializedInstance.descriptor -> {
val typeParameterT = context.ir.symbols.createUninitializedInstance.descriptor.typeParameters[0]
val enumClass = callee.getTypeArgument(typeParameterT)!!
val enumClassDescriptor = enumClass.constructor.declarationDescriptor as ClassDescriptor
functionGenerationContext.allocInstance(typeInfoForAllocation(enumClassDescriptor), resultLifetime(callee))
}
else -> TODO(callee.descriptor.original.toString())
}
}
private fun genReadBits(args: List<LLVMValueRef>): LLVMValueRef {
val ptr = args[0]
assert(ptr.type == int8TypePtr)
val offset = extractConstUnsignedInt(args[1])
val size = extractConstUnsignedInt(args[2]).toInt()
val signed = extractConstUnsignedInt(args[3]) != 0L
val prefixBitsNum = (offset % 8).toInt()
val suffixBitsNum = (8 - ((size + offset) % 8).toInt()) % 8
// Note: LLVM allows to read without padding tail up to byte boundary, but the result seems to be incorrect.
val bitsWithPaddingNum = prefixBitsNum + size + suffixBitsNum
val bitsWithPaddingType = LLVMIntType(bitsWithPaddingNum)!!
with (functionGenerationContext) {
val bitsWithPaddingPtr = bitcast(pointerType(bitsWithPaddingType), gep(ptr, Int64(offset / 8).llvm))
val bitsWithPadding = load(bitsWithPaddingPtr).setUnaligned()
val bits = shr(
shl(bitsWithPadding, suffixBitsNum),
prefixBitsNum + suffixBitsNum, signed
)
return if (bitsWithPaddingNum == 64) {
bits
} else if (bitsWithPaddingNum > 64) {
trunc(bits, kInt64)
} else {
ext(bits, kInt64, signed)
}
}
}
private fun genWriteBits(args: List<LLVMValueRef>): LLVMValueRef {
val ptr = args[0]
assert(ptr.type == int8TypePtr)
val offset = extractConstUnsignedInt(args[1])
val size = extractConstUnsignedInt(args[2]).toInt()
val value = args[3]
assert(value.type == kInt64)
val bitsType = LLVMIntType(size)!!
val prefixBitsNum = (offset % 8).toInt()
val suffixBitsNum = (8 - ((size + offset) % 8).toInt()) % 8
val bitsWithPaddingNum = prefixBitsNum + size + suffixBitsNum
val bitsWithPaddingType = LLVMIntType(bitsWithPaddingNum)!!
// 0011111000:
val discardBitsMask = LLVMConstShl(
LLVMConstZExt(
LLVMConstAllOnes(bitsType), // 11111
bitsWithPaddingType
), // 1111100000
LLVMConstInt(bitsWithPaddingType, prefixBitsNum.toLong(), 0)
)
val preservedBitsMask = LLVMConstNot(discardBitsMask)!!
with (functionGenerationContext) {
val bitsWithPaddingPtr = bitcast(pointerType(bitsWithPaddingType), gep(ptr, Int64(offset / 8).llvm))
val bits = trunc(value, bitsType)
val bitsToStore = if (prefixBitsNum == 0 && suffixBitsNum == 0) {
bits
} else {
val previousValue = load(bitsWithPaddingPtr).setUnaligned()
val preservedBits = and(previousValue, preservedBitsMask)
val bitsWithPadding = shl(zext(bits, bitsWithPaddingType), prefixBitsNum)
or(bitsWithPadding, preservedBits)
}
LLVMBuildStore(builder, bitsToStore, bitsWithPaddingPtr)!!.setUnaligned()
}
return codegen.theUnitInstanceRef.llvm
}
private fun extractConstUnsignedInt(value: LLVMValueRef): Long {
assert(LLVMIsConstant(value) != 0)
return LLVMConstIntGetZExtValue(value)
}
private fun genGetObjCClass(classDescriptor: ClassDescriptor): LLVMValueRef {
assert(!classDescriptor.isInterface)
return if (classDescriptor.isExternalObjCClass()) {
context.llvm.imports.add(classDescriptor.llvmSymbolOrigin)
val lookUpFunction = context.llvm.externalFunction("Kotlin_Interop_getObjCClass",
functionType(int8TypePtr, false, int8TypePtr),
origin = context.standardLlvmSymbolsOrigin
)
call(lookUpFunction,
listOf(codegen.staticData.cStringLiteral(classDescriptor.name.asString()).llvm))
} else {
val objCDeclarations = context.llvmDeclarations.forClass(classDescriptor).objCDeclarations!!
val classPointerGlobal = objCDeclarations.classPointerGlobal.llvmGlobal
val gen = functionGenerationContext
val storedClass = gen.load(classPointerGlobal)
val storedClassIsNotNull = gen.icmpNe(storedClass, kNullInt8Ptr)
return gen.ifThenElse(storedClassIsNotNull, storedClass) {
val newClass = call(context.llvm.createKotlinObjCClass,
listOf(objCDeclarations.classInfoGlobal.llvmGlobal))
gen.store(newClass, classPointerGlobal)
newClass
}
}
}
private fun genGetObjCMessenger(args: List<LLVMValueRef>, isLU: Boolean): LLVMValueRef {
val gen = functionGenerationContext
// 'LU' means "large or unaligned".
// objc_msgSend*_stret functions must be used when return value is returned through memory
// pointed by implicit argument, which is passed on the register that would otherwise be used for receiver.
// On aarch64 it is never the case, since such implicit argument gets passed on x8.
// On x86_64 it is the case if the return value takes more than 16 bytes or is the structure with
// unaligned fields (there are some complicated exceptions currently ignored). The latter condition
// is "encoded" by stub generator by emitting either `getMessenger` or `getMessengerLU` intrinsic call.
val isStret = when (context.config.targetManager.target) {
KonanTarget.MACBOOK, KonanTarget.IPHONE_SIM -> isLU // x86_64
KonanTarget.IPHONE -> false // aarch64
else -> TODO()
}
val messengerNameSuffix = if (isStret) "_stret" else ""
val functionType = functionType(int8TypePtr, true, int8TypePtr, int8TypePtr)
val libobjc = context.standardLlvmSymbolsOrigin
val normalMessenger = context.llvm.externalFunction(
"objc_msgSend$messengerNameSuffix",
functionType,
origin = libobjc
)
val superMessenger = context.llvm.externalFunction(
"objc_msgSendSuper$messengerNameSuffix",
functionType,
origin = libobjc
)
val superClass = args.single()
val messenger = LLVMBuildSelect(gen.builder,
If = gen.icmpEq(superClass, kNullInt8Ptr),
Then = normalMessenger,
Else = superMessenger,
Name = ""
)!!
return gen.bitcast(int8TypePtr, messenger)
}
private fun genObjCObjectInitFromPtr(args: List<LLVMValueRef>): LLVMValueRef {
return callDirect(context.interopBuiltIns.objCPointerHolder.unsubstitutedPrimaryConstructor!!,
args, Lifetime.IRRELEVANT)
}
private fun genGetObjCReceiverOrSuper(args: List<LLVMValueRef>): LLVMValueRef {
val gen = functionGenerationContext
assert(args.size == 2)
val receiver = args[0]
val superClass = args[1]
val superClassIsNull = gen.icmpEq(superClass, kNullInt8Ptr)
return gen.ifThenElse(superClassIsNull, receiver) {
val structType = structType(kInt8Ptr, kInt8Ptr)
val ptr = gen.alloca(structType)
gen.store(receiver,
LLVMBuildGEP(gen.builder, ptr, cValuesOf(kImmZero, kImmZero), 2, "")!!)
gen.store(superClass,
LLVMBuildGEP(gen.builder, ptr, cValuesOf(kImmZero, kImmOne), 2, "")!!)
gen.bitcast(int8TypePtr, ptr)
}
}
//-------------------------------------------------------------------------//
private val kImmZero = LLVMConstInt(LLVMInt32Type(), 0, 1)!!
private val kImmOne = LLVMConstInt(LLVMInt32Type(), 1, 1)!!
private val kTrue = LLVMConstInt(LLVMInt1Type(), 1, 1)!!
private val kFalse = LLVMConstInt(LLVMInt1Type(), 0, 1)!!
private fun evaluateOperatorCall(callee: IrCall, args: List<LLVMValueRef>): LLVMValueRef {
context.log{"evaluateCall : origin:${ir2string(callee)}"}
val descriptor = callee.descriptor
val ib = context.irModule!!.irBuiltins
when (descriptor) {
ib.eqeqeq -> return functionGenerationContext.icmpEq(args[0], args[1])
ib.gt0 -> return functionGenerationContext.icmpGt(args[0], kImmZero)
ib.gteq0 -> return functionGenerationContext.icmpGe(args[0], kImmZero)
ib.lt0 -> return functionGenerationContext.icmpLt(args[0], kImmZero)
ib.lteq0 -> return functionGenerationContext.icmpLe(args[0], kImmZero)
ib.booleanNot -> return functionGenerationContext.icmpNe(args[0], kTrue)
else -> {
TODO(descriptor.name.toString())
}
}
}
//-------------------------------------------------------------------------//
private fun generateWhenCase(resultPhi: LLVMValueRef?, branch: IrBranch,
bbNext: LLVMBasicBlockRef?, bbExit: LLVMBasicBlockRef?) {
val branchResult = branch.result
val brResult = if (isUnconditional(branch)) { // It is the "else" clause.
evaluateExpression(branchResult) // Generate clause body.
} else { // It is conditional clause.
val bbCase = functionGenerationContext.basicBlock("when_case", branch.startLocation) // Create block for clause body.
val condition = evaluateExpression(branch.condition) // Generate cmp instruction.
functionGenerationContext.condBr(condition, bbCase, bbNext) // Conditional branch depending on cmp result.
functionGenerationContext.positionAtEnd(bbCase) // Switch generation to block for clause body.
evaluateExpression(branch.result) // Generate clause body.
}
if (!functionGenerationContext.isAfterTerminator()) {
if (resultPhi != null)
functionGenerationContext.assignPhis(resultPhi to brResult)
if (bbExit != null)
functionGenerationContext.br(bbExit)
}
if (bbNext != null) // Switch generation to next or exit.
functionGenerationContext.positionAtEnd(bbNext)
else if (bbExit != null)
functionGenerationContext.positionAtEnd(bbExit)
}
//-------------------------------------------------------------------------//
// Checks if the branch is unconditional
private fun isUnconditional(branch: IrBranch): Boolean =
branch.condition is IrConst<*> // If branch condition is constant.
&& (branch.condition as IrConst<*>).value as Boolean // If condition is "true"
//-------------------------------------------------------------------------//
fun callDirect(descriptor: FunctionDescriptor, args: List<LLVMValueRef>,
resultLifetime: Lifetime): LLVMValueRef {
val realDescriptor = descriptor.target
val llvmFunction = codegen.functionLlvmValue(realDescriptor)
return call(descriptor, llvmFunction, args, resultLifetime)
}
//-------------------------------------------------------------------------//
fun callVirtual(descriptor: FunctionDescriptor, args: List<LLVMValueRef>,
resultLifetime: Lifetime): LLVMValueRef {
val function = functionGenerationContext.lookupVirtualImpl(args.first(), descriptor)
return call(descriptor, function, args, resultLifetime) // Invoke the method
}
//-------------------------------------------------------------------------//
// TODO: it seems to be much more reliable to get args as a mapping from parameter descriptor to LLVM value,
// instead of a plain list.
// In such case it would be possible to check that all args are available and in the correct order.
// However, it currently requires some refactoring to be performed.
private fun call(descriptor: FunctionDescriptor, function: LLVMValueRef, args: List<LLVMValueRef>,
resultLifetime: Lifetime): LLVMValueRef {
val result = call(function, args, resultLifetime)
if (descriptor.returnType?.isNothing() == true) {
functionGenerationContext.unreachable()
}
if (LLVMGetReturnType(getFunctionType(function)) == voidType) {
return codegen.theUnitInstanceRef.llvm
}
return result
}
private fun call(function: LLVMValueRef, args: List<LLVMValueRef>,
resultLifetime: Lifetime = Lifetime.IRRELEVANT): LLVMValueRef {
return currentCodeContext.genCall(function, args, resultLifetime)
}
//-------------------------------------------------------------------------//
private fun delegatingConstructorCall(
descriptor: ClassConstructorDescriptor, args: List<LLVMValueRef>): LLVMValueRef {
val constructedClass = functionGenerationContext.constructedClass!!
val thisPtr = currentCodeContext.genGetValue(constructedClass.thisAsReceiverParameter)
if (constructedClass.isObjCClass()) {
return codegen.theUnitInstanceRef.llvm
}
val thisPtrArgType = codegen.getLLVMType(descriptor.allParameters[0].type)
val thisPtrArg = if (thisPtr.type == thisPtrArgType) {
thisPtr
} else {
// e.g. when array constructor calls super (i.e. Any) constructor.
functionGenerationContext.bitcast(thisPtrArgType, thisPtr)
}
return callDirect(descriptor, listOf(thisPtrArg) + args,
Lifetime.IRRELEVANT /* no value returned */)
}
//-------------------------------------------------------------------------//
private fun appendLlvmUsed(name: String, args: List<LLVMValueRef>) {
if (args.isEmpty()) return
memScoped {
val argsCasted = args.map { it -> constPointer(it).bitcast(int8TypePtr) }
val llvmUsedGlobal =
context.llvm.staticData.placeGlobalArray(name, int8TypePtr, argsCasted)
LLVMSetLinkage(llvmUsedGlobal.llvmGlobal, LLVMLinkage.LLVMAppendingLinkage);
LLVMSetSection(llvmUsedGlobal.llvmGlobal, "llvm.metadata");
}
}
//-------------------------------------------------------------------------//
private fun entryPointSelector(entryPoint: LLVMValueRef,
entryPointType: LLVMTypeRef, selectorName: String): LLVMValueRef {
assert(LLVMCountParams(entryPoint) == 1)
val selector = LLVMAddFunction(context.llvmModule, selectorName, entryPointType)!!
generateFunction(codegen, selector) {
// Note, that 'parameter' is an object reference, and as such, shall
// be accounted for in the rootset. However, current object management
// scheme for arguments guarantees, that reference is being held in C++
// launcher, so we could optimize out creating slot for 'parameter' in
// this function.
val parameter = LLVMGetParam(selector, 0)!!
callAtFunctionScope(entryPoint, listOf(parameter), Lifetime.IRRELEVANT)
ret(null)
}
return selector
}
//-------------------------------------------------------------------------//
private fun appendEntryPointSelector(descriptor: FunctionDescriptor?) {
if (descriptor == null) return
val entryPoint = codegen.llvmFunction(descriptor)
val selectorName = "EntryPointSelector"
val entryPointType = getFunctionType(entryPoint)
val selector = entryPointSelector(entryPoint, entryPointType, selectorName)
LLVMSetLinkage(selector, LLVMLinkage.LLVMExternalLinkage)
}
//-------------------------------------------------------------------------//
// Create type { i32, void ()*, i8* }
val kCtorType = LLVMStructType(
cValuesOf(
LLVMInt32Type(),
LLVMPointerType(kVoidFuncType, 0),
kInt8Ptr
),
3, 0)!!
//-------------------------------------------------------------------------//
// Create object { i32, void ()*, i8* } { i32 1, void ()* @ctorFunction, i8* null }
fun createGlobalCtor(ctorFunction: LLVMValueRef): ConstPointer {
val priority = kImmInt32One
val data = kNullInt8Ptr
val argList = cValuesOf(priority, ctorFunction, data)
val ctorItem = LLVMConstNamedStruct(kCtorType, argList, 3)!!
return constPointer(ctorItem)
}
//-------------------------------------------------------------------------//
// Append initializers of global variables in "llvm.global_ctors" array
fun appendStaticInitializers(initializers: List<LLVMValueRef>) {
if (initializers.isEmpty()) return
val ctorList = initializers.map { it -> createGlobalCtor(it) }
val globalCtors = context.llvm.staticData.placeGlobalArray("llvm.global_ctors", kCtorType, ctorList)
LLVMSetLinkage(globalCtors.llvmGlobal, LLVMLinkage.LLVMAppendingLinkage)
}
//-------------------------------------------------------------------------//
fun FunctionGenerationContext.basicBlock(name: String, locationInfo: LocationInfo?, code: () -> Unit) = functionGenerationContext.basicBlock(name, locationInfo).apply {
appendingTo(this) {
code()
}
}
}
internal data class LocationInfo(val scope:DIScopeOpaqueRef?, val line:Int, val column:Int)
private fun IrFunction.hasNotReceiver() = this.extensionReceiverParameter == null && this.dispatchReceiverParameter == null
| apache-2.0 | d5b991550ba12ffec2df1300f9e7f6f0 | 43.961415 | 305 | 0.589966 | 5.388699 | false | false | false | false |
salRoid/Filmy | app/src/main/java/tech/salroid/filmy/ui/activities/FullCastActivity.kt | 1 | 2265 | package tech.salroid.filmy.ui.activities
import android.content.Intent
import android.os.Bundle
import androidx.preference.PreferenceManager
import android.view.MenuItem
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityOptionsCompat
import androidx.core.util.Pair
import androidx.recyclerview.widget.LinearLayoutManager
import tech.salroid.filmy.R
import tech.salroid.filmy.ui.adapters.CastAdapter
import tech.salroid.filmy.data.local.model.Cast
import tech.salroid.filmy.databinding.ActivityFullCastBinding
class FullCastActivity : AppCompatActivity() {
private var nightMode = false
private lateinit var binding: ActivityFullCastBinding
override fun onCreate(savedInstanceState: Bundle?) {
val sp = PreferenceManager.getDefaultSharedPreferences(this)
nightMode = sp.getBoolean("dark", false)
if (nightMode) setTheme(R.style.AppTheme_Base_Dark) else setTheme(R.style.AppTheme_Base)
super.onCreate(savedInstanceState)
binding = ActivityFullCastBinding.inflate(layoutInflater)
setContentView(binding.root)
setSupportActionBar(binding.toolbar)
binding.fullCastRecycler.layoutManager = LinearLayoutManager(this@FullCastActivity)
val castList = intent?.getSerializableExtra("cast_list") as? List<Cast>
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.title = intent?.getStringExtra("toolbar_title")
val fullCastAdapter = castList?.let {
CastAdapter(it, false) { castData, _, _ ->
val intent = Intent(this, CharacterDetailsActivity::class.java)
intent.putExtra("id", castData.id.toString())
startActivity(intent)
}
}
binding.fullCastRecycler.adapter = fullCastAdapter
}
override fun onResume() {
super.onResume()
val sp = PreferenceManager.getDefaultSharedPreferences(this)
val nightModeNew = sp.getBoolean("dark", false)
if (nightMode != nightModeNew) recreate()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) finish()
return super.onOptionsItemSelected(item)
}
} | apache-2.0 | cecb793b8db7b95b5c2ec743c2e78029 | 36.766667 | 96 | 0.725828 | 4.829424 | false | false | false | false |
smmribeiro/intellij-community | plugins/maven/src/main/java/org/jetbrains/idea/maven/wizards/archetype/MavenEditCatalogDialog.kt | 1 | 968 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.idea.maven.wizards.archetype
import com.intellij.openapi.project.Project
import org.jetbrains.idea.maven.indices.arhetype.MavenCatalog
import org.jetbrains.idea.maven.indices.arhetype.MavenCatalogManager
import org.jetbrains.idea.maven.wizards.MavenWizardBundle
class MavenEditCatalogDialog(project: Project, private val initialCatalog: MavenCatalog) : AbstractMavenCatalogDialog(project) {
override fun onApply() {
val catalog = getCatalog() ?: return
val catalogManager = MavenCatalogManager.getInstance()
catalogManager.removeCatalog(initialCatalog)
catalogManager.addCatalog(catalog)
}
init {
name = initialCatalog.name
location = initialCatalog.location
}
init {
title = MavenWizardBundle.message("maven.new.project.wizard.archetype.catalog.edit.dialog.title")
init()
}
} | apache-2.0 | 82c37b5b7068611b958ebf576b22c799 | 34.888889 | 128 | 0.784091 | 4.172414 | false | false | false | false |
HolodeckOne-Minecraft/WorldEdit | worldedit-core/doctools/src/main/kotlin/com/sk89q/worldedit/internal/util/DocumentationPrinter.kt | 2 | 13953 | /*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* 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 <https://www.gnu.org/licenses/>.
*/
package com.sk89q.worldedit.internal.util
import com.google.common.base.Strings
import com.sk89q.worldedit.WorldEdit
import com.sk89q.worldedit.command.BiomeCommands
import com.sk89q.worldedit.command.ChunkCommands
import com.sk89q.worldedit.command.ClipboardCommands
import com.sk89q.worldedit.command.GeneralCommands
import com.sk89q.worldedit.command.GenerationCommands
import com.sk89q.worldedit.command.HistoryCommands
import com.sk89q.worldedit.command.NavigationCommands
import com.sk89q.worldedit.command.RegionCommands
import com.sk89q.worldedit.command.ScriptingCommands
import com.sk89q.worldedit.command.SelectionCommands
import com.sk89q.worldedit.command.SnapshotUtilCommands
import com.sk89q.worldedit.command.ToolCommands
import com.sk89q.worldedit.command.ToolUtilCommands
import com.sk89q.worldedit.command.UtilityCommands
import com.sk89q.worldedit.command.util.PermissionCondition
import com.sk89q.worldedit.internal.command.CommandUtil
import com.sk89q.worldedit.util.formatting.text.TextComponent
import org.enginehub.piston.Command
import org.enginehub.piston.config.TextConfig
import org.enginehub.piston.part.SubCommandPart
import org.enginehub.piston.util.HelpGenerator
import java.nio.file.Files
import java.nio.file.Paths
import java.util.stream.Stream
import kotlin.streams.toList
class DocumentationPrinter private constructor() {
private val nameRegex = Regex("name = \"(.+?)\"")
private val commands = WorldEdit.getInstance().platformManager.platformCommandManager.commandManager.allCommands
.map { it.name to it }.toList().toMap()
private val cmdOutput = StringBuilder()
private val permsOutput = StringBuilder()
private val matchedCommands = mutableSetOf<String>()
private inline fun <reified T> findCommandsIn(): Sequence<String> {
return sequence {
val sourceFile = Paths.get("worldedit-core/src/main/java/" + T::class.qualifiedName!!.replace('.', '/') + ".java")
require(Files.exists(sourceFile)) {
"Source not found for ${T::class.qualifiedName}, looked at ${sourceFile.toAbsolutePath()}"
}
Files.newBufferedReader(sourceFile).useLines { lines ->
var inCommand = false
for (line in lines) {
if (inCommand) {
when (val match = nameRegex.find(line)) {
null -> if (line.trim() == ")") inCommand = false
else -> yield(match.groupValues[1])
}
} else if (line.contains("@Command(")) {
inCommand = true
}
}
}
}
}
private fun writeAllCommands() {
writeHeader()
dumpSection("General Commands") {
yield("worldedit")
yieldAll(findCommandsIn<HistoryCommands>())
yieldAll(findCommandsIn<GeneralCommands>())
}
dumpSection("Navigation Commands") {
yieldAll(findCommandsIn<NavigationCommands>())
}
dumpSection("Selection Commands") {
yieldAll(findCommandsIn<SelectionCommands>())
yield("/expand")
}
dumpSection("Region Commands") {
yieldAll(findCommandsIn<RegionCommands>())
}
dumpSection("Generation Commands") {
yieldAll(findCommandsIn<GenerationCommands>())
}
dumpSection("Schematic and Clipboard Commands") {
yield("schematic")
yieldAll(findCommandsIn<ClipboardCommands>())
}
dumpSection("Tool Commands") {
yield("tool")
yieldAll(findCommandsIn<ToolCommands>().filter { it != "stacker" })
yieldAll(findCommandsIn<ToolUtilCommands>())
}
dumpSection("Super Pickaxe Commands") {
yield("superpickaxe")
}
dumpSection("Brush Commands") {
yield("brush")
}
dumpSection("Biome Commands") {
yieldAll(findCommandsIn<BiomeCommands>())
}
dumpSection("Chunk Commands") {
yieldAll(findCommandsIn<ChunkCommands>())
}
dumpSection("Snapshot Commands") {
yieldAll(findCommandsIn<SnapshotUtilCommands>())
yield("snapshot")
}
dumpSection("Scripting Commands") {
yieldAll(findCommandsIn<ScriptingCommands>())
}
dumpSection("Utility Commands") {
yieldAll(findCommandsIn<UtilityCommands>())
}
writeFooter()
val missingCommands = commands.keys.filterNot { it in matchedCommands }
require(missingCommands.isEmpty()) { "Missing commands: $missingCommands" }
}
private fun writeHeader() {
cmdOutput.appendLine("""
========
Commands
========
.. contents::
:local:
.. note::
Arguments enclosed in ``[ ]`` are optional, those enclosed in ``< >`` are required.
.. tip::
You can access a command listing in-game via the ``//help`` command.
""".trim())
permsOutput.appendLine("""
===========
Permissions
===========
By default, no one can use WorldEdit. In order for yourself, moderators, and players to use WorldEdit, you must provide the proper permissions. One way is to provide op to moderators and administrators (unless disabled in the :doc:`configuration <config>`), but providing the permission nodes on this page (through a permissions plugin) is the more flexible.
You can give the ``worldedit.*`` permission to give yourself and other administrators full access to WorldEdit.
Commands
=========
See the :doc:`commands` page for an explanation of some of these commands.
.. csv-table::
:header: Command, Permission
:widths: 15, 25
""".trim())
permsOutput.appendLine()
}
private fun writeFooter() {
permsOutput.appendLine()
permsOutput.append("""
Other Permissions
==================
.. csv-table::
:header: Permission, Explanation
:widths: 15, 25
``worldedit.navigation.jumpto.tool``,"Allows usage of the navigation wand's ``/jumpto`` shortcut (left click)."
``worldedit.navigation.thru.tool``,"Allows usage of the navigation wand's ``/thru`` shortcut (right click)."
``worldedit.anyblock``,"Allows usage of blocks in the :doc:`disallowed-blocks <config>` config option."
``worldedit.limit.unrestricted``,"Allows setting the limit via the ``//limit`` :doc:`command <commands>` higher than the maximum in the :doc:`configuration <config>`, as well as other limit bypasses."
``worldedit.timeout.unrestricted``,"Allows setting the calculation timeout via the ``//timeout`` :doc:`command <commands>` higher than the maximum in the :doc:`configuration <config>`."
``worldedit.inventory.unrestricted``,"Override the ``use-inventory`` option if enabled in the :doc:`configuration <config>`."
``worldedit.override.bedrock``,"Allows breaking of bedrock with the super-pickaxe tool."
``worldedit.override.data-cycler``,"Allows cycling non-whitelisted blocks with the data cycler tool."
``worldedit.setnbt``,"Allows setting `extra data <https://minecraft.gamepedia.com/Block_entity>`_ on blocks (such as signs, chests, etc)."
``worldedit.report.pastebin``,"Allows uploading report files to pastebin automatically for the ``/worldedit report`` :doc:`command <commands>`."
``worldedit.scripting.execute.<filename>``,"Allows using the CraftScript with the given filename."
""".trim())
}
private fun dumpSection(title: String, addCommandNames: suspend SequenceScope<String>.() -> Unit) {
cmdOutput.append("\n").append(title).append("\n").append(Strings.repeat("~", title.length)).append("\n")
val prefix = reduceToRst(TextConfig.commandPrefixValue())
val commands = sequence(addCommandNames).map { this.commands.getValue(it) }.toList()
matchedCommands.addAll(commands.map { it.name })
cmdsToPerms(commands, prefix)
for (command in commands) {
writeCommandBlock(command, prefix, Stream.empty())
command.parts.stream().filter { p -> p is SubCommandPart }
.flatMap { p -> (p as SubCommandPart).commands.stream() }
.forEach { sc ->
writeCommandBlock(sc, prefix + command.name + " ", Stream.of(command))
}
}
}
private fun cmdsToPerms(cmds: List<Command>, prefix: String) {
cmds.forEach { c ->
permsOutput.append(" ").append(cmdToPerm(prefix, c)).append("\n")
c.parts.filterIsInstance<SubCommandPart>()
.forEach { scp ->
cmdsToPerms(scp.commands.sortedBy { it.name }, prefix + c.name + " ")
}
}
}
private fun cmdToPerm(prefix: String, c: Command): String {
val cond = c.condition
val permissions = when {
cond is PermissionCondition && cond.permissions.isNotEmpty() ->
cond.permissions.joinToString(", ") { "``$it``" }
else -> ""
}
return "``$prefix${c.name}``,\"$permissions\""
}
private fun writeCommandBlock(command: Command, prefix: String, parents: Stream<Command>) {
val name = prefix + command.name
val entries = commandTableEntries(command, parents)
cmdOutput.appendLine(".. raw:: html")
cmdOutput.appendLine()
cmdOutput.appendLine(""" <span id="command-${linkSafe(name)}"></span>""")
cmdOutput.appendLine()
cmdOutput.append(".. topic:: ``$name``")
if (!command.aliases.isEmpty()) {
command.aliases.joinTo(cmdOutput, ", ",
prefix = " (or ",
postfix = ")",
transform = { "``$prefix$it``" })
}
cmdOutput.appendLine()
cmdOutput.appendLine(" :class: command-topic").appendLine()
CommandUtil.deprecationWarning(command).ifPresent { warning ->
cmdOutput.appendLine("""
| .. WARNING::
| ${reduceToRst(warning).makeRstSafe("\n\n")}
""".trimMargin())
}
cmdOutput.appendLine("""
| .. csv-table::
| :widths: 8, 15
""".trimMargin())
cmdOutput.appendLine()
for ((k, v) in entries) {
val rstSafe = v.makeRstSafe("\n")
cmdOutput.append(" ".repeat(2))
.append(k)
.append(",")
.append('"')
.append(rstSafe)
.append('"').appendLine()
}
cmdOutput.appendLine()
}
private fun String.makeRstSafe(lineJoiner: String) = trim()
.replace("\"", "\\\"").replace("\n", "\n" + " ".repeat(2))
.lineSequence()
.map { line -> line.ifBlank { "" } }
.joinToString(separator = lineJoiner)
private fun linkSafe(text: String) = text.replace(" ", "-")
private fun commandTableEntries(command: Command, parents: Stream<Command>): Map<String, String> {
return sequence {
val desc = command.description.run {
val footer = CommandUtil.footerWithoutDeprecation(command)
when {
footer.isPresent -> append(
TextComponent.builder("\n\n").append(footer.get())
)
else -> this
}
}
yield("**Description**" to reduceToRst(desc))
val cond = command.condition
if (cond is PermissionCondition && cond.permissions.isNotEmpty()) {
val perms = cond.permissions.joinToString(", ") { "``$it``" }
yield("**Permissions**" to perms)
}
val usage = reduceToRst(HelpGenerator.create(Stream.concat(parents, Stream.of(command)).toList()).usage)
yield("**Usage**" to "``$usage``")
// Part descriptions
command.parts.filterNot { it is SubCommandPart }
.forEach {
val title = "\u2001\u2001``" + reduceToRst(it.textRepresentation) + "``"
yield(title to reduceToRst(it.description))
}
}.toMap()
}
companion object {
/**
* Generates documentation.
*/
@JvmStatic
fun main(args: Array<String>) {
try {
WorldEdit.getInstance().platformManager.register(DocumentationPlatform())
val printer = DocumentationPrinter()
printer.writeAllCommands()
writeOutput("commands.rst", printer.cmdOutput.toString())
writeOutput("permissions.rst", printer.permsOutput.toString())
} finally {
WorldEdit.getInstance().sessionManager.unload()
}
}
private fun writeOutput(file: String, output: String) {
Files.newBufferedWriter(Paths.get(file)).use {
it.write(output)
}
}
}
}
| gpl-3.0 | 7d24293023d021516f502970479654ac | 38.084034 | 358 | 0.608256 | 4.380848 | false | false | false | false |
mdaniel/intellij-community | platform/execution-impl/src/com/intellij/execution/runToolbar/RunToolbarPopupController.kt | 1 | 6883 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.runToolbar
import com.intellij.openapi.Disposable
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.JBPopup
import com.intellij.openapi.util.Disposer
import com.intellij.ui.awt.RelativePoint
import com.intellij.ui.popup.AbstractPopup
import com.intellij.ui.popup.ComponentPopupBuilderImpl
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.PositionTracker
import com.intellij.util.ui.UIUtil
import java.awt.*
import java.awt.event.*
import java.util.function.Supplier
import javax.swing.SwingUtilities
import javax.swing.event.AncestorEvent
import javax.swing.event.AncestorListener
class RunToolbarPopupController(val project: Project,
val mainWidgetComponent: RunToolbarMainWidgetComponent) : PopupControllerComponentListener, Disposable {
private var popup: JBPopup? = null
private var pane: RunToolbarExtraSlotPane = RunToolbarExtraSlotPane(project, { mainWidgetComponent.width })
private val t: Int = JBUI.scale(4)
private val popupControllerComponents = mutableListOf<Component>()
private var componentPressed = false
private var canClose = false
init {
Disposer.register(project, this)
}
internal fun updateControllerComponents(components: MutableList<Component>) {
getPopupControllers().forEach { it.removeListener(this) }
popupControllerComponents.clear()
popupControllerComponents.addAll(components)
getPopupControllers().forEach { it.addListener(this) }
}
private fun getPopupControllers(): MutableList<PopupControllerComponent> {
return popupControllerComponents.filter { it is PopupControllerComponent }.map { (it as PopupControllerComponent).getController() }.toMutableList()
}
private fun show() {
if (mainWidgetComponent.isOpened) {
cancel()
return
}
mainWidgetComponent.isOpened = true
val slotPane = (if (pane.project == project) pane else null) ?:
run {
pane.clear()
RunToolbarExtraSlotPane(project, { mainWidgetComponent.width })
}
pane = slotPane
fun getTrackerRelativePoint(): RelativePoint {
return RelativePoint(mainWidgetComponent, Point(0, mainWidgetComponent.height + t))
}
val tracker = object : PositionTracker<AbstractPopup>(mainWidgetComponent) {
override fun recalculateLocation(b: AbstractPopup): RelativePoint {
return getTrackerRelativePoint()
}
}
val builder = object : ComponentPopupBuilderImpl(slotPane.getView(), mainWidgetComponent) {
override fun createPopup(): JBPopup {
return createPopup(Supplier<AbstractPopup?> {
object : AbstractPopup() {
override fun cancel(e: InputEvent?) {
e?.let {
if (it is MouseEvent) {
checkBounds(it)
}
}
super.cancel(e)
}
}
})
}
}
val popup = builder
.setCancelOnClickOutside(true)
.setCancelCallback {
(canClose || popup?.isFocused == false) && !componentPressed
}
.setMayBeParent(true)
.setShowBorder(true)
.createPopup()
fun updatePopupLocation() {
if (popup is AbstractPopup) {
popup.setLocation(tracker.recalculateLocation(popup))
popup.popupWindow?.let {
if (it.isShowing) {
it.pack()
}
}
}
}
SwingUtilities.invokeLater {
updatePopupLocation()
}
popup.show(if (popup is AbstractPopup)
tracker.recalculateLocation(popup)
else
getTrackerRelativePoint()
)
updatePopupLocation()
val ancestorListener = object : AncestorListener {
override fun ancestorAdded(event: AncestorEvent?) {
}
override fun ancestorRemoved(event: AncestorEvent?) {
cancel()
}
override fun ancestorMoved(event: AncestorEvent?) {
}
}
mainWidgetComponent.addAncestorListener(ancestorListener)
val adapterListener = object : ComponentAdapter() {
override fun componentMoved(e: ComponentEvent?) {
updateLocation()
}
override fun componentResized(e: ComponentEvent?) {
updateLocation()
}
private fun updateLocation() {
updatePopupLocation()
}
}
mainWidgetComponent.addComponentListener(adapterListener)
val awtEventListener = AWTEventListener {
if (it.id == MouseEvent.MOUSE_RELEASED) {
componentPressed = false
}
else if (it is WindowEvent) {
if (it.window is Dialog) {
cancel()
}
}
}
Toolkit.getDefaultToolkit().addAWTEventListener(
awtEventListener, AWTEvent.MOUSE_EVENT_MASK or AWTEvent.WINDOW_EVENT_MASK)
UIUtil.getRootPane(mainWidgetComponent)?.layeredPane?.let {
it.addComponentListener(adapterListener)
Disposer.register(popup) {
it.removeComponentListener(adapterListener)
}
}
Disposer.register(popup) {
componentPressed = false
mainWidgetComponent.isOpened = false
getPopupControllers().forEach { it.updateIconImmediately(mainWidgetComponent.isOpened) }
mainWidgetComponent.removeAncestorListener(ancestorListener)
mainWidgetComponent.removeComponentListener(adapterListener)
Toolkit.getDefaultToolkit().removeAWTEventListener(awtEventListener)
canClose = false
pane.clear()
this.popup = null
}
getPopupControllers().forEach { it.updateIconImmediately(mainWidgetComponent.isOpened) }
this.popup = popup
}
private fun checkBounds(e: MouseEvent) {
val bounds = mainWidgetComponent.bounds
bounds.location = Point(0, 0)
if (bounds.contains(RelativePoint(e).getPoint(mainWidgetComponent))) {
componentPressed = true
}
}
internal fun cancel() {
componentPressed = false
canClose = true
pane.clear()
popup?.cancel()
}
override fun dispose() {
cancel()
getPopupControllers().forEach { it.removeListener(this) }
}
private var firstShow = true
override fun actionPerformedHandler() {
show()
if(firstShow) {
cancel()
SwingUtilities.invokeLater {
show()
firstShow = false
}
}
}
}
interface PopupControllerComponent {
fun addListener(listener: PopupControllerComponentListener)
fun removeListener(listener: PopupControllerComponentListener)
fun updateIconImmediately(isOpened: Boolean)
fun getController(): PopupControllerComponent {
return this
}
}
interface PopupControllerComponentListener {
fun actionPerformedHandler()
} | apache-2.0 | eead3034c19e83618d6d9b8f2be9774f | 27.803347 | 158 | 0.680081 | 4.973266 | false | false | false | false |
mhickman/mandelbrot-explorer | src/main/kotlin/mandelbrot/Image.kt | 1 | 2266 | package mandelbrot
import java.awt.Color
import java.awt.image.BufferedImage
import java.lang.Math.max
import java.lang.Math.min
import java.lang.Math.sqrt
interface ColorPalette {
/**
* Gives a color for a particular {@code ImagePoint}.
* @param point This point to color.
*/
fun getColor(point: ImagePoint): Color
}
class BasicColorPalette(points: List<ImagePoint>,
val lowColor: Color = Color.WHITE,
val highColor: Color = Color.BLACK) : ColorPalette {
val minIterations: Int
val maxIterations: Int
val minSqrt: Double
val maxSqrt: Double
init {
val iterations = points.map { point -> point.mandelbrotPoint.iterations }
minIterations = iterations.min() ?: 0
maxIterations = iterations.max() ?: 0
minSqrt = sqrt(minIterations.toDouble())
maxSqrt = sqrt(maxIterations.toDouble())
}
override fun getColor(point: ImagePoint): Color {
val percent = getPercent(point.mandelbrotPoint.iterations)
return interpolateColor(percent)
}
private fun interpolateColor(percent: Double): Color {
return Color(sanitizeColor((lowColor.red + percent * (highColor.red - lowColor.red)).toInt()),
sanitizeColor((lowColor.blue + percent * (highColor.green - lowColor.green)).toInt()),
sanitizeColor((lowColor.green + percent * (highColor.blue - lowColor.blue)).toInt()))
}
private fun sanitizeColor(color: Int): Int {
return min(max(0, color), 255)
}
private fun getPercent(value: Int): Double {
val valueSqrt = sqrt(value.toDouble())
return (valueSqrt - minSqrt) / (maxSqrt - minSqrt)
}
}
class ImageCreator(val computer: MandelbrotComputer, val colorPalette: ColorPalette) {
val imageDescription = computer.description
val bufferedImage = BufferedImage(imageDescription.xPixels,
imageDescription.yPixels,
BufferedImage.TYPE_INT_ARGB)
fun getImage(): BufferedImage {
computer.points.forEach { point ->
bufferedImage.setRGB(point.xPixel,
point.yPixel,
colorPalette.getColor(point).rgb)
}
return bufferedImage
}
} | apache-2.0 | b516c9cd2c39426e3ba63aacef44448b | 31.385714 | 102 | 0.646072 | 4.275472 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/groovy/src/org/jetbrains/kotlin/idea/groovy/inspections/DifferentStdlibGradleVersionInspection.kt | 2 | 4899 | // 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.groovy.inspections
import com.intellij.openapi.externalSystem.model.ProjectKeys
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.psi.PsiFile
import org.jetbrains.annotations.NonNls
import org.jetbrains.kotlin.idea.compiler.configuration.IdeKotlinVersion
import org.jetbrains.kotlin.idea.configuration.KOTLIN_GROUP_ID
import org.jetbrains.kotlin.idea.extensions.gradle.KotlinGradleFacade
import org.jetbrains.kotlin.idea.extensions.gradle.SCRIPT_PRODUCTION_DEPENDENCY_STATEMENTS
import org.jetbrains.kotlin.idea.groovy.KotlinGroovyBundle
import org.jetbrains.kotlin.idea.platform.tooling
import org.jetbrains.kotlin.idea.roots.findAll
import org.jetbrains.kotlin.idea.roots.findGradleProjectStructure
import org.jetbrains.kotlin.platform.impl.JvmIdePlatformKind
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.plugins.groovy.codeInspection.BaseInspection
import org.jetbrains.plugins.groovy.codeInspection.BaseInspectionVisitor
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrCallExpression
class DifferentStdlibGradleVersionInspection : BaseInspection() {
override fun buildVisitor(): BaseInspectionVisitor = MyVisitor(KOTLIN_GROUP_ID, JvmIdePlatformKind.tooling.mavenLibraryIds)
override fun buildErrorString(vararg args: Any) =
KotlinGroovyBundle.message("error.text.different.kotlin.library.version", args[0], args[1])
private abstract class VersionFinder(private val groupId: String, private val libraryIds: List<String>) :
KotlinGradleInspectionVisitor() {
protected abstract fun onFound(stdlibVersion: IdeKotlinVersion, stdlibStatement: GrCallExpression)
override fun visitClosure(closure: GrClosableBlock) {
super.visitClosure(closure)
val dependenciesCall = closure.getStrictParentOfType<GrMethodCall>() ?: return
if (dependenciesCall.invokedExpression.text != "dependencies") return
if (dependenciesCall.parent !is PsiFile) return
val stdlibStatement = findLibraryStatement(closure, "org.jetbrains.kotlin", libraryIds) ?: return
val stdlibVersion = getResolvedLibVersion(closure.containingFile, groupId, libraryIds) ?: return
onFound(stdlibVersion, stdlibStatement)
}
}
private inner class MyVisitor(groupId: String, libraryIds: List<String>) : VersionFinder(groupId, libraryIds) {
override fun onFound(stdlibVersion: IdeKotlinVersion, stdlibStatement: GrCallExpression) {
val gradlePluginVersion = findResolvedKotlinGradleVersion(stdlibStatement.containingFile)
if (stdlibVersion != gradlePluginVersion) {
registerError(stdlibStatement, gradlePluginVersion, stdlibVersion)
}
}
}
companion object {
private fun findLibraryStatement(
closure: GrClosableBlock,
@NonNls libraryGroup: String,
libraryIds: List<String>
): GrCallExpression? {
return GradleHeuristicHelper.findStatementWithPrefixes(closure, SCRIPT_PRODUCTION_DEPENDENCY_STATEMENTS).firstOrNull { statement ->
libraryIds.any {
val index = statement.text.indexOf(it)
// This prevents detecting kotlin-stdlib inside kotlin-stdlib-common, -jdk8, etc.
index != -1 && statement.text.getOrNull(index + it.length) != '-'
} && statement.text.contains(libraryGroup)
}
}
fun getRawResolvedLibVersion(file: PsiFile, groupId: String, libraryIds: List<String>): String? {
val projectStructureNode = findGradleProjectStructure(file) ?: return null
val module = ProjectRootManager.getInstance(file.project).fileIndex.getModuleForFile(file.virtualFile) ?: return null
val gradleFacade = KotlinGradleFacade.instance ?: return null
for (moduleData in projectStructureNode.findAll(ProjectKeys.MODULE).filter { it.data.internalName == module.name }) {
gradleFacade.findLibraryVersionByModuleData(moduleData.node, groupId, libraryIds)?.let {
return it
}
}
return null
}
fun getResolvedLibVersion(file: PsiFile, groupId: String, libraryIds: List<String>): IdeKotlinVersion? {
val rawVersion = getRawResolvedLibVersion(file, groupId, libraryIds) ?: return null
return IdeKotlinVersion.opt(rawVersion)
}
}
} | apache-2.0 | 12859478312666199eef11596497fd4f | 51.12766 | 158 | 0.73117 | 5.071429 | false | false | false | false |
JetBrains/kotlin-native | backend.native/tests/codegen/bridges/test15.kt | 4 | 745 | /*
* 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 file.
*/
package codegen.bridges.test15
import kotlin.test.*
// non-generic interface, generic impl, vtable call + interface call
open class A<T> {
open var size: T = 56 as T
}
interface C {
var size: Int
}
open class B : C, A<Int>()
open class D: B() {
override var size: Int = 117
}
fun <T> foo(a: A<T>) {
a.size = 42 as T
}
fun box(): String {
val b = B()
foo(b)
if (b.size != 42) return "fail 1"
val d = D()
if (d.size != 117) return "fail 2"
foo(d)
if (d.size != 42) return "fail 3"
return "OK"
}
@Test fun runTest() {
println(box())
} | apache-2.0 | b97d213de35bb918965d7c7b95997fb9 | 15.954545 | 101 | 0.593289 | 2.933071 | false | true | false | false |
allotria/intellij-community | python/src/com/jetbrains/python/console/PydevConsoleCommunicationServer.kt | 3 | 6989 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.console
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressIndicatorProvider
import com.intellij.openapi.project.Project
import com.jetbrains.python.PyBundle
import com.jetbrains.python.console.protocol.PythonConsoleBackendService
import com.jetbrains.python.console.protocol.PythonConsoleFrontendService
import com.jetbrains.python.console.transport.server.ServerClosedException
import com.jetbrains.python.console.transport.server.TNettyServer
import com.jetbrains.python.console.transport.server.TNettyServerTransport
import com.jetbrains.python.debugger.PyDebugValueExecutionService
import org.apache.thrift.protocol.TBinaryProtocol
import org.apache.thrift.transport.TTransport
import java.util.concurrent.Future
import java.util.concurrent.TimeUnit
import java.util.concurrent.locks.Condition
import java.util.concurrent.locks.Lock
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
class PydevConsoleCommunicationServer(project: Project,
host: String,
port: Int) : PydevConsoleCommunication(project) {
private val serverTransport: TNettyServerTransport
/**
* This is the server responsible for giving input to a raw_input() requested.
*/
private val server: TNettyServer
/**
* Thrift RPC client for sending messages to the server.
*/
private var client: PythonConsoleBackendServiceDisposable? = null
private val stateLock: Lock = ReentrantLock()
private val stateChanged: Condition = stateLock.newCondition()
/**
* Initial non-thread safe [PythonConsoleBackendService.Client].
*
* Guarded by [stateLock].
*/
private var initialPythonConsoleClient: PythonConsoleBackendService.Iface? = null
/**
* Guarded by [stateLock].
*/
private var _pythonConsoleProcess: Process? = null
/**
* Guarded by [stateLock].
*/
private var isFailedOnBound: Boolean = false
/**
* Guarded by [stateLock].
*/
private var isServerBound: Boolean = false
/**
* Guarded by [stateLock].
*/
private var isClosed: Boolean = false
init {
val serverHandler = createPythonConsoleFrontendHandler()
val serverProcessor = PythonConsoleFrontendService.Processor<PythonConsoleFrontendService.Iface>(serverHandler)
//noinspection IOResourceOpenedButNotSafelyClosed
serverTransport = TNettyServerTransport(host, port)
server = TNettyServer(serverTransport, serverProcessor)
}
/**
* Must be called once.
*/
fun serve() {
// start server in the separate thread
ApplicationManager.getApplication().executeOnPooledThread { server.serve() }
ApplicationManager.getApplication().executeOnPooledThread {
// this will wait for the connection of Python Console to the IDE
val clientTransport: TTransport
try {
clientTransport = serverTransport.getReverseTransport()
}
catch (e: ServerClosedException) {
// this is the normal execution flow
throw ProcessCanceledException(e)
}
val clientProtocol = TBinaryProtocol(clientTransport)
val client = PythonConsoleBackendService.Client(clientProtocol)
stateLock.withLock {
// early close
if (isClosed) {
server.stop()
// this is the normal execution flow
throw ProcessCanceledException()
}
initialPythonConsoleClient = client
stateChanged.signalAll()
}
val executionService = PyDebugValueExecutionService.getInstance(myProject)
executionService.sessionStarted(this)
addFrameListener { executionService.cancelSubmittedTasks(this@PydevConsoleCommunicationServer) }
}
stateLock.withLock {
try {
// waiting on `CountDownLatch.await()` within `stateLock` might be harmful
serverTransport.waitForBind()
isServerBound = true
}
finally {
isFailedOnBound = !isServerBound
stateChanged.signalAll()
}
}
}
/**
* The Python Console process is expected to be set after the server is
* bound.
*/
fun setPythonConsoleProcess(pythonConsoleProcess: Process) {
stateLock.withLock {
if (isClosed) {
throw CommunicationClosedException()
}
if (!isServerBound) {
LOG.warn("Python Console process is set before IDE server is bound, the process may not be able to connect to the server")
}
_pythonConsoleProcess = pythonConsoleProcess
stateChanged.signalAll()
}
}
override fun getPythonConsoleBackendClient(): PythonConsoleBackendServiceDisposable {
stateLock.withLock {
while (!isClosed && !isFailedOnBound) {
// if `client` is set just return it
client?.let {
return it
}
val initialPythonConsoleClient = initialPythonConsoleClient
val pythonConsoleProcess = _pythonConsoleProcess
if (initialPythonConsoleClient != null && pythonConsoleProcess != null) {
val newClient = synchronizedPythonConsoleClient(PydevConsoleCommunication::class.java.classLoader,
initialPythonConsoleClient, pythonConsoleProcess)
client = newClient
return newClient
}
else {
stateChanged.await()
}
}
throw CommunicationClosedException()
}
}
override fun closeCommunication(): Future<*> {
val progressIndicator: ProgressIndicator? = ProgressIndicatorProvider.getInstance().progressIndicator
stateLock.withLock {
try {
isClosed = true
}
finally {
stateChanged.signalAll()
}
}
// if client exists then try to gracefully `close()` it
try {
client?.apply {
progressIndicator?.text2 = PyBundle.message("debugger.sending.close.message")
close()
dispose()
}
}
catch (e: Exception) {
// ignore exceptions on `client` shutdown
}
_pythonConsoleProcess?.let {
progressIndicator?.text2 = PyBundle.message("debugger.waiting.to.finish")
// TODO move under feature!
try {
do {
progressIndicator?.checkCanceled()
}
while (!it.waitFor(500, TimeUnit.MILLISECONDS))
}
catch (e: InterruptedException) {
Thread.currentThread().interrupt()
}
}
return server.stop()
}
override fun isCommunicationClosed(): Boolean = stateLock.withLock { isClosed }
companion object {
val LOG: Logger = Logger.getInstance(PydevConsoleCommunicationServer::class.java)
}
} | apache-2.0 | 0b37a6940c19f9bef1f32336024f29ef | 29.792952 | 140 | 0.695378 | 5.060825 | false | false | false | false |
pokk/SSFM | app/src/main/kotlin/taiwan/no1/app/ssfm/pattern/decorate/NormalPlayerButtonDecorator.kt | 1 | 835 | package taiwan.no1.app.ssfm.pattern.decorate
import android.widget.ImageButton
/**
* Decorator of normal player button without changing button image.
*
* @author jieyi
* @since 7/3/17
*/
class NormalPlayerButtonDecorator(val btn: ImageButton, setting: (Wrapper.() -> Unit)? = null) :
PlayerButtonDecorator(btn) {
init {
val wrapper = setting?.let(Wrapper()::also)
wrapper?.imageResource?.let(btn::setImageResource)
wrapper?.padding?.let { btn.setPadding(it, it, it, it) }
}
override fun changeNextState(imageBtn: ImageButton) {}
data class Wrapper(
var imageResource: Int? = null,
var padding: Int? = null,
var paddingStart: Int? = null,
var paddingEnd: Int? = null,
var paddingTop: Int? = null,
var paddingBottom: Int? = null)
} | apache-2.0 | f0dbfb7642a12e582c8cdd59d5bb4af4 | 26.866667 | 96 | 0.645509 | 3.97619 | false | false | false | false |
shogo4405/HaishinKit.java | haishinkit/src/main/java/com/haishinkit/rtmp/RtmpMuxer.kt | 1 | 13381 | package com.haishinkit.rtmp
import android.graphics.ImageFormat
import android.media.MediaFormat
import android.os.SystemClock
import android.util.Log
import com.haishinkit.BuildConfig
import com.haishinkit.codec.MediaCodec
import com.haishinkit.event.Event
import com.haishinkit.flv.FlvAacPacketType
import com.haishinkit.flv.FlvAudioCodec
import com.haishinkit.flv.FlvAvcPacketType
import com.haishinkit.flv.FlvFlameType
import com.haishinkit.flv.FlvVideoCodec
import com.haishinkit.iso.AvcConfigurationRecord
import com.haishinkit.lang.Running
import com.haishinkit.media.BufferController
import com.haishinkit.media.MediaLink
import com.haishinkit.metric.FrameTracker
import com.haishinkit.rtmp.message.RtmpAudioMessage
import com.haishinkit.rtmp.message.RtmpVideoMessage
import com.haishinkit.util.MediaFormatUtil
import java.nio.ByteBuffer
import java.util.concurrent.atomic.AtomicBoolean
internal class RtmpMuxer(private val stream: RtmpStream) :
Running,
BufferController.Listener,
MediaCodec.Listener {
override var isRunning = AtomicBoolean(false)
var mode = MediaCodec.Mode.DECODE
set(value) {
stream.audioCodec.mode = value
stream.videoCodec.mode = value
field = value
}
var hasAudio: Boolean
get() = mediaLink.hasAudio
set(value) {
mediaLink.hasAudio = value
}
var hasVideo: Boolean
get() = mediaLink.hasVideo
set(value) {
mediaLink.hasVideo = value
}
var bufferTime = BufferController.DEFAULT_BUFFER_TIME
set(value) {
audioBufferController.bufferTime = bufferTime
videoBufferController.bufferTime = bufferTime
field = value
}
private var hasFirstFlame = false
private var audioTimestamp = 0L
private var videoTimestamp = 0L
private var frameTracker: FrameTracker? = null
get() {
if (field == null && BuildConfig.DEBUG) {
field = FrameTracker()
}
return field
}
private val mediaLink: MediaLink by lazy {
MediaLink(stream.audioCodec, stream.videoCodec)
}
private val audioBufferController: BufferController<RtmpAudioMessage> by lazy {
val controller = BufferController<RtmpAudioMessage>("audio")
controller.bufferTime = bufferTime
controller.listener = this
controller
}
private val videoBufferController: BufferController<RtmpVideoMessage> by lazy {
val controller = BufferController<RtmpVideoMessage>("video")
controller.bufferTime = bufferTime
controller.listener = this
controller
}
fun enqueueAudio(message: RtmpAudioMessage) {
audioBufferController.enqueue(message, message.timestamp)
}
fun enqueueVideo(message: RtmpVideoMessage) {
videoBufferController.enqueue(message, message.timestamp)
}
@Synchronized
override fun startRunning() {
if (isRunning.get()) return
if (BuildConfig.DEBUG) {
Log.d(TAG, "startRunning()")
}
hasFirstFlame = false
when (mode) {
MediaCodec.Mode.ENCODE -> {
stream.audio?.let {
it.startRunning()
stream.audioCodec.listener = this
stream.audioCodec.startRunning()
}
stream.video?.let {
it.startRunning()
stream.videoCodec.listener = this
stream.videoCodec.startRunning()
}
}
MediaCodec.Mode.DECODE -> {
mediaLink.startRunning()
}
}
isRunning.set(true)
}
@Synchronized
override fun stopRunning() {
if (!isRunning.get()) return
if (BuildConfig.DEBUG) {
Log.d(TAG, "stopRunning()")
}
when (mode) {
MediaCodec.Mode.ENCODE -> {
stream.audio?.let {
it.stopRunning()
stream.audioCodec.stopRunning()
}
stream.video?.let {
it.stopRunning()
stream.videoCodec.stopRunning()
}
}
MediaCodec.Mode.DECODE -> {
clear()
mediaLink.stopRunning()
}
}
isRunning.set(false)
}
fun clear() {
audioTimestamp = 0L
videoTimestamp = 0L
frameTracker?.clear()
audioBufferController.clear()
videoBufferController.clear()
}
override fun onInputBufferAvailable(mime: String, codec: android.media.MediaCodec, index: Int) {
when (mime) {
MediaCodec.MIME_AUDIO_MP4A -> {
stream.audio?.onInputBufferAvailable(codec, index)
}
MediaCodec.MIME_VIDEO_RAW -> {
try {
val inputBuffer = codec.getInputBuffer(index) ?: return
videoBufferController.stop(!hasFirstFlame)
val message = videoBufferController.take()
videoBufferController.consume(message.timestamp)
message.data?.let {
it.position(4)
inputBuffer.put(it)
}
videoTimestamp += message.timestamp * 1000
codec.queueInputBuffer(
index,
0,
message.length - 5,
videoTimestamp,
message.toFlags()
)
message.release()
} catch (e: InterruptedException) {
Log.w(TAG, "", e)
}
}
MediaCodec.MIME_AUDIO_RAW -> {
try {
val inputBuffer = codec.getInputBuffer(index) ?: return
audioBufferController.stop()
val message = audioBufferController.take()
audioBufferController.consume(message.timestamp)
message.data?.let {
it.position(1)
inputBuffer.put(it)
}
audioTimestamp += message.timestamp * 1000
codec.queueInputBuffer(
index,
0,
message.length - 2,
audioTimestamp,
message.toFlags()
)
message.release()
} catch (e: InterruptedException) {
Log.w(TAG, "", e)
}
}
}
}
override fun onFormatChanged(mime: String, mediaFormat: MediaFormat) {
when (mime) {
MediaCodec.MIME_VIDEO_RAW -> {
mediaFormat.apply {
val width = MediaFormatUtil.getWidth(this)
val height = MediaFormatUtil.getHeight(this)
stream.renderer?.pixelTransform?.createInputSurface(
width,
height,
ImageFormat.NV21
)
}
stream.dispatchEventWith(
Event.RTMP_STATUS,
false,
RtmpStream.Code.VIDEO_DIMENSION_CHANGE.data("")
)
}
MediaCodec.MIME_VIDEO_AVC -> {
val config = AvcConfigurationRecord.create(mediaFormat)
val video = stream.messageFactory.createRtmpVideoMessage()
video.packetType = FlvAvcPacketType.SEQ
video.frame = FlvFlameType.KEY
video.codec = FlvVideoCodec.AVC
video.data = config.allocate().apply {
config.encode(this)
flip()
}
video.chunkStreamID = RtmpChunk.VIDEO
video.streamID = stream.id
video.timestamp = 0
video.compositeTime = 0
stream.doOutput(RtmpChunk.ZERO, video)
}
MediaCodec.MIME_AUDIO_RAW -> {
mediaLink.audioTrack = stream.createAudioTrack(mediaFormat)
}
MediaCodec.MIME_AUDIO_MP4A -> {
val config = mediaFormat.getByteBuffer("csd-0") ?: return
val audio = stream.messageFactory.createRtmpAudioMessage()
audio.codec = FlvAudioCodec.AAC
audio.aacPacketType = FlvAacPacketType.SEQ
audio.data = config
audio.chunkStreamID = RtmpChunk.AUDIO
audio.streamID = stream.id
audio.timestamp = 0
stream.doOutput(RtmpChunk.ZERO, audio)
}
}
}
override fun onSampleOutput(
mime: String,
index: Int,
info: android.media.MediaCodec.BufferInfo,
buffer: ByteBuffer
): Boolean {
when (mime) {
MediaCodec.MIME_VIDEO_RAW -> {
if (!hasFirstFlame) {
hasFirstFlame =
(info.flags and android.media.MediaCodec.BUFFER_FLAG_KEY_FRAME) != 0
stream.videoCodec.codec?.releaseOutputBuffer(index, hasFirstFlame)
return false
}
mediaLink.queueVideo(
MediaLink.Buffer(
index,
null,
info.presentationTimeUs,
(info.flags and android.media.MediaCodec.BUFFER_FLAG_KEY_FRAME) != 0
)
)
return false
}
MediaCodec.MIME_VIDEO_AVC -> {
if (info.flags and android.media.MediaCodec.BUFFER_FLAG_CODEC_CONFIG != 0) {
return true
}
frameTracker?.track(FrameTracker.TYPE_VIDEO, SystemClock.uptimeMillis())
if (videoTimestamp == 0L) {
videoTimestamp = info.presentationTimeUs
}
val timestamp = (info.presentationTimeUs - videoTimestamp).toInt()
val keyframe = info.flags and android.media.MediaCodec.BUFFER_FLAG_KEY_FRAME != 0
val video = stream.messageFactory.createRtmpVideoMessage()
video.packetType = FlvAvcPacketType.NAL
video.frame = if (keyframe) FlvFlameType.KEY else FlvFlameType.INTER
video.codec = FlvVideoCodec.AVC
video.data = buffer
video.chunkStreamID = RtmpChunk.VIDEO
video.timestamp = timestamp / 1000
video.streamID = stream.id
video.compositeTime = 0
stream.doOutput(RtmpChunk.ONE, video)
stream.frameCount.incrementAndGet()
videoTimestamp = info.presentationTimeUs
return true
}
MediaCodec.MIME_AUDIO_RAW -> {
mediaLink.queueAudio(MediaLink.Buffer(index, buffer, info.presentationTimeUs, true))
return false
}
MediaCodec.MIME_AUDIO_MP4A -> {
if (info.flags and android.media.MediaCodec.BUFFER_FLAG_CODEC_CONFIG != 0) {
return true
}
frameTracker?.track(FrameTracker.TYPE_AUDIO, SystemClock.uptimeMillis())
if (audioTimestamp == 0L) {
audioTimestamp = info.presentationTimeUs
}
val timestamp = (info.presentationTimeUs - audioTimestamp).toInt()
val audio = stream.messageFactory.createRtmpAudioMessage()
audio.codec = FlvAudioCodec.AAC
audio.aacPacketType = FlvAacPacketType.RAW
audio.data = buffer
audio.chunkStreamID = RtmpChunk.AUDIO
audio.timestamp = timestamp / 1000
audio.streamID = stream.id
stream.doOutput(RtmpChunk.ONE, audio)
audioTimestamp = info.presentationTimeUs
return true
}
}
return true
}
override fun onCaptureOutput(type: Byte, buffer: ByteBuffer, timestamp: Long) {
stream.listener?.onCaptureOutput(stream, type, buffer, timestamp)
}
override fun <T> onBufferFull(controller: BufferController<T>) {
if (controller == videoBufferController) {
if (stream.receiveVideo) {
mediaLink.paused = false
} else {
return
}
}
stream.dispatchEventWith(Event.RTMP_STATUS, false, RtmpStream.Code.BUFFER_FULL.data(""))
}
override fun <T> onBufferEmpty(controller: BufferController<T>) {
if (controller == videoBufferController) {
if (stream.receiveVideo) {
mediaLink.paused = true
} else {
return
}
}
stream.dispatchEventWith(Event.RTMP_STATUS, false, RtmpStream.Code.BUFFER_EMPTY.data(""))
}
companion object {
private const val VERBOSE = false
private var TAG = RtmpMuxer::class.java.simpleName
}
}
| bsd-3-clause | 7cd15a667620b5549837352383d08f5c | 35.964088 | 100 | 0.538151 | 5.128785 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/references/KDocReference.kt | 2 | 933 | // 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.references
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.kdoc.psi.impl.KDocName
import org.jetbrains.kotlin.name.Name
abstract class KDocReference(element: KDocName) : KtMultiReference<KDocName>(element) {
override fun getRangeInElement(): TextRange = element.getNameTextRange()
override fun canRename(): Boolean = true
override fun resolve(): PsiElement? = multiResolve(false).firstOrNull()?.element
abstract override fun handleElementRename(newElementName: String): PsiElement?
override fun getCanonicalText(): String = element.getNameText()
override val resolvesByNames: Collection<Name> get() = listOf(Name.identifier(element.getNameText()))
}
| apache-2.0 | 8a724a57651d40a274d8e4a142e540e9 | 41.409091 | 158 | 0.782422 | 4.485577 | false | false | false | false |
smmribeiro/intellij-community | plugins/stream-debugger/src/com/intellij/debugger/streams/lib/impl/LibrarySupportBase.kt | 23 | 3176 | // 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.intellij.debugger.streams.lib.impl
import com.intellij.debugger.streams.lib.*
import com.intellij.debugger.streams.resolve.ValuesOrderResolver
import com.intellij.debugger.streams.trace.CallTraceInterpreter
import com.intellij.debugger.streams.trace.IntermediateCallHandler
import com.intellij.debugger.streams.trace.TerminatorCallHandler
import com.intellij.debugger.streams.trace.dsl.Dsl
import com.intellij.debugger.streams.wrapper.IntermediateStreamCall
import com.intellij.debugger.streams.wrapper.TerminatorStreamCall
/**
* @author Vitaliy.Bibaev
*/
abstract class LibrarySupportBase(private val compatibleLibrary: LibrarySupport = LibrarySupportBase.EMPTY) : LibrarySupport {
companion object {
val EMPTY: LibrarySupport = DefaultLibrarySupport()
}
private val mySupportedIntermediateOperations: MutableMap<String, IntermediateOperation> = mutableMapOf()
private val mySupportedTerminalOperations: MutableMap<String, TerminalOperation> = mutableMapOf()
final override fun createHandlerFactory(dsl: Dsl): HandlerFactory {
val compatibleLibraryFactory = compatibleLibrary.createHandlerFactory(dsl)
return object : HandlerFactory {
override fun getForIntermediate(number: Int, call: IntermediateStreamCall): IntermediateCallHandler {
val operation = mySupportedIntermediateOperations[call.name]
return operation?.getTraceHandler(number, call, dsl)
?: compatibleLibraryFactory.getForIntermediate(number, call)
}
override fun getForTermination(call: TerminatorStreamCall, resultExpression: String): TerminatorCallHandler {
val terminalOperation = mySupportedTerminalOperations[call.name]
return terminalOperation?.getTraceHandler(call, resultExpression, dsl)
?: compatibleLibraryFactory.getForTermination(call, resultExpression)
}
}
}
final override val interpreterFactory: InterpreterFactory = object : InterpreterFactory {
override fun getInterpreter(callName: String): CallTraceInterpreter {
val operation = findOperationByName(callName)
return operation?.traceInterpreter
?: compatibleLibrary.interpreterFactory.getInterpreter(callName)
}
}
final override val resolverFactory: ResolverFactory = object : ResolverFactory {
override fun getResolver(callName: String): ValuesOrderResolver {
val operation = findOperationByName(callName)
return operation?.valuesOrderResolver
?: compatibleLibrary.resolverFactory.getResolver(callName)
}
}
protected fun addIntermediateOperationsSupport(vararg operations: IntermediateOperation) {
operations.forEach { mySupportedIntermediateOperations[it.name] = it }
}
protected fun addTerminationOperationsSupport(vararg operations: TerminalOperation) {
operations.forEach { mySupportedTerminalOperations[it.name] = it }
}
private fun findOperationByName(name: String): Operation? =
mySupportedIntermediateOperations[name] ?: mySupportedTerminalOperations[name]
} | apache-2.0 | 1a11900b84a332ed17c352740d87d6c1 | 45.720588 | 140 | 0.785264 | 5.033281 | false | false | false | false |
anastr/SpeedView | speedviewlib/src/main/java/com/github/anastr/speedviewlib/TubeSpeedometer.kt | 1 | 3204 | package com.github.anastr.speedviewlib
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.RectF
import android.os.Build
import android.util.AttributeSet
/**
* this Library build By Anas Altair
* see it on [GitHub](https://github.com/anastr/SpeedView)
*/
open class TubeSpeedometer @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0,
) : Speedometer(context, attrs, defStyleAttr) {
private val tubePaint = Paint(Paint.ANTI_ALIAS_FLAG)
private val tubeBacPaint = Paint(Paint.ANTI_ALIAS_FLAG)
private val speedometerRect = RectF()
var speedometerBackColor: Int
get() = tubeBacPaint.color
set(speedometerBackColor) {
tubeBacPaint.color = speedometerBackColor
invalidateGauge()
}
init {
init()
initAttributeSet(context, attrs)
}
override fun defaultGaugeValues() {
super.speedometerWidth = dpTOpx(40f)
sections[0].color = 0xff00BCD4.toInt()
sections[1].color = 0xffFFC107.toInt()
sections[2].color = 0xffF44336.toInt()
}
override fun defaultSpeedometerValues() {
super.backgroundCircleColor = 0
}
private fun init() {
tubePaint.style = Paint.Style.STROKE
tubeBacPaint.style = Paint.Style.STROKE
tubeBacPaint.color = 0xff757575.toInt()
if (Build.VERSION.SDK_INT >= 11)
setLayerType(LAYER_TYPE_SOFTWARE, null)
}
private fun initAttributeSet(context: Context, attrs: AttributeSet?) {
if (attrs == null)
return
val a = context.theme.obtainStyledAttributes(attrs, R.styleable.TubeSpeedometer, 0, 0)
tubeBacPaint.color = a.getColor(R.styleable.TubeSpeedometer_sv_speedometerBackColor, tubeBacPaint.color)
a.recycle()
}
override fun onSizeChanged(w: Int, h: Int, oldW: Int, oldH: Int) {
super.onSizeChanged(w, h, oldW, oldH)
updateBackgroundBitmap()
}
private fun initDraw() {
tubePaint.strokeWidth = speedometerWidth
if (currentSection != null)
tubePaint.color = currentSection!!.color
else
tubePaint.color = 0 // transparent color
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
initDraw()
val sweepAngle = (getEndDegree() - getStartDegree()) * getOffsetSpeed()
canvas.drawArc(speedometerRect, getStartDegree().toFloat(), sweepAngle, false, tubePaint)
drawSpeedUnitText(canvas)
drawIndicator(canvas)
drawNotes(canvas)
}
override fun updateBackgroundBitmap() {
val c = createBackgroundBitmapCanvas()
tubeBacPaint.strokeWidth = speedometerWidth
val risk = speedometerWidth * .5f + padding
speedometerRect.set(risk, risk, size - risk, size - risk)
c.drawArc(speedometerRect, getStartDegree().toFloat(), (getEndDegree() - getStartDegree()).toFloat(), false, tubeBacPaint)
drawMarks(c)
if (tickNumber > 0)
drawTicks(c)
else
drawDefMinMaxSpeedPosition(c)
}
}
| apache-2.0 | 1c1bd14475f694fbf3b3179081056bc3 | 28.666667 | 130 | 0.652622 | 3.985075 | false | false | false | false |
intrigus/jtransc | jtransc-gen-haxe/src/com/jtransc/gen/haxe/HaxeCompiler.kt | 1 | 7857 | package com.jtransc.gen.haxe
import com.jtransc.io.ProcessUtils
import com.jtransc.vfs.LocalVfs
import com.jtransc.vfs.SyncVfsFile
import java.io.File
import java.io.FileNotFoundException
object HaxeCompiler {
fun ensureHaxeSubtarget(subtarget: String) {
}
fun ensureHaxeCompilerVfs(): SyncVfsFile {
val haxePath = ProcessUtils.locateCommand("haxe") ?: throw FileNotFoundException("Can't find haxe command")
return LocalVfs(File(haxePath).parentFile)
}
fun getExtraEnvs(): Map<String, String> {
return mapOf()
}
}
/*
object HaxeCompiler {
val HAXE_VERSION = "3.3.0-rc.1"
val NEKO_VERSION = "2.1.0"
val HAXE_FILE: String by lazy {
if (JTranscSystem.isWindows()) "haxe-$HAXE_VERSION-win.zip"
else if (JTranscSystem.isMac()) "haxe-$HAXE_VERSION-osx.tar.gz"
else if (JTranscSystem.isLinux() && JTranscSystem.isOs32()) "haxe-$HAXE_VERSION-linux32.tar.gz"
else if (JTranscSystem.isLinux() && JTranscSystem.isOs64()) "haxe-$HAXE_VERSION-linux64.tar.gz"
else invalidOp("Not supported operaning system. Just supporting windows, osx and linux.")
}
val NEKO_FILE: String by lazy {
if (JTranscSystem.isWindows()) "neko-$NEKO_VERSION-win.zip"
else if (JTranscSystem.isMac()) "neko-$NEKO_VERSION-osx64.tar.gz"
else if (JTranscSystem.isLinux() && JTranscSystem.isOs32()) "neko-$NEKO_VERSION-linux.tar.gz"
else if (JTranscSystem.isLinux() && JTranscSystem.isOs64()) "neko-$NEKO_VERSION-linux64.tar.gz"
else invalidOp("Not supported operaning system. Just supporting windows, osx and linux.")
}
//https://github.com/jtransc/haxe-releases/releases/download/neko-2.1.0/neko-2.1.0-linux.tar.gz
//http://haxe.org/website-content/downloads/3.3.0-rc.1/downloads/haxe-3.3.0-rc.1-win.zip
//http://nekovm.org/media/neko-2.1.0-linux64.tar.gz
//val haxeCompilerUrl: URL by lazy { URL("https://github.com/jtransc/haxe-releases/releases/download/haxe-$HaxeVersion/$haxeCompilerFile") }
//val nekoUrl: URL by lazy { URL("https://github.com/jtransc/haxe-releases/releases/download/neko-$NekoVersion/$nekoFile") }
val ON_CI by lazy { CI.isOnCiSystem }
val HAXE_URL: URL by lazy {
if (ON_CI) {
// Unsecure but official download to avoid spamming github
// It would be great to use maven
// https://github.com/HaxeFoundation/haxe/issues/5331
URL("http://haxe.org/website-content/downloads/$HAXE_VERSION/downloads/$HAXE_FILE")
} else {
URL("https://github.com/jtransc/haxe-releases/blob/master/haxe/$HAXE_VERSION/$HAXE_FILE?raw=true")
}
}
val NEKO_URL: URL by lazy {
if (ON_CI) {
// Unsecure but official download to avoid spamming github
// It would be great to use maven
// https://github.com/HaxeFoundation/haxe/issues/5331
URL("http://nekovm.org/media/$NEKO_FILE")
} else {
URL("https://github.com/jtransc/haxe-releases/blob/master/neko/$NEKO_VERSION/$NEKO_FILE?raw=true")
}
}
val jtranscHaxeFolder: String by lazy { JTranscSystem.getUserHome() + "/.jtransc/haxe" }
val jtranscNekoFolder: String by lazy { JTranscSystem.getUserHome() + "/.jtransc/neko" }
val jtranscHaxeNekoFolder: String by lazy { JTranscSystem.getUserHome() + "/.jtransc/haxeneko" }
val haxeCompilerUrlVfs: SyncVfsFile by lazy { UrlVfs(HAXE_URL) }
val haxeCompilerLocalFileVfs: SyncVfsFile by lazy { LocalVfsEnsureDirs(File(jtranscHaxeFolder)).access(HAXE_FILE) }
val haxeLocalFolderVfs: SyncVfsFile by lazy { LocalVfsEnsureDirs(File("$jtranscHaxeFolder/$HAXE_VERSION")) }
val nekoUrlVfs: SyncVfsFile by lazy { UrlVfs(NEKO_URL) }
val nekoLocalFileVfs: SyncVfsFile by lazy { LocalVfsEnsureDirs(File(jtranscNekoFolder)).access(NEKO_FILE) }
val nekoLocalFolderVfs: SyncVfsFile by lazy { LocalVfsEnsureDirs(File("$jtranscNekoFolder/$NEKO_VERSION")) }
val haxeNekoLocalFolderVfs: SyncVfsFile by lazy { LocalVfsEnsureDirs(File("$jtranscHaxeNekoFolder/${HAXE_VERSION}_$NEKO_VERSION")) }
fun getHaxeTargetLibraries(subtarget: String): List<String> = when (subtarget) {
"cpp", "windows", "linux", "mac", "osx" -> listOf("hxcpp")
"c#", "cs", "csharp" -> listOf("hxcs")
"java", "jvm" -> listOf("hxjava")
else -> listOf()
}
var ensured = false
fun ensureHaxeCompilerVfs(): SyncVfsFile {
if (!ensured) {
ensured = true
log.info("ensureHaxeCompilerVfs:")
/////////////////////////////////////////
// NEKO
/////////////////////////////////////////
if (!nekoLocalFileVfs.exists) {
log.info("Downloading neko: $NEKO_URL...")
nekoUrlVfs.copyTo(nekoLocalFileVfs)
}
if (!nekoLocalFolderVfs["std.ndll"].exists) {
//for (syncVfsStat in CompressedVfs(nekoLocalFileVfs.realfile).listdirRecursive()) println(syncVfsStat)
val compvfsBase = CompressedVfs(nekoLocalFileVfs.realfile).firstRecursive { it.file.name == "std.ndll" }.file.parent
compvfsBase.copyTreeTo(nekoLocalFolderVfs, doLog = false)
if (!JTranscSystem.isWindows()) {
nekoLocalFolderVfs["neko"].chmod(FileMode.fromString("-rwxr-xr-x"))
nekoLocalFolderVfs["nekoc"].chmod(FileMode.fromString("-rwxr-xr-x"))
nekoLocalFolderVfs["nekoml"].chmod(FileMode.fromString("-rwxr-xr-x"))
}
}
/////////////////////////////////////////
// HAXE
/////////////////////////////////////////
if (!haxeCompilerLocalFileVfs.exists) {
log.info("Downloading haxe: $HAXE_URL...")
haxeCompilerUrlVfs.copyTo(haxeCompilerLocalFileVfs)
}
if (!haxeLocalFolderVfs["std"].exists) {
val compvfsBase = CompressedVfs(haxeCompilerLocalFileVfs.realfile).firstRecursive { it.file.name == "std" }.file.parent
compvfsBase.copyTreeTo(haxeLocalFolderVfs, doLog = false)
if (!JTranscSystem.isWindows()) {
haxeLocalFolderVfs["haxe"].chmod(FileMode.fromString("-rwxr-xr-x"))
haxeLocalFolderVfs["haxelib"].chmod(FileMode.fromString("-rwxr-xr-x"))
}
}
/////////////////////////////////////////
// NEKO-HAXE mixed so haxelib works fine without strange stuff
/////////////////////////////////////////
if (
(!haxeNekoLocalFolderVfs["haxe"].exists || !haxeNekoLocalFolderVfs["neko"].exists) &&
(!haxeNekoLocalFolderVfs["haxe.exe"].exists || !haxeNekoLocalFolderVfs["neko.exe"].exists)
) {
haxeNekoLocalFolderVfs.ensuredir()
haxeLocalFolderVfs.copyTreeTo(haxeNekoLocalFolderVfs, doLog = false)
nekoLocalFolderVfs.copyTreeTo(haxeNekoLocalFolderVfs, doLog = false)
if (JTranscSystem.isNotWindows()) {
haxeNekoLocalFolderVfs["neko"].chmod(FileMode.fromString("-rwxr-xr-x"))
haxeNekoLocalFolderVfs["nekoc"].chmod(FileMode.fromString("-rwxr-xr-x"))
haxeNekoLocalFolderVfs["nekoml"].chmod(FileMode.fromString("-rwxr-xr-x"))
haxeNekoLocalFolderVfs["haxe"].chmod(FileMode.fromString("-rwxr-xr-x"))
haxeNekoLocalFolderVfs["haxelib"].chmod(FileMode.fromString("-rwxr-xr-x"))
}
}
/////////////////////////////////////////
// HAXELIB
/////////////////////////////////////////
if (!haxeNekoLocalFolderVfs["lib"].exists || HaxeLib.getHaxelibFolderFile() == null) {
HaxeLib.setup(haxeNekoLocalFolderVfs["lib"].realpathOS)
}
if (!haxeNekoLocalFolderVfs["lib"].exists) {
throw RuntimeException("haxelib setup failed!")
}
}
return haxeNekoLocalFolderVfs
}
fun getExtraEnvs(): Map<String, String> = mapOf(
"HAXE_STD_PATH" to haxeNekoLocalFolderVfs["std"].realpathOS,
"HAXE_HOME" to haxeNekoLocalFolderVfs.realpathOS,
"HAXEPATH" to haxeNekoLocalFolderVfs.realpathOS,
"NEKOPATH" to haxeNekoLocalFolderVfs.realpathOS,
// OSX
"*DYLD_LIBRARY_PATH" to haxeNekoLocalFolderVfs.realpathOS + File.pathSeparator,
// Linux
"*LD_LIBRARY_PATH" to haxeNekoLocalFolderVfs.realpathOS + File.pathSeparator,
"*PATH" to haxeNekoLocalFolderVfs.realpathOS + File.pathSeparator
)
fun ensureHaxeSubtarget(subtarget: String) {
ensureHaxeCompilerVfs()
for (lib in getHaxeTargetLibraries(subtarget)) {
HaxeLib.installIfNotExists(HaxeLib.LibraryRef.fromVersion(lib))
}
}
}
*/
| apache-2.0 | 0d8a26c40389d6cd245b91b821036cb0 | 39.086735 | 141 | 0.694158 | 3.052448 | false | false | false | false |
mitchell-johnson/kimber | kimber-sample/src/main/kotlin/com/example/kimber/ExampleApp.kt | 1 | 902 | package com.example.kimber
import android.app.Application
import android.util.Log
import kimber.log.DebugTree
import kimber.log.Kimber
import kimber.log.Tree
class ExampleApp() : Application() {
override fun onCreate() {
super.onCreate()
Kimber.plant(DebugTree())
Kimber.plant(CrashReportingTree)
}
object CrashReportingTree : Tree() {
override fun log(priority: Int, tag: String?, message: String, t: Throwable?) {
if (priority == Log.VERBOSE || priority == Log.DEBUG) {
return
}
FakeCrashLibrary.log(priority, tag, message)
if (t != null) {
if (priority == Log.ERROR) {
FakeCrashLibrary.logError(t)
} else if (priority == Log.WARN) {
FakeCrashLibrary.logWarning(t)
}
}
}
}
} | apache-2.0 | ad6330fba0875181068fa5d491594c23 | 25.558824 | 87 | 0.55765 | 4.195349 | false | false | false | false |
hazuki0x0/YuzuBrowser | module/ui/src/main/java/jp/hazuki/yuzubrowser/ui/widget/PaddingFrameLayout.kt | 1 | 2052 | /*
* Copyright (C) 2017-2019 Hazuki
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jp.hazuki.yuzubrowser.ui.widget
import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.view.View
import android.widget.FrameLayout
class PaddingFrameLayout @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
var realHeight = 0
private set
private var isBlackMode = false
var visible = false
set(value) {
field = value
setVisible()
}
var forceHide = false
set(value) {
field = value
setVisible()
}
fun setBlackColorMode(blackMode: Boolean) {
if (blackMode) {
if (!isBlackMode) {
setBackgroundColor(Color.BLACK)
isBlackMode = true
}
} else {
if (isBlackMode) {
setBackgroundColor(Color.WHITE)
isBlackMode = false
}
}
}
fun setHeight(height: Int) {
if (realHeight != height) {
realHeight = height
val params = layoutParams
params.height = height
layoutParams = params
}
}
private fun setVisible() {
visibility = when {
forceHide -> View.GONE
visible -> View.VISIBLE
else -> View.GONE
}
}
}
| apache-2.0 | 1319d43dd9ad3fc4285b01361fddea84 | 26 | 75 | 0.601365 | 4.642534 | false | false | false | false |
EMResearch/EvoMaster | core/src/main/kotlin/org/evomaster/core/output/service/PartialOracles.kt | 1 | 8184 | package org.evomaster.core.output.service
import com.google.inject.Inject
import io.swagger.v3.oas.models.OpenAPI
import org.evomaster.core.EMConfig
import org.evomaster.core.output.Lines
import org.evomaster.core.output.ObjectGenerator
import org.evomaster.core.output.OutputFormat
import org.evomaster.core.output.oracles.ImplementedOracle
import org.evomaster.core.output.oracles.SchemaOracle
import org.evomaster.core.output.oracles.SupportedCodeOracle
import org.evomaster.core.problem.rest.RestCallAction
import org.evomaster.core.problem.httpws.service.HttpWsCallResult
import org.evomaster.core.problem.rest.RestIndividual
import org.evomaster.core.search.EvaluatedAction
import org.evomaster.core.search.EvaluatedIndividual
/**
* [PartialOracles] are meant to be a way to handle different types of soft assertions/expectations (name may change in future)
*
* The idea is that any new type of expectation is a partial oracle (again, name may change, if anything more appropriate
* emerges). For example, if a return object is specified in the Swagger for a given endpoint with a given status code,
* then the object returned should have the same structure as the Swagger reference (see [responseStructure] below.
*
* They are "partial" because failing such a test is not necessarily indicative of a bug, as it could be some sort
* or shortcut or something (and since REST semantics are not strictly enforced, it cannot be an assert). Nevertheless,
* it would be a break with expected semantics and could be indicative of a fault or design problem.
*
* The [PartialOracles] would (in future) each receive their own variable to turn on or off, and only those selected
* would be added to the code. So they should be independent from each other. The idea is that, either during generation
* or during execution, the user can decide if certain partial oracles are of interest at the moment, and turn then
* on or off as required.
*
*/
class PartialOracles {
@Inject
private lateinit var config: EMConfig
private val objectGenerator = ObjectGenerator()
private val oracles = mutableListOf<ImplementedOracle>()
private val expectationsMasterSwitch = "ems"
fun setupForRest(schema: OpenAPI){
oracles.add(SupportedCodeOracle())
oracles.add(SchemaOracle())
oracles.forEach {
it.setObjectGenerator(objectGenerator)
}
objectGenerator.setSwagger(schema)
}
/**
* The [variableDeclaration] method handles the generation of auxiliary variables for the partial oracles.
* The parameters [lines] and [format] are received from the [TestCaseWriter].
* The parameter [active] records which partial oracles are active (i.e. which actually generate
* a failing expectation). [active] is a mutable map, where the key is a string containing the name of
* an [ImplementedOracle], and the key is a boolean indicating whether the oracle is active (i.e. will
* generate a failing expectation, and thus require the additional variables) or inactive (i.e. it will
* not generate a failing expectation and thus can be skipped).
*
* The goal of this method is to ensure that only relevant variables are generated (i.e. to avoid
* generating stub variables that are never used).
*/
fun variableDeclaration(lines: Lines, format: OutputFormat, active: Map<String, Boolean>){
for (oracle in oracles){
if(active.get(oracle.getName()) == true) {
oracle.variableDeclaration(lines, format)
}
}
}
fun addExpectations(call: RestCallAction, lines: Lines, res: HttpWsCallResult, name: String, format: OutputFormat) {
val generates = oracles.any {
it.generatesExpectation(call, res)
}
if (!generates) return
lines.add("expectationHandler.expect($expectationsMasterSwitch)")
lines.indented {
for (oracle in oracles) { oracle.addExpectations(call, lines, res, name, format) }
if (format.isJava()) { lines.append(";") }
}
}
fun selectForClustering(action: EvaluatedAction): Boolean{
return oracles.any { oracle ->
oracle.selectForClustering(action)
}
}
/**
* The [generatesExpectation] method evaluates is, for any given test case, any expectation is generated.
* This is used in the [ExpectationsWriter] to ensure that, if no (failing) expectation is generated,
* the variable [ExpectationHandler] is not added to the generated code.
*/
fun generatesExpectation(individual: EvaluatedIndividual<RestIndividual>): Boolean{
return oracles.any { oracle ->
individual.evaluatedMainActions().any {
oracle.generatesExpectation(
(it.action as RestCallAction),
(it.result as HttpWsCallResult)
)
}
}
}
fun generatesExpectation(call: RestCallAction, res: HttpWsCallResult): Boolean{
return oracles.any { oracle ->
oracle.generatesExpectation( call, res)
}
}
/**
* [failByOracle] is an auxiliary method that generates a mutable map. The key for each entry in this
* mutable map is the name of an [ImplementedOracle], and the value is a list of [EvaluatedIndividual]
* that are selected for clustering (i.e. for which a failing expectation is generated) by that
* specific oracle.
*
* The values are sorted by size, measured in terms of number of [EvaluatedAction] in the respective
* [EvaluatedIndividual]. This sorting ensures that the shortest of the available Individuals is selected
* for the executive summary.
*
* The method is used to create the executive summary in the [TestSuiteSplitter]. The executive
* summary is created by selecting from each of the sets returned by the [failByOracle] method that
* [EvaluatedIndividual] fulfils some additional requirements (for example, does not repeat - if an
* [EvaluatedIndividual] has failing expectations generated by more than one oracle, it should not be
* repeated in the executive summary, but the next shortest candidate (if available) will be selected
* instead.
*
* The method uses MutableMap and MutableList only as a necessity for selection and sorting, and no
* changes are made to the [EvaluatedIndividual] objects themselves.
*
*/
fun failByOracle(individuals: List<EvaluatedIndividual<RestIndividual>>): MutableMap<String, MutableList<EvaluatedIndividual<RestIndividual>>>{
val oracleInds = mutableMapOf<String, MutableList<EvaluatedIndividual<RestIndividual>>>()
oracles.forEach { oracle ->
val failindInds = individuals.filter {
it.evaluatedMainActions().any { oracle.selectForClustering(it) }
}.toMutableList()
failindInds.sortBy { it.evaluatedMainActions().size }
oracleInds.put(oracle.getName(), failindInds)
}
return oracleInds
}
fun activeOracles(individuals: List<EvaluatedIndividual<*>>): MutableMap<String, Boolean>{
val active = mutableMapOf<String, Boolean>()
oracles.forEach { oracle ->
active.put(oracle.getName(), individuals.any { individual ->
individual.evaluatedMainActions().any {
it.action is RestCallAction && oracle.generatesExpectation(
(it.action as RestCallAction),
(it.result as HttpWsCallResult)
)
} })
}
return active
}
fun activeOracles(call: RestCallAction, res: HttpWsCallResult): MutableMap<String, Boolean>{
val active = mutableMapOf<String, Boolean>()
oracles.forEach { oracle ->
active.put(oracle.getName(), oracle.generatesExpectation(call, res))
}
return active
}
fun adjustName(): MutableList<ImplementedOracle>{
return oracles.filter { !it.adjustName().isNullOrBlank() }.toMutableList()
}
} | lgpl-3.0 | d07656d9d5f064d46b59d87042de923c | 43.972527 | 147 | 0.690005 | 4.717003 | false | false | false | false |
savoirfairelinux/ring-client-android | ring-android/app/src/main/java/cx/ring/client/AccountSpinnerAdapter.kt | 1 | 7266 | /*
* Copyright (C) 2004-2021 Savoir-faire Linux Inc.
*
* Author: AmirHossein Naghshzan <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package cx.ring.client
import android.content.Context
import android.util.Log
import android.widget.ArrayAdapter
import cx.ring.R
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import cx.ring.views.AvatarDrawable
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import android.widget.RelativeLayout
import cx.ring.databinding.ItemToolbarSelectedBinding
import cx.ring.databinding.ItemToolbarSpinnerBinding
import io.reactivex.rxjava3.disposables.CompositeDisposable
import net.jami.model.Account
import net.jami.model.Profile
import net.jami.services.AccountService
class AccountSpinnerAdapter(context: Context, accounts: List<Account>, val disposable: CompositeDisposable, var mAccountService: AccountService) :
ArrayAdapter<Account>(context, R.layout.item_toolbar_spinner, accounts) {
private val mInflater: LayoutInflater = LayoutInflater.from(context)
private val logoSize: Int = context.resources.getDimensionPixelSize(R.dimen.list_medium_icon_size)
private fun getTitle(account: Account, profile: Profile): String {
return profile.displayName.orEmpty().ifEmpty {
account.registeredName.ifEmpty {
account.alias.orEmpty().ifEmpty {
context.getString(R.string.ring_account)
}
}
}
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
var view = convertView
val type = getItemViewType(position)
val holder: ViewHolderHeader
if (view == null) {
holder = ViewHolderHeader(ItemToolbarSelectedBinding.inflate(mInflater, parent, false), disposable)
view = holder.binding.root
view.setTag(holder)
} else {
holder = view.tag as ViewHolderHeader
holder.loader.clear()
}
if (type == TYPE_ACCOUNT) {
val account = getItem(position)!!
holder.loader.add(mAccountService.getObservableAccountProfile(account.accountId)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ profile ->
holder.binding.logo.setImageDrawable(AvatarDrawable.build(holder.binding.root.context, profile.first, profile.second, true, profile.first.isRegistered))
holder.binding.title.text = getTitle(profile.first, profile.second)
}){ e: Throwable -> Log.e(TAG, "Error loading avatar", e) })
}
return view
}
override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
val type = getItemViewType(position)
val holder: ViewHolder
var rowView = convertView
if (rowView == null) {
holder = ViewHolder(ItemToolbarSpinnerBinding.inflate(mInflater, parent, false), disposable)
rowView = holder.binding.root
rowView.setTag(holder)
} else {
holder = rowView.tag as ViewHolder
holder.loader.clear()
}
holder.binding.logo.visibility = View.VISIBLE
val logoParam = holder.binding.logo.layoutParams
if (type == TYPE_ACCOUNT) {
val account = getItem(position)!!
val ip2ipString = rowView.context.getString(R.string.account_type_ip2ip)
val params = holder.binding.title.layoutParams as RelativeLayout.LayoutParams
params.removeRule(RelativeLayout.CENTER_VERTICAL)
holder.binding.title.layoutParams = params
logoParam.width = logoSize
logoParam.height = logoSize
holder.binding.logo.layoutParams = logoParam
holder.loader.add(mAccountService.getObservableAccountProfile(account.accountId)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ profile ->
val subtitle = getUri(account, ip2ipString)
holder.binding.logo.setImageDrawable(AvatarDrawable.build(holder.binding.root.context, profile.first, profile.second, true, profile.first.isRegistered))
holder.binding.title.text = getTitle(profile.first, profile.second)
if (holder.binding.title.text == subtitle) {
holder.binding.subtitle.visibility = View.GONE
} else {
holder.binding.subtitle.visibility = View.VISIBLE
holder.binding.subtitle.text = subtitle
}
}){ e: Throwable -> Log.e(TAG, "Error loading avatar", e) })
} else {
holder.binding.title.setText(
if (type == TYPE_CREATE_JAMI) R.string.add_ring_account_title else R.string.add_sip_account_title)
holder.binding.subtitle.visibility = View.GONE
holder.binding.logo.setImageResource(R.drawable.baseline_add_24)
logoParam.width = ViewGroup.LayoutParams.WRAP_CONTENT
logoParam.height = ViewGroup.LayoutParams.WRAP_CONTENT
holder.binding.logo.layoutParams = logoParam
val params = holder.binding.title.layoutParams as RelativeLayout.LayoutParams
params.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE)
holder.binding.title.layoutParams = params
}
return rowView
}
override fun getItemViewType(position: Int): Int {
if (position == super.getCount()) {
return TYPE_CREATE_JAMI
}
return if (position == super.getCount() + 1) TYPE_CREATE_SIP else TYPE_ACCOUNT
}
override fun getCount(): Int {
return super.getCount() + 2
}
private class ViewHolder(val binding: ItemToolbarSpinnerBinding, parentDisposable: CompositeDisposable) {
val loader = CompositeDisposable().apply { parentDisposable.add(this) }
}
private class ViewHolderHeader(val binding: ItemToolbarSelectedBinding, parentDisposable: CompositeDisposable) {
val loader = CompositeDisposable().apply { parentDisposable.add(this) }
}
private fun getUri(account: Account, defaultNameSip: CharSequence): String {
return if (account.isIP2IP) defaultNameSip.toString() else account.displayUri!!
}
companion object {
private val TAG = AccountSpinnerAdapter::class.simpleName!!
const val TYPE_ACCOUNT = 0
const val TYPE_CREATE_JAMI = 1
const val TYPE_CREATE_SIP = 2
}
} | gpl-3.0 | c24c5e8426d215031b4cd1b93379f160 | 44.993671 | 172 | 0.669144 | 4.654709 | false | false | false | false |
RocketChat/Rocket.Chat.Android | app/src/main/java/chat/rocket/android/authentication/ui/AuthenticationActivity.kt | 2 | 5371 | package chat.rocket.android.authentication.ui
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import chat.rocket.android.R
import chat.rocket.android.authentication.domain.model.DeepLinkInfo
import chat.rocket.android.authentication.presentation.AuthenticationPresenter
import chat.rocket.android.dynamiclinks.DynamicLinksForFirebase
import chat.rocket.android.util.extensions.getDeepLinkInfo
import chat.rocket.android.util.extensions.isDynamicLink
import chat.rocket.android.util.extensions.isSupportedLink
import chat.rocket.common.util.ifNull
import dagger.android.AndroidInjection
import dagger.android.AndroidInjector
import dagger.android.DispatchingAndroidInjector
import dagger.android.support.HasSupportFragmentInjector
import kotlinx.android.synthetic.main.app_bar.*
import javax.inject.Inject
class AuthenticationActivity : AppCompatActivity(), HasSupportFragmentInjector {
@Inject
lateinit var fragmentDispatchingAndroidInjector: DispatchingAndroidInjector<Fragment>
@Inject
lateinit var presenter: AuthenticationPresenter
@Inject
lateinit var dynamicLinksManager: DynamicLinksForFirebase
override fun onCreate(savedInstanceState: Bundle?) {
AndroidInjection.inject(this)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_authentication)
setupToolbar()
processIncomingIntent(intent)
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
intent?.let {
processIncomingIntent(it)
}
}
private fun processIncomingIntent(intent: Intent) {
if (intent.isSupportedLink(this)) {
intent.data?.let { uri ->
if (uri.isDynamicLink(this)) {
resolveDynamicLink(intent)
} else {
uri.getDeepLinkInfo(baseContext)?.let {
routeDeepLink(it)
}.ifNull {
loadCredentials()
}
}
}
} else {
loadCredentials()
}
}
private fun resolveDynamicLink(intent: Intent) {
val deepLinkCallback = { returnedUri: Uri? ->
returnedUri?.let {
returnedUri.getDeepLinkInfo(baseContext)?.let {
routeDeepLink(it)
}
}.ifNull {
loadCredentials()
}
}
dynamicLinksManager.getDynamicLink(intent, deepLinkCallback)
}
private fun setupToolbar() {
with(toolbar) {
setSupportActionBar(this)
setNavigationIcon(R.drawable.ic_arrow_back_white_24dp)
setNavigationOnClickListener { onBackPressed() }
}
supportActionBar?.setDisplayShowTitleEnabled(false)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
val currentFragment = supportFragmentManager.findFragmentById(R.id.fragment_container)
currentFragment?.onActivityResult(requestCode, resultCode, data)
}
override fun supportFragmentInjector(): AndroidInjector<Fragment> =
fragmentDispatchingAndroidInjector
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.legal, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
R.id.action_terms_of_Service -> presenter.termsOfService(getString(R.string.action_terms_of_service))
R.id.action_privacy_policy -> presenter.privacyPolicy(getString(R.string.action_privacy_policy))
}
return super.onOptionsItemSelected(item)
}
private fun routeDeepLink(deepLinkInfo: DeepLinkInfo) {
presenter.loadCredentials(false) { isAuthenticated ->
if (isAuthenticated) {
showChatList(deepLinkInfo)
} else {
presenter.saveDeepLinkInfo(deepLinkInfo)
if (getString(R.string.server_url).isEmpty()) {
presenter.toOnBoarding()
} else {
presenter.toSignInToYourServer()
}
}
}
}
private fun loadCredentials() {
val newServer = intent.getBooleanExtra(INTENT_ADD_NEW_SERVER, false)
presenter.loadCredentials(newServer) { isAuthenticated ->
when {
isAuthenticated -> showChatList()
getString(R.string.server_url).isEmpty() -> presenter.toOnBoarding()
else -> presenter.toSignInToYourServer()
}
}
}
private fun showChatList() = presenter.toChatList()
private fun showChatList(deepLinkInfo: DeepLinkInfo) = presenter.toChatList(deepLinkInfo)
}
const val INTENT_ADD_NEW_SERVER = "INTENT_ADD_NEW_SERVER"
fun Context.newServerIntent(): Intent {
return Intent(this, AuthenticationActivity::class.java).apply {
putExtra(INTENT_ADD_NEW_SERVER, true)
flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
}
| mit | 66ac7c21e8d8d279f83b6656bccf7605 | 35.04698 | 113 | 0.665053 | 5.086174 | false | false | false | false |
darekp7/Embedis | src/Embedis.kt | 1 | 6790 | package embedis
import kotlin.coroutines.experimental.buildSequence
interface EmbdObject {
val id: Long
}
class EmbdSnapshot<TObject: EmbdObject>(head: HashMap<Long, TObject?>?, tail: Array<Map<Long, TObject?>>) {
private val deltas = if (head == null || head.count() <= 0)
tail
else {
Array<Map<Long, TObject?>>(tail.count() + 1) {
if (it == 0)
head
else
tail[it - 1]
}
}
fun containsId(id: Long) = this[id] != null
val deltasCount: Int
get() = deltas.count()
val head: Map<Long, TObject?>?
get() = if (deltas.count() <= 0) null else deltas[0]
fun tail() = Array<Map<Long, TObject?>>(if(deltas.count() <= 1) 0 else deltas.count() - 1) { deltas[it + 1] }
fun tail2() = Array<Map<Long, TObject?>>(if(deltas.count() <= 2) 0 else deltas.count() - 2) { deltas[it + 2] }
val allDeltas
get() = deltas
operator fun get(id: Long): TObject? {
for (m in deltas) {
if (m.containsKey(id)) {
return m[id]
}
}
return null
}
fun toCanonicalForm(): EmbdSnapshot<TObject> {
var res = this
while(res.deltasCount >= 2 && res.deltas[0].count() > res.deltas[1].count() / 2) {
val merged = merge(HashMap(deltas[0]), deltas[1])
res = EmbdSnapshot(merged, res.tail2())
if(res.deltasCount == 1) {
removeNulls(merged)
}
}
return res
}
fun toFlatForm() : EmbdSnapshot<TObject> {
var res = this
if(res.deltasCount == 1) {
if(res.deltas[0].any {(_, v) -> v == null }) {
val notNull = removeNulls(HashMap(deltas[0]))
res = EmbdSnapshot(notNull, Array<Map<Long, TObject?>>(0) { null!! })
}
} else {
while (res.deltasCount >= 2) {
val merged = merge(HashMap(deltas[0]), deltas[1])
res = EmbdSnapshot(merged, res.tail2())
if (res.deltasCount == 1) {
removeNulls(merged)
}
}
}
return res
}
fun merge(merged: HashMap<Long, TObject?>, map2: Map<Long, TObject?>): HashMap<Long, TObject?> {
for((id, obj) in map2) {
if(!merged.containsKey(id)) {
merged[id] = obj
}
}
return merged
}
private fun removeNulls(map: HashMap<Long, TObject?>): HashMap<Long, TObject?> {
val nulls = map.filter { (_, v) -> v == null }
for((k, _ ) in nulls) {
map.remove(k)
}
return map
}
}
class EmbdTableBuilder<TObject: EmbdObject>(private var deltas: EmbdSnapshot<TObject>) {
private val SMALL_SIZE = 16
private var head: HashMap<Long, TObject?>? = null
private var isSeparated = false
private var sortedImage: ArrayList<TObject>? = null
operator fun get(id: Long): TObject? {
return if (head != null && (head?.containsKey(id) ?: false))
head?.get(id)
else
deltas[id]
}
fun add(obj: TObject): Unit {
if (obj !== this[obj.id]) { // if not reference equals - comparing by reference is fast
sortedImage = null
if (isSeparated) {
head = head ?: HashMap<Long, TObject?>()
head?.put(obj.id, obj)
} else {
allocHead()
head?.put(obj.id, obj)
makeCanonicalIfHeadIsTooBig(true)
}
}
}
fun getOrInsert(id: Long, defaultObj: () -> TObject): TObject {
val res = this[id]
return if (res != null) {
res
} else {
val res = defaultObj()
add(res)
res
}
}
fun delete(id: Long) {
if(sortedImage != null && this[id] != null)
sortedImage = null
if (!deltas.containsId(id)) {
head?.remove(id)
} else {
allocHead()
head?.put(id, null)
makeCanonicalIfHeadIsTooBig(true)
}
}
fun selectUnsorted(predicate: (TObject) -> Boolean) = buildSequence {
separate()
if(head != null) {
for ((_, v) in head ?: HashMap<Long, TObject?>())
if (v != null && predicate(v))
yield(v)
}
}
fun selectOrderById(predicate: (TObject) -> Boolean) = buildSequence {
separateAndSort()
if(sortedImage != null) {
for (v in sortedImage ?: ArrayList<TObject>(0))
if (predicate(v))
yield(v)
}
}
fun selectOrderByIdDesc(predicate: (TObject) -> Boolean) = buildSequence {
separateAndSort()
if(sortedImage != null) {
val arr = sortedImage ?: ArrayList<TObject>(0)
for (i in arr.count()-1 downTo 0)
if (predicate(arr[i]))
yield(arr[i])
}
}
private fun separateAndSort() {
separate()
if (sortedImage == null) {
val h = head ?: HashMap<Long, TObject?>()
sortedImage = ArrayList(h.values.filter { it != null }.map { it!! }.sortedBy { it -> it.id })
}
}
private fun separate() {
if(!isSeparated) {
head = HashMap(EmbdSnapshot(head, deltas.allDeltas).toFlatForm().head)
deltas = EmbdSnapshot(null, Array<Map<Long, TObject?>>(0) { HashMap<Long, TObject?>()})
isSeparated = true
}
}
/**
* This function forces head to be non-null. In most cases it must be called before inserting and/or deleting an object.
*/
private fun allocHead() {
if ((head == null || head?.count() ?: 0 <= 0) && deltas.head != null && deltas.head?.count() ?: 0 <= SMALL_SIZE) {
head = HashMap(deltas.head)
deltas = EmbdSnapshot(null, deltas.tail())
}
if (head == null) {
head = HashMap<Long, TObject?>()
}
}
private fun makeCanonicalIfHeadIsTooBig(allowSeparation: Boolean) {
if (head?.count() ?: 0 > 2 * SMALL_SIZE) {
makeCanonical(allowSeparation)
}
}
private fun makeCanonical (allowSeparation: Boolean) {
if(!isSeparated) {
val bothBefore = head?.count() ?: 0 > 0 && deltas.deltasCount > 0
deltas = EmbdSnapshot(head, deltas.allDeltas).toCanonicalForm()
head = null
if (allowSeparation && deltas.deltasCount == 1 && bothBefore) {
head = HashMap(deltas.head)
deltas = EmbdSnapshot(null, deltas.tail())
isSeparated = true
}
}
}
}
| unlicense | 6c2e474d2c5cee2cf382545376e7c4bd | 30.004566 | 124 | 0.507216 | 3.987082 | false | false | false | false |
katanagari7c1/wolverine-comics-kotlin | app/src/main/kotlin/dev/katanagari7c1/wolverine/presentation/search_result/SearchResultActivity.kt | 1 | 4192 | package dev.katanagari7c1.wolverine.presentation.search_result
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.Toolbar
import android.view.View.GONE
import android.view.View.VISIBLE
import dev.katanagari7c1.wolverine.R
import dev.katanagari7c1.wolverine.domain.repository.ComicPersistanceRepository
import dev.katanagari7c1.wolverine.domain.repository.ComicRepository
import dev.katanagari7c1.wolverine.domain.use_case.ComicFindContainingTextInTitleAndOffsetUseCase
import dev.katanagari7c1.wolverine.domain.use_case.ComicSaveOrUpdateUseCase
import dev.katanagari7c1.wolverine.domain.util.ImageLoader
import dev.katanagari7c1.wolverine.presentation.application.WolverineApplication
import dev.katanagari7c1.wolverine.presentation.base.DialogActivity
import dev.katanagari7c1.wolverine.presentation.main.data_loader.ComicListDataLoader
import dev.katanagari7c1.wolverine.presentation.main.data_loader.LoadMoreItemsCallback
import dev.katanagari7c1.wolverine.presentation.main.list.ComicListAdapter
import dev.katanagari7c1.wolverine.presentation.main.list.ComicListScrollListener
import kotlinx.android.synthetic.main.activity_search_result.*
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.find
import org.jetbrains.anko.uiThread
import javax.inject.Inject
import javax.inject.Named
class SearchResultActivity : DialogActivity(), LoadMoreItemsCallback {
companion object {
const val EXTRA_SEARCH_QUERY = "search_query"
}
@field:[Inject Named("network")]
lateinit var repository:ComicRepository
@Inject
lateinit var persistanceRepository: ComicPersistanceRepository
@Inject
lateinit var imageLoader:ImageLoader
private lateinit var adapter: ComicListAdapter
private lateinit var dataLoader: ComicListDataLoader
private var isRequestingComics = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_search_result)
WolverineApplication.getInjectorComponent(this).inject(this)
val queryString = getQueryFromIntent(this.intent)
this.initializeToolbar(find<Toolbar>(R.id.search_toolbar))
.withUpNavigation()
.title(formatTitle(queryString))
this.dataLoader = this.initializeDataLoader(queryString)
this.initializeList(this.dataLoader)
this.fetchComics()
}
private fun formatTitle(queryString: String): String {
return String.format(getString(R.string.search_screen_title), queryString)
}
private fun getQueryFromIntent(intent: Intent?): String {
if (intent != null) {
return intent.getStringExtra(EXTRA_SEARCH_QUERY)
}
return ""
}
private fun initializeDataLoader(queryString: String): ComicListDataLoader {
return ComicListDataLoader(
loadWithOffsetUseCase = ComicFindContainingTextInTitleAndOffsetUseCase(queryString, repository),
saveUseCase = ComicSaveOrUpdateUseCase(persistanceRepository)
)
}
private fun fetchComics() {
if (!this.isRequestingComics) {
this.isRequestingComics = true
this.showLoading(R.string.loading_comics)
doAsync {
val comics = dataLoader.load()
uiThread {
adapter.appendComics(comics)
hideLoading()
showNoResultScreen(adapter)
isRequestingComics = false
}
}
}
}
private fun showNoResultScreen(adapter: ComicListAdapter) {
this.search_no_result_view.visibility = if (adapter.comics.isEmpty()) VISIBLE else GONE
}
override fun shouldLoadMoreItems() {
this.fetchComics()
}
private fun initializeList(dataLoader: ComicListDataLoader) {
this.adapter = ComicListAdapter(
activity = this,
imageLoader = this.imageLoader
)
val itemsPerRow = resources.getInteger(R.integer.items_per_row)
val layoutManager = GridLayoutManager(this, itemsPerRow)
this.search_comic_recycler_view.setHasFixedSize(true)
this.search_comic_recycler_view.layoutManager = layoutManager
this.search_comic_recycler_view.adapter = this.adapter
this.search_comic_recycler_view.addOnScrollListener(
ComicListScrollListener(
itemsPerRequest = dataLoader.numberOfItemsToLoad,
layoutManager = layoutManager,
loadMoreItemsCallback = this
)
)
}
} | mit | de56ee7b933ffbab306e1c2243b5b42a | 31.253846 | 99 | 0.807013 | 3.928772 | false | false | false | false |
kamgurgul/cpu-info | app/src/main/java/com/kgurgul/cpuinfo/features/applications/NewApplicationsViewModel.kt | 1 | 2513 | package com.kgurgul.cpuinfo.features.applications
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.kgurgul.cpuinfo.R
import com.kgurgul.cpuinfo.domain.model.ExtendedApplicationData
import com.kgurgul.cpuinfo.domain.model.sortOrderFromBoolean
import com.kgurgul.cpuinfo.domain.observable.ApplicationsDataObservable
import com.kgurgul.cpuinfo.domain.result.GetPackageNameInteractor
import com.kgurgul.cpuinfo.utils.wrappers.Result
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.collections.immutable.ImmutableList
import kotlinx.collections.immutable.persistentListOf
import kotlinx.collections.immutable.toImmutableList
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class NewApplicationsViewModel @Inject constructor(
private val applicationsDataObservable: ApplicationsDataObservable,
private val getPackageNameInteractor: GetPackageNameInteractor,
) : ViewModel() {
private val _uiStateFlow = MutableStateFlow(UiState())
val uiStateFlow = _uiStateFlow.asStateFlow()
init {
applicationsDataObservable.observe()
.onEach(::handleApplicationsResult)
.launchIn(viewModelScope)
onRefreshApplications()
}
fun onRefreshApplications() {
applicationsDataObservable.invoke(
ApplicationsDataObservable.Params(
withSystemApps = false,
sortOrderFromBoolean(true)
)
)
}
fun onApplicationClicked(packageName: String) {
viewModelScope.launch {
if (getPackageNameInteractor.invoke(Unit) == packageName) {
_uiStateFlow.update { it.copy(snackbarMessage = R.string.cpu_open) }
}
}
}
fun onSnackbarDismissed() {
_uiStateFlow.update { it.copy(snackbarMessage = -1) }
}
private fun handleApplicationsResult(result: Result<List<ExtendedApplicationData>>) {
_uiStateFlow.update {
it.copy(
isLoading = result is Result.Loading,
applications = if (result is Result.Success) {
result.data.toImmutableList()
} else {
it.applications
}
)
}
}
data class UiState(
val isLoading: Boolean = false,
val applications: ImmutableList<ExtendedApplicationData> = persistentListOf(),
val snackbarMessage: Int = -1
)
} | apache-2.0 | 74414f376bc18239f9b4279fb66a0bf7 | 32.972973 | 89 | 0.693593 | 5.066532 | false | false | false | false |
UweTrottmann/SeriesGuide | app/src/main/java/com/battlelancer/seriesguide/shows/search/popular/ShowsPopularDataSource.kt | 1 | 3668 | package com.battlelancer.seriesguide.shows.search.popular
import android.content.Context
import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.battlelancer.seriesguide.R
import com.battlelancer.seriesguide.shows.search.discover.SearchResult
import com.battlelancer.seriesguide.shows.search.discover.SearchTools
import com.battlelancer.seriesguide.tmdbapi.TmdbTools2
import com.battlelancer.seriesguide.util.Errors
import com.uwetrottmann.androidutils.AndroidUtils
import com.uwetrottmann.tmdb2.Tmdb
import java.io.IOException
/**
* Loads popular shows in pages from TMDB.
*/
class ShowsPopularDataSource(
private val context: Context,
private val tmdb: Tmdb,
private val languageCode: String,
private val watchProviderIds: List<Int>?,
private val watchRegion: String?
) : PagingSource<Int, SearchResult>() {
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, SearchResult> {
val pageNumber = params.key ?: 1
val action = "load popular shows"
val result = TmdbTools2().getPopularShows(
tmdb,
languageCode,
pageNumber,
watchProviderIds,
watchRegion
)
if (result == null) {
// Not checking for connection until here to allow hitting the response cache.
return if (AndroidUtils.isNetworkConnected(context)) {
buildResultGenericFailure()
} else {
buildResultOffline()
}
}
val totalResults = result.total_results
if (totalResults == null) {
Errors.logAndReport(action, IllegalStateException("total_results is null"))
return buildResultGenericFailure()
}
val shows = result.results?.filterNotNull()
return if (shows == null || shows.isEmpty()) {
// return empty list right away if there are no results
LoadResult.Page(
data = emptyList(),
prevKey = null, // Only paging forward.
nextKey = null
)
} else {
val searchResults = SearchTools.mapTvShowsToSearchResults(languageCode, shows)
SearchTools.markLocalShowsAsAddedAndPreferLocalPoster(context, searchResults)
LoadResult.Page(
data = searchResults,
prevKey = null, // Only paging forward.
nextKey = pageNumber + 1
)
}
}
private fun buildResultGenericFailure(): LoadResult.Error<Int, SearchResult> {
val message =
context.getString(R.string.api_error_generic, context.getString(R.string.tmdb))
return LoadResult.Error(IOException(message))
}
private fun buildResultOffline(): LoadResult.Error<Int, SearchResult> {
val message = context.getString(R.string.offline)
return LoadResult.Error(IOException(message))
}
override fun getRefreshKey(state: PagingState<Int, SearchResult>): Int? {
// Try to find the page key of the closest page to anchorPosition, from
// either the prevKey or the nextKey, but you need to handle nullability
// here:
// * prevKey == null -> anchorPage is the first page.
// * nextKey == null -> anchorPage is the last page.
// * both prevKey and nextKey null -> anchorPage is the initial page, so
// just return null.
return state.anchorPosition?.let { anchorPosition ->
val anchorPage = state.closestPageToPosition(anchorPosition)
anchorPage?.prevKey?.plus(1) ?: anchorPage?.nextKey?.minus(1)
}
}
}
| apache-2.0 | c585e6b3183779e742b90bf640ba95a5 | 38.021277 | 91 | 0.648037 | 4.950067 | false | false | false | false |
ratedali/EEESE-android | app/src/main/java/edu/uofk/eeese/eeese/data/Event.kt | 1 | 1435 | /*
* Copyright 2017 Ali Salah Alddin
*
* 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 edu.uofk.eeese.eeese.data
import android.net.Uri
import org.joda.time.DateTime
data class Event(val id: String, val name: String,
val desc: String, val imageUri: Uri? = null,
val longitude: String? = null, val latitude: String? = null,
val start: DateTime? = null, val end: DateTime? = null)
| mit | f6b6da36b72a4f81e1c75896b1253389 | 74.526316 | 463 | 0.749129 | 4.599359 | false | false | false | false |
AsynkronIT/protoactor-kotlin | proto-mailbox/src/main/kotlin/actor/proto/mailbox/AffinityDispatcher.kt | 1 | 2146 | //package actor.proto.mailbox
//
//import kotlinx.coroutines.experimental.CoroutineDispatcher
//import net.openhft.affinity.AffinityLock
//import net.openhft.affinity.AffinityStrategies
//import net.openhft.affinity.AffinityThreadFactory
//import org.jctools.queues.MpscUnboundedArrayQueue
//import java.util.*
//import java.util.concurrent.ConcurrentLinkedQueue
//import java.util.concurrent.locks.LockSupport
//import kotlin.coroutines.experimental.CoroutineContext
//import kotlin.coroutines.experimental.startCoroutine
//
//class AffinityDispatcher(override var throughput: Int) : Dispatcher{
// private val dispatchers : Array<ThreadDispatcher> = (0 until Runtime.getRuntime().availableProcessors()).map { i -> ThreadDispatcher(i) }.toTypedArray()
// private val continuations = dispatchers.map {EmptyContinuation(it)}.toTypedArray()
// override fun schedule(mailbox: Mailbox) {
// val hash = mailbox.hashCode()
// val index = hash % continuations.count()
// val continuation = continuations[index]
//
// val runner: suspend () -> Unit = {mailbox.run()}
// runner.startCoroutine(continuation)
// }
//
// fun stop(){
// dispatchers.forEach { it.stop() }
// }
//}
//val f = AffinityThreadFactory("threads",true,AffinityStrategies.SAME_CORE)
//class ThreadDispatcher(index : Int) : CoroutineDispatcher() {
// private val queue : Queue<Runnable> = MpscUnboundedArrayQueue(1000)
// private val thread : Thread =Thread(this::run)
// @Volatile private var running = true
// init{
// thread.isDaemon = true
// thread.priority = Thread.MAX_PRIORITY
// thread.start()
// }
//
// fun stop(){
// running = false
//
// }
// private fun run() {
// while(running) {
// spin@for (i in 0..100) {
// while(true) {
// val w = queue.poll() ?: break@spin
// w.run()
// }
// }
// LockSupport.parkNanos(1000000)
// }
// }
// override fun dispatch(context: CoroutineContext, block: Runnable) {
// queue.add(block)
// }
//} | apache-2.0 | fd54d3b7fa6ebb0b9abfe9041aad31aa | 35.389831 | 158 | 0.641659 | 3.930403 | false | false | false | false |
cketti/k-9 | app/core/src/main/java/com/fsck/k9/AccountPreferenceSerializer.kt | 1 | 35406 | package com.fsck.k9
import com.fsck.k9.Account.Companion.DEFAULT_SORT_ASCENDING
import com.fsck.k9.Account.Companion.DEFAULT_SORT_TYPE
import com.fsck.k9.Account.Companion.DEFAULT_SYNC_INTERVAL
import com.fsck.k9.Account.Companion.NO_OPENPGP_KEY
import com.fsck.k9.Account.Companion.UNASSIGNED_ACCOUNT_NUMBER
import com.fsck.k9.Account.DeletePolicy
import com.fsck.k9.Account.Expunge
import com.fsck.k9.Account.FolderMode
import com.fsck.k9.Account.MessageFormat
import com.fsck.k9.Account.QuoteStyle
import com.fsck.k9.Account.Searchable
import com.fsck.k9.Account.ShowPictures
import com.fsck.k9.Account.SortType
import com.fsck.k9.Account.SpecialFolderSelection
import com.fsck.k9.helper.Utility
import com.fsck.k9.mailstore.StorageManager
import com.fsck.k9.preferences.Storage
import com.fsck.k9.preferences.StorageEditor
import timber.log.Timber
class AccountPreferenceSerializer(
private val storageManager: StorageManager,
private val resourceProvider: CoreResourceProvider,
private val serverSettingsSerializer: ServerSettingsSerializer
) {
@Synchronized
fun loadAccount(account: Account, storage: Storage) {
val accountUuid = account.uuid
with(account) {
incomingServerSettings = serverSettingsSerializer.deserialize(
storage.getString("$accountUuid.$INCOMING_SERVER_SETTINGS_KEY", "")
)
outgoingServerSettings = serverSettingsSerializer.deserialize(
storage.getString("$accountUuid.$OUTGOING_SERVER_SETTINGS_KEY", "")
)
oAuthState = storage.getString("$accountUuid.oAuthState", null)
localStorageProviderId = storage.getString("$accountUuid.localStorageProvider", storageManager.defaultProviderId)
name = storage.getString("$accountUuid.description", null)
alwaysBcc = storage.getString("$accountUuid.alwaysBcc", alwaysBcc)
automaticCheckIntervalMinutes = storage.getInt("$accountUuid.automaticCheckIntervalMinutes", DEFAULT_SYNC_INTERVAL)
idleRefreshMinutes = storage.getInt("$accountUuid.idleRefreshMinutes", 24)
displayCount = storage.getInt("$accountUuid.displayCount", K9.DEFAULT_VISIBLE_LIMIT)
if (displayCount < 0) {
displayCount = K9.DEFAULT_VISIBLE_LIMIT
}
isNotifyNewMail = storage.getBoolean("$accountUuid.notifyNewMail", false)
folderNotifyNewMailMode = getEnumStringPref<FolderMode>(storage, "$accountUuid.folderNotifyNewMailMode", FolderMode.ALL)
isNotifySelfNewMail = storage.getBoolean("$accountUuid.notifySelfNewMail", true)
isNotifyContactsMailOnly = storage.getBoolean("$accountUuid.notifyContactsMailOnly", false)
isIgnoreChatMessages = storage.getBoolean("$accountUuid.ignoreChatMessages", false)
isNotifySync = storage.getBoolean("$accountUuid.notifyMailCheck", false)
messagesNotificationChannelVersion = storage.getInt("$accountUuid.messagesNotificationChannelVersion", 0)
deletePolicy = DeletePolicy.fromInt(storage.getInt("$accountUuid.deletePolicy", DeletePolicy.NEVER.setting))
legacyInboxFolder = storage.getString("$accountUuid.inboxFolderName", null)
importedDraftsFolder = storage.getString("$accountUuid.draftsFolderName", null)
importedSentFolder = storage.getString("$accountUuid.sentFolderName", null)
importedTrashFolder = storage.getString("$accountUuid.trashFolderName", null)
importedArchiveFolder = storage.getString("$accountUuid.archiveFolderName", null)
importedSpamFolder = storage.getString("$accountUuid.spamFolderName", null)
inboxFolderId = storage.getString("$accountUuid.inboxFolderId", null)?.toLongOrNull()
outboxFolderId = storage.getString("$accountUuid.outboxFolderId", null)?.toLongOrNull()
val draftsFolderId = storage.getString("$accountUuid.draftsFolderId", null)?.toLongOrNull()
val draftsFolderSelection = getEnumStringPref<SpecialFolderSelection>(
storage, "$accountUuid.draftsFolderSelection",
SpecialFolderSelection.AUTOMATIC
)
setDraftsFolderId(draftsFolderId, draftsFolderSelection)
val sentFolderId = storage.getString("$accountUuid.sentFolderId", null)?.toLongOrNull()
val sentFolderSelection = getEnumStringPref<SpecialFolderSelection>(
storage, "$accountUuid.sentFolderSelection",
SpecialFolderSelection.AUTOMATIC
)
setSentFolderId(sentFolderId, sentFolderSelection)
val trashFolderId = storage.getString("$accountUuid.trashFolderId", null)?.toLongOrNull()
val trashFolderSelection = getEnumStringPref<SpecialFolderSelection>(
storage, "$accountUuid.trashFolderSelection",
SpecialFolderSelection.AUTOMATIC
)
setTrashFolderId(trashFolderId, trashFolderSelection)
val archiveFolderId = storage.getString("$accountUuid.archiveFolderId", null)?.toLongOrNull()
val archiveFolderSelection = getEnumStringPref<SpecialFolderSelection>(
storage, "$accountUuid.archiveFolderSelection",
SpecialFolderSelection.AUTOMATIC
)
setArchiveFolderId(archiveFolderId, archiveFolderSelection)
val spamFolderId = storage.getString("$accountUuid.spamFolderId", null)?.toLongOrNull()
val spamFolderSelection = getEnumStringPref<SpecialFolderSelection>(
storage, "$accountUuid.spamFolderSelection",
SpecialFolderSelection.AUTOMATIC
)
setSpamFolderId(spamFolderId, spamFolderSelection)
autoExpandFolderId = storage.getString("$accountUuid.autoExpandFolderId", null)?.toLongOrNull()
expungePolicy = getEnumStringPref<Expunge>(storage, "$accountUuid.expungePolicy", Expunge.EXPUNGE_IMMEDIATELY)
isSyncRemoteDeletions = storage.getBoolean("$accountUuid.syncRemoteDeletions", true)
maxPushFolders = storage.getInt("$accountUuid.maxPushFolders", 10)
isSubscribedFoldersOnly = storage.getBoolean("$accountUuid.subscribedFoldersOnly", false)
maximumPolledMessageAge = storage.getInt("$accountUuid.maximumPolledMessageAge", -1)
maximumAutoDownloadMessageSize = storage.getInt("$accountUuid.maximumAutoDownloadMessageSize", 32768)
messageFormat = getEnumStringPref<MessageFormat>(storage, "$accountUuid.messageFormat", DEFAULT_MESSAGE_FORMAT)
val messageFormatAuto = storage.getBoolean("$accountUuid.messageFormatAuto", DEFAULT_MESSAGE_FORMAT_AUTO)
if (messageFormatAuto && messageFormat == MessageFormat.TEXT) {
messageFormat = MessageFormat.AUTO
}
isMessageReadReceipt = storage.getBoolean("$accountUuid.messageReadReceipt", DEFAULT_MESSAGE_READ_RECEIPT)
quoteStyle = getEnumStringPref<QuoteStyle>(storage, "$accountUuid.quoteStyle", DEFAULT_QUOTE_STYLE)
quotePrefix = storage.getString("$accountUuid.quotePrefix", DEFAULT_QUOTE_PREFIX)
isDefaultQuotedTextShown = storage.getBoolean("$accountUuid.defaultQuotedTextShown", DEFAULT_QUOTED_TEXT_SHOWN)
isReplyAfterQuote = storage.getBoolean("$accountUuid.replyAfterQuote", DEFAULT_REPLY_AFTER_QUOTE)
isStripSignature = storage.getBoolean("$accountUuid.stripSignature", DEFAULT_STRIP_SIGNATURE)
useCompression = storage.getBoolean("$accountUuid.useCompression", true)
importedAutoExpandFolder = storage.getString("$accountUuid.autoExpandFolderName", null)
accountNumber = storage.getInt("$accountUuid.accountNumber", UNASSIGNED_ACCOUNT_NUMBER)
chipColor = storage.getInt("$accountUuid.chipColor", FALLBACK_ACCOUNT_COLOR)
sortType = getEnumStringPref<SortType>(storage, "$accountUuid.sortTypeEnum", SortType.SORT_DATE)
setSortAscending(sortType, storage.getBoolean("$accountUuid.sortAscending", false))
showPictures = getEnumStringPref<ShowPictures>(storage, "$accountUuid.showPicturesEnum", ShowPictures.NEVER)
updateNotificationSettings {
NotificationSettings(
isRingEnabled = storage.getBoolean("$accountUuid.ring", true),
ringtone = storage.getString("$accountUuid.ringtone", DEFAULT_RINGTONE_URI),
light = getEnumStringPref(storage, "$accountUuid.notificationLight", NotificationLight.Disabled),
vibration = NotificationVibration(
isEnabled = storage.getBoolean("$accountUuid.vibrate", false),
pattern = VibratePattern.deserialize(storage.getInt("$accountUuid.vibratePattern", 0)),
repeatCount = storage.getInt("$accountUuid.vibrateTimes", 5)
)
)
}
folderDisplayMode = getEnumStringPref<FolderMode>(storage, "$accountUuid.folderDisplayMode", FolderMode.NOT_SECOND_CLASS)
folderSyncMode = getEnumStringPref<FolderMode>(storage, "$accountUuid.folderSyncMode", FolderMode.FIRST_CLASS)
folderPushMode = getEnumStringPref<FolderMode>(storage, "$accountUuid.folderPushMode", FolderMode.NONE)
folderTargetMode = getEnumStringPref<FolderMode>(storage, "$accountUuid.folderTargetMode", FolderMode.NOT_SECOND_CLASS)
searchableFolders = getEnumStringPref<Searchable>(storage, "$accountUuid.searchableFolders", Searchable.ALL)
isSignatureBeforeQuotedText = storage.getBoolean("$accountUuid.signatureBeforeQuotedText", false)
replaceIdentities(loadIdentities(accountUuid, storage))
openPgpProvider = storage.getString("$accountUuid.openPgpProvider", "")
openPgpKey = storage.getLong("$accountUuid.cryptoKey", NO_OPENPGP_KEY)
isOpenPgpHideSignOnly = storage.getBoolean("$accountUuid.openPgpHideSignOnly", true)
isOpenPgpEncryptSubject = storage.getBoolean("$accountUuid.openPgpEncryptSubject", true)
isOpenPgpEncryptAllDrafts = storage.getBoolean("$accountUuid.openPgpEncryptAllDrafts", true)
autocryptPreferEncryptMutual = storage.getBoolean("$accountUuid.autocryptMutualMode", false)
isRemoteSearchFullText = storage.getBoolean("$accountUuid.remoteSearchFullText", false)
remoteSearchNumResults = storage.getInt("$accountUuid.remoteSearchNumResults", DEFAULT_REMOTE_SEARCH_NUM_RESULTS)
isUploadSentMessages = storage.getBoolean("$accountUuid.uploadSentMessages", true)
isMarkMessageAsReadOnView = storage.getBoolean("$accountUuid.markMessageAsReadOnView", true)
isMarkMessageAsReadOnDelete = storage.getBoolean("$accountUuid.markMessageAsReadOnDelete", true)
isAlwaysShowCcBcc = storage.getBoolean("$accountUuid.alwaysShowCcBcc", false)
lastSyncTime = storage.getLong("$accountUuid.lastSyncTime", 0L)
lastFolderListRefreshTime = storage.getLong("$accountUuid.lastFolderListRefreshTime", 0L)
shouldMigrateToOAuth = storage.getBoolean("$accountUuid.migrateToOAuth", false)
val isFinishedSetup = storage.getBoolean("$accountUuid.isFinishedSetup", true)
if (isFinishedSetup) markSetupFinished()
resetChangeMarkers()
}
}
@Synchronized
private fun loadIdentities(accountUuid: String, storage: Storage): List<Identity> {
val newIdentities = ArrayList<Identity>()
var ident = 0
var gotOne: Boolean
do {
gotOne = false
val name = storage.getString("$accountUuid.$IDENTITY_NAME_KEY.$ident", null)
val email = storage.getString("$accountUuid.$IDENTITY_EMAIL_KEY.$ident", null)
val signatureUse = storage.getBoolean("$accountUuid.signatureUse.$ident", false)
val signature = storage.getString("$accountUuid.signature.$ident", null)
val description = storage.getString("$accountUuid.$IDENTITY_DESCRIPTION_KEY.$ident", null)
val replyTo = storage.getString("$accountUuid.replyTo.$ident", null)
if (email != null) {
val identity = Identity(
name = name,
email = email,
signatureUse = signatureUse,
signature = signature,
description = description,
replyTo = replyTo
)
newIdentities.add(identity)
gotOne = true
}
ident++
} while (gotOne)
if (newIdentities.isEmpty()) {
val name = storage.getString("$accountUuid.name", null)
val email = storage.getString("$accountUuid.email", null)
val signatureUse = storage.getBoolean("$accountUuid.signatureUse", false)
val signature = storage.getString("$accountUuid.signature", null)
val identity = Identity(
name = name,
email = email,
signatureUse = signatureUse,
signature = signature,
description = email
)
newIdentities.add(identity)
}
return newIdentities
}
@Synchronized
fun save(editor: StorageEditor, storage: Storage, account: Account) {
val accountUuid = account.uuid
if (!storage.getString("accountUuids", "").contains(account.uuid)) {
var accountUuids = storage.getString("accountUuids", "")
accountUuids += (if (accountUuids.isNotEmpty()) "," else "") + account.uuid
editor.putString("accountUuids", accountUuids)
}
with(account) {
editor.putString("$accountUuid.$INCOMING_SERVER_SETTINGS_KEY", serverSettingsSerializer.serialize(incomingServerSettings))
editor.putString("$accountUuid.$OUTGOING_SERVER_SETTINGS_KEY", serverSettingsSerializer.serialize(outgoingServerSettings))
editor.putString("$accountUuid.oAuthState", oAuthState)
editor.putString("$accountUuid.localStorageProvider", localStorageProviderId)
editor.putString("$accountUuid.description", name)
editor.putString("$accountUuid.alwaysBcc", alwaysBcc)
editor.putInt("$accountUuid.automaticCheckIntervalMinutes", automaticCheckIntervalMinutes)
editor.putInt("$accountUuid.idleRefreshMinutes", idleRefreshMinutes)
editor.putInt("$accountUuid.displayCount", displayCount)
editor.putBoolean("$accountUuid.notifyNewMail", isNotifyNewMail)
editor.putString("$accountUuid.folderNotifyNewMailMode", folderNotifyNewMailMode.name)
editor.putBoolean("$accountUuid.notifySelfNewMail", isNotifySelfNewMail)
editor.putBoolean("$accountUuid.notifyContactsMailOnly", isNotifyContactsMailOnly)
editor.putBoolean("$accountUuid.ignoreChatMessages", isIgnoreChatMessages)
editor.putBoolean("$accountUuid.notifyMailCheck", isNotifySync)
editor.putInt("$accountUuid.messagesNotificationChannelVersion", messagesNotificationChannelVersion)
editor.putInt("$accountUuid.deletePolicy", deletePolicy.setting)
editor.putString("$accountUuid.inboxFolderName", legacyInboxFolder)
editor.putString("$accountUuid.draftsFolderName", importedDraftsFolder)
editor.putString("$accountUuid.sentFolderName", importedSentFolder)
editor.putString("$accountUuid.trashFolderName", importedTrashFolder)
editor.putString("$accountUuid.archiveFolderName", importedArchiveFolder)
editor.putString("$accountUuid.spamFolderName", importedSpamFolder)
editor.putString("$accountUuid.inboxFolderId", inboxFolderId?.toString())
editor.putString("$accountUuid.outboxFolderId", outboxFolderId?.toString())
editor.putString("$accountUuid.draftsFolderId", draftsFolderId?.toString())
editor.putString("$accountUuid.sentFolderId", sentFolderId?.toString())
editor.putString("$accountUuid.trashFolderId", trashFolderId?.toString())
editor.putString("$accountUuid.archiveFolderId", archiveFolderId?.toString())
editor.putString("$accountUuid.spamFolderId", spamFolderId?.toString())
editor.putString("$accountUuid.archiveFolderSelection", archiveFolderSelection.name)
editor.putString("$accountUuid.draftsFolderSelection", draftsFolderSelection.name)
editor.putString("$accountUuid.sentFolderSelection", sentFolderSelection.name)
editor.putString("$accountUuid.spamFolderSelection", spamFolderSelection.name)
editor.putString("$accountUuid.trashFolderSelection", trashFolderSelection.name)
editor.putString("$accountUuid.autoExpandFolderName", importedAutoExpandFolder)
editor.putString("$accountUuid.autoExpandFolderId", autoExpandFolderId?.toString())
editor.putInt("$accountUuid.accountNumber", accountNumber)
editor.putString("$accountUuid.sortTypeEnum", sortType.name)
editor.putBoolean("$accountUuid.sortAscending", isSortAscending(sortType))
editor.putString("$accountUuid.showPicturesEnum", showPictures.name)
editor.putString("$accountUuid.folderDisplayMode", folderDisplayMode.name)
editor.putString("$accountUuid.folderSyncMode", folderSyncMode.name)
editor.putString("$accountUuid.folderPushMode", folderPushMode.name)
editor.putString("$accountUuid.folderTargetMode", folderTargetMode.name)
editor.putBoolean("$accountUuid.signatureBeforeQuotedText", isSignatureBeforeQuotedText)
editor.putString("$accountUuid.expungePolicy", expungePolicy.name)
editor.putBoolean("$accountUuid.syncRemoteDeletions", isSyncRemoteDeletions)
editor.putInt("$accountUuid.maxPushFolders", maxPushFolders)
editor.putString("$accountUuid.searchableFolders", searchableFolders.name)
editor.putInt("$accountUuid.chipColor", chipColor)
editor.putBoolean("$accountUuid.subscribedFoldersOnly", isSubscribedFoldersOnly)
editor.putInt("$accountUuid.maximumPolledMessageAge", maximumPolledMessageAge)
editor.putInt("$accountUuid.maximumAutoDownloadMessageSize", maximumAutoDownloadMessageSize)
val messageFormatAuto = if (MessageFormat.AUTO == messageFormat) {
// saving MessageFormat.AUTO as is to the database will cause downgrades to crash on
// startup, so we save as MessageFormat.TEXT instead with a separate flag for auto.
editor.putString("$accountUuid.messageFormat", MessageFormat.TEXT.name)
true
} else {
editor.putString("$accountUuid.messageFormat", messageFormat.name)
false
}
editor.putBoolean("$accountUuid.messageFormatAuto", messageFormatAuto)
editor.putBoolean("$accountUuid.messageReadReceipt", isMessageReadReceipt)
editor.putString("$accountUuid.quoteStyle", quoteStyle.name)
editor.putString("$accountUuid.quotePrefix", quotePrefix)
editor.putBoolean("$accountUuid.defaultQuotedTextShown", isDefaultQuotedTextShown)
editor.putBoolean("$accountUuid.replyAfterQuote", isReplyAfterQuote)
editor.putBoolean("$accountUuid.stripSignature", isStripSignature)
editor.putLong("$accountUuid.cryptoKey", openPgpKey)
editor.putBoolean("$accountUuid.openPgpHideSignOnly", isOpenPgpHideSignOnly)
editor.putBoolean("$accountUuid.openPgpEncryptSubject", isOpenPgpEncryptSubject)
editor.putBoolean("$accountUuid.openPgpEncryptAllDrafts", isOpenPgpEncryptAllDrafts)
editor.putString("$accountUuid.openPgpProvider", openPgpProvider)
editor.putBoolean("$accountUuid.autocryptMutualMode", autocryptPreferEncryptMutual)
editor.putBoolean("$accountUuid.remoteSearchFullText", isRemoteSearchFullText)
editor.putInt("$accountUuid.remoteSearchNumResults", remoteSearchNumResults)
editor.putBoolean("$accountUuid.uploadSentMessages", isUploadSentMessages)
editor.putBoolean("$accountUuid.markMessageAsReadOnView", isMarkMessageAsReadOnView)
editor.putBoolean("$accountUuid.markMessageAsReadOnDelete", isMarkMessageAsReadOnDelete)
editor.putBoolean("$accountUuid.alwaysShowCcBcc", isAlwaysShowCcBcc)
editor.putBoolean("$accountUuid.vibrate", notificationSettings.vibration.isEnabled)
editor.putInt("$accountUuid.vibratePattern", notificationSettings.vibration.pattern.serialize())
editor.putInt("$accountUuid.vibrateTimes", notificationSettings.vibration.repeatCount)
editor.putBoolean("$accountUuid.ring", notificationSettings.isRingEnabled)
editor.putString("$accountUuid.ringtone", notificationSettings.ringtone)
editor.putString("$accountUuid.notificationLight", notificationSettings.light.name)
editor.putLong("$accountUuid.lastSyncTime", lastSyncTime)
editor.putLong("$accountUuid.lastFolderListRefreshTime", lastFolderListRefreshTime)
editor.putBoolean("$accountUuid.isFinishedSetup", isFinishedSetup)
editor.putBoolean("$accountUuid.useCompression", useCompression)
editor.putBoolean("$accountUuid.migrateToOAuth", shouldMigrateToOAuth)
}
saveIdentities(account, storage, editor)
}
@Synchronized
fun delete(editor: StorageEditor, storage: Storage, account: Account) {
val accountUuid = account.uuid
// Get the list of account UUIDs
val uuids = storage.getString("accountUuids", "").split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
// Create a list of all account UUIDs excluding this account
val newUuids = ArrayList<String>(uuids.size)
for (uuid in uuids) {
if (uuid != accountUuid) {
newUuids.add(uuid)
}
}
// Only change the 'accountUuids' value if this account's UUID was listed before
if (newUuids.size < uuids.size) {
val accountUuids = Utility.combine(newUuids.toTypedArray(), ',')
editor.putString("accountUuids", accountUuids)
}
editor.remove("$accountUuid.$INCOMING_SERVER_SETTINGS_KEY")
editor.remove("$accountUuid.$OUTGOING_SERVER_SETTINGS_KEY")
editor.remove("$accountUuid.oAuthState")
editor.remove("$accountUuid.description")
editor.remove("$accountUuid.name")
editor.remove("$accountUuid.email")
editor.remove("$accountUuid.alwaysBcc")
editor.remove("$accountUuid.automaticCheckIntervalMinutes")
editor.remove("$accountUuid.idleRefreshMinutes")
editor.remove("$accountUuid.lastAutomaticCheckTime")
editor.remove("$accountUuid.notifyNewMail")
editor.remove("$accountUuid.notifySelfNewMail")
editor.remove("$accountUuid.ignoreChatMessages")
editor.remove("$accountUuid.messagesNotificationChannelVersion")
editor.remove("$accountUuid.deletePolicy")
editor.remove("$accountUuid.draftsFolderName")
editor.remove("$accountUuid.sentFolderName")
editor.remove("$accountUuid.trashFolderName")
editor.remove("$accountUuid.archiveFolderName")
editor.remove("$accountUuid.spamFolderName")
editor.remove("$accountUuid.archiveFolderSelection")
editor.remove("$accountUuid.draftsFolderSelection")
editor.remove("$accountUuid.sentFolderSelection")
editor.remove("$accountUuid.spamFolderSelection")
editor.remove("$accountUuid.trashFolderSelection")
editor.remove("$accountUuid.autoExpandFolderName")
editor.remove("$accountUuid.accountNumber")
editor.remove("$accountUuid.vibrate")
editor.remove("$accountUuid.vibratePattern")
editor.remove("$accountUuid.vibrateTimes")
editor.remove("$accountUuid.ring")
editor.remove("$accountUuid.ringtone")
editor.remove("$accountUuid.folderDisplayMode")
editor.remove("$accountUuid.folderSyncMode")
editor.remove("$accountUuid.folderPushMode")
editor.remove("$accountUuid.folderTargetMode")
editor.remove("$accountUuid.signatureBeforeQuotedText")
editor.remove("$accountUuid.expungePolicy")
editor.remove("$accountUuid.syncRemoteDeletions")
editor.remove("$accountUuid.maxPushFolders")
editor.remove("$accountUuid.searchableFolders")
editor.remove("$accountUuid.chipColor")
editor.remove("$accountUuid.notificationLight")
editor.remove("$accountUuid.subscribedFoldersOnly")
editor.remove("$accountUuid.maximumPolledMessageAge")
editor.remove("$accountUuid.maximumAutoDownloadMessageSize")
editor.remove("$accountUuid.messageFormatAuto")
editor.remove("$accountUuid.quoteStyle")
editor.remove("$accountUuid.quotePrefix")
editor.remove("$accountUuid.sortTypeEnum")
editor.remove("$accountUuid.sortAscending")
editor.remove("$accountUuid.showPicturesEnum")
editor.remove("$accountUuid.replyAfterQuote")
editor.remove("$accountUuid.stripSignature")
editor.remove("$accountUuid.cryptoApp") // this is no longer set, but cleans up legacy values
editor.remove("$accountUuid.cryptoAutoSignature")
editor.remove("$accountUuid.cryptoAutoEncrypt")
editor.remove("$accountUuid.cryptoApp")
editor.remove("$accountUuid.cryptoKey")
editor.remove("$accountUuid.cryptoSupportSignOnly")
editor.remove("$accountUuid.openPgpProvider")
editor.remove("$accountUuid.openPgpHideSignOnly")
editor.remove("$accountUuid.openPgpEncryptSubject")
editor.remove("$accountUuid.openPgpEncryptAllDrafts")
editor.remove("$accountUuid.autocryptMutualMode")
editor.remove("$accountUuid.enabled")
editor.remove("$accountUuid.markMessageAsReadOnView")
editor.remove("$accountUuid.markMessageAsReadOnDelete")
editor.remove("$accountUuid.alwaysShowCcBcc")
editor.remove("$accountUuid.remoteSearchFullText")
editor.remove("$accountUuid.remoteSearchNumResults")
editor.remove("$accountUuid.uploadSentMessages")
editor.remove("$accountUuid.defaultQuotedTextShown")
editor.remove("$accountUuid.displayCount")
editor.remove("$accountUuid.inboxFolderName")
editor.remove("$accountUuid.localStorageProvider")
editor.remove("$accountUuid.messageFormat")
editor.remove("$accountUuid.messageReadReceipt")
editor.remove("$accountUuid.notifyMailCheck")
editor.remove("$accountUuid.inboxFolderId")
editor.remove("$accountUuid.outboxFolderId")
editor.remove("$accountUuid.draftsFolderId")
editor.remove("$accountUuid.sentFolderId")
editor.remove("$accountUuid.trashFolderId")
editor.remove("$accountUuid.archiveFolderId")
editor.remove("$accountUuid.spamFolderId")
editor.remove("$accountUuid.autoExpandFolderId")
editor.remove("$accountUuid.lastSyncTime")
editor.remove("$accountUuid.lastFolderListRefreshTime")
editor.remove("$accountUuid.isFinishedSetup")
editor.remove("$accountUuid.useCompression")
editor.remove("$accountUuid.migrateToOAuth")
deleteIdentities(account, storage, editor)
// TODO: Remove preference settings that may exist for individual folders in the account.
}
@Synchronized
private fun saveIdentities(account: Account, storage: Storage, editor: StorageEditor) {
deleteIdentities(account, storage, editor)
var ident = 0
with(account) {
for (identity in identities) {
editor.putString("$uuid.$IDENTITY_NAME_KEY.$ident", identity.name)
editor.putString("$uuid.$IDENTITY_EMAIL_KEY.$ident", identity.email)
editor.putBoolean("$uuid.signatureUse.$ident", identity.signatureUse)
editor.putString("$uuid.signature.$ident", identity.signature)
editor.putString("$uuid.$IDENTITY_DESCRIPTION_KEY.$ident", identity.description)
editor.putString("$uuid.replyTo.$ident", identity.replyTo)
ident++
}
}
}
@Synchronized
private fun deleteIdentities(account: Account, storage: Storage, editor: StorageEditor) {
val accountUuid = account.uuid
var identityIndex = 0
var gotOne: Boolean
do {
gotOne = false
val email = storage.getString("$accountUuid.$IDENTITY_EMAIL_KEY.$identityIndex", null)
if (email != null) {
editor.remove("$accountUuid.$IDENTITY_NAME_KEY.$identityIndex")
editor.remove("$accountUuid.$IDENTITY_EMAIL_KEY.$identityIndex")
editor.remove("$accountUuid.signatureUse.$identityIndex")
editor.remove("$accountUuid.signature.$identityIndex")
editor.remove("$accountUuid.$IDENTITY_DESCRIPTION_KEY.$identityIndex")
editor.remove("$accountUuid.replyTo.$identityIndex")
gotOne = true
}
identityIndex++
} while (gotOne)
}
fun move(editor: StorageEditor, account: Account, storage: Storage, newPosition: Int) {
val accountUuids = storage.getString("accountUuids", "").split(",").filter { it.isNotEmpty() }
val oldPosition = accountUuids.indexOf(account.uuid)
if (oldPosition == -1 || oldPosition == newPosition) return
val newAccountUuidsString = accountUuids.toMutableList()
.apply {
removeAt(oldPosition)
add(newPosition, account.uuid)
}
.joinToString(separator = ",")
editor.putString("accountUuids", newAccountUuidsString)
}
private fun <T : Enum<T>> getEnumStringPref(storage: Storage, key: String, defaultEnum: T): T {
val stringPref = storage.getString(key, null)
return if (stringPref == null) {
defaultEnum
} else {
try {
java.lang.Enum.valueOf<T>(defaultEnum.declaringJavaClass, stringPref)
} catch (ex: IllegalArgumentException) {
Timber.w(
ex, "Unable to convert preference key [%s] value [%s] to enum of type %s",
key, stringPref, defaultEnum.declaringJavaClass
)
defaultEnum
}
}
}
fun loadDefaults(account: Account) {
with(account) {
localStorageProviderId = storageManager.defaultProviderId
automaticCheckIntervalMinutes = DEFAULT_SYNC_INTERVAL
idleRefreshMinutes = 24
displayCount = K9.DEFAULT_VISIBLE_LIMIT
accountNumber = UNASSIGNED_ACCOUNT_NUMBER
isNotifyNewMail = true
folderNotifyNewMailMode = FolderMode.ALL
isNotifySync = false
isNotifySelfNewMail = true
isNotifyContactsMailOnly = false
isIgnoreChatMessages = false
messagesNotificationChannelVersion = 0
folderDisplayMode = FolderMode.NOT_SECOND_CLASS
folderSyncMode = FolderMode.FIRST_CLASS
folderPushMode = FolderMode.NONE
folderTargetMode = FolderMode.NOT_SECOND_CLASS
sortType = DEFAULT_SORT_TYPE
setSortAscending(DEFAULT_SORT_TYPE, DEFAULT_SORT_ASCENDING)
showPictures = ShowPictures.NEVER
isSignatureBeforeQuotedText = false
expungePolicy = Expunge.EXPUNGE_IMMEDIATELY
importedAutoExpandFolder = null
legacyInboxFolder = null
maxPushFolders = 10
isSubscribedFoldersOnly = false
maximumPolledMessageAge = -1
maximumAutoDownloadMessageSize = 32768
messageFormat = DEFAULT_MESSAGE_FORMAT
isMessageFormatAuto = DEFAULT_MESSAGE_FORMAT_AUTO
isMessageReadReceipt = DEFAULT_MESSAGE_READ_RECEIPT
quoteStyle = DEFAULT_QUOTE_STYLE
quotePrefix = DEFAULT_QUOTE_PREFIX
isDefaultQuotedTextShown = DEFAULT_QUOTED_TEXT_SHOWN
isReplyAfterQuote = DEFAULT_REPLY_AFTER_QUOTE
isStripSignature = DEFAULT_STRIP_SIGNATURE
isSyncRemoteDeletions = true
openPgpKey = NO_OPENPGP_KEY
isRemoteSearchFullText = false
remoteSearchNumResults = DEFAULT_REMOTE_SEARCH_NUM_RESULTS
isUploadSentMessages = true
isMarkMessageAsReadOnView = true
isMarkMessageAsReadOnDelete = true
isAlwaysShowCcBcc = false
lastSyncTime = 0L
lastFolderListRefreshTime = 0L
setArchiveFolderId(null, SpecialFolderSelection.AUTOMATIC)
setDraftsFolderId(null, SpecialFolderSelection.AUTOMATIC)
setSentFolderId(null, SpecialFolderSelection.AUTOMATIC)
setSpamFolderId(null, SpecialFolderSelection.AUTOMATIC)
setTrashFolderId(null, SpecialFolderSelection.AUTOMATIC)
setArchiveFolderId(null, SpecialFolderSelection.AUTOMATIC)
searchableFolders = Searchable.ALL
identities = ArrayList<Identity>()
val identity = Identity(
signatureUse = false,
signature = resourceProvider.defaultSignature(),
description = resourceProvider.defaultIdentityDescription()
)
identities.add(identity)
updateNotificationSettings {
NotificationSettings(
isRingEnabled = true,
ringtone = DEFAULT_RINGTONE_URI,
light = NotificationLight.Disabled,
vibration = NotificationVibration.DEFAULT
)
}
resetChangeMarkers()
}
}
companion object {
const val ACCOUNT_DESCRIPTION_KEY = "description"
const val INCOMING_SERVER_SETTINGS_KEY = "incomingServerSettings"
const val OUTGOING_SERVER_SETTINGS_KEY = "outgoingServerSettings"
const val IDENTITY_NAME_KEY = "name"
const val IDENTITY_EMAIL_KEY = "email"
const val IDENTITY_DESCRIPTION_KEY = "description"
const val FALLBACK_ACCOUNT_COLOR = 0x0099CC
@JvmField
val DEFAULT_MESSAGE_FORMAT = MessageFormat.HTML
@JvmField
val DEFAULT_QUOTE_STYLE = QuoteStyle.PREFIX
const val DEFAULT_MESSAGE_FORMAT_AUTO = false
const val DEFAULT_MESSAGE_READ_RECEIPT = false
const val DEFAULT_QUOTE_PREFIX = ">"
const val DEFAULT_QUOTED_TEXT_SHOWN = true
const val DEFAULT_REPLY_AFTER_QUOTE = false
const val DEFAULT_STRIP_SIGNATURE = true
const val DEFAULT_REMOTE_SEARCH_NUM_RESULTS = 25
const val DEFAULT_RINGTONE_URI = "content://settings/system/notification_sound"
}
}
| apache-2.0 | d9df12920a4b2b17d24e3574f6cb311d | 54.321875 | 134 | 0.682116 | 5.409626 | false | false | false | false |
RedMillLtd/DribbbleViewer | app/src/main/java/uk/co/redmill/viewabbble/login/LoginActivity.kt | 1 | 3292 | package uk.co.redmill.viewabbble.login
/**
* Created by dave on 5/22/17.
*/
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.webkit.WebChromeClient
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_login_dribbble.*
import uk.co.redmill.viewabbble.base.BaseActivity
import uk.co.redmill.viewabbble.BuildConfig
import uk.co.redmill.viewabbble.main.MainActivity
import uk.co.redmill.viewabbble.R
class LoginActivity : BaseActivity(), LoginContract.View {
private val mPresenter: LoginPresenter = LoginPresenter(this)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login_dribbble)
setupWebView()
}
private fun setupWebView() {
mWebView.clearCache(true)
mWebView.getSettings().setJavaScriptEnabled(true)
mWebView.getSettings().setSupportZoom(false)
mWebView.getSettings().setBuiltInZoomControls(false)
mWebView.setWebViewClient(OAuthWebViewClient())
mWebView.setWebChromeClient(object : WebChromeClient() {
override fun onProgressChanged(view: WebView, newProgress: Int) {
if (newProgress == 100) {
progressBar.setVisibility(View.INVISIBLE)
} else {
if (View.INVISIBLE == progressBar.getVisibility()) {
progressBar.setVisibility(View.VISIBLE)
}
progressBar.setProgress(newProgress)
}
super.onProgressChanged(view, newProgress)
}
})
mWebView.loadUrl(String.format(AUTHORIZE_URL, BuildConfig.CLIENT_ID))
}
override fun loginSuccess() {
val intent = Intent(activity, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
startActivity(intent)
}
override fun loginFailure() {
Toast.makeText(activity, "sign in failed , please try again .", Toast.LENGTH_SHORT).show()
finish()
}
internal inner class OAuthWebViewClient : WebViewClient() {
private var index = 0
override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
view.loadUrl(url)
return true
}
override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
super.onPageStarted(view, url, favicon)
if (url.contains(BuildConfig.REDIRECT_URI + "?code=") && index == 0) {
index++
val uri = Uri.parse(url)
val code = uri.getQueryParameter("code")
if (!TextUtils.isEmpty(code)) {
mPresenter.loadToken(code)
}
}
}
override fun onPageFinished(view: WebView, url: String) {
super.onPageFinished(view, url)
}
}
companion object {
private val TAG = "LoginActivity"
val AUTHORIZE_URL = "https://dribbble.com/oauth/authorize?client_id=%s"
}
} | apache-2.0 | d0a8402ea83ad1e5853d84e6794cd71f | 31.93 | 98 | 0.641859 | 4.649718 | false | false | false | false |
XiaoQiWen/KRefreshLayout | app_kotlin/src/main/kotlin/gorden/krefreshlayout/demo/ui/fragment/ISampleFragment.kt | 1 | 2442 | package gorden.krefreshlayout.demo.ui.fragment
import android.support.v4.app.Fragment
import android.view.ViewGroup
import gorden.krefreshlayout.demo.header.ClassicalHeader
import gorden.krefreshlayout.demo.header.WechatHeader
import gorden.krefreshlayout.demo.header.circle.CircleHeader
import gorden.krefreshlayout.demo.header.fungame.FunGameHeader
import gorden.krefreshlayout.demo.header.materia.MateriaProgressHeader
import gorden.krefreshlayout.demo.header.rentals.RentalsSunHeaderView
import gorden.krefreshlayout.demo.header.storehouse.StoreHouseHeader
import gorden.krefreshlayout.demo.util.DensityUtil
import gorden.refresh.KRefreshLayout
/**
* document
* Created by Gordn on 2017/6/21.
*/
abstract class ISampleFragment : Fragment() {
abstract val mRefreshLayout: KRefreshLayout
var headerPosition: Int = 0
get() = field
set(value) {
if (field != value) {
field = value
header()
}
}
var pinContent: Boolean = false
get() = field
set(value) {
if (field != value) {
field = value
mRefreshLayout.pinContent = field
}
}
var keepHeaderWhenRefresh: Boolean = true
get() = field
set(value) {
if (field != value) {
field = value
mRefreshLayout.keepHeaderWhenRefresh = field
}
}
var durationOffset: Long = 200
get() = field
set(value) {
if (field != value) {
field = value
mRefreshLayout.durationOffset=field
}
}
var refreshTime: Long = 2000
get() = field
set(value) {
field = value
}
fun header(): Unit {
when (headerPosition) {
0 -> mRefreshLayout.setHeader(ClassicalHeader(context))
1 -> mRefreshLayout.setHeader(MateriaProgressHeader(context), ViewGroup.LayoutParams.MATCH_PARENT, DensityUtil.dip2px(80))
2 -> mRefreshLayout.setHeader(RentalsSunHeaderView(context))
3 -> mRefreshLayout.setHeader(StoreHouseHeader(context))
4 -> mRefreshLayout.setHeader(CircleHeader(context))
5 -> mRefreshLayout.setHeader(FunGameHeader(context))
6 -> mRefreshLayout.setHeader(WechatHeader(context))
else -> mRefreshLayout.removeHeader()
}
}
} | apache-2.0 | 3a5516b23dd343b6ec7e27cfee5f0a9b | 31.573333 | 134 | 0.627764 | 4.505535 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/fun/JankenponExecutor.kt | 1 | 4994 | package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.`fun`
import net.perfectdreams.i18nhelper.core.keydata.StringI18nData
import net.perfectdreams.loritta.common.emotes.Emote
import net.perfectdreams.loritta.cinnamon.emotes.Emotes
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.`fun`.declarations.JankenponCommand
import net.perfectdreams.discordinteraktions.common.commands.options.SlashCommandArguments
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.*
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.options.LocalizedApplicationCommandOptions
class JankenponExecutor(loritta: LorittaBot) : CinnamonSlashCommandExecutor(loritta) {
inner class Options : LocalizedApplicationCommandOptions(loritta) {
val value = string("value", JankenponCommand.I18N_PREFIX.Options.Action) {
choice(JankenponCommand.I18N_PREFIX.Rock, "rock")
choice(JankenponCommand.I18N_PREFIX.Paper, "paper")
choice(JankenponCommand.I18N_PREFIX.Scissors, "scissors")
choice(JankenponCommand.I18N_PREFIX.JesusChrist, "jesus")
}
}
override val options = Options()
override suspend fun execute(context: ApplicationCommandContext, args: SlashCommandArguments) {
val argument = args[options.value]
val janken = Jankenpon.getJanken(argument)
if (janken != null) {
val opponent = Jankenpon.values()[loritta.random.nextInt(Jankenpon.values().size)]
val status = janken.getStatus(opponent)
val fancy = buildString {
when (status) {
Jankenpon.JankenponStatus.WIN -> {
append("**${context.i18nContext.get(JankenponCommand.I18N_PREFIX.Win)} ")
append(Emotes.LoriWow.asMention + "**")
}
Jankenpon.JankenponStatus.LOSE -> {
append("**${context.i18nContext.get(JankenponCommand.I18N_PREFIX.Lose)} ")
append(Emotes.LoriPat.asMention + "**")
}
Jankenpon.JankenponStatus.DRAW -> {
append("**${context.i18nContext.get(JankenponCommand.I18N_PREFIX.Draw)} ")
append(Emotes.LoriSmile.asMention + "**")
}
}
}
val jankenPrefix = when (status) {
Jankenpon.JankenponStatus.WIN -> Emotes.Tada
Jankenpon.JankenponStatus.DRAW -> Emotes.WhiteFlag
Jankenpon.JankenponStatus.LOSE -> Emotes.BlackFlag
}
context.sendMessage {
styled(
prefix = jankenPrefix,
content = context.i18nContext.get(JankenponCommand.I18N_PREFIX.Chosen(janken.getEmoji(), opponent.getEmoji()))
)
styled(fancy)
}
} else {
if (argument.equals("jesus", ignoreCase = true)) {
val jesus = "${Emotes.Jesus} *${context.i18nContext.get(JankenponCommand.I18N_PREFIX.JesusChrist)}* ${Emotes.Jesus}"
context.sendMessage {
styled(
prefix = Emotes.WhiteFlag,
content = context.i18nContext.get(JankenponCommand.I18N_PREFIX.Chosen(jesus, jesus))
)
styled("**${context.i18nContext.get(JankenponCommand.I18N_PREFIX.MaybeDraw)} ${Emotes.Thinking} ${Emotes.Shrug}**")
}
}
}
}
enum class Jankenpon(var lang: StringI18nData, var wins: String, var loses: String) {
// Os wins e os loses precisam ser uma string já que os enums ainda não foram inicializados
ROCK(JankenponCommand.I18N_PREFIX.Rock, "SCISSORS", "PAPER"),
PAPER(JankenponCommand.I18N_PREFIX.Paper, "ROCK", "SCISSORS"),
SCISSORS(JankenponCommand.I18N_PREFIX.Scissors, "PAPER", "ROCK");
fun getStatus(janken: Jankenpon): JankenponStatus {
if (this.name.equals(janken.loses, ignoreCase = true)) {
return JankenponStatus.WIN
}
if (this == janken) {
return JankenponStatus.DRAW
}
return JankenponStatus.LOSE
}
fun getEmoji(): Emote {
return when (this) {
ROCK -> Emotes.Rock
PAPER -> Emotes.Newspaper
SCISSORS -> Emotes.Scissors
}
}
enum class JankenponStatus {
WIN,
LOSE,
DRAW
}
companion object {
fun getJanken(str: String): Jankenpon? {
return try {
valueOf(str.toUpperCase())
} catch (e: IllegalArgumentException) {
null
}
}
}
}
}
| agpl-3.0 | 854596d2a52cd90cb728bd0b908db6e9 | 40.256198 | 135 | 0.586939 | 4.325823 | false | false | false | false |
NoodleMage/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/data/database/tables/ChapterTable.kt | 2 | 1819 | package eu.kanade.tachiyomi.data.database.tables
object ChapterTable {
const val TABLE = "chapters"
const val COL_ID = "_id"
const val COL_MANGA_ID = "manga_id"
const val COL_URL = "url"
const val COL_NAME = "name"
const val COL_READ = "read"
const val COL_SCANLATOR = "scanlator"
const val COL_BOOKMARK = "bookmark"
const val COL_DATE_FETCH = "date_fetch"
const val COL_DATE_UPLOAD = "date_upload"
const val COL_LAST_PAGE_READ = "last_page_read"
const val COL_CHAPTER_NUMBER = "chapter_number"
const val COL_SOURCE_ORDER = "source_order"
val createTableQuery: String
get() = """CREATE TABLE $TABLE(
$COL_ID INTEGER NOT NULL PRIMARY KEY,
$COL_MANGA_ID INTEGER NOT NULL,
$COL_URL TEXT NOT NULL,
$COL_NAME TEXT NOT NULL,
$COL_SCANLATOR TEXT,
$COL_READ BOOLEAN NOT NULL,
$COL_BOOKMARK BOOLEAN NOT NULL,
$COL_LAST_PAGE_READ INT NOT NULL,
$COL_CHAPTER_NUMBER FLOAT NOT NULL,
$COL_SOURCE_ORDER INTEGER NOT NULL,
$COL_DATE_FETCH LONG NOT NULL,
$COL_DATE_UPLOAD LONG NOT NULL,
FOREIGN KEY($COL_MANGA_ID) REFERENCES ${MangaTable.TABLE} (${MangaTable.COL_ID})
ON DELETE CASCADE
)"""
val createMangaIdIndexQuery: String
get() = "CREATE INDEX ${TABLE}_${COL_MANGA_ID}_index ON $TABLE($COL_MANGA_ID)"
val sourceOrderUpdateQuery: String
get() = "ALTER TABLE $TABLE ADD COLUMN $COL_SOURCE_ORDER INTEGER DEFAULT 0"
val bookmarkUpdateQuery: String
get() = "ALTER TABLE $TABLE ADD COLUMN $COL_BOOKMARK BOOLEAN DEFAULT FALSE"
val addScanlator: String
get() = "ALTER TABLE $TABLE ADD COLUMN $COL_SCANLATOR TEXT DEFAULT NULL"
}
| apache-2.0 | 552d0a9ddafa9e95c7928f5b6675da20 | 28.819672 | 92 | 0.617922 | 3.903433 | false | false | false | false |
spinnaker/spinnaker-gradle-project | spinnaker-extensions/src/main/kotlin/com/netflix/spinnaker/gradle/extension/tasks/AssembleJavaPluginZipTask.kt | 1 | 2311 | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.gradle.extension.tasks
import com.netflix.spinnaker.gradle.extension.Plugins
import com.netflix.spinnaker.gradle.extension.extensions.SpinnakerPluginExtension
import org.gradle.api.plugins.JavaPlugin
import org.gradle.api.plugins.JavaPluginConvention
import org.gradle.api.tasks.Internal
import org.gradle.api.tasks.bundling.Zip
import java.io.File
import java.lang.IllegalStateException
/**
* Task to assemble plugin related files(dependency jars, class files etc) into a zip.
*/
open class AssembleJavaPluginZipTask : Zip() {
@Internal
override fun getGroup(): String = Plugins.GROUP
init {
val ext = project.extensions.findByType(SpinnakerPluginExtension::class.java)
?: throw IllegalStateException("A 'spinnakerPlugin' configuration block is required")
this.archiveBaseName.set(ext.serviceName)
this.archiveVersion.set("")
this.archiveExtension.set("zip")
val sourceSets = project.convention.getPlugin(JavaPluginConvention::class.java).sourceSets
val configs = listOf("implementation", "runtimeOnly").map { project.configurations.getByName(it).copy() }
configs.forEach { it.isCanBeResolved = true }
val copySpecs = configs.map {
project.copySpec().from(it)
.into("lib/")
}
this.with(
*(copySpecs.toTypedArray()),
project.copySpec()
.from(sourceSets.getByName("main").runtimeClasspath.files.filter { !it.absolutePath.endsWith(".jar") })
.from(sourceSets.getByName("main").resources)
.into("classes/"),
project.copySpec().from(File(project.buildDir, "tmp/jar"))
.into("classes/META-INF/")
)
this.dependsOn(JavaPlugin.JAR_TASK_NAME)
}
}
| apache-2.0 | 3fbbceac98e199ba00b9b62c85a1e28e | 35.68254 | 111 | 0.728256 | 4.149013 | false | true | false | false |
carlphilipp/chicago-commutes | android-app/src/main/kotlin/fr/cph/chicago/core/activity/station/BikeStationActivity.kt | 1 | 7523 | /**
* Copyright 2021 Carl-Philipp Harmant
*
*
* 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 fr.cph.chicago.core.activity.station
import android.os.Bundle
import androidx.appcompat.widget.Toolbar
import fr.cph.chicago.R
import fr.cph.chicago.core.listener.GoogleStreetOnClickListener
import fr.cph.chicago.core.listener.OpenMapDirectionOnClickListener
import fr.cph.chicago.core.listener.OpenMapOnClickListener
import fr.cph.chicago.core.model.BikeStation
import fr.cph.chicago.core.model.Position
import fr.cph.chicago.databinding.ActivityBikeStationBinding
import fr.cph.chicago.redux.AddBikeFavoriteAction
import fr.cph.chicago.redux.BikeStationAction
import fr.cph.chicago.redux.RemoveBikeFavoriteAction
import fr.cph.chicago.redux.State
import fr.cph.chicago.redux.Status
import fr.cph.chicago.redux.store
import fr.cph.chicago.util.Color
import org.rekotlin.StoreSubscriber
import timber.log.Timber
/**
* Activity the list of train stations
*
* @author Carl-Philipp Harmant
* @version 1
*/
class BikeStationActivity : StationActivity(), StoreSubscriber<State> {
private lateinit var bikeStation: BikeStation
private lateinit var binding: ActivityBikeStationBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityBikeStationBinding.inflate(layoutInflater)
setContentView(binding.root)
setupView(
swipeRefreshLayout = binding.activityStationSwipeRefreshLayout,
streetViewImage = binding.header.streetViewImage,
streetViewProgressBar = binding.header.streetViewProgressBar,
streetViewText = binding.header.streetViewText,
favoritesImage = binding.header.favorites.favoritesImage,
mapImage = binding.header.favorites.mapImage,
favoritesImageContainer = binding.header.favorites.favoritesImageContainer
)
bikeStation = intent.extras?.getParcelable(getString(R.string.bundle_bike_station))
?: BikeStation.buildUnknownStation()
position = Position(bikeStation.latitude, bikeStation.longitude)
loadGoogleStreetImage(position)
handleFavorite()
binding.bikeStationValue.text = bikeStation.address
streetViewImage.setOnClickListener(GoogleStreetOnClickListener(position.latitude, position.longitude))
binding.header.favorites.mapContainer.setOnClickListener(OpenMapOnClickListener(position.latitude, position.longitude))
binding.header.favorites.walkContainer.setOnClickListener(OpenMapDirectionOnClickListener(position.latitude, position.longitude))
drawData()
buildToolbar(binding.included.toolbar)
}
override fun onPause() {
super.onPause()
store.unsubscribe(this)
}
override fun onResume() {
super.onResume()
store.subscribe(this)
}
override fun newState(state: State) {
Timber.d("New state")
when (state.bikeStationsStatus) {
Status.FAILURE, Status.FULL_FAILURE -> util.showSnackBar(swipeRefreshLayout, state.bikeStationsErrorMessage)
Status.ADD_FAVORITES -> {
if (applyFavorite) {
util.showSnackBar(swipeRefreshLayout, R.string.message_add_fav, true)
applyFavorite = false
favoritesImage.setColorFilter(Color.yellowLineDark)
}
}
Status.REMOVE_FAVORITES -> {
if (applyFavorite) {
util.showSnackBar(swipeRefreshLayout, R.string.message_remove_fav, true)
applyFavorite = false
favoritesImage.drawable.colorFilter = mapImage.drawable.colorFilter
}
}
else -> {
state.bikeStations
.filter { station -> bikeStation.id == station.id }
.elementAtOrElse(0) { BikeStation.buildDefaultBikeStationWithName("error") }
.also { station ->
if (station.name != "error") {
refreshStation(station)
intent.extras?.putParcelable(getString(R.string.bundle_bike_station), station)
} else {
Timber.w("Train station id [%s] not found", bikeStation.id)
util.showOopsSomethingWentWrong(swipeRefreshLayout)
}
}
}
}
stopRefreshing()
}
override fun refresh() {
super.refresh()
store.dispatch(BikeStationAction())
loadGoogleStreetImage(position)
}
override fun buildToolbar(toolbar: Toolbar) {
super.buildToolbar(toolbar)
toolbar.title = bikeStation.name
}
private fun drawData() {
if (bikeStation.availableBikes == -1) {
binding.availableBikes.text = "?"
binding.availableBikes.setTextColor(Color.orange)
} else {
binding.availableBikes.text = util.formatBikesDocksValues(bikeStation.availableBikes)
val color = if (bikeStation.availableBikes == 0) Color.red else Color.green
binding.availableBikes.setTextColor(color)
}
if (bikeStation.availableDocks == -1) {
binding.availableDocks.text = "?"
binding.availableDocks.setTextColor(Color.orange)
} else {
binding.availableDocks.text = util.formatBikesDocksValues(bikeStation.availableDocks)
val color = if (bikeStation.availableDocks == 0) Color.red else Color.green
binding.availableDocks.setTextColor(color)
}
}
public override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
bikeStation = savedInstanceState.getParcelable(getString(R.string.bundle_bike_station))
?: BikeStation.buildUnknownStation()
position = Position(bikeStation.latitude, bikeStation.longitude)
}
public override fun onSaveInstanceState(savedInstanceState: Bundle) {
if (::bikeStation.isInitialized) savedInstanceState.putParcelable(getString(R.string.bundle_bike_station), bikeStation)
super.onSaveInstanceState(savedInstanceState)
}
/**
* Is favorite or not ?
*
* @return if the train station is favorite
*/
override fun isFavorite(): Boolean {
return preferenceService.isBikeStationFavorite(bikeStation.id)
}
private fun refreshStation(station: BikeStation) {
this.bikeStation = station
drawData()
}
/**
* Add/remove favorites
*/
override fun switchFavorite() {
super.switchFavorite()
if (isFavorite()) {
store.dispatch(RemoveBikeFavoriteAction(bikeStation.id))
} else {
store.dispatch(AddBikeFavoriteAction(bikeStation.id, bikeStation.name))
}
}
}
| apache-2.0 | b7c18e1ecd0302de51523de1291f5188 | 37.187817 | 137 | 0.66835 | 4.779543 | false | false | false | false |
jitsi/jitsi-videobridge | rtp/src/main/kotlin/org/jitsi/rtp/rtp/RtpPacket.kt | 1 | 20686 | /*
* Copyright @ 2018 - present 8x8, 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 org.jitsi.rtp.rtp
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings
import org.jitsi.rtp.Packet
import org.jitsi.rtp.extensions.bytearray.hashCodeOfSegment
import org.jitsi.rtp.extensions.bytearray.putShort
import org.jitsi.rtp.rtp.header_extensions.HeaderExtensionHelpers
import org.jitsi.rtp.util.BufferPool
import org.jitsi.rtp.util.RtpUtils
import org.jitsi.rtp.util.getByteAsInt
import org.jitsi.rtp.util.isPadding
import kotlin.experimental.or
/**
*
* https://tools.ietf.org/html/rfc3550#section-5.1
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |V=2|P|X| CC |M| PT | sequence number |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | timestamp |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | synchronization source (SSRC) identifier |
* +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
* | contributing source (CSRC) identifiers |
* | .... |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | ...extensions (if present)... |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | payload |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
@SuppressFBWarnings(
value = ["EI_EXPOSE_REP2"],
justification = "We intentionally pass a reference to our buffer when using observableWhenChanged."
)
open class RtpPacket(
buffer: ByteArray,
offset: Int,
length: Int
) : Packet(buffer, offset, length) {
constructor(buffer: ByteArray) : this(buffer, 0, buffer.size)
var version: Int
get() = RtpHeader.getVersion(buffer, offset)
set(value) = RtpHeader.setVersion(buffer, offset, value)
var hasPadding: Boolean
get() = RtpHeader.hasPadding(buffer, offset)
set(value) = RtpHeader.setPadding(buffer, offset, value)
private var hasEncodedExtensions: Boolean
get() = RtpHeader.hasExtensions(buffer, offset)
set(value) = RtpHeader.setHasExtensions(buffer, offset, value)
val csrcCount: Int
get() = RtpHeader.getCsrcCount(buffer, offset)
var isMarked: Boolean
get() = RtpHeader.getMarker(buffer, offset)
set(value) = RtpHeader.setMarker(buffer, offset, value)
/* The four values below (payloadType, sequenceNumber, timestamp, and ssrc)
* are very frequently accessed in our pipeline; store their values in
* delegated properties, rather than re-reading them from the buffer every time.
*/
private var _payloadType: Int = RtpHeader.getPayloadType(buffer, offset)
var payloadType: Int
get() = _payloadType
set(newValue) {
if (newValue != _payloadType) {
RtpHeader.setPayloadType(this.buffer, this.offset, newValue)
_payloadType = newValue
}
}
private var _sequenceNumber: Int = RtpHeader.getSequenceNumber(buffer, offset)
var sequenceNumber: Int
get() = _sequenceNumber
set(newValue) {
if (newValue != _sequenceNumber) {
RtpHeader.setSequenceNumber(this.buffer, this.offset, newValue)
_sequenceNumber = newValue
}
}
private var _timestamp: Long = RtpHeader.getTimestamp(buffer, offset)
var timestamp: Long
get() = _timestamp
set(newValue) {
if (newValue != _timestamp) {
RtpHeader.setTimestamp(this.buffer, this.offset, newValue)
_timestamp = newValue
}
}
private var _ssrc: Long = RtpHeader.getSsrc(buffer, offset)
var ssrc: Long
get() = _ssrc
set(newValue) {
if (newValue != _ssrc) {
RtpHeader.setSsrc(this.buffer, this.offset, newValue)
_ssrc = newValue
}
}
val csrcs: List<Long>
get() = RtpHeader.getCsrcs(buffer, offset)
/**
* The length of the entire RTP header, including any extensions, in bytes
*/
var headerLength: Int = RtpHeader.getTotalLength(buffer, offset)
protected set
init {
if (headerLength > length) {
throw IllegalArgumentException("RTP packet header length $headerLength > length $length")
}
}
val payloadLength: Int
get() = length - headerLength
val payloadOffset: Int
get() = offset + headerLength
var paddingSize: Int
get() {
if (!hasPadding) {
return 0
}
// The last octet of the padding contains a count of how many
// padding octets should be ignored, including itself.
// It's an 8-bit unsigned number.
return buffer.getByteAsInt(offset + length - 1)
}
set(value) {
if (value > 0) {
hasPadding = true
buffer[offset + length - 1] = value.toByte()
} else {
hasPadding = false
}
}
private val _encodedHeaderExtensions: EncodedHeaderExtensions = EncodedHeaderExtensions()
private val encodedHeaderExtensions: EncodedHeaderExtensions
get() {
_encodedHeaderExtensions.reset()
return _encodedHeaderExtensions
}
/**
* For [RtpPacket] the payload is everything after the RTP Header.
*/
override val payloadVerification: String
get() = "type=RtpPacket len=$payloadLength " +
"hashCode=${buffer.hashCodeOfSegment(payloadOffset, payloadOffset + payloadLength)}"
private var pendingHeaderExtensions: MutableList<HeaderExtension>? = null
private fun getEncodedHeaderExtension(extensionId: Int): HeaderExtension? {
if (!hasEncodedExtensions) return null
encodedHeaderExtensions.forEach { ext ->
if (ext.id == extensionId) {
return ext
}
}
return null
}
var hasExtensions: Boolean
get() = pendingHeaderExtensions?.isNotEmpty() ?: hasEncodedExtensions
set(value) {
val p = pendingHeaderExtensions
if (p != null) {
if (value && p.isEmpty()) {
throw java.lang.IllegalStateException(
"Cannot set hasExtensions to true with empty pending extensions"
)
}
if (!value) {
p.clear()
}
} else {
hasEncodedExtensions = value
}
}
fun getHeaderExtension(extensionId: Int): HeaderExtension? {
val activeHeaderExtensions = pendingHeaderExtensions?.iterator() ?: encodedHeaderExtensions
activeHeaderExtensions.forEach { ext ->
if (ext.id == extensionId) {
return ext
}
}
return null
}
private fun createPendingHeaderExtensions(removeIf: ((HeaderExtension) -> Boolean)?) {
if (pendingHeaderExtensions != null) {
return
}
pendingHeaderExtensions = ArrayList<HeaderExtension>().also { l ->
encodedHeaderExtensions.forEach {
if (removeIf == null || !removeIf(it)) {
l.add(PendingHeaderExtension(it))
}
}
}
}
/**
* Removes the header extension (or all header extensions) with the given ID.
*/
fun removeHeaderExtension(id: Int) {
pendingHeaderExtensions?.removeIf { h -> h.id == id }
?: createPendingHeaderExtensions { h -> h.id == id }
}
/**
* Removes all header extensions except those with ID values in [retain]
*/
fun removeHeaderExtensionsExcept(retain: Set<Int>) {
pendingHeaderExtensions?.removeIf { h -> !retain.contains(h.id) }
?: createPendingHeaderExtensions { h -> !retain.contains(h.id) }
}
/**
* Adds an RTP header extension with ID [id] and data length [extDataLength] to this
* packet. The contents of the extension are not set to anything, and the
* caller of this method is responsible for filling them in via the
* [HeaderExtension] reference returned.
*
* This method MUST NOT be called while iterating over the extensions using
* {@link #getHeaderExtensions()}, or while manipulating the state of this
* {@link NewRawPacket}.
*
*/
fun addHeaderExtension(id: Int, extDataLength: Int): HeaderExtension {
if (id !in 1..15 || extDataLength !in 1..16) {
throw IllegalArgumentException("id=$id len=$extDataLength)")
}
val newHeader = PendingHeaderExtension(id, extDataLength)
if (pendingHeaderExtensions == null) {
createPendingHeaderExtensions(null)
}
pendingHeaderExtensions!!.add(newHeader)
return newHeader
}
fun encodeHeaderExtensions() {
val pendingHeaderExtensions = this.pendingHeaderExtensions ?: return
// The byte[] of an RtpPacket has the following structure:
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | A: unused | B: hdr + ext | C: payload | D: unused |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// And the regions have the following sizes:
// A: this.offset
// B: this.getHeaderLength()
// C: this.getPayloadLength()
// D: this.buffer.length - this.length - this.offset
// If the newly-encoded header extensions block results in a header
// longer than the current one,
// we will try to extend the packet so that it uses A and/or D if
// possible, in order to avoid allocating new memory.
// We get this early, before we modify the buffer.
val currHeaderLength = headerLength
val currPayloadLength = payloadLength
val baseHeaderLength = RtpHeader.FIXED_HEADER_SIZE_BYTES + csrcCount * 4
val newExtHeaderLength = if (pendingHeaderExtensions.isEmpty()) {
0
} else {
val rawHeaderLength = RtpHeader.EXT_HEADER_SIZE_BYTES +
pendingHeaderExtensions.sumOf { h -> h.totalLengthBytes }
rawHeaderLength + RtpUtils.getNumPaddingBytes(rawHeaderLength)
}
val newHeaderLength = baseHeaderLength + newExtHeaderLength
val newPacketLength = newHeaderLength + currPayloadLength
val newPayloadOffset: Int
val newBuffer = if (buffer.size >= (newPacketLength + BYTES_TO_LEAVE_AT_END_OF_PACKET)) {
// We don't need a new buffer
if ((offset + currHeaderLength) >= (newPacketLength - currPayloadLength)) {
// Region A (see above) is enough to accommodate the new
// packet, keep the payload where it is.
newPayloadOffset = payloadOffset
} else {
// We have to use region D, so move the payload all the way to the right
newPayloadOffset = buffer.size - currPayloadLength - BYTES_TO_LEAVE_AT_END_OF_PACKET
System.arraycopy(buffer, payloadOffset, buffer, newPayloadOffset, currPayloadLength)
}
buffer
} else {
// We need a new buffer. We will place the payload almost to the end
// (leaving room for an SRTP tag)
BufferPool.getArray(newPacketLength + BYTES_TO_LEAVE_AT_END_OF_PACKET).apply {
newPayloadOffset = size - currPayloadLength - BYTES_TO_LEAVE_AT_END_OF_PACKET
System.arraycopy(buffer, payloadOffset, this, newPayloadOffset, currPayloadLength)
}
}
val newOffset = newPayloadOffset - newHeaderLength
if (buffer !== newBuffer || offset != newOffset) {
// Copy the base header into place.
System.arraycopy(buffer, offset, newBuffer, newOffset, baseHeaderLength)
}
if (pendingHeaderExtensions.isNotEmpty()) {
var off = newOffset + baseHeaderLength
// Write the header extension
newBuffer.putShort(off, 0xBEDE.toShort())
newBuffer.putShort(off + 2, ((newExtHeaderLength - RtpHeader.EXT_HEADER_SIZE_BYTES) / 4).toShort())
off += 4
// Write pending header extension elements
pendingHeaderExtensions.forEach { h ->
System.arraycopy(h.currExtBuffer, h.currExtOffset, newBuffer, off, h.currExtLength)
off += h.currExtLength
}
// Write padding
while (off < newOffset + newHeaderLength) {
newBuffer[off] = 0
off++
}
}
val oldBuffer = buffer
buffer = newBuffer
// Reference comparison to see if we got a new buffer. If so, return the old one to the pool
if (oldBuffer !== newBuffer) {
BufferPool.returnArray(oldBuffer)
}
offset = newOffset
length = newPacketLength
headerLength = newHeaderLength
// ... and set the extension bit.
hasEncodedExtensions = pendingHeaderExtensions.isNotEmpty()
// Clear pending extensions.
this.pendingHeaderExtensions = null
}
override fun clone(): RtpPacket {
return RtpPacket(
cloneBuffer(BYTES_TO_LEAVE_AT_START_OF_PACKET),
BYTES_TO_LEAVE_AT_START_OF_PACKET,
length
).also { if (pendingHeaderExtensions != null) it.pendingHeaderExtensions = ArrayList(pendingHeaderExtensions) }
}
override fun toString(): String = with(StringBuilder()) {
append("RtpPacket: ")
append("PT=$payloadType")
append(", Ssrc=$ssrc")
append(", SeqNum=$sequenceNumber")
append(", M=$isMarked")
append(", X=$hasEncodedExtensions")
append(", Ts=$timestamp")
toString()
}
/**
* Represents an RTP header extension with the RFC5285 one-byte header:
*
* 0
* 0 1 2 3 4 5 6 7
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | ID | len | data... |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* Note that this class requires its offset to be set manually by an outside entity, and that
* it ALWAYS uses the CURRENT buffer set in [RtpPacket] (though it maintains its own
* offset and length, which are specific to the current header extension).
*
*/
abstract class HeaderExtension {
var currExtOffset: Int = 0
protected set
var currExtLength: Int = 0
protected set
abstract val currExtBuffer: ByteArray
fun setOffsetLength(nextHeaderExtOffset: Int, nextHeaderExtLength: Int) {
currExtOffset = nextHeaderExtOffset
currExtLength = nextHeaderExtLength
}
var id: Int
get() {
if (currExtLength <= 0) {
return -1
}
return HeaderExtensionHelpers.getId(currExtBuffer, currExtOffset)
}
set(newId) {
if (currExtLength <= 0) {
throw IllegalStateException("Can't set ID on header extension with no length")
}
HeaderExtensionHelpers.setId(newId, currExtBuffer, currExtOffset)
}
val dataLengthBytes: Int
get() = HeaderExtensionHelpers.getDataLengthBytes(currExtBuffer, currExtOffset)
val totalLengthBytes: Int
get() = 1 + dataLengthBytes
}
inner class EncodedHeaderExtension : HeaderExtension() {
override val currExtBuffer: ByteArray
get() = [email protected]
}
@SuppressFBWarnings(
value = ["EI_EXPOSE_REP"],
justification = "We intentionally expose the internal buffer."
)
class PendingHeaderExtension(id: Int, extDataLength: Int) : HeaderExtension() {
override val currExtBuffer = ByteArray(extDataLength + 1)
init {
currExtLength = extDataLength + 1
currExtBuffer[0] = ((id and 0x0F) shl 4).toByte() or ((extDataLength - 1) and 0x0F).toByte()
}
constructor(other: HeaderExtension) : this(other.id, other.dataLengthBytes) {
System.arraycopy(other.currExtBuffer, other.currExtOffset + 1, currExtBuffer, 1, dataLengthBytes)
}
}
inner class EncodedHeaderExtensions : Iterator<HeaderExtension> {
/**
* The offset of the next extension
*/
private var nextOffset = 0
/**
* The remaining length of the extensions headers.
*/
private var remainingLength = 0
val currHeaderExtension: HeaderExtension = EncodedHeaderExtension()
override fun hasNext(): Boolean {
// Consume any padding
while (remainingLength > 0 && buffer.get(nextOffset).isPadding()) {
nextOffset++
remainingLength--
}
if (remainingLength <= 0 || nextOffset < 0) {
return false
}
return getNextExtLength() > 0
}
override fun next(): HeaderExtension {
val nextExtLen = getNextExtLength()
if (nextExtLen <= 0) {
throw Exception("Invalid extension length. Did hasNext() return true?")
}
currHeaderExtension.setOffsetLength(nextOffset, nextExtLen)
nextOffset += nextExtLen
remainingLength -= nextExtLen
return currHeaderExtension
}
/**
* Return the entire length (including the header), in bytes, of the 'next' RTP extension
* according to [nextOffset]. If [remainingLength] is less than the minimum size for
* an extension, or the parsed length is larger than [remainingLength], return -1
*/
private fun getNextExtLength(): Int {
if (remainingLength < HeaderExtensionHelpers.MINIMUM_EXT_SIZE_BYTES) {
return -1
}
val extLen = HeaderExtensionHelpers.getEntireLengthBytes(buffer, nextOffset)
return if (extLen > remainingLength) -1 else extLen
}
/**
* Resets this iterator back to the beginning of the extensions
*/
internal fun reset() {
val extLength =
if (hasEncodedExtensions) {
val extensionBlockLength = HeaderExtensionHelpers.getExtensionsTotalLength(
buffer, offset + RtpHeader.FIXED_HEADER_SIZE_BYTES + csrcCount * 4
)
extensionBlockLength - HeaderExtensionHelpers.TOP_LEVEL_EXT_HEADER_SIZE_BYTES
} else 0
if (extLength <= 0) {
// No extensions
nextOffset = -1
remainingLength = -1
} else {
nextOffset = offset +
RtpHeader.FIXED_HEADER_SIZE_BYTES +
csrcCount * 4 +
RtpHeader.EXT_HEADER_SIZE_BYTES
remainingLength = extLength
}
}
}
companion object {
/**
* The size of the header for individual extensions. Currently we only
* support 1 byte header extensions
*/
const val HEADER_EXT_HEADER_SIZE = 1
/**
* How much space to leave in the beginning of new RTP packets. Having space in the beginning allows us to
* implement adding RTP header extensions efficiently (by keeping the RTP payload in place and shifting the
* header left).
*/
const val BYTES_TO_LEAVE_AT_START_OF_PACKET = 10
}
}
| apache-2.0 | 613129bf903b8a4043be1d0d2364de02 | 36.33935 | 119 | 0.570386 | 4.779575 | false | false | false | false |
wireapp/wire-android | storage/src/androidTest/kotlin/com/waz/zclient/storage/globaldatabase/GlobalSQLiteDbTestHelper.kt | 1 | 5977 | package com.waz.zclient.storage.globaldatabase
import android.content.ContentValues
import android.database.sqlite.SQLiteDatabase
import com.waz.zclient.storage.DbSQLiteOpenHelper
import org.json.JSONObject
class GlobalSQLiteDbTestHelper private constructor() {
companion object {
//ActiveAccount
private const val ACTIVE_ACCOUNT_ID_COL = "_id"
private const val ACTIVE_ACCOUNT_TEAM_ID_COL = "team_id"
private const val ACTIVE_ACCOUNT_COOKIE_COL = "cookie"
private const val ACTIVE_ACCOUNT_ACCESS_TOKEN_COL = "access_token"
private const val ACTIVE_ACCOUNT_REGISTERED_PUSH_COL = "registered_push"
private const val ACTIVE_ACCOUNT_SSO_ID_COL = "sso_id"
private const val ACTIVE_ACCOUNTS_TABLE_NAME = "ActiveAccounts"
//Teams
private const val TEAMS_ID_COL = "_id"
private const val TEAM_NAME_COL = "name"
private const val TEAM_CREATOR_COL = "creator"
private const val TEAM_ICON_ID = "icon"
private const val TEAM_TABLE_NAME = "Teams"
//CacheEntry
private const val CACHE_ENTRY_ID_COL = "key"
private const val CACHE_ENTRY_FILE_ID_COL = "file"
private const val CACHE_ENTRY_DATA_COL = "data"
private const val CACHE_ENTRY_LAST_USED_COL = "lastUsed"
private const val CACHE_ENTRY_TIMEOUT_COL = "timeout"
private const val CACHE_ENTRY_PATH_COL = "path"
private const val CACHE_ENTRY_FILE_NAME_COL = "file_name"
private const val CACHE_ENTRY_MIME_COL = "mime"
private const val CACHE_ENTRY_ENC_KEY_COL = "enc_key"
private const val CACHE_ENTRY_LENGTH_COL = "length"
private const val CACHE_ENTRY_TABLE_NAME = "CacheEntry"
fun insertActiveAccount(
id: String,
teamId: String? = null,
cookie: String,
accessToken: JSONObject,
registeredPush: String,
ssoId: String? = null,
openHelper: DbSQLiteOpenHelper
) {
val contentValues = ContentValues().also {
it.put(ACTIVE_ACCOUNT_ID_COL, id)
it.put(ACTIVE_ACCOUNT_TEAM_ID_COL, teamId)
it.put(ACTIVE_ACCOUNT_COOKIE_COL, cookie)
it.put(ACTIVE_ACCOUNT_ACCESS_TOKEN_COL, accessToken.toString())
it.put(ACTIVE_ACCOUNT_REGISTERED_PUSH_COL, registeredPush)
it.put(ACTIVE_ACCOUNT_SSO_ID_COL, ssoId)
}
with(openHelper.writableDatabase) {
insertWithOnConflict(
ACTIVE_ACCOUNTS_TABLE_NAME,
null,
contentValues,
SQLiteDatabase.CONFLICT_REPLACE
)
}
}
fun insertTeam(
id: String,
name: String,
creator: String,
icon: String,
openHelper: DbSQLiteOpenHelper
) {
val contentValues = ContentValues().also {
it.put(TEAMS_ID_COL, id)
it.put(TEAM_NAME_COL, name)
it.put(TEAM_CREATOR_COL, creator)
it.put(TEAM_ICON_ID, icon)
}
with(openHelper.writableDatabase) {
insertWithOnConflict(
TEAM_TABLE_NAME,
null,
contentValues,
SQLiteDatabase.CONFLICT_REPLACE
)
}
}
fun insertCacheEntry(
id: String,
fileId: String,
lastUsed: Long,
data: ByteArray? = null,
timeout: Long,
filePath: String? = null,
fileName: String? = null,
mime: String,
encKey: String? = null,
length: Long? = null,
openHelper: DbSQLiteOpenHelper
) {
val contentValues = ContentValues().also {
it.put(CACHE_ENTRY_ID_COL, id)
it.put(CACHE_ENTRY_FILE_ID_COL, fileId)
it.put(CACHE_ENTRY_LAST_USED_COL, lastUsed)
it.put(CACHE_ENTRY_DATA_COL, data)
it.put(CACHE_ENTRY_TIMEOUT_COL, timeout)
it.put(CACHE_ENTRY_PATH_COL, filePath)
it.put(CACHE_ENTRY_FILE_NAME_COL, fileName)
it.put(CACHE_ENTRY_MIME_COL, mime)
it.put(CACHE_ENTRY_ENC_KEY_COL, encKey)
it.put(CACHE_ENTRY_LENGTH_COL, length)
}
with(openHelper.writableDatabase) {
insertWithOnConflict(
CACHE_ENTRY_TABLE_NAME,
null,
contentValues,
SQLiteDatabase.CONFLICT_REPLACE
)
}
}
fun createTable(testOpenHelper: DbSQLiteOpenHelper) {
with(testOpenHelper) {
execSQL("""
CREATE TABLE IF NOT EXISTS ActiveAccounts (_id TEXT PRIMARY KEY, team_id TEXT , cookie TEXT , access_token TEXT , registered_push TEXT , sso_id TEXT )
""".trimIndent())
execSQL("""
CREATE TABLE Teams (_id TEXT PRIMARY KEY, name TEXT , creator TEXT , icon TEXT )
""".trimIndent())
execSQL("""
CREATE TABLE CacheEntry (key TEXT PRIMARY KEY, file TEXT , data BLOB , lastUsed INTEGER , timeout INTEGER , enc_key TEXT , path TEXT , mime TEXT , file_name TEXT , length INTEGER )
""".trimIndent())
}
}
fun clearDatabase(testOpenHelper: DbSQLiteOpenHelper) {
with(testOpenHelper) {
execSQL("DROP TABLE IF EXISTS ActiveAccounts")
execSQL("DROP TABLE IF EXISTS Teams")
execSQL("DROP TABLE IF EXISTS CacheEntry")
}
}
fun closeDatabase(testOpenHelper: DbSQLiteOpenHelper) {
testOpenHelper.close()
}
}
}
| gpl-3.0 | 8ed4f613d712bb59be2191d960179543 | 37.070064 | 200 | 0.550276 | 4.658613 | false | false | false | false |
facebook/litho | sample/src/main/java/com/facebook/samples/litho/documentation/flexbox/TextInRow.kt | 1 | 1700 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.samples.litho.documentation.flexbox
import com.facebook.litho.Component
import com.facebook.litho.ComponentScope
import com.facebook.litho.KComponent
import com.facebook.litho.Row
import com.facebook.litho.Style
import com.facebook.litho.core.margin
import com.facebook.litho.core.padding
import com.facebook.litho.dp
import com.facebook.litho.flexbox.flex
import com.facebook.litho.kotlin.widget.Text
import com.facebook.litho.sp
class TextInRow : KComponent() {
// start_example
override fun ComponentScope.render(): Component {
return Row(style = Style.padding(16.dp)) {
child(
Text(
style =
Style.flex(shrink = 0f), // If flexShrink is 1f then this text will be truncated
text = "This is a really long text.",
textSize = 20.sp,
maxLines = 1))
child(
Text(
style = Style.margin(start = 8.dp),
text = "Another long text",
textSize = 20.sp,
maxLines = 1))
}
}
// end_example
}
| apache-2.0 | 4a24de6adc5994f2fac0e0c8a1f25f37 | 31.692308 | 98 | 0.675882 | 4.086538 | false | false | false | false |
anton-okolelov/intellij-rust | src/main/kotlin/org/rust/lang/core/psi/ext/RsModDeclItem.kt | 2 | 2353 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.psi.ext
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.stubs.IStubElementType
import org.rust.ide.icons.RsIcons
import org.rust.lang.core.macros.ExpansionResult
import org.rust.lang.core.psi.RsBlock
import org.rust.lang.core.psi.RsModDeclItem
import org.rust.lang.core.psi.RsPsiImplUtil
import org.rust.lang.core.resolve.ref.RsModReferenceImpl
import org.rust.lang.core.resolve.ref.RsReference
import org.rust.lang.core.stubs.RsModDeclItemStub
import javax.swing.Icon
fun RsModDeclItem.getOrCreateModuleFile(): PsiFile? {
val existing = reference.resolve()?.containingFile
if (existing != null) return existing
return suggestChildFileName?.let { containingMod.ownedDirectory?.createFile(it) }
}
val RsModDeclItem.isLocal: Boolean
get() = stub?.isLocal ?: (ancestorStrict<RsBlock>() != null)
//TODO: use explicit path if present.
private val RsModDeclItem.suggestChildFileName: String?
get() = implicitPaths.firstOrNull()
private val RsModDeclItem.implicitPaths: List<String> get() {
val name = name ?: return emptyList()
return if (isLocal) emptyList() else listOf("$name.rs", "$name/mod.rs")
}
val RsModDeclItem.pathAttribute: String? get() = queryAttributes.lookupStringValueForKey("path")
abstract class RsModDeclItemImplMixin : RsStubbedNamedElementImpl<RsModDeclItemStub>,
RsModDeclItem {
constructor(node: ASTNode) : super(node)
constructor(stub: RsModDeclItemStub, nodeType: IStubElementType<*, *>) : super(stub, nodeType)
override fun getReference(): RsReference = RsModReferenceImpl(this)
override val referenceNameElement: PsiElement get() = identifier
override val referenceName: String get() = name!!
override fun getIcon(flags: Int): Icon? = iconWithVisibility(flags, RsIcons.MODULE)
override val isPublic: Boolean get() = RsPsiImplUtil.isPublic(this, stub)
override val crateRelativePath: String? get() = RsPsiImplUtil.crateRelativePath(this)
override fun getContext() = ExpansionResult.getContextImpl(this)
}
val RsModDeclItem.hasMacroUse: Boolean get() =
queryAttributes.hasAttribute("macro_use")
| mit | e6cb38b8402d33cb9af4381fbc73acbf | 33.602941 | 98 | 0.755206 | 4.23964 | false | false | false | false |
Zhuinden/simple-stack | samples/scoping-samples/simple-stack-example-scoping-kotlin/src/main/java/com/zhuinden/simplestackexamplescoping/utils/CompositeNotificationToken.kt | 1 | 1161 | package com.zhuinden.simplestackexamplescoping.utils
import com.zhuinden.eventemitter.EventSource
import java.util.*
class CompositeNotificationToken : EventSource.NotificationToken {
private val threadId = Thread.currentThread().id
private val notificationTokens: LinkedList<EventSource.NotificationToken> = LinkedList()
@Suppress("MemberVisibilityCanBePrivate")
fun add(notificationToken: EventSource.NotificationToken) {
notificationTokens.add(notificationToken)
}
private var isDisposing = false
override fun stopListening() {
if (threadId != Thread.currentThread().id) {
throw IllegalStateException("Cannot stop listening on a different thread where it was created")
}
if (isDisposing) {
return
}
isDisposing = true
val size = notificationTokens.size
for (i in size - 1 downTo 0) {
val token = notificationTokens.removeAt(i)
token.stopListening()
}
isDisposing = false
}
operator fun plusAssign(notificationToken: EventSource.NotificationToken) {
add(notificationToken)
}
} | apache-2.0 | 8c4b98fa9f1e4f576c555a84c09ef009 | 30.405405 | 107 | 0.687339 | 5.16 | false | false | false | false |
angryziber/picasa-gallery | src/views/dsl.kt | 1 | 487 | package views
val newline = "\r?\n".toRegex()
operator fun Boolean.div(s: String) = if (this) s else ""
operator fun Any?.div(s: String) = if (this != null) s else ""
fun String?.escapeHTML() = this?.replace("&", "&")?.replace("<", "<")?.replace("\"", """) ?: ""
fun String?.escapeJS() = this?.replace("'", "\\'") ?: ""
operator fun String?.unaryPlus() = escapeHTML()
fun <T> Collection<T>.each(itemTemplate: T.() -> String) = joinToString("", transform = itemTemplate)
| gpl-3.0 | c9b45a1116453d11e753c4076bf7c989 | 36.461538 | 107 | 0.609856 | 3.429577 | false | false | false | false |
google/ksp | compiler-plugin/src/main/kotlin/com/google/devtools/ksp/symbol/impl/synthetic/KSErrorTypeClassDeclaration.kt | 1 | 3022 | /*
* Copyright 2020 Google LLC
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language 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.google.devtools.ksp.symbol.impl.synthetic
import com.google.devtools.ksp.processing.impl.ResolverImpl
import com.google.devtools.ksp.symbol.*
import com.google.devtools.ksp.symbol.impl.kotlin.KSNameImpl
object KSErrorTypeClassDeclaration : KSClassDeclaration {
override val annotations: Sequence<KSAnnotation> = emptySequence()
override val classKind: ClassKind = ClassKind.CLASS
override val containingFile: KSFile? = null
override val declarations: Sequence<KSDeclaration> = emptySequence()
override val isActual: Boolean = false
override val isExpect: Boolean = false
override val isCompanionObject: Boolean = false
override val location: Location = NonExistLocation
override val parent: KSNode? = null
override val modifiers: Set<Modifier> = emptySet()
override val origin: Origin = Origin.SYNTHETIC
override val packageName: KSName = KSNameImpl.getCached("")
override val parentDeclaration: KSDeclaration? = null
override val primaryConstructor: KSFunctionDeclaration? = null
override val qualifiedName: KSName? = null
override val simpleName: KSName = KSNameImpl.getCached("<Error>")
override val superTypes: Sequence<KSTypeReference> = emptySequence()
override val typeParameters: List<KSTypeParameter> = emptyList()
override fun getSealedSubclasses(): Sequence<KSClassDeclaration> = emptySequence()
override fun asStarProjectedType(): KSType {
return ResolverImpl.instance!!.builtIns.nothingType
}
override fun asType(typeArguments: List<KSTypeArgument>): KSType {
return ResolverImpl.instance!!.builtIns.nothingType
}
override fun findActuals(): Sequence<KSDeclaration> {
return emptySequence()
}
override fun findExpects(): Sequence<KSDeclaration> {
return emptySequence()
}
override fun getAllFunctions(): Sequence<KSFunctionDeclaration> {
return emptySequence()
}
override fun getAllProperties(): Sequence<KSPropertyDeclaration> {
return emptySequence()
}
override fun <D, R> accept(visitor: KSVisitor<D, R>, data: D): R {
return visitor.visitClassDeclaration(this, data)
}
override fun toString(): String {
return "Error type synthetic declaration"
}
override val docString = null
}
| apache-2.0 | 23b41bed829e7fb23fd27d86ced72815 | 30.479167 | 86 | 0.731635 | 4.94599 | false | false | false | false |
chrisbanes/tivi | data-android/src/main/java/app/tivi/data/TiviRoomDatabase.kt | 1 | 2408 | /*
* Copyright 2017 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 app.tivi.data
import androidx.room.AutoMigration
import androidx.room.Database
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import app.tivi.data.entities.Episode
import app.tivi.data.entities.EpisodeWatchEntry
import app.tivi.data.entities.FollowedShowEntry
import app.tivi.data.entities.LastRequest
import app.tivi.data.entities.PopularShowEntry
import app.tivi.data.entities.RecommendedShowEntry
import app.tivi.data.entities.RelatedShowEntry
import app.tivi.data.entities.Season
import app.tivi.data.entities.ShowTmdbImage
import app.tivi.data.entities.TiviShow
import app.tivi.data.entities.TiviShowFts
import app.tivi.data.entities.TraktUser
import app.tivi.data.entities.TrendingShowEntry
import app.tivi.data.entities.WatchedShowEntry
import app.tivi.data.views.FollowedShowsLastWatched
import app.tivi.data.views.FollowedShowsNextToWatch
import app.tivi.data.views.FollowedShowsWatchStats
@Database(
entities = [
TiviShow::class,
TiviShowFts::class,
TrendingShowEntry::class,
PopularShowEntry::class,
TraktUser::class,
WatchedShowEntry::class,
FollowedShowEntry::class,
Season::class,
Episode::class,
RelatedShowEntry::class,
EpisodeWatchEntry::class,
LastRequest::class,
ShowTmdbImage::class,
RecommendedShowEntry::class
],
views = [
FollowedShowsWatchStats::class,
FollowedShowsLastWatched::class,
FollowedShowsNextToWatch::class
],
version = 27,
autoMigrations = [
AutoMigration(from = 24, to = 25),
AutoMigration(from = 25, to = 26),
AutoMigration(from = 26, to = 27)
]
)
@TypeConverters(TiviTypeConverters::class)
abstract class TiviRoomDatabase : RoomDatabase(), TiviDatabase
| apache-2.0 | 1d235a1b90f848f8399817a9218efb3c | 32.915493 | 75 | 0.74294 | 4.102215 | false | false | false | false |
alygin/intellij-rust | src/main/kotlin/org/rust/ide/actions/RsAbstractUpDownMover.kt | 1 | 3342 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.actions
import com.intellij.codeInsight.editorActions.moveUpDown.LineRange
import com.intellij.codeInsight.editorActions.moveUpDown.StatementUpDownMover
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.tree.IElementType
import org.rust.ide.utils.findElementAtIgnoreWhitespaceAfter
import org.rust.ide.utils.findElementAtIgnoreWhitespaceBefore
import org.rust.lang.core.psi.RsFile
import org.rust.lang.core.psi.ext.elementType
val PsiElement.line: Int? get() = containingFile.viewProvider.document?.getLineNumber(textRange.startOffset)
abstract class RsAbstractUpDownMover : StatementUpDownMover() {
abstract val containers: List<IElementType>
abstract val jumpOver: List<IElementType>
abstract fun collectedElement(element: PsiElement): Pair<PsiElement, List<Int>>?
override fun checkAvailable(editor: Editor, file: PsiFile, info: MoveInfo, down: Boolean): Boolean {
if (file !is RsFile) {
return false
}
val selectionRange = getLineRangeFromSelection(editor)
val start = file.findElementAtIgnoreWhitespaceBefore(
editor.document.getLineStartOffset(selectionRange.startLine)
) ?: return false
val (collectedElement, possibleStartLines) = collectedElement(start) ?: return false
if (!possibleStartLines.contains(selectionRange.startLine)) {
return false
}
val range = LineRange(collectedElement)
info.toMove = range
val line = if (!down) {
info.toMove.startLine - 1
} else {
info.toMove.endLine + 1
}
if (line < 0 || line >= editor.document.lineCount) {
return info.prohibitMove()
}
val offset = editor.document.getLineStartOffset(line)
var element: PsiElement? = if (!down) {
file.findElementAtIgnoreWhitespaceBefore(offset)
} else {
file.findElementAtIgnoreWhitespaceAfter(offset)
} ?: return info.prohibitMove()
while (element != null && element !is RsFile) {
if (containers.any { element?.elementType == it }) {
var parentOfFn = collectedElement.parent
while (parentOfFn !is RsFile) {
if (element == parentOfFn) {
return info.prohibitMove()
}
parentOfFn = parentOfFn.parent
}
}
if (jumpOver.any { element?.elementType == it }) {
break
}
val parent = element.parent
if (parent is RsFile) {
break
}
element = parent
}
if (element != null) {
info.toMove2 = LineRange(element)
}
if (down) {
if (info.toMove2.startLine - 1 == range.endLine || element == collectedElement) {
info.toMove2 = LineRange(line - 1, line)
}
} else {
if (info.toMove2.startLine == range.startLine) {
info.toMove2 = LineRange(line, line + 1)
}
}
return true
}
}
| mit | 28787b4cb5b1d0a0ad93153f8920c96d | 34.553191 | 108 | 0.614901 | 4.680672 | false | false | false | false |
ntemplon/legends-of-omterra | core/src/com/jupiter/europa/screen/MainMenuScreen.kt | 1 | 31547 | /*
* 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.screen
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.InputProcessor
import com.badlogic.gdx.Screen
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.GL20
import com.badlogic.gdx.graphics.Pixmap
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.Sprite
import com.badlogic.gdx.graphics.g2d.TextureAtlas
import com.badlogic.gdx.graphics.g2d.TextureRegion
import com.badlogic.gdx.scenes.scene2d.Stage
import com.badlogic.gdx.scenes.scene2d.ui.*
import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle
import com.badlogic.gdx.scenes.scene2d.ui.List.ListStyle
import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane.ScrollPaneStyle
import com.badlogic.gdx.scenes.scene2d.ui.SelectBox.SelectBoxStyle
import com.badlogic.gdx.scenes.scene2d.ui.Slider.SliderStyle
import com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle
import com.badlogic.gdx.scenes.scene2d.ui.TextField.TextFieldStyle
import com.badlogic.gdx.scenes.scene2d.ui.Window.WindowStyle
import com.badlogic.gdx.scenes.scene2d.utils.SpriteDrawable
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable
import com.badlogic.gdx.utils.Json
import com.badlogic.gdx.utils.JsonReader
import com.badlogic.gdx.utils.viewport.ScreenViewport
import com.jupiter.europa.EuropaGame
import com.jupiter.europa.audio.AudioService
import com.jupiter.europa.entity.Party
import com.jupiter.europa.geometry.Size
import com.jupiter.europa.io.FileLocations
import com.jupiter.europa.save.SaveGame
import com.jupiter.europa.scene2d.ui.EffectPoolSelector.TraitPoolSelectorStyle
import com.jupiter.europa.scene2d.ui.EuropaButton
import com.jupiter.europa.scene2d.ui.EuropaButton.ClickEvent
import com.jupiter.europa.scene2d.ui.MultipleNumberSelector
import com.jupiter.europa.scene2d.ui.NumberSelector.NumberSelectorStyle
import com.jupiter.europa.scene2d.ui.ObservableDialog.DialogEventArgs
import com.jupiter.europa.scene2d.ui.ObservableDialog.DialogEvents
import com.jupiter.europa.screen.dialog.*
import com.jupiter.europa.screen.dialog.CreateCharacterDialog.CreateCharacterExitStates
import com.jupiter.europa.screen.dialog.NewGameDialog.NewGameExitStates
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Path
/**
* @author Nathan Templon
*/
public class MainMenuScreen : Screen, InputProcessor {
// Enumerations
public enum class DialogExitStates {
NEXT,
BACK
}
// Fields
private var stage: Stage? = null
private var background: Image? = null
private var titleTable: Table? = null
private var buttonTable: Table? = null
private var titleWrapperTable: Table? = null
private var newGameButton: EuropaButton? = null
private var loadGameButton: EuropaButton? = null
private var multiplayerButton: EuropaButton? = null
private var optionsButton: EuropaButton? = null
private var creditsButton: EuropaButton? = null
private var quitButton: EuropaButton? = null
private var createCharacterDialog: CreateCharacterDialog? = null
private var newGameDialog: NewGameDialog? = null
private var loadGameDialog: LoadGameDialog? = null
private var creditsDialog: CreditsDialog? = null
private var optionsDialog: OptionsDialog? = null
private var size = Size(0, 0)
// Screen Implementation
override fun render(delta: Float) {
Gdx.gl.glClearColor(BACKGROUND_COLOR.r, BACKGROUND_COLOR.g, BACKGROUND_COLOR.b, BACKGROUND_COLOR.a)
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT)
this.stage!!.act(delta)
this.stage!!.draw()
}
override fun resize(width: Int, height: Int) {
this.size = Size(width, height)
// True puts 0, 0 at the bottom left corner, false or omission puts 0, 0 at the center
this.stage!!.getViewport().update(width, height, true)
// Resize dialogs
if (this.createCharacterDialog != null) {
this.createCharacterDialog!!.setSize(width.toFloat(), height.toFloat())
}
if (this.newGameDialog != null) {
this.newGameDialog!!.setSize(width.toFloat(), height.toFloat())
}
if (this.loadGameDialog != null) {
this.loadGameDialog!!.setSize(width.toFloat(), height.toFloat())
}
if (this.creditsDialog != null) {
this.creditsDialog!!.setSize(width.toFloat(), height.toFloat())
}
if (this.optionsDialog != null) {
this.optionsDialog!!.setSize(width.toFloat(), height.toFloat())
}
}
override fun show() {
EuropaGame.game.inspectSaves()
this.init()
// Play Music
EuropaGame.game.audioService?.playMusic(AudioService.TITLE_MUSIC)
// Create Screens
this.optionsDialog = OptionsDialog()
this.creditsDialog = CreditsDialog()
}
override fun hide() {
EuropaGame.game.audioService?.stop()
}
override fun pause() {
}
override fun resume() {
}
override fun dispose() {
if (this.stage != null) {
this.stage!!.dispose()
}
}
// InputProcessor Implementation
override fun keyDown(i: Int): Boolean {
return this.stage!!.keyDown(i)
}
override fun keyUp(i: Int): Boolean {
return this.stage!!.keyUp(i)
}
override fun keyTyped(c: Char): Boolean {
return this.stage!!.keyTyped(c)
}
override fun touchDown(i: Int, i1: Int, i2: Int, i3: Int): Boolean {
return this.stage!!.touchDown(i, i1, i2, i3)
}
override fun touchUp(i: Int, i1: Int, i2: Int, i3: Int): Boolean {
return this.stage!!.touchUp(i, i1, i2, i3)
}
override fun touchDragged(i: Int, i1: Int, i2: Int): Boolean {
return this.stage!!.touchDragged(i, i1, i2)
}
override fun mouseMoved(i: Int, i1: Int): Boolean {
return this.stage!!.mouseMoved(i, i1)
}
override fun scrolled(i: Int): Boolean {
return this.stage!!.scrolled(i)
}
// Private Methods
private fun init() {
this.stage = Stage(ScreenViewport())
val skin = createMainMenuSkin()
// Background
this.background = Image(EuropaGame.game.assetManager?.get(BACKGROUND_FILE_NAME, javaClass<Texture>()))
this.background!!.setFillParent(true)
this.stage!!.addActor(this.background)
// Create Buttons
this.buttonTable = Table()
this.buttonTable!!.setFillParent(false)
this.buttonTable!!.center()
this.newGameButton = EuropaButton("New Game", skin.get(DEFAULT_KEY, javaClass<TextButtonStyle>())) // Use the initialized skin
this.newGameButton!!.addClickListener { args -> this.onNewGameClick(args) }
this.loadGameButton = EuropaButton("Load Game", skin.get(DEFAULT_KEY, javaClass<TextButtonStyle>()))
this.loadGameButton!!.addClickListener { args -> this.onLoadGameClick(args) }
this.loadGameButton!!.setDisabled(EuropaGame.game.getSaveNames().size() == 0)
this.multiplayerButton = EuropaButton("Multiplayer", skin.get(DEFAULT_KEY, javaClass<TextButtonStyle>()))
this.multiplayerButton!!.addClickListener { args -> this.onMultiplayerClick(args) }
this.multiplayerButton!!.setDisabled(true)
this.optionsButton = EuropaButton("Options", skin.get(DEFAULT_KEY, javaClass<TextButtonStyle>()))
this.optionsButton!!.addClickListener { args -> this.onOptionsClick(args) }
this.creditsButton = EuropaButton("Credits", skin.get(DEFAULT_KEY, javaClass<TextButtonStyle>()))
this.creditsButton!!.addClickListener { args -> this.onCreditsClick(args) }
this.quitButton = EuropaButton("Exit", skin.get(DEFAULT_KEY, javaClass<TextButtonStyle>()))
this.quitButton!!.addClickListener { args -> this.onQuitClick(args) }
// Configure Button Table
this.buttonTable!!.add<EuropaButton>(this.newGameButton).width(TITLE_BUTTON_WIDTH.toFloat()).space(MainMenuScreen.COMPONENT_SPACING.toFloat())
this.buttonTable!!.row()
this.buttonTable!!.add<EuropaButton>(this.loadGameButton).width(TITLE_BUTTON_WIDTH.toFloat()).space(MainMenuScreen.COMPONENT_SPACING.toFloat())
this.buttonTable!!.row()
this.buttonTable!!.add<EuropaButton>(this.multiplayerButton).width(TITLE_BUTTON_WIDTH.toFloat()).space(MainMenuScreen.COMPONENT_SPACING.toFloat())
this.buttonTable!!.row()
this.buttonTable!!.add<EuropaButton>(this.optionsButton).width(TITLE_BUTTON_WIDTH.toFloat()).space(MainMenuScreen.COMPONENT_SPACING.toFloat())
this.buttonTable!!.row()
this.buttonTable!!.add<EuropaButton>(this.creditsButton).width(TITLE_BUTTON_WIDTH.toFloat()).space(MainMenuScreen.COMPONENT_SPACING.toFloat())
this.buttonTable!!.row()
this.buttonTable!!.add<EuropaButton>(this.quitButton).width(TITLE_BUTTON_WIDTH.toFloat()).space(MainMenuScreen.COMPONENT_SPACING.toFloat())
this.buttonTable!!.row()
// Title
this.titleTable = Table()
this.titleTable!!.setFillParent(true)
this.titleTable!!.center()
this.titleWrapperTable = Table()
val titleWords = EuropaGame.TITLE.split("\\s+")
this.titleWrapperTable!!.add(Label(titleWords[0].substring(0, 1), skin.get(FANCY_KEY, javaClass<LabelStyle>()))).right().expandX()
this.titleWrapperTable!!.add(Label(titleWords[0].substring(1), skin.get(DEFAULT_KEY, javaClass<LabelStyle>())))
for (i in 1..titleWords.size() - 1 - 1) {
var text = titleWords[i]
if (i == 1) {
text = " " + text
}
if (i == titleWords.size() - 1) {
text += " "
}
this.titleWrapperTable!!.add(Label(text, skin.get(DEFAULT_KEY, javaClass<LabelStyle>())))
}
this.titleWrapperTable!!.add(Label(titleWords[titleWords.size() - 1].substring(0, 1), skin.get(FANCY_KEY, javaClass<LabelStyle>())))
this.titleWrapperTable!!.add(Label(titleWords[titleWords.size() - 1].substring(1), skin.get(DEFAULT_KEY, javaClass<LabelStyle>()))).left().expandX()
this.titleWrapperTable!!.background(skin.get(TITLE_BACKGROUND_KEY, javaClass<TextureRegionDrawable>()))
this.titleTable!!.add<Table>(this.titleWrapperTable).pad(COMPONENT_SPACING.toFloat()).top()
this.titleTable!!.row()
this.titleTable!!.add<Table>(this.buttonTable).center().expandY()
this.titleTable!!.row()
this.stage!!.addActor(this.titleTable)
}
private fun onNewGameClick(event: ClickEvent) {
this.createCharacterDialog = CreateCharacterDialog()
this.createCharacterDialog!!.addDialogListener({ args -> this.onCharacterCreationCompleted(args) }, DialogEvents.HIDDEN)
this.showDialog(this.createCharacterDialog!!)
}
private fun onLoadGameClick(event: ClickEvent) {
this.loadGameDialog = LoadGameDialog()
this.loadGameDialog!!.addDialogListener({ args -> this.onLoadGameDialogHidden(args) }, DialogEvents.HIDDEN)
this.showDialog(this.loadGameDialog!!)
}
private fun onMultiplayerClick(event: ClickEvent) {
println("Multiplayer is not yet implemented!")
}
private fun onOptionsClick(event: ClickEvent) {
this.showDialog(this.optionsDialog!!)
}
private fun onCreditsClick(event: ClickEvent) {
this.showDialog(this.creditsDialog!!)
}
private fun onQuitClick(event: ClickEvent) {
Gdx.app.exit()
}
private fun onCharacterCreationCompleted(args: DialogEventArgs) {
if (this.createCharacterDialog!!.exitState == CreateCharacterExitStates.OK) {
this.newGameDialog = NewGameDialog()
this.newGameDialog!!.addDialogListener({ args -> this.onNewGameDialogHidden(args) }, DialogEvents.HIDDEN)
this.showDialog(this.newGameDialog!!)
}
}
private fun onNewGameDialogHidden(args: DialogEventArgs) {
if (this.newGameDialog!!.exitState == NewGameExitStates.START_GAME) {
this.startNewGame()
} else {
this.showDialog(this.createCharacterDialog!!)
}
}
private fun onLoadGameDialogHidden(args: DialogEventArgs) {
if (this.loadGameDialog!!.exitState === LoadGameDialog.LoadGameExitStates.LOAD) {
this.loadGame()
}
}
private fun startNewGame() {
var gameName: String? = this.newGameDialog!!.getNewGameName()
if (gameName == null || gameName.isEmpty()) {
gameName = "default"
}
val world = EuropaGame.game.getWorld(this.newGameDialog!!.getNewGameWorldName())
val party = Party()
// Get Entities here
val entity = this.createCharacterDialog!!.createdEntity
if (entity != null) {
party.addPlayer(entity)
party.selectPlayer(entity)
EuropaGame.game.startGame(gameName, world, party)
}
}
private fun loadGame() {
val saveFile = FileLocations.SAVE_DIRECTORY.resolve(this.loadGameDialog!!.gameToLoad + "." + SaveGame.SAVE_EXTENSION)
if (!Files.exists(saveFile)) {
return
}
try {
Files.newBufferedReader(saveFile).use { reader ->
val json = Json()
val value = JsonReader().parse(reader)
val save = json.fromJson(javaClass<SaveGame>(), value.toString())
EuropaGame.game.startGame(save)
}
} catch (ex: IOException) {
}
}
private fun showDialog(dialog: Dialog) {
dialog.show(this.stage).setSize(this.size.width.toFloat(), this.size.height.toFloat())
}
companion object {
// Constants
public val MAIN_MENU_SKIN_DIRECTORY: Path = FileLocations.SKINS_DIRECTORY.resolve("main_menu")
public val TITLE_FANCY_FONT: String = "Diploma56-bold.fnt"
public val TITLE_FONT: String = "MagicMedieval48-bold.fnt"
public val BUTTON_FONT: String = "MagicMedieval40.fnt"
public val LIST_FONT: String = "MagicMedieval32.fnt"
public val TEXT_FIELD_FONT: String = "MagicMedieval32.fnt"
public val INFO_LABEL_FONT: String = "MagicMedieval24.fnt"
public val DEFAULT_KEY: String = "default"
public val FANCY_KEY: String = "fancy"
public val INFO_STYLE_KEY: String = "info"
public val TAB_STYLE_KEY: String = "tab-style"
public val POPUP_DIALOG_STYLE_KEY: String = "popup-dialog-style"
public val BACKGROUND_FILE_NAME: String = FileLocations.UI_IMAGES_DIRECTORY.resolve("main_menu_background.png").toString()
public val ATLAS_KEY: String = "main_menu.atlas"
public val SOLID_TEXTURE_KEY: String = "solid-texture"
public val DIALOG_BACKGROUND_KEY: String = "dialog-border"
public val POPUP_BACKGROUND_KEY: String = "popup-border"
public val TITLE_BACKGROUND_KEY: String = "title-border"
public val BUTTON_BACKGROUND_KEY: String = "button-background"
public val BUTTON_DOWN_KEY: String = "button-background-down"
public val SLIDER_BACKGROUND_KEY: String = "slider-background-main_menu"
public val LIST_BACKGROUND_KEY: String = "list-background"
public val LIST_SELECTION_KEY: String = "list-selection"
public val SLIDER_KNOB_KEY: String = "slider-knob-main_menu"
public val TITLE_FONT_KEY: String = "title-font"
public val TITLE_FANCY_FONT_KEY: String = "title-font-fancy"
public val BUTTON_FONT_KEY: String = "button-font"
public val TEXT_FIELD_FONT_KEY: String = "text-field-font"
public val LIST_FONT_KEY: String = "list-font"
public val INFO_LABEL_FONT_KEY: String = "info-label-font"
public val SCROLL_BAR_VERTICAL_KEY: String = "scroll-bar-vertical"
public val SCROLL_BAR_VERTICAL_KNOB_KEY: String = "scroll-bar-vertical-knob"
public val DROP_DOWN_LIST_BACKGROUND: String = "drop-down-list-background"
public val CREDITS_BACKGROUND_KEY: String = "credits-background"
public val TAB_BUTTON_BACKGROUND_KEY: String = "tab-button-background"
public val TAB_BUTTON_SELECTED_KEY: String = "tab-button-background-selected"
public val NUMBER_SELECTOR_INCREASE_KEY: String = "number-increase"
public val NUMBER_SELECTOR_DECREASE_KEY: String = "number-decrease"
public var mainMenuSkin: Skin? = null
public val COMPONENT_SPACING: Int = 4
public val TITLE_BUTTON_WIDTH: Int = 250
public val DIALOG_BUTTON_WIDTH: Int = 190
public val TABLE_PADDING: Int = 14
public val LIST_WRAPPER_PADDING: Int = 20
public val DIALOG_WIDTH: Int = 850
public val BACKGROUND_COLOR: Color = Color(Color.WHITE)
public val SELECTION_COLOR: Color = Color(0.0f, 0.0f, 0.0f, 0.2f)
public val TRANSPARENT: Color = Color(1f, 1f, 1f, 0f)
// Static Methods
public fun createMainMenuSkin(): Skin {
if (mainMenuSkin == null) {
buildMainMenuSkin()
}
return mainMenuSkin!!
}
private fun buildMainMenuSkin() {
val skin = Skin()
// Fonts
skin.add(BUTTON_FONT_KEY, EuropaGame.game.assetManager!!.get<Any>(FileLocations.FONTS_DIRECTORY.resolve(BUTTON_FONT).toString()))
skin.add(TITLE_FANCY_FONT_KEY, EuropaGame.game.assetManager!!.get<Any>(FileLocations.FONTS_DIRECTORY.resolve(TITLE_FANCY_FONT).toString()))
skin.add(TITLE_FONT_KEY, EuropaGame.game.assetManager!!.get<Any>(FileLocations.FONTS_DIRECTORY.resolve(TITLE_FONT).toString()))
skin.add(LIST_FONT_KEY, EuropaGame.game.assetManager!!.get<Any>(FileLocations.FONTS_DIRECTORY.resolve(LIST_FONT).toString()))
skin.add(TEXT_FIELD_FONT_KEY, EuropaGame.game.assetManager!!.get<Any>(FileLocations.FONTS_DIRECTORY.resolve(TEXT_FIELD_FONT).toString()))
skin.add(INFO_LABEL_FONT_KEY, EuropaGame.game.assetManager!!.get<Any>(FileLocations.FONTS_DIRECTORY.resolve(INFO_LABEL_FONT).toString()))
// Set the background texture
val pixmap = Pixmap(1, 1, Pixmap.Format.RGB888)
pixmap.setColor(Color.WHITE)
pixmap.fill()
skin.add(SOLID_TEXTURE_KEY, Texture(pixmap))
val transparentDrawable = skin.newDrawable(SOLID_TEXTURE_KEY, TRANSPARENT)
// Get values from the atlas
skin.addRegions(EuropaGame.game.assetManager!!.get(MAIN_MENU_SKIN_DIRECTORY.resolve(ATLAS_KEY).toString(), javaClass<TextureAtlas>()))
// Colors
val textButtonFontColor = Color(0.85f, 0.85f, 0.85f, 1.0f)
// Set images
val textButtonBackground = TextureRegionDrawable(skin.get(BUTTON_BACKGROUND_KEY, javaClass<TextureRegion>()))
textButtonBackground.setLeftWidth(32f)
textButtonBackground.setRightWidth(32f)
textButtonBackground.setTopHeight(5f)
textButtonBackground.setBottomHeight(5f)
skin.add(BUTTON_BACKGROUND_KEY, textButtonBackground)
val textButtonBackgroundDown = TextureRegionDrawable(skin.get(BUTTON_DOWN_KEY, javaClass<TextureRegion>()))
textButtonBackgroundDown.setLeftWidth(32f)
textButtonBackgroundDown.setRightWidth(32f)
textButtonBackgroundDown.setTopHeight(5f)
textButtonBackgroundDown.setBottomHeight(5f)
skin.add(BUTTON_DOWN_KEY, textButtonBackgroundDown)
val listSelection = TextureRegionDrawable(skin.get(LIST_SELECTION_KEY, javaClass<TextureRegion>()))
listSelection.setLeftWidth(7f)
listSelection.setRightWidth(7f)
listSelection.setTopHeight(0f)
listSelection.setBottomHeight(0f)
skin.add(LIST_SELECTION_KEY, listSelection)
val tabButtonBackground = TextureRegionDrawable(skin.get(TAB_BUTTON_BACKGROUND_KEY, javaClass<TextureRegion>()))
tabButtonBackground.setLeftWidth(5f)
tabButtonBackground.setRightWidth(5f)
tabButtonBackground.setTopHeight(0f)
tabButtonBackground.setBottomHeight(0f)
skin.add(TAB_BUTTON_BACKGROUND_KEY, tabButtonBackground)
val tabButtonBackgroundSelected = TextureRegionDrawable(skin.get(TAB_BUTTON_SELECTED_KEY, javaClass<TextureRegion>()))
tabButtonBackgroundSelected.setLeftWidth(5f)
tabButtonBackgroundSelected.setRightWidth(5f)
tabButtonBackgroundSelected.setTopHeight(0f)
tabButtonBackgroundSelected.setBottomHeight(0f)
skin.add(TAB_BUTTON_SELECTED_KEY, tabButtonBackgroundSelected)
val titleBackground = TextureRegionDrawable(skin.get(TITLE_BACKGROUND_KEY, javaClass<TextureRegion>()))
titleBackground.setLeftWidth(10f)
titleBackground.setRightWidth(10f)
titleBackground.setTopHeight(0f)
titleBackground.setBottomHeight(0f)
skin.add(TITLE_BACKGROUND_KEY, titleBackground)
val numberIncreaseDrawable = TextureRegionDrawable(skin.get(NUMBER_SELECTOR_INCREASE_KEY, javaClass<TextureRegion>()))
numberIncreaseDrawable.setLeftWidth(0f)
numberIncreaseDrawable.setRightWidth(0f)
numberIncreaseDrawable.setTopHeight(0f)
numberIncreaseDrawable.setBottomHeight(0f)
skin.add(NUMBER_SELECTOR_INCREASE_KEY, numberIncreaseDrawable)
val numberDecreaseDrawable = TextureRegionDrawable(skin.get(NUMBER_SELECTOR_DECREASE_KEY, javaClass<TextureRegion>()))
numberDecreaseDrawable.setLeftWidth(0f)
numberDecreaseDrawable.setRightWidth(0f)
numberDecreaseDrawable.setTopHeight(0f)
numberDecreaseDrawable.setBottomHeight(0f)
skin.add(NUMBER_SELECTOR_DECREASE_KEY, numberDecreaseDrawable)
skin.add(DIALOG_BACKGROUND_KEY, skin.newDrawable(TextureRegionDrawable(skin.get(DIALOG_BACKGROUND_KEY, javaClass<TextureRegion>())), Color(1.0f, 1.0f, 1.0f, 1.0f)))
skin.add(POPUP_BACKGROUND_KEY, skin.newDrawable(TextureRegionDrawable(skin.get(POPUP_BACKGROUND_KEY, javaClass<TextureRegion>())), Color(1.0f, 1.0f, 1.0f, 1.0f)))
skin.add(LIST_BACKGROUND_KEY, skin.newDrawable(TextureRegionDrawable(skin.get(LIST_BACKGROUND_KEY, javaClass<TextureRegion>())), Color(1.0f, 1.0f, 1.0f, 1.0f)))
skin.add(LIST_SELECTION_KEY, skin.newDrawable(TextureRegionDrawable(skin.get(LIST_SELECTION_KEY, javaClass<TextureRegion>())), Color(1.0f, 1.0f, 1.0f, 1.0f)))
skin.add(CREDITS_BACKGROUND_KEY, skin.newDrawable(TextureRegionDrawable(skin.get(CREDITS_BACKGROUND_KEY, javaClass<TextureRegion>())), Color(1.0f, 1.0f, 1.0f, 1.0f)))
val dropdownListBackground = skin.newDrawable(TextureRegionDrawable(skin.get(DROP_DOWN_LIST_BACKGROUND, javaClass<TextureRegion>())), Color(1f, 1f, 1f, 1f))
dropdownListBackground.setLeftWidth(28f)
dropdownListBackground.setRightWidth(28f)
dropdownListBackground.setTopHeight(0f)
dropdownListBackground.setBottomHeight(0f)
skin.add(DROP_DOWN_LIST_BACKGROUND, dropdownListBackground)
// Create a Label style for the title
val titleStyle = Label.LabelStyle()
titleStyle.background = transparentDrawable
titleStyle.font = skin.getFont(TITLE_FONT_KEY)
titleStyle.fontColor = Color(Color.BLACK)
skin.add(DEFAULT_KEY, titleStyle)
// Fancy Character Label Style
val fancyTitleStyle = Label.LabelStyle()
fancyTitleStyle.background = transparentDrawable
fancyTitleStyle.font = skin.getFont(TITLE_FANCY_FONT_KEY)
fancyTitleStyle.fontColor = Color(Color.BLACK)
skin.add(FANCY_KEY, fancyTitleStyle)
// Create a Label style for dialogs
val infoStyle = LabelStyle()
infoStyle.background = transparentDrawable
infoStyle.font = skin.getFont(INFO_LABEL_FONT_KEY)
infoStyle.fontColor = Color(Color.BLACK)
skin.add(INFO_STYLE_KEY, infoStyle)
// Default Button Style
val textButtonStyle = TextButton.TextButtonStyle()
textButtonStyle.up = textButtonBackground
textButtonStyle.down = textButtonBackgroundDown
textButtonStyle.checked = textButtonBackground
textButtonStyle.over = textButtonBackgroundDown
textButtonStyle.disabled = textButtonBackground
textButtonStyle.font = skin.getFont(BUTTON_FONT_KEY)
textButtonStyle.fontColor = textButtonFontColor
textButtonStyle.disabledFontColor = Color(0.3f, 0.3f, 0.3f, 1.0f)
// textButtonStyle.pressedOffsetX = 2f;
// textButtonStyle.pressedOffsetY = -3f;
skin.add(DEFAULT_KEY, textButtonStyle)
// Tab Button Style
val tabButtonStyle = TextButtonStyle()
tabButtonStyle.up = tabButtonBackground
tabButtonStyle.down = tabButtonBackground
tabButtonStyle.checked = tabButtonBackgroundSelected
tabButtonStyle.over = tabButtonBackground
tabButtonStyle.disabled = tabButtonBackground
tabButtonStyle.font = skin.getFont(BUTTON_FONT_KEY)
tabButtonStyle.fontColor = textButtonFontColor
tabButtonStyle.overFontColor = textButtonFontColor
tabButtonStyle.disabledFontColor = Color(Color.GRAY)
skin.add(TAB_STYLE_KEY, tabButtonStyle)
// Create a TextField style
val textFieldStyle = TextFieldStyle()
textFieldStyle.background = skin.newDrawable(SOLID_TEXTURE_KEY, Color(0f, 0f, 0f, 0.1f))
textFieldStyle.selection = skin.newDrawable(SOLID_TEXTURE_KEY, Color(0f, 0f, 1f, 0.3f))
textFieldStyle.cursor = skin.newDrawable(SOLID_TEXTURE_KEY, Color.BLACK)
textFieldStyle.font = skin.getFont(TEXT_FIELD_FONT_KEY)
textFieldStyle.fontColor = Color.BLACK
skin.add(DEFAULT_KEY, textFieldStyle)
// Create a List style
val listStyle = ListStyle()
listStyle.font = skin.getFont(LIST_FONT_KEY)
listStyle.fontColorSelected = Color.BLACK
listStyle.fontColorUnselected = Color.BLACK
listStyle.selection = listSelection
listStyle.background = transparentDrawable
skin.add(DEFAULT_KEY, listStyle)
// Create a Scroll Pane Style
val scrollPaneStyle = ScrollPaneStyle()
scrollPaneStyle.background = transparentDrawable
// scrollPaneStyle.vScroll = skin.newDrawable(MainMenuScreen.SCROLL_BAR_VERTICAL_KEY);
// scrollPaneStyle.vScrollKnob = skin.newDrawable(MainMenuScreen.SCROLL_BAR_VERTICAL_KNOB_KEY);
skin.add(DEFAULT_KEY, scrollPaneStyle)
// Create a Dialog Style
val dialogStyle = WindowStyle()
dialogStyle.background = SpriteDrawable(Sprite(EuropaGame.game.assetManager!!.get(BACKGROUND_FILE_NAME, javaClass<Texture>())))
dialogStyle.titleFont = skin.getFont(TITLE_FONT_KEY)
dialogStyle.titleFontColor = Color(Color.BLACK)
skin.add(DEFAULT_KEY, dialogStyle)
// Popup Dialog Style
val popupStyle = WindowStyle()
popupStyle.titleFont = skin.getFont(TITLE_FONT_KEY)
popupStyle.titleFontColor = Color(Color.BLACK)
skin.add(POPUP_DIALOG_STYLE_KEY, popupStyle)
// Create a Slider Skin
val sliderStyle = SliderStyle()
sliderStyle.background = TextureRegionDrawable(skin.get(SLIDER_BACKGROUND_KEY, javaClass<TextureRegion>()))
sliderStyle.knob = TextureRegionDrawable(skin.get(SLIDER_KNOB_KEY, javaClass<TextureRegion>()))
skin.add(DEFAULT_KEY, sliderStyle)
// Create a Drop Down Menu Skin
val selectBoxStyle = SelectBoxStyle()
selectBoxStyle.background = textButtonBackground
selectBoxStyle.backgroundOpen = textButtonBackgroundDown
selectBoxStyle.backgroundOver = textButtonBackgroundDown
selectBoxStyle.scrollStyle = scrollPaneStyle
selectBoxStyle.font = skin.getFont(TEXT_FIELD_FONT_KEY)
selectBoxStyle.fontColor = textButtonFontColor
val selectBoxListStyle = ListStyle()
selectBoxListStyle.font = skin.getFont(LIST_FONT_KEY)
selectBoxListStyle.fontColorSelected = textButtonFontColor
selectBoxListStyle.fontColorUnselected = textButtonFontColor
selectBoxListStyle.selection = skin.newDrawable(SOLID_TEXTURE_KEY, SELECTION_COLOR)
selectBoxListStyle.background = dropdownListBackground
selectBoxStyle.listStyle = selectBoxListStyle
skin.add(DEFAULT_KEY, selectBoxStyle)
// NumberSelectorStyle
val numberStyle = NumberSelectorStyle()
numberStyle.decrease = numberDecreaseDrawable
numberStyle.increase = numberIncreaseDrawable
numberStyle.minimumNumberSize = 50
numberStyle.numberLabelStyle = infoStyle
numberStyle.spacing = COMPONENT_SPACING
skin.add(DEFAULT_KEY, numberStyle)
// AttributeSelectorStyle
val attrStyle = MultipleNumberSelector.MultipleNumberSelectorStyle()
attrStyle.labelStyle = infoStyle
attrStyle.numberSelectorStyle = numberStyle
attrStyle.spacing = COMPONENT_SPACING
skin.add(DEFAULT_KEY, attrStyle)
// TraitPoolSelectorStyle
val tpsStyle = TraitPoolSelectorStyle()
tpsStyle.add = numberIncreaseDrawable
tpsStyle.remove = numberDecreaseDrawable
tpsStyle.spacing = MainMenuScreen.COMPONENT_SPACING
tpsStyle.labelStyle = infoStyle
tpsStyle.scrollPaneStyle = scrollPaneStyle
tpsStyle.background = skin.newDrawable(SOLID_TEXTURE_KEY, Color(0.4f, 0.4f, 0.4f, 0.2f))
tpsStyle.selectedBackground = skin.newDrawable(SOLID_TEXTURE_KEY, SELECTION_COLOR)
skin.add(DEFAULT_KEY, tpsStyle)
mainMenuSkin = skin
}
}
}
| mit | 9187818fc3c3c8b3369e12640057fa69 | 45.324523 | 178 | 0.677941 | 4.307934 | false | false | false | false |
jtransc/jtransc | jtransc-core/src/com/jtransc/graph/Relooper.kt | 2 | 3852 | package com.jtransc.graph
import com.jtransc.ast.*
import java.util.*
class Relooper(val types: AstTypes) {
class Graph
class Node(val types: AstTypes, val body: List<AstStm>) {
var next: Node? = null
val edges = arrayListOf<Edge>()
val possibleNextNodes: List<Node> get() = listOf(next).filterNotNull() + edges.map { it.dst }
override fun toString(): String = dump(types, body.stm()).toString().trim()
}
class Edge(val dst: Node, val cond: AstExpr) {
override fun toString(): String = "IF ($cond) goto $dst;"
}
fun node(body: List<AstStm>): Node = Node(types, body)
fun node(body: AstStm): Node = Node(types, listOf(body))
fun edge(a: Node, b: Node) {
a.next = b
}
fun edge(a: Node, b: Node, cond: AstExpr) {
a.edges += Edge(b, cond)
}
private fun prepare(entry: Node): List<Node> {
val exit = node(listOf())
val explored = LinkedHashSet<Node>()
fun explore(node: Node) {
if (node in explored) return
explored += node
if (node.next != null) {
explore(node.next!!)
} else {
node.next = exit
}
for (edge in node.edges) explore(edge.dst)
}
explore(entry)
explored += exit
return explored.toList()
}
fun render(entry: Node): AstStm? {
val nodes = prepare(entry)
val graph = graphList(nodes.map {
//println("$it -> ${it.possibleNextNodes}")
it to it.possibleNextNodes
})
//println("----------")
//graph.dump()
//println("----------")
if (graph.hasCycles()) {
//noImpl("acyclic!")
//println("cyclic!")
return null
}
val graph2 = graph.tarjanStronglyConnectedComponentsAlgorithm()
val entry2 = graph2.findComponentIndexWith(entry)
//graph2.outputEdges
scgraph = graph2
lookup = scgraph.assertAcyclic().createCommonDescendantLookup()
processedCount = IntArray(scgraph.size)
return renderInternal(entry2, -1).stm()
/*
println(entry)
println(entry2)
*/
//graph.dump()
//println(graph)
// @TODO: strong components
}
lateinit var processedCount: IntArray
lateinit var scgraph: Digraph<StrongComponent<Node>>
lateinit var lookup: AcyclicDigraphLookup<StrongComponent<Node>>
private fun getEdge(from: Node, to: Node): Edge? {
return from.edges.firstOrNull() { it.dst == to }
}
private fun renderInternal(node: Int, endnode: Int): List<AstStm> {
processedCount[node]++
if (processedCount[node] > 4) {
//println("Processed several!")
throw RelooperException("Node processed several times!")
}
if (node == endnode) return listOf()
val stms = arrayListOf<AstStm>()
stms += scgraph.getNode(node).nodes.flatMap { it.body }
//node.scgraph.dump()
val nodeNode = scgraph.getNode(node)
val targets = scgraph.getOut(node)
val nodeSrc = nodeNode.nodes.last()
val nodeDsts = targets.map { scgraph.getNode(it).nodes.first() }
when (targets.size) {
0 -> Unit
1 -> stms += renderInternal(targets.first(), endnode)
2 -> {
val common = lookup.common(targets)
val branches = targets.map { branch -> renderInternal(branch, common) }
val edge = nodeDsts.map { getEdge(nodeSrc, it) }.filterNotNull().first()
val cond = edge.cond
// IF
if (common in targets) {
//val type1 = targets.indexOfFirst { it != common }
//stms += AstStm.IF(cond.not(), AstStmUtils.stms(branches[type1]))
stms += AstStm.IF(cond.not(), branches[0].stm())
}
// IF-ELSE
else {
stms += AstStm.IF_ELSE(cond.not(), branches[0].stm(), branches[1].stm())
}
stms += renderInternal(common, endnode)
}
else -> {
val common = lookup.common(targets)
val branches = targets.map { branch -> renderInternal(branch, common) }
println(branches)
println("COMMON: $common")
//println(outNode.next)
//println(outNode.possibleNextNodes.size)
}
}
return stms
}
}
class RelooperException(message: String) : RuntimeException(message) | apache-2.0 | 791fe1ee4383e23ff4b37a899cd140a2 | 24.85906 | 95 | 0.656542 | 3.162562 | false | false | false | false |
http4k/http4k | http4k-multipart/src/test/kotlin/org/http4k/lens/MultipartFormFieldTest.kt | 1 | 4519 | package org.http4k.lens
import com.natpryce.hamkrest.absent
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import com.natpryce.hamkrest.throws
import org.junit.jupiter.api.Test
class MultipartFormFieldTest {
private val form = MultipartForm(mapOf("hello" to listOf(MultipartFormField("world"), MultipartFormField("world2"))))
@Test
fun `value present`() {
assertThat(MultipartFormField.string().optional("hello")(form), equalTo("world"))
assertThat(MultipartFormField.string().required("hello")(form), equalTo("world"))
assertThat(MultipartFormField.string().map { it.length }.required("hello")(form), equalTo(5))
assertThat(MultipartFormField.string().map { it.length }.optional("hello")(form), equalTo(5))
val expected: List<String?> = listOf("world", "world2")
assertThat(MultipartFormField.string().multi.required("hello")(form), equalTo(expected))
assertThat(MultipartFormField.string().multi.optional("hello")(form), equalTo(expected))
}
@Test
fun `value missing`() {
assertThat(MultipartFormField.optional("world")(form), absent())
val requiredFormField = MultipartFormField.required("world")
assertThat({ requiredFormField(form) }, throws(lensFailureWith<MultipartForm>(Missing(requiredFormField.meta), overallType = Failure.Type.Missing)))
assertThat(MultipartFormField.multi.optional("world")(form), absent())
val optionalMultiFormField = MultipartFormField.multi.required("world")
assertThat({ optionalMultiFormField(form) }, throws(lensFailureWith<MultipartForm>(Missing(optionalMultiFormField.meta), overallType = Failure.Type.Missing)))
}
@Test
fun `value replaced`() {
val single = MultipartFormField.string().required("world")
assertThat(single("value2", single("value1", form)), equalTo(form + ("world" to "value2")))
val multi = MultipartFormField.string().multi.required("world")
assertThat(multi(listOf("value3", "value4"), multi(listOf("value1", "value2"), form)),
equalTo(form + ("world" to "value3") + ("world" to "value4")))
}
@Test
fun `invalid value`() {
val requiredFormField = MultipartFormField.string().map(String::toInt).required("hello")
assertThat({ requiredFormField(form) }, throws(lensFailureWith<MultipartForm>(Invalid(requiredFormField.meta), overallType = Failure.Type.Invalid)))
val optionalFormField = MultipartFormField.string().map(String::toInt).optional("hello")
assertThat({ optionalFormField(form) }, throws(lensFailureWith<MultipartForm>(Invalid(optionalFormField.meta), overallType = Failure.Type.Invalid)))
val requiredMultiFormField = MultipartFormField.string().map(String::toInt).multi.required("hello")
assertThat({ requiredMultiFormField(form) }, throws(lensFailureWith<MultipartForm>(Invalid(requiredMultiFormField.meta), overallType = Failure.Type.Invalid)))
val optionalMultiFormField = MultipartFormField.string().map(String::toInt).multi.optional("hello")
assertThat({ optionalMultiFormField(form) }, throws(lensFailureWith<MultipartForm>(Invalid(optionalMultiFormField.meta), overallType = Failure.Type.Invalid)))
}
@Test
fun `sets value on form`() {
val formField = MultipartFormField.string().required("bob")
val withFormField = formField("hello", form)
assertThat(formField(withFormField), equalTo("hello"))
}
@Test
fun `can create a custom type and get and set on request`() {
val custom = MultipartFormField.string().map(::MyCustomType, MyCustomType::value).required("bob")
val instance = MyCustomType("hello world!")
val formWithField = custom(instance, MultipartForm())
assertThat(formWithField.fields["bob"], equalTo(listOf(MultipartFormField("hello world!"))))
assertThat(custom(formWithField), equalTo(MyCustomType("hello world!")))
}
@Test
fun `toString is ok`() {
assertThat(MultipartFormField.string().required("hello").toString(), equalTo("Required form 'hello'"))
assertThat(MultipartFormField.string().optional("hello").toString(), equalTo("Optional form 'hello'"))
assertThat(MultipartFormField.string().multi.required("hello").toString(), equalTo("Required form 'hello'"))
assertThat(MultipartFormField.string().multi.optional("hello").toString(), equalTo("Optional form 'hello'"))
}
}
| apache-2.0 | a80c450aaa508779e48d006a7f876d92 | 51.546512 | 166 | 0.70613 | 4.56004 | false | true | false | false |
http4k/http4k | http4k-multipart/src/test/kotlin/org/http4k/multipart/StreamingMultipartFormHappyTests.kt | 1 | 14977 | package org.http4k.multipart
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.fail
import java.io.FileInputStream
import java.io.InputStream
import java.nio.charset.Charset
import java.nio.charset.StandardCharsets
class StreamingMultipartFormHappyTests {
@Test
fun uploadEmptyContents() {
val boundary = "-----1234"
val form = getMultipartFormParts(boundary, MultipartFormBuilder(boundary).stream())
assertThereAreNoMoreParts(form)
}
@Test
fun uploadEmptyFile() {
val boundary = "-----2345"
val form = getMultipartFormParts(boundary, MultipartFormBuilder(boundary)
.file("aFile", "", "doesnt/matter", "".byteInputStream(), emptyList()).stream())
assertFilePart(form, "aFile", "", "doesnt/matter", "")
assertThereAreNoMoreParts(form)
}
@Test
fun hasNextIsIdempotent() {
val boundary = "-----2345"
val form = getMultipartFormParts(boundary, MultipartFormBuilder(boundary)
.file("aFile", "", "application/octet-stream", "".byteInputStream(), emptyList())
.file("anotherFile", "", "application/octet-stream", "".byteInputStream(), emptyList()).stream())
assertThereAreMoreParts(form)
assertThereAreMoreParts(form)
form.next()
assertThereAreMoreParts(form)
assertThereAreMoreParts(form)
form.next()
assertThereAreNoMoreParts(form)
assertThereAreNoMoreParts(form)
}
@Test
fun uploadEmptyField() {
val boundary = "-----3456"
val form = getMultipartFormParts(boundary, MultipartFormBuilder(boundary)
.field("aField", "", emptyList()).stream())
assertFieldPart(form, "aField", "")
assertThereAreNoMoreParts(form)
}
@Test
fun uploadSmallFile() {
val boundary = "-----2345"
val form = getMultipartFormParts(boundary, MultipartFormBuilder(boundary)
.file("aFile", "file.name", "application/octet-stream", "File contents here".byteInputStream(), emptyList()).stream())
assertFilePart(form, "aFile", "file.name", "application/octet-stream", "File contents here")
assertThereAreNoMoreParts(form)
}
@Test
fun uploadFileWithLowercaseContentDisposition() {
val boundary = "-----2345"
val form = getMultipartFormParts(boundary, MultipartFormBuilder(boundary)
.part("File contents here".byteInputStream(),
listOf(
"content-disposition" to "form-data; name=\"aFile\"; filename=\"file.name\"",
"Content-Type" to "application/octet-stream")
)
.stream())
assertFilePart(form, "aFile", "file.name", "application/octet-stream", "File contents here")
assertThereAreNoMoreParts(form)
}
@Test
fun uploadSmallFileAsAttachment() {
val boundary = "-----4567"
val form = getMultipartFormParts(boundary, MultipartFormBuilder(boundary)
.file("beforeFile", "before.txt", "application/json", "[]".byteInputStream(), emptyList())
.startMultipart("multipartFieldName", "7890")
.attachment("during.txt", "plain/text", "Attachment contents here", emptyList())
.attachment("during2.txt", "plain/text", "More text here", emptyList())
.endMultipart()
.file("afterFile", "after.txt", "application/json", "[]".byteInputStream(), emptyList())
.stream())
assertFilePart(form, "beforeFile", "before.txt", "application/json", "[]")
assertFilePart(form, "multipartFieldName", "during.txt", "plain/text", "Attachment contents here")
assertFilePart(form, "multipartFieldName", "during2.txt", "plain/text", "More text here")
assertFilePart(form, "afterFile", "after.txt", "application/json", "[]")
assertThereAreNoMoreParts(form)
}
@Test
fun uploadSmallField() {
val boundary = "-----3456"
val form = getMultipartFormParts(boundary, MultipartFormBuilder(boundary)
.field("aField", "Here is the value of the field\n", emptyList()).stream())
assertFieldPart(form, "aField", "Here is the value of the field\n")
assertThereAreNoMoreParts(form)
}
@Test
fun uploadMultipleFilesAndFields() {
val boundary = "-----1234"
val form = getMultipartFormParts(boundary,
MultipartFormBuilder(boundary)
.file("file", "foo.tab", "text/whatever", "This is the content of the file\n".byteInputStream(), emptyList())
.field("field", "fieldValue" + CR_LF + "with cr lf", emptyList())
.field("multi", "value1", emptyList())
.file("anotherFile", "BAR.tab", "text/something", "This is another file\n".byteInputStream(), emptyList())
.field("multi", "value2", emptyList())
.stream())
assertFilePart(form, "file", "foo.tab", "text/whatever", "This is the content of the file\n")
assertFieldPart(form, "field", "fieldValue" + CR_LF + "with cr lf")
assertFieldPart(form, "multi", "value1")
assertFilePart(form, "anotherFile", "BAR.tab", "text/something", "This is another file\n")
assertFieldPart(form, "multi", "value2")
assertThereAreNoMoreParts(form)
}
@Test
fun uploadFieldsWithMultilineHeaders() {
val boundary = "-----1234"
val form = getMultipartFormParts(boundary,
MultipartFormBuilder(boundary)
.part("Content-Disposition: form-data; \r\n" +
"\tname=\"field\"\r\n" +
"\r\n" +
"fieldValue", emptyList())
.part("Content-Disposition: form-data;\r\n" +
" name=\"multi\"\r\n" +
"\r\n" +
"value1", emptyList())
.field("multi", "value2", emptyList())
.stream())
assertFieldPart(form, "field", "fieldValue")
assertFieldPart(form, "multi", "value1")
assertFieldPart(form, "multi", "value2")
assertThereAreNoMoreParts(form)
}
@Test
fun partsCanHaveLotsOfHeaders() {
val boundary = "-----1234"
val form = getMultipartFormParts(boundary,
MultipartFormBuilder(boundary)
.part("This is the content of the file\n",
listOf("Content-Disposition" to "form-data; name=\"fileFieldName\"; filename=\"filename.txt\"",
"Content-Type" to "plain/text",
"Some-header" to "some value"))
.part("This is the content of the field\n",
listOf("Content-Disposition" to "form-data; name=\"fieldFieldName\"",
"Another-header" to "some-key=\"some-value\""))
.stream())
val file = assertFilePart(form, "fileFieldName", "filename.txt", "plain/text", "This is the content of the file\n")
val fileHeaders = file.headers
assertThat(fileHeaders.size, equalTo(3))
assertThat(fileHeaders["Content-Disposition"], equalTo("form-data; name=\"fileFieldName\"; filename=\"filename.txt\""))
assertThat(fileHeaders["Content-Type"], equalTo("plain/text"))
assertThat(fileHeaders["Some-header"], equalTo("some value"))
val field = assertFieldPart(form, "fieldFieldName", "This is the content of the field\n")
val fieldHeaders = field.headers
assertThat(fieldHeaders.size, equalTo(2))
assertThat(fieldHeaders["Content-Disposition"], equalTo("form-data; name=\"fieldFieldName\""))
assertThat(fieldHeaders["Another-header"], equalTo("some-key=\"some-value\""))
assertThereAreNoMoreParts(form)
}
@Test
fun closedPartsCannotBeReadFrom() {
val boundary = "-----2345"
val form = getMultipartFormParts(boundary, MultipartFormBuilder(boundary)
.file("aFile", "file.name", "application/octet-stream", "File contents here".byteInputStream(), emptyList()).stream())
val file = form.next()
while (file.inputStream.read() > 0) {
// keep reading.
}
assertThat(file.inputStream.read(), equalTo(-1))
file.inputStream.close()
file.inputStream.close() // can close multiple times
try {
val ignored = file.inputStream.read()
fail("Should have complained that the StreamingPart has been closed $ignored")
} catch (e: AlreadyClosedException) {
// pass
}
}
@Test
fun readingPartsContentsAsStringClosesStream() {
val boundary = "-----2345"
val form = getMultipartFormParts(boundary, MultipartFormBuilder(boundary)
.file("aFile", "file.name", "application/octet-stream", "File contents here".byteInputStream(), emptyList()).stream())
val file = form.next()
file.contentsAsString
try {
val ignored = file.inputStream.read()
fail("Should have complained that the StreamingPart has been closed $ignored")
} catch (e: AlreadyClosedException) {
// pass
}
file.inputStream.close() // can close multiple times
}
@Test
fun gettingNextPartClosesOldPart() {
val boundary = "-----2345"
val form = getMultipartFormParts(boundary, MultipartFormBuilder(boundary)
.file("aFile", "file.name", "application/octet-stream", "File contents here".byteInputStream(), emptyList())
.file("anotherFile", "your.name", "application/octet-stream", "Different file contents here".byteInputStream(), emptyList()).stream())
val file1 = form.next()
val file2 = form.next()
assertThat(file1, !equalTo(file2))
try {
val ignored = file1.inputStream.read()
fail("Should have complained that the StreamingPart has been closed $ignored")
} catch (e: AlreadyClosedException) {
// pass
}
file1.inputStream.close() // can close multiple times
assertThat(file2.contentsAsString, equalTo("Different file contents here"))
}
@Test
fun canLoadComplexRealLifeSafariExample() {
val parts = StreamingMultipartFormParts.parse(
"----WebKitFormBoundary6LmirFeqsyCQRtbj".toByteArray(StandardCharsets.UTF_8),
FileInputStream("examples/safari-example.multipart"),
StandardCharsets.UTF_8
).iterator()
assertFieldPart(parts, "articleType", "obituary")
assertRealLifeFile(parts, "simple7bit.txt", "text/plain")
assertRealLifeFile(parts, "starbucks.jpeg", "image/jpeg")
assertRealLifeFile(parts, "utf8\uD83D\uDCA9.file", "application/octet-stream")
assertRealLifeFile(parts, "utf8\uD83D\uDCA9.txt", "text/plain")
}
@Test
fun canLoadComplexRealLifeChromeExample() {
val parts = StreamingMultipartFormParts.parse(
"----WebKitFormBoundaryft3FGhOMTYoOkCCc".toByteArray(StandardCharsets.UTF_8),
FileInputStream("examples/chrome-example.multipart"),
StandardCharsets.UTF_8
).iterator()
assertFieldPart(parts, "articleType", "obituary")
assertRealLifeFile(parts, "simple7bit.txt", "text/plain")
assertRealLifeFile(parts, "starbucks.jpeg", "image/jpeg")
assertRealLifeFile(parts, "utf8\uD83D\uDCA9.file", "application/octet-stream")
assertRealLifeFile(parts, "utf8\uD83D\uDCA9.txt", "text/plain")
}
}
const val CR_LF = "\r\n"
internal fun assertRealLifeFile(parts: Iterator<StreamingPart>, fileName: String, contentType: String) {
val file = parts.next()
assertThat("field name", file.fieldName, equalTo("uploadManuscript"))
assertThat("file name", file.fileName, equalTo(fileName))
assertThat("content type", file.contentType, equalTo(contentType))
assertPartIsNotField(file)
compareStreamToFile(file)
}
internal fun compareStreamToFile(file: StreamingPart) {
val formFile = file.inputStream
compareStreamToFile(formFile, file.fileName)
}
fun compareStreamToFile(actualSream: InputStream, fileName: String?) {
val original = FileInputStream("examples/" + fileName!!)
compareOneStreamToAnother(actualSream, original)
}
fun compareOneStreamToAnother(actualStream: InputStream, expectedStream: InputStream) {
var index = 0
while (true) {
val actual = actualStream.read()
val expected = expectedStream.read()
assertThat("index $index", actual, equalTo(expected))
index++
if (actual < 0) {
break
}
}
}
internal fun getMultipartFormParts(boundary: String, multipartFormContents: InputStream): Iterator<StreamingPart> =
getMultipartFormParts(boundary.toByteArray(StandardCharsets.UTF_8), multipartFormContents, StandardCharsets.UTF_8)
internal fun getMultipartFormParts(boundary: ByteArray, multipartFormContents: InputStream, encoding: Charset): Iterator<StreamingPart> =
StreamingMultipartFormParts.parse(boundary, multipartFormContents, encoding).iterator()
internal fun assertFilePart(form: Iterator<StreamingPart>, fieldName: String, fileName: String, contentType: String, contents: String, encoding: Charset = StandardCharsets.UTF_8): StreamingPart {
assertThereAreMoreParts(form)
val file = form.next()
assertThat("file name", file.fileName, equalTo(fileName))
assertThat("content type", file.contentType, equalTo(contentType))
assertPartIsNotField(file)
assertPart(fieldName, contents, file, encoding)
return file
}
internal fun assertFieldPart(form: Iterator<StreamingPart>, fieldName: String, fieldValue: String, encoding: Charset = StandardCharsets.UTF_8): StreamingPart {
assertThereAreMoreParts(form)
val field = form.next()
assertPartIsFormField(field)
assertPart(fieldName, fieldValue, field, encoding)
return field
}
internal fun assertPart(fieldName: String, fieldValue: String, StreamingPart: StreamingPart, encoding: Charset) {
assertThat("field name", StreamingPart.fieldName, equalTo(fieldName))
assertThat("contents", StreamingPart.inputStream.reader(encoding).use { it.readText() }, equalTo(fieldValue))
}
internal fun assertThereAreNoMoreParts(form: Iterator<StreamingPart>) {
assertThat("Too many parts", form.hasNext(), equalTo(false))
}
internal fun assertThereAreMoreParts(form: Iterator<StreamingPart>) {
assertThat("Not enough parts", form.hasNext(), equalTo(true))
}
internal fun assertPartIsFormField(field: StreamingPart) {
assertThat("the StreamingPart is a form field", field.isFormField, equalTo(true))
}
internal fun assertPartIsNotField(file: StreamingPart) {
assertThat("the StreamingPart is not a form field", file.isFormField, equalTo(false))
}
| apache-2.0 | 8a2a021dbeaaea3912441a37781c65da | 38.832447 | 195 | 0.647259 | 4.372847 | false | false | false | false |
openMF/android-client | mifosng-android/src/main/java/com/mifos/mifosxdroid/online/grouploanaccount/GroupLoanAccountPresenter.kt | 1 | 7380 | package com.mifos.mifosxdroid.online.grouploanaccount
import com.mifos.api.DataManager
import com.mifos.mifosxdroid.base.BasePresenter
import com.mifos.objects.accounts.loan.Loans
import com.mifos.objects.organisation.LoanProducts
import com.mifos.objects.templates.loans.*
import com.mifos.services.data.GroupLoanPayload
import rx.Observable
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 08/06/16.
*/
class GroupLoanAccountPresenter @Inject constructor(private val mDataManager: DataManager) : BasePresenter<GroupLoanAccountMvpView?>() {
private val mSubscriptions: CompositeSubscription
override fun attachView(mvpView: GroupLoanAccountMvpView?) {
super.attachView(mvpView)
}
override fun detachView() {
super.detachView()
mSubscriptions.clear()
}
fun loadAllLoans() {
checkViewAttached()
mvpView!!.showProgressbar(true)
mSubscriptions.add(mDataManager.allLoans
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(object : Subscriber<List<LoanProducts?>?>() {
override fun onCompleted() {
mvpView!!.showProgressbar(false)
}
override fun onError(e: Throwable) {
mvpView!!.showProgressbar(false)
mvpView!!.showFetchingError("Failed to fetch Loans")
}
override fun onNext(productLoans: List<LoanProducts?>?) {
mvpView!!.showProgressbar(false)
mvpView!!.showAllLoans(productLoans)
}
})
)
}
fun loadGroupLoansAccountTemplate(groupId: Int, productId: Int) {
checkViewAttached()
mvpView!!.showProgressbar(true)
mSubscriptions.add(mDataManager.getGroupLoansAccountTemplate(groupId, productId)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(object : Subscriber<GroupLoanTemplate?>() {
override fun onCompleted() {
mvpView!!.showProgressbar(false)
}
override fun onError(e: Throwable) {
mvpView!!.showProgressbar(false)
mvpView!!.showFetchingError("Failed to load GroupLoan")
}
override fun onNext(groupLoanTemplate: GroupLoanTemplate?) {
mvpView!!.showProgressbar(false)
mvpView!!.showGroupLoanTemplate(
groupLoanTemplate)
}
})
)
}
fun createGroupLoanAccount(loansPayload: GroupLoanPayload?) {
checkViewAttached()
mvpView!!.showProgressbar(true)
mSubscriptions.add(mDataManager.createGroupLoansAccount(loansPayload)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(object : Subscriber<Loans?>() {
override fun onCompleted() {
mvpView!!.showProgressbar(false)
}
override fun onError(e: Throwable) {
mvpView!!.showProgressbar(false)
mvpView!!.showFetchingError("Try Again")
}
override fun onNext(loans: Loans?) {
mvpView!!.showProgressbar(false)
mvpView!!.showGroupLoansAccountCreatedSuccessfully(loans)
}
})
)
}
fun filterAmortizations(amortizationTypeOptions: List<AmortizationTypeOptions>?): List<String> {
val amortizationNameList = ArrayList<String>()
Observable.from(amortizationTypeOptions)
.subscribe { amortizationTypeOptions -> amortizationNameList.add(amortizationTypeOptions.value) }
return amortizationNameList
}
fun filterInterestCalculationPeriods(interestCalculationPeriodType: List<InterestCalculationPeriodType>?): List<String> {
val interestCalculationPeriodNameList = ArrayList<String>()
Observable.from(interestCalculationPeriodType)
.subscribe { interestCalculationPeriodType ->
interestCalculationPeriodNameList.add(
interestCalculationPeriodType.value)
}
return interestCalculationPeriodNameList
}
fun filterTransactionProcessingStrategies(transactionProcessingStrategyOptions: List<TransactionProcessingStrategyOptions>?): List<String> {
val transactionProcessingStrategyNameList = ArrayList<String>()
Observable.from(transactionProcessingStrategyOptions)
.subscribe { transactionProcessingStrategyOptions ->
transactionProcessingStrategyNameList.add(
transactionProcessingStrategyOptions.name)
}
return transactionProcessingStrategyNameList
}
fun filterLoanProducts(loanProducts: List<LoanProducts>?): List<String> {
val loanProductsNameList = ArrayList<String>()
Observable.from(loanProducts)
.subscribe { loanProducts -> loanProductsNameList.add(loanProducts.name) }
return loanProductsNameList
}
fun filterTermFrequencyTypes(termFrequencyTypeOptions: List<TermFrequencyTypeOptions>?): List<String> {
val termFrequencyNameList = ArrayList<String>()
Observable.from(termFrequencyTypeOptions)
.subscribe { termFrequencyTypeOptions -> termFrequencyNameList.add(termFrequencyTypeOptions.value) }
return termFrequencyNameList
}
fun filterLoanPurposeTypes(loanPurposeOptions: List<LoanPurposeOptions>?): List<String> {
val loanPurposeNameList = ArrayList<String>()
Observable.from(loanPurposeOptions)
.subscribe { loanPurposeOptions -> loanPurposeNameList.add(loanPurposeOptions.name) }
return loanPurposeNameList
}
fun filterInterestTypeOptions(interestTypeOptions: List<InterestTypeOptions>?): List<String> {
val interestTypeNameList = ArrayList<String>()
Observable.from(interestTypeOptions)
.subscribe { interestTypeOptions -> interestTypeNameList.add(interestTypeOptions.value) }
return interestTypeNameList
}
fun filterLoanOfficers(loanOfficerOptions: List<LoanOfficerOptions>?): List<String> {
val loanOfficerNameList = ArrayList<String>()
Observable.from(loanOfficerOptions)
.subscribe { loanOfficerOptions -> loanOfficerNameList.add(loanOfficerOptions.displayName) }
return loanOfficerNameList
}
fun filterFunds(fundOptions: List<FundOptions>?): List<String> {
val fundNameList = ArrayList<String>()
Observable.from(fundOptions)
.subscribe { fundOptions -> fundNameList.add(fundOptions.name) }
return fundNameList
}
init {
mSubscriptions = CompositeSubscription()
}
} | mpl-2.0 | e4b3b7130125f2b9ed9de52f81a7fb64 | 40.9375 | 144 | 0.637669 | 5.507463 | false | false | false | false |
msebire/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/GithubPullRequestsListComponent.kt | 1 | 8626 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest.ui
import com.intellij.codeInsight.AutoPopupController
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.ActionGroup
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.DataProvider
import com.intellij.openapi.ide.CopyPasteManager
import com.intellij.openapi.progress.util.ProgressWindow
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.ui.*
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.components.BorderLayoutPanel
import com.intellij.vcs.log.ui.frame.ProgressStripe
import org.jetbrains.annotations.CalledInAwt
import org.jetbrains.plugins.github.api.data.GithubSearchedIssue
import org.jetbrains.plugins.github.exceptions.GithubStatusCodeException
import org.jetbrains.plugins.github.pullrequest.action.GithubPullRequestKeys
import org.jetbrains.plugins.github.pullrequest.avatars.CachingGithubAvatarIconsProvider
import org.jetbrains.plugins.github.pullrequest.data.GithubPullRequestsLoader
import org.jetbrains.plugins.github.pullrequest.search.GithubPullRequestSearchComponent
import org.jetbrains.plugins.github.pullrequest.search.GithubPullRequestSearchModel
import org.jetbrains.plugins.github.util.GithubAsyncUtil
import org.jetbrains.plugins.github.util.ProgressStripeProgressIndicator
import org.jetbrains.plugins.github.util.handleOnEdt
import java.awt.Component
import javax.swing.JScrollBar
import javax.swing.ScrollPaneConstants
import javax.swing.event.ListSelectionEvent
internal class GithubPullRequestsListComponent(project: Project,
copyPasteManager: CopyPasteManager,
actionManager: ActionManager,
autoPopupController: AutoPopupController,
private val loader: GithubPullRequestsLoader,
avatarIconsProviderFactory: CachingGithubAvatarIconsProvider.Factory)
: BorderLayoutPanel(), Disposable, DataProvider {
val selectionModel = GithubPullRequestsListSelectionModel()
private val listModel = CollectionListModel<GithubSearchedIssue>()
private val list = GithubPullRequestsList(copyPasteManager, avatarIconsProviderFactory, listModel)
private val scrollPane = ScrollPaneFactory.createScrollPane(list,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER).apply {
border = JBUI.Borders.empty()
verticalScrollBar.model.addChangeListener { potentiallyLoadMore() }
}
private var loadOnScrollThreshold = true
private var isDisposed = false
private val errorPanel = HtmlErrorPanel()
private val progressStripe = ProgressStripe(scrollPane, this, ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS)
private var progressIndicator = ProgressStripeProgressIndicator(progressStripe, true)
private val searchModel = GithubPullRequestSearchModel()
private val search = GithubPullRequestSearchComponent(project, autoPopupController, searchModel).apply {
border = IdeBorderFactory.createBorder(SideBorder.BOTTOM)
}
init {
searchModel.addListener(object : GithubPullRequestSearchModel.StateListener {
override fun queryChanged() {
loader.setSearchQuery(searchModel.query)
refresh()
}
}, this)
list.selectionModel.addListSelectionListener { e: ListSelectionEvent ->
if (!e.valueIsAdjusting) {
if (list.selectedIndex < 0) selectionModel.current = null
else selectionModel.current = listModel.getElementAt(list.selectedIndex)
}
}
val popupHandler = object : PopupHandler() {
override fun invokePopup(comp: Component, x: Int, y: Int) {
if (ListUtil.isPointOnSelection(list, x, y)) {
val popupMenu = actionManager
.createActionPopupMenu("GithubPullRequestListPopup",
actionManager.getAction("Github.PullRequest.ToolWindow.List.Popup") as ActionGroup)
popupMenu.setTargetComponent(this@GithubPullRequestsListComponent)
popupMenu.component.show(comp, x, y)
}
}
}
list.addMouseListener(popupHandler)
val tableWithError = JBUI.Panels
.simplePanel(progressStripe)
.addToTop(errorPanel)
addToTop(search)
addToCenter(tableWithError)
resetSearch()
Disposer.register(this, list)
}
override fun getData(dataId: String): Any? {
return if (GithubPullRequestKeys.SELECTED_PULL_REQUEST.`is`(dataId)) selectionModel.current else null
}
@CalledInAwt
fun refresh() {
loadOnScrollThreshold = false
list.selectionModel.clearSelection()
listModel.removeAll()
progressIndicator.cancel()
progressIndicator = ProgressStripeProgressIndicator(progressStripe, true)
loader.reset()
loadMore()
}
private fun potentiallyLoadMore() {
if (loadOnScrollThreshold && isScrollAtThreshold(scrollPane.verticalScrollBar)) {
loadMore()
}
}
private fun loadMore() {
if (isDisposed) return
loadOnScrollThreshold = false
errorPanel.setError(null)
list.emptyText.text = "Loading pull requests..."
val indicator = progressIndicator
loader.requestLoadMore(indicator).handleOnEdt { responsePage, error ->
if (indicator.isCanceled) return@handleOnEdt
when {
error != null && !GithubAsyncUtil.isCancellation(error) -> {
loadingErrorOccurred(error)
}
responsePage != null -> {
moreDataLoaded(responsePage.items, responsePage.hasNext)
}
}
}
}
private fun isScrollAtThreshold(verticalScrollBar: JScrollBar): Boolean {
val visibleAmount = verticalScrollBar.visibleAmount
val value = verticalScrollBar.value
val maximum = verticalScrollBar.maximum
if (maximum == 0) return false
val scrollFraction = (visibleAmount + value) / maximum.toFloat()
if (scrollFraction < 0.5) return false
return true
}
private fun moreDataLoaded(data: List<GithubSearchedIssue>, hasNext: Boolean) {
if (searchModel.query.isEmpty()) {
list.emptyText.text = "No pull requests loaded."
}
else {
list.emptyText.text = "No pull requests matching filters."
list.emptyText.appendSecondaryText("Reset Filters", SimpleTextAttributes.LINK_ATTRIBUTES) {
resetSearch()
}
}
loadOnScrollThreshold = hasNext
listModel.add(data)
//otherwise scrollbar will have old values (before data insert)
scrollPane.viewport.validate()
potentiallyLoadMore()
}
private fun resetSearch() {
search.searchText = "state:open"
}
private fun loadingErrorOccurred(error: Throwable) {
loadOnScrollThreshold = false
val prefix = if (list.isEmpty) "Can't load pull requests." else "Can't load full pull requests list."
list.emptyText.clear().appendText(prefix, SimpleTextAttributes.ERROR_ATTRIBUTES)
.appendSecondaryText(getLoadingErrorText(error), SimpleTextAttributes.ERROR_ATTRIBUTES, null)
.appendSecondaryText(" ", SimpleTextAttributes.ERROR_ATTRIBUTES, null)
.appendSecondaryText("Retry", SimpleTextAttributes.LINK_ATTRIBUTES) { refresh() }
if (!list.isEmpty) {
//language=HTML
val errorText = "<html><body>$prefix<br/>${getLoadingErrorText(error, "<br/>")}<a href=''>Retry</a></body></html>"
errorPanel.setError(errorText, linkActivationListener = { refresh() })
}
}
private fun getLoadingErrorText(error: Throwable, newLineSeparator: String = "\n"): String {
if (error is GithubStatusCodeException && error.error != null) {
val githubError = error.error!!
val builder = StringBuilder(githubError.message)
if (githubError.errors.isNotEmpty()) {
builder.append(": ").append(newLineSeparator)
for (e in githubError.errors) {
builder.append(e.message ?: "${e.code} error in ${e.resource} field ${e.field}").append(newLineSeparator)
}
}
return builder.toString()
}
return error.message?.let { addDotIfNeeded(it) } ?: "Unknown loading error."
}
private fun addDotIfNeeded(line: String) = if (line.endsWith('.')) line else "$line."
override fun dispose() {
isDisposed = true
}
} | apache-2.0 | 3d47f0cf02e842962e8eb42121acf5e5 | 40.277512 | 140 | 0.716439 | 5.00058 | false | false | false | false |
Yubyf/QuoteLock | app/src/main/java/com/crossbowffs/quotelock/components/FontListPreferenceDialogFragmentCompat.kt | 1 | 5492 | package com.crossbowffs.quotelock.components
import android.content.Context
import android.content.DialogInterface
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.preference.ListPreference
import com.crossbowffs.quotelock.R
import com.crossbowffs.quotelock.utils.Xlog
import com.crossbowffs.quotelock.utils.className
import com.crossbowffs.quotelock.utils.getFontFromName
/**
* Show font list with specific font styles
* based on [androidx.preference.ListPreferenceDialogFragmentCompat].
*
* @author Yubyf
*/
class FontListPreferenceDialogFragmentCompat : MaterialPreferenceDialogFragmentCompat() {
private var mClickedDialogEntryIndex/* synthetic access */ = 0
private lateinit var mEntries: Array<CharSequence?>
private lateinit var mEntryValues: Array<CharSequence>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState == null) {
check(listPreference.entries != null && listPreference.entryValues != null) {
"ListPreference requires an entries array and an entryValues array."
}
mClickedDialogEntryIndex = listPreference.findIndexOfValue(listPreference.value)
mEntries = listPreference.entries
mEntryValues = listPreference.entryValues
} else {
mClickedDialogEntryIndex = savedInstanceState.getInt(SAVE_STATE_INDEX, 0)
mEntries = savedInstanceState.getCharSequenceArray(SAVE_STATE_ENTRIES) ?: arrayOf()
mEntryValues =
savedInstanceState.getCharSequenceArray(SAVE_STATE_ENTRY_VALUES) ?: arrayOf()
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putInt(SAVE_STATE_INDEX, mClickedDialogEntryIndex)
outState.putCharSequenceArray(SAVE_STATE_ENTRIES, mEntries)
outState.putCharSequenceArray(SAVE_STATE_ENTRY_VALUES, mEntryValues)
}
private val listPreference: ListPreference
get() = preference as ListPreference
override fun onPrepareDialogBuilder(builder: AlertDialog.Builder) {
super.onPrepareDialogBuilder(builder)
//region Modified part
val a = requireContext().obtainStyledAttributes(null, R.styleable.AlertDialog,
R.attr.alertDialogStyle, 0)
val layout =
a.getResourceId(androidx.appcompat.R.styleable.AlertDialog_singleChoiceItemLayout, 0)
a.recycle()
val adapter = FontStyleCheckedItemAdapter(requireContext(), layout,
android.R.id.text1, mEntries, mEntryValues)
builder.setSingleChoiceItems(adapter, mClickedDialogEntryIndex
) { dialog, which ->
mClickedDialogEntryIndex = which
// Clicking on an item simulates the positive button click, and dismisses
// the dialog.
onClick(dialog, DialogInterface.BUTTON_POSITIVE)
dialog.dismiss()
}
//endregion
// The typical interaction for list-based dialogs is to have click-on-an-item dismiss the
// dialog instead of the user having to press 'Ok'.
builder.setPositiveButton(null, null)
}
override fun onDialogClosed(positiveResult: Boolean) {
if (positiveResult && mClickedDialogEntryIndex >= 0) {
val value = mEntryValues[mClickedDialogEntryIndex].toString()
val preference = listPreference
if (preference.callChangeListener(value)) {
preference.value = value
}
}
}
//region Modified part
/**
* Stylize the list item by specific font family.
*/
private class FontStyleCheckedItemAdapter(
context: Context, resource: Int, textViewResourceId: Int,
objects: Array<CharSequence?>, private val values: Array<CharSequence>,
) : ArrayAdapter<CharSequence?>(context, resource, textViewResourceId, objects) {
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val view = super.getView(position, convertView, parent)
if (view is TextView && values.size > position) {
val fontName = values[position] as String
runCatching {
view.typeface = context.getFontFromName(fontName)
}.onFailure {
view.typeface = null
Xlog.e(TAG, "Failed to get font from name: $fontName")
}
}
return view
}
override fun hasStableIds(): Boolean {
return true
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
}
//endregion
companion object {
val TAG = className<FontListPreferenceDialogFragmentCompat>()
private const val SAVE_STATE_INDEX = "ListPreferenceDialogFragment.index"
private const val SAVE_STATE_ENTRIES = "ListPreferenceDialogFragment.entries"
private const val SAVE_STATE_ENTRY_VALUES = "ListPreferenceDialogFragment.entryValues"
fun newInstance(key: String?): FontListPreferenceDialogFragmentCompat =
FontListPreferenceDialogFragmentCompat().apply {
arguments = Bundle(1).apply { putString(ARG_KEY, key) }
}
}
} | mit | f4253e09dc2a23b2794ebb73d8f47d22 | 39.688889 | 97 | 0.676074 | 5.240458 | false | false | false | false |
yamamotoj/workshop-jb | src/i_introduction/_10_Object_Expressions/ObjectExpressions.kt | 1 | 1163 | package i_introduction._10_Object_Expressions
import java.util.Comparator
import util.TODO
import java.io.File
import java.awt.event.MouseListener
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
fun objectLiteral() {
abstract class Foo {
abstract fun foo()
}
// Anonymous object extending a class
val foo: Foo = object : Foo() {
override fun foo() {
// ...
}
}
// Anonymous object extending an interface
runInANewThread(object : Runnable {
override fun run() {
// ...
}
})
}
fun runInANewThread(runnable: Runnable) = Thread(runnable).start()
fun todoTask10() = TODO(
"""
Task 10.
Add an object expression that extends MouseAdapter and counts the number of mouse clicks
as an argument to the function 'handleMouse()'.
"""
)
fun task10(handleMouse: (MouseListener) -> Unit): Int {
var mouseClicks = 0
val adapter = object : MouseAdapter() {
override fun mouseClicked(e: MouseEvent) {
mouseClicks += e.clickCount
}
}
handleMouse(adapter)
return mouseClicks
} | mit | a845ec8fef21d3a3a04ab045e164ba0e | 22.28 | 96 | 0.626827 | 4.37218 | false | false | false | false |
openhab/openhab.android | mobile/src/main/java/org/openhab/habdroid/ui/activity/ContentController.kt | 1 | 32961 | /*
* Copyright (c) 2010-2022 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.habdroid.ui.activity
import android.content.Context
import android.content.Intent
import android.graphics.PorterDuff
import android.graphics.PorterDuffColorFilter
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewStub
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.AnimRes
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.core.content.ContextCompat
import androidx.core.content.edit
import androidx.core.net.toUri
import androidx.core.os.bundleOf
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.commit
import androidx.fragment.app.commitNow
import java.util.ArrayList
import java.util.HashSet
import java.util.Stack
import org.openhab.habdroid.R
import org.openhab.habdroid.core.OpenHabApplication
import org.openhab.habdroid.core.connection.Connection
import org.openhab.habdroid.core.connection.ConnectionFactory
import org.openhab.habdroid.model.LinkedPage
import org.openhab.habdroid.model.Sitemap
import org.openhab.habdroid.model.WebViewUi
import org.openhab.habdroid.model.Widget
import org.openhab.habdroid.ui.CloudNotificationListFragment
import org.openhab.habdroid.ui.MainActivity
import org.openhab.habdroid.ui.PreferencesActivity
import org.openhab.habdroid.ui.WidgetListFragment
import org.openhab.habdroid.ui.activity.AbstractWebViewFragment.Companion.KEY_IS_STACK_ROOT
import org.openhab.habdroid.ui.activity.AbstractWebViewFragment.Companion.KEY_SUBPAGE
import org.openhab.habdroid.util.CrashReportingHelper
import org.openhab.habdroid.util.HttpClient
import org.openhab.habdroid.util.PrefKeys
import org.openhab.habdroid.util.getHumanReadableErrorMessage
import org.openhab.habdroid.util.getPrefs
import org.openhab.habdroid.util.getWifiManager
import org.openhab.habdroid.util.isDebugModeEnabled
import org.openhab.habdroid.util.openInBrowser
/**
* Controller class for the content area of [MainActivity]
*
* It manages the stack of widget lists shown, and shows error UI if needed.
* The layout of the content area is up to the respective subclasses.
*/
abstract class ContentController protected constructor(private val activity: MainActivity) :
PageConnectionHolderFragment.ParentCallback, AbstractWebViewFragment.ParentCallback {
protected val fm: FragmentManager = activity.supportFragmentManager
private var noConnectionFragment: Fragment? = null
protected var defaultProgressFragment: Fragment
private val connectionFragment: PageConnectionHolderFragment
private var temporaryPage: Fragment? = null
private var currentSitemap: Sitemap? = null
protected var sitemapFragment: WidgetListFragment? = null
protected val pageStack = Stack<Pair<LinkedPage, WidgetListFragment>>()
private val pendingDataLoadUrls = HashSet<String>()
override val isDetailedLoggingEnabled get() = activity.getPrefs().isDebugModeEnabled()
override val serverProperties get() = activity.serverProperties
/**
* Get title describing current UI state
*
* @return Title to show in action bar, or null if none can be determined
*/
val currentTitle get() = when {
noConnectionFragment != null -> null
temporaryPage is CloudNotificationListFragment ->
(temporaryPage as CloudNotificationListFragment).getTitle(activity)
temporaryPage is AbstractWebViewFragment -> (temporaryPage as AbstractWebViewFragment).title
temporaryPage != null -> null
else -> fragmentForTitle?.title
}
protected abstract val fragmentForTitle: WidgetListFragment?
protected val overridingFragment get() = when {
temporaryPage != null -> temporaryPage
noConnectionFragment != null -> noConnectionFragment
else -> null
}
init {
var connectionFragment = fm.findFragmentByTag("connections") as PageConnectionHolderFragment?
if (connectionFragment == null) {
connectionFragment = PageConnectionHolderFragment()
fm.commit {
add(connectionFragment, "connections")
}
}
this.connectionFragment = connectionFragment
defaultProgressFragment = ProgressFragment.newInstance(null, 0)
connectionFragment.setCallback(this)
}
/**
* Saves the controller's instance state
* To be called from the onSaveInstanceState callback of the activity
*
* @param state Bundle to save state into
*/
fun onSaveInstanceState(state: Bundle) {
CrashReportingHelper.d(TAG, "onSaveInstanceState()")
val pages = ArrayList<LinkedPage>()
for ((page, fragment) in pageStack) {
pages.add(page)
if (fragment.isAdded) {
fm.putFragment(state, makeStateKeyForPage(page), fragment)
}
}
state.putParcelable(STATE_KEY_SITEMAP, currentSitemap)
sitemapFragment?.let { page ->
if (page.isAdded) {
fm.putFragment(state, STATE_KEY_SITEMAP_FRAGMENT, page)
}
}
if (defaultProgressFragment.isAdded) {
fm.putFragment(state, STATE_KEY_PROGRESS_FRAGMENT, defaultProgressFragment)
}
state.putParcelableArrayList(STATE_KEY_PAGES, pages)
temporaryPage?.let { page ->
fm.putFragment(state, STATE_KEY_TEMPORARY_PAGE, page)
}
noConnectionFragment?.let { page ->
if (page.isAdded) {
fm.putFragment(state, STATE_KEY_ERROR_FRAGMENT, page)
}
}
}
/**
* Restore instance state previously saved by onSaveInstanceState
* To be called from the onRestoreInstanceState or onCreate callbacks of the activity
*
* @param state Bundle including previously saved state
*/
open fun onRestoreInstanceState(state: Bundle) {
CrashReportingHelper.d(TAG, "onRestoreInstanceState()")
currentSitemap = state.getParcelable(STATE_KEY_SITEMAP)
currentSitemap?.let { sitemap ->
sitemapFragment = fm.getFragment(state, STATE_KEY_SITEMAP_FRAGMENT) as WidgetListFragment?
?: makeSitemapFragment(sitemap)
}
val progressFragment = fm.getFragment(state, STATE_KEY_PROGRESS_FRAGMENT)
if (progressFragment != null) {
defaultProgressFragment = progressFragment
}
pageStack.clear()
state.getParcelableArrayList<LinkedPage>(STATE_KEY_PAGES)?.forEach { page ->
val f = fm.getFragment(state, makeStateKeyForPage(page)) as WidgetListFragment?
pageStack.add(Pair(page, f ?: makePageFragment(page)))
}
temporaryPage = fm.getFragment(state, STATE_KEY_TEMPORARY_PAGE)
(temporaryPage as? AbstractWebViewFragment)?.setCallback(this)
noConnectionFragment = fm.getFragment(state, STATE_KEY_ERROR_FRAGMENT)
updateConnectionState()
}
/**
* Show contents of a sitemap
* Sets up UI to show the sitemap's contents
*
* @param sitemap Sitemap to show
*/
fun openSitemap(sitemap: Sitemap) {
CrashReportingHelper.d(TAG, "openSitemap()", remoteOnly = true)
Log.d(TAG, "Opening sitemap $sitemap (current: $currentSitemap)")
currentSitemap = sitemap
// First clear the old fragment stack to show the progress spinner...
pageStack.clear()
sitemapFragment = null
temporaryPage = null
updateFragmentState(FragmentUpdateReason.PAGE_UPDATE)
// ... and clear remaining page connections ...
updateConnectionState()
// ...then create the new sitemap fragment and trigger data loading.
val newFragment = makeSitemapFragment(sitemap)
sitemapFragment = newFragment
handleNewWidgetFragment(newFragment)
}
/**
* Follow a link in a sitemap page
* Sets up UI to show the contents of the given page
*
* @param page Page link to follow
* @param source Fragment this action was triggered from
*/
open fun openPage(page: LinkedPage, source: WidgetListFragment) {
CrashReportingHelper.d(TAG, "openPage(LinkedPage, WidgetListFragment)", remoteOnly = true)
Log.d(TAG, "Opening page $page")
val f = makePageFragment(page)
while (!pageStack.isEmpty() && pageStack.peek().second !== source) {
pageStack.pop()
}
pageStack.push(Pair(page, f))
handleNewWidgetFragment(f)
activity.setProgressIndicatorVisible(true)
}
/**
* Follow a sitemap page link via URL
* If a page with the given URL is already present in the back stack,
* that page is brought to the front; otherwise a temporary page with showing
* the contents of the linked page is opened.
*
* @param url URL to follow
*/
fun openPage(url: String) {
CrashReportingHelper.d(TAG, "openPage(String)", remoteOnly = true)
val matchingPageIndex = pageStack.indexOfFirst { entry -> entry.first.link == url }
Log.d(TAG, "Opening page $url (present at $matchingPageIndex)")
temporaryPage = null
if (matchingPageIndex >= 0) {
for (i in matchingPageIndex + 1 until pageStack.size) {
pageStack.pop()
}
updateFragmentState(FragmentUpdateReason.PAGE_UPDATE)
updateConnectionState()
activity.updateTitle()
} else {
// we didn't find it
val page = LinkedPage("", "", null, url)
val f = makePageFragment(page)
pageStack.clear()
pageStack.push(Pair(page, f))
handleNewWidgetFragment(f)
activity.setProgressIndicatorVisible(true)
}
}
fun showWebViewUi(ui: WebViewUi, isStackRoot: Boolean, subpage: String?) {
val webViewFragment = ui.fragment.newInstance()
webViewFragment.arguments = bundleOf(
KEY_IS_STACK_ROOT to isStackRoot,
KEY_SUBPAGE to subpage
)
webViewFragment.setCallback(this)
showTemporaryPage(webViewFragment)
}
/**
* Indicate to the user that no network connectivity is present.
*
* @param message Error message to show
* @param shouldSuggestEnablingWifi
*/
fun indicateNoNetwork(message: CharSequence, shouldSuggestEnablingWifi: Boolean) {
CrashReportingHelper.d(TAG, "Indicate no network (message $message)")
resetState()
noConnectionFragment = if (shouldSuggestEnablingWifi) {
EnableWifiNetworkFragment.newInstance(message)
} else {
NoNetworkFragment.newInstance(message)
}
updateFragmentState(FragmentUpdateReason.PAGE_UPDATE)
activity.updateTitle()
}
/**
* Indicate to the user that the current Wi-Fi shouldn't be used.
*
* @param message Error message to show
*/
fun indicateWrongWifi(message: CharSequence) {
CrashReportingHelper.d(TAG, "Indicate wrong Wi-Fi (message $message)")
resetState()
noConnectionFragment = WrongWifiFragment.newInstance(message)
updateFragmentState(FragmentUpdateReason.PAGE_UPDATE)
activity.updateTitle()
}
/**
* Indicate to the user that server configuration is missing.
*
* @param resolveAttempted Indicate if discovery was attempted, but not successful
*/
fun indicateMissingConfiguration(resolveAttempted: Boolean, wouldHaveUsedOfficialServer: Boolean) {
CrashReportingHelper.d(TAG, "Indicate missing configuration (resolveAttempted $resolveAttempted)")
resetState()
val wifiManager = activity.getWifiManager(OpenHabApplication.DATA_ACCESS_TAG_SUGGEST_TURN_ON_WIFI)
noConnectionFragment = MissingConfigurationFragment.newInstance(
activity,
resolveAttempted,
wifiManager.isWifiEnabled,
wouldHaveUsedOfficialServer
)
updateFragmentState(FragmentUpdateReason.PAGE_UPDATE)
activity.updateTitle()
}
/**
* Indicate to the user that there was a failure in talking to the server
*
* @param message Error message to show
*/
fun indicateServerCommunicationFailure(message: CharSequence) {
CrashReportingHelper.d(TAG, "Indicate server failure (message $message)")
noConnectionFragment = CommunicationFailureFragment.newInstance(message)
updateFragmentState(FragmentUpdateReason.PAGE_UPDATE)
activity.updateTitle()
}
/**
* Clear the error previously set by [indicateServerCommunicationFailure]
*/
fun clearServerCommunicationFailure() {
CrashReportingHelper.d(TAG, "clearServerCommunicationFailure()")
if (noConnectionFragment is CommunicationFailureFragment) {
noConnectionFragment = null
resetState()
updateFragmentState(FragmentUpdateReason.PAGE_UPDATE)
activity.updateTitle()
}
}
/**
* Update the used connection.
* To be called when the available connection changes.
*
* @param connection New connection to use; might be null if none is currently available
* @param progressMessage Message to show to the user if no connection is available
*/
fun updateConnection(connection: Connection?, progressMessage: CharSequence?, @DrawableRes icon: Int) {
CrashReportingHelper.d(TAG, "Update to connection $connection (message $progressMessage)")
noConnectionFragment = if (connection == null)
ProgressFragment.newInstance(progressMessage, icon) else null
resetState()
updateFragmentState(FragmentUpdateReason.PAGE_UPDATE)
// Make sure dropped fragments are destroyed immediately to get their views recycled
fm.executePendingTransactions()
}
/**
* Open a temporary page showing the notification list
*
* @param highlightedId ID of notification to be highlighted initially
*/
fun openNotifications(highlightedId: String?, primaryServer: Boolean) {
showTemporaryPage(CloudNotificationListFragment.newInstance(highlightedId, primaryServer))
}
/**
* Recreate all UI state
* To be called from the activity's onCreate callback if the used controller changes
*/
fun recreateFragmentState() {
fm.commitNow {
@Suppress("DEPRECATION") // TODO: Replace deprecated function
fm.fragments
.filterNot { f -> f.retainInstance }
.forEach { f -> remove(f) }
}
updateFragmentState(FragmentUpdateReason.PAGE_UPDATE)
}
/**
* Inflate controller views
* To be called after activity content view inflation
*
* @param stub View stub to inflate controller views into
*/
abstract fun inflateViews(stub: ViewStub)
/**
* Ask the connection controller to deliver content updates for a given page
*
* @param pageUrl URL of the content page
* @param forceReload Whether to discard previously cached state
*/
fun triggerPageUpdate(pageUrl: String, forceReload: Boolean) {
connectionFragment.triggerUpdate(pageUrl, forceReload)
}
/**
* Checks whether the controller currently can consume the back key
*
* @return true if back key can be consumed, false otherwise
*/
fun canGoBack(): Boolean {
val tempPageAsWebView = temporaryPage as? AbstractWebViewFragment
return if (tempPageAsWebView?.isStackRoot == true) {
return tempPageAsWebView.canGoBack()
} else {
temporaryPage != null || !pageStack.empty()
}
}
/**
* Consumes the back key
* To be called from activity onBackKeyPressed callback
*
* @return true if back key was consumed, false otherwise
*/
fun goBack(): Boolean {
if (temporaryPage is AbstractWebViewFragment) {
if ((temporaryPage as AbstractWebViewFragment).goBack()) {
return true
}
}
if (temporaryPage != null) {
if ((temporaryPage as? AbstractWebViewFragment)?.isStackRoot == true) {
return false
}
temporaryPage = null
activity.updateTitle()
updateFragmentState(FragmentUpdateReason.PAGE_UPDATE)
updateConnectionState()
return true
}
if (!pageStack.empty()) {
pageStack.pop()
activity.updateTitle()
updateFragmentState(FragmentUpdateReason.BACK_NAVIGATION)
updateConnectionState()
return true
}
return false
}
override fun closeFragment() {
if (temporaryPage != null) {
temporaryPage = null
activity.updateTitle()
updateFragmentState(FragmentUpdateReason.PAGE_UPDATE)
updateConnectionState()
}
}
override fun onPageUpdated(pageUrl: String, pageTitle: String?, widgets: List<Widget>) {
Log.d(TAG, "Got update for URL $pageUrl, pending $pendingDataLoadUrls")
val fragment = findWidgetFragmentForUrl(pageUrl)
fragment?.updateTitle(pageTitle.orEmpty())
fragment?.updateWidgets(widgets)
if (pendingDataLoadUrls.remove(pageUrl) && pendingDataLoadUrls.isEmpty()) {
activity.setProgressIndicatorVisible(false)
activity.updateTitle()
updateFragmentState(if (pageStack.isEmpty())
FragmentUpdateReason.PAGE_UPDATE else FragmentUpdateReason.PAGE_ENTER)
}
}
override fun onWidgetUpdated(pageUrl: String, widget: Widget) {
findWidgetFragmentForUrl(pageUrl)?.updateWidget(widget)
}
override fun onPageTitleUpdated(pageUrl: String, title: String) {
findWidgetFragmentForUrl(pageUrl)?.updateTitle(title)
}
override fun onLoadFailure(error: HttpClient.HttpException) {
val url = error.request.url.toString()
val errorMessage = activity.getHumanReadableErrorMessage(url, error.statusCode, error, false)
.toString()
CrashReportingHelper.d(TAG, "onLoadFailure() with message $errorMessage")
noConnectionFragment = CommunicationFailureFragment.newInstance(
activity.getString(R.string.error_sitemap_generic_load_error, errorMessage))
updateFragmentState(FragmentUpdateReason.PAGE_UPDATE)
activity.updateTitle()
if (pendingDataLoadUrls.remove(error.originalUrl) && pendingDataLoadUrls.isEmpty()) {
activity.setProgressIndicatorVisible(false)
}
activity.scheduleRetry {
activity.retryServerPropertyQuery()
}
}
override fun onSseFailure() {
activity.showSnackbar(MainActivity.SNACKBAR_TAG_SSE_ERROR, R.string.error_sse_failed)
}
internal abstract fun executeStateUpdate(reason: FragmentUpdateReason)
private fun updateFragmentState(reason: FragmentUpdateReason) {
if (fm.isDestroyed) {
return
}
executeStateUpdate(reason)
collectWidgetFragments().forEach { f -> f.closeAllDialogs() }
}
private fun handleNewWidgetFragment(f: WidgetListFragment) {
pendingDataLoadUrls.add(f.displayPageUrl)
// no fragment update yet; fragment state will be updated when data arrives
updateConnectionState()
activity.updateTitle()
}
private fun showTemporaryPage(page: Fragment) {
temporaryPage = page
updateFragmentState(FragmentUpdateReason.TEMPORARY_PAGE)
updateConnectionState()
activity.updateTitle()
}
private fun updateConnectionState() {
val pageUrls = collectWidgetFragments().map { f -> f.displayPageUrl }
pendingDataLoadUrls.retainAll { url -> pageUrls.contains(url) }
connectionFragment.updateActiveConnections(pageUrls, activity.connection)
}
private fun resetState() {
currentSitemap = null
sitemapFragment = null
pageStack.clear()
updateConnectionState()
}
private fun findWidgetFragmentForUrl(url: String): WidgetListFragment? {
return collectWidgetFragments().firstOrNull { f -> f.displayPageUrl == url }
}
private fun collectWidgetFragments(): List<WidgetListFragment> {
val result = ArrayList<WidgetListFragment>()
sitemapFragment?.let { result.add(it) }
for ((_, fragment) in pageStack) {
result.add(fragment)
}
return result
}
private fun makeSitemapFragment(sitemap: Sitemap): WidgetListFragment {
return WidgetListFragment.withPage(sitemap.homepageLink, sitemap.label)
}
private fun makePageFragment(page: LinkedPage): WidgetListFragment {
return WidgetListFragment.withPage(page.link, page.title)
}
internal enum class FragmentUpdateReason {
PAGE_ENTER,
BACK_NAVIGATION,
TEMPORARY_PAGE,
PAGE_UPDATE
}
internal class CommunicationFailureFragment : StatusFragment() {
override fun onClick(view: View) {
(activity as MainActivity).retryServerPropertyQuery()
}
companion object {
fun newInstance(message: CharSequence): CommunicationFailureFragment {
val f = CommunicationFailureFragment()
f.arguments = buildArgs(
message,
R.string.try_again_button,
R.drawable.ic_openhab_appicon_340dp,
false
)
return f
}
}
}
internal class ProgressFragment : StatusFragment() {
override fun onClick(view: View) {
// No-op, we don't show the button
}
companion object {
fun newInstance(message: CharSequence?, @DrawableRes image: Int): ProgressFragment {
val f = ProgressFragment()
f.arguments = buildArgs(message, 0, image, true)
return f
}
}
}
internal class NoNetworkFragment : StatusFragment() {
override fun onClick(view: View) {
ConnectionFactory.restartNetworkCheck()
activity?.recreate()
}
companion object {
fun newInstance(message: CharSequence): NoNetworkFragment {
val f = NoNetworkFragment()
f.arguments = buildArgs(message, R.string.try_again_button,
R.drawable.ic_network_strength_off_outline_black_24dp, false)
return f
}
}
}
internal class EnableWifiNetworkFragment : StatusFragment() {
override fun onClick(view: View) {
(activity as MainActivity).enableWifiAndIndicateStartup()
}
companion object {
fun newInstance(message: CharSequence): EnableWifiNetworkFragment {
val f = EnableWifiNetworkFragment()
f.arguments = buildArgs(message, R.string.enable_wifi_button,
R.drawable.ic_wifi_strength_off_outline_grey_24dp, false)
return f
}
}
}
internal class WrongWifiFragment : StatusFragment() {
override fun onClick(view: View) {
if (view.id == R.id.button1) {
val preferencesIntent = Intent(activity, PreferencesActivity::class.java)
startActivity(preferencesIntent)
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
// Open panel to switch Wi-Fi
val panelIntent = Intent(Settings.Panel.ACTION_WIFI)
startActivity(panelIntent)
}
}
}
companion object {
fun newInstance(
message: CharSequence
): WrongWifiFragment {
val f = WrongWifiFragment()
val args = buildArgs(
message = message,
button1TextResId = R.string.go_to_settings_button,
button2TextResId = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)
R.string.switch_wifi_button else 0,
drawableResId = R.drawable.ic_wifi_strength_off_outline_grey_24dp,
showProgress = false
)
f.arguments = args
return f
}
}
}
internal class MissingConfigurationFragment : StatusFragment() {
override fun onClick(view: View) {
if (view.id == R.id.button1) when {
arguments?.getBoolean(KEY_RESOLVE_ATTEMPTED) == true -> {
// If we attempted resolving, primary button opens settings
val preferencesIntent = Intent(activity, PreferencesActivity::class.java)
startActivity(preferencesIntent)
}
arguments?.getBoolean(KEY_WIFI_ENABLED) == true -> {
// If Wifi is enabled, primary button suggests retrying
ConnectionFactory.restartNetworkCheck()
activity?.recreate()
}
else -> {
// If Wifi is disabled, primary button suggests enabling Wifi
(activity as MainActivity?)?.enableWifiAndIndicateStartup()
}
} else when {
arguments?.getBoolean(KEY_RESOLVE_ATTEMPTED) == true -> {
// If we attempted resolving, secondary button enables demo mode
context?.apply {
getPrefs().edit {
putBoolean(PrefKeys.DEMO_MODE, true)
}
}
}
else -> {
// If connection issue, secondary button suggests opening status.openhab.org
"https://status.openhab.org".toUri().openInBrowser(requireContext())
}
}
}
companion object {
fun newInstance(
context: Context,
resolveAttempted: Boolean,
hasWifiEnabled: Boolean,
wouldHaveUsedOfficialServer: Boolean
): MissingConfigurationFragment {
val f = MissingConfigurationFragment()
val args = when {
resolveAttempted -> buildArgs(context.getString(R.string.configuration_missing),
R.string.go_to_settings_button, R.string.enable_demo_mode_button,
R.drawable.ic_home_search_outline_grey_340dp, false)
hasWifiEnabled -> buildArgs(context.getString(R.string.no_remote_server),
R.string.try_again_button,
if (wouldHaveUsedOfficialServer) R.string.visit_status_openhab_org else 0,
R.drawable.ic_network_strength_off_outline_black_24dp, false)
else -> buildArgs(context.getString(R.string.no_remote_server),
R.string.enable_wifi_button,
if (wouldHaveUsedOfficialServer) R.string.visit_status_openhab_org else 0,
R.drawable.ic_wifi_strength_off_outline_grey_24dp, false)
}
args.putBoolean(KEY_RESOLVE_ATTEMPTED, resolveAttempted)
args.putBoolean(KEY_WIFI_ENABLED, hasWifiEnabled)
f.arguments = args
return f
}
}
}
internal abstract class StatusFragment : Fragment(), View.OnClickListener {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val arguments = requireArguments()
val view = inflater.inflate(R.layout.fragment_status, container, false)
val descriptionText = view.findViewById<TextView>(R.id.description)
descriptionText.text = arguments.getCharSequence(KEY_MESSAGE)
descriptionText.isVisible = !descriptionText.text.isNullOrEmpty()
view.findViewById<View>(R.id.progress).isVisible = arguments.getBoolean(KEY_PROGRESS)
val watermark = view.findViewById<ImageView>(R.id.image)
@DrawableRes val drawableResId = arguments.getInt(KEY_DRAWABLE)
if (drawableResId != 0) {
val drawable = ContextCompat.getDrawable(view.context, drawableResId)
drawable?.colorFilter = PorterDuffColorFilter(
ContextCompat.getColor(view.context, R.color.empty_list_text_color),
PorterDuff.Mode.SRC_IN)
watermark.setImageDrawable(drawable)
} else {
watermark.isVisible = false
}
for ((id, key) in mapOf(R.id.button1 to KEY_BUTTON_1_TEXT, R.id.button2 to KEY_BUTTON_2_TEXT)) {
val button = view.findViewById<Button>(id)
val buttonTextResId = arguments.getInt(key)
if (buttonTextResId != 0) {
button.setText(buttonTextResId)
button.setOnClickListener(this)
} else {
button.isVisible = false
}
}
return view
}
companion object {
internal const val KEY_MESSAGE = "message"
internal const val KEY_DRAWABLE = "drawable"
internal const val KEY_BUTTON_1_TEXT = "button1text"
internal const val KEY_BUTTON_2_TEXT = "button2text"
internal const val KEY_PROGRESS = "progress"
internal const val KEY_RESOLVE_ATTEMPTED = "resolveAttempted"
internal const val KEY_WIFI_ENABLED = "wifiEnabled"
internal fun buildArgs(
message: CharSequence?,
@StringRes buttonTextResId: Int,
@DrawableRes drawableResId: Int,
showProgress: Boolean
): Bundle {
return buildArgs(message, buttonTextResId,
0, drawableResId, showProgress)
}
internal fun buildArgs(
message: CharSequence?,
@StringRes button1TextResId: Int,
@StringRes button2TextResId: Int,
@DrawableRes drawableResId: Int,
showProgress: Boolean
): Bundle {
return bundleOf(
KEY_MESSAGE to message,
KEY_DRAWABLE to drawableResId,
KEY_BUTTON_1_TEXT to button1TextResId,
KEY_BUTTON_2_TEXT to button2TextResId,
KEY_PROGRESS to showProgress
)
}
}
}
companion object {
private val TAG = ContentController::class.java.simpleName
private const val STATE_KEY_SITEMAP = "controllerSitemap"
private const val STATE_KEY_PAGES = "controllerPages"
private const val STATE_KEY_SITEMAP_FRAGMENT = "sitemapFragment"
private const val STATE_KEY_PROGRESS_FRAGMENT = "progressFragment"
private const val STATE_KEY_ERROR_FRAGMENT = "errorFragment"
private const val STATE_KEY_TEMPORARY_PAGE = "temporaryPage"
private fun makeStateKeyForPage(page: LinkedPage) = "pageFragment-${page.link}"
@AnimRes
internal fun determineEnterAnim(reason: FragmentUpdateReason): Int {
return when (reason) {
FragmentUpdateReason.PAGE_ENTER -> R.anim.slide_in_right
FragmentUpdateReason.TEMPORARY_PAGE -> R.anim.slide_in_bottom
FragmentUpdateReason.BACK_NAVIGATION -> R.anim.slide_in_left
else -> 0
}
}
@AnimRes
internal fun determineExitAnim(reason: FragmentUpdateReason): Int {
return when (reason) {
FragmentUpdateReason.PAGE_ENTER -> R.anim.slide_out_left
FragmentUpdateReason.TEMPORARY_PAGE -> R.anim.slide_out_bottom
FragmentUpdateReason.BACK_NAVIGATION -> R.anim.slide_out_right
else -> 0
}
}
}
}
| epl-1.0 | 1c849c1762957386a12c3f2d0af3de35 | 38.332936 | 120 | 0.637208 | 4.959525 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/wildplot/android/rendering/PlotSheet.kt | 1 | 18238 | /****************************************************************************************
* Copyright (c) 2014 Michael Goldbach <[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.wildplot.android.rendering
import android.graphics.Typeface
import com.wildplot.android.rendering.graphics.wrapper.ColorWrap
import com.wildplot.android.rendering.graphics.wrapper.GraphicsWrap
import com.wildplot.android.rendering.graphics.wrapper.RectangleWrap
import com.wildplot.android.rendering.interfaces.Drawable
import com.wildplot.android.rendering.interfaces.Legendable
import timber.log.Timber
import java.util.*
/**
* This is a sheet that is used to plot mathematical functions including coordinate systems and optional extras like
* legends and descriptors. Additionally all conversions from image to plot coordinates are done here
*/
class PlotSheet : Drawable {
protected var typeface = Typeface.DEFAULT
private var hasTitle = false
private var fontSize = 10f
private var fontSizeSet = false
private var backgroundColor = ColorWrap.white
var textColor = ColorWrap.black
/**
* title of plotSheet
*/
protected var title = "PlotSheet"
/**
* set the title of the plot
*
* @param value title string shown above plot
*/
set(value) {
field = value
hasTitle = true
}
private var isBackwards = false
/**
* thickness of frame in pixel
*/
private var leftFrameThickness = 0f
private var upperFrameThickness = 0f
private var rightFrameThickness = 0f
private var bottomFrameThickness = 0f
/**
* states if there is a border between frame and plot
*/
private var isBordered = true
// if class should be made threadable for mulitplot mode, than
// this must be done otherwise
/**
* screen that is currently rendered
*/
private val currentScreen = 0
/**
* the ploting screens, screen 0 is the only one in single mode
*/
private val screenParts = Vector<MultiScreenPart>()
// Use LinkedHashMap so that the legend items will be displayed in the order
// in which they were added
private val mLegendMap: MutableMap<String?, ColorWrap> = LinkedHashMap()
private var mDrawablesPrepared = false
/**
* Create a virtual sheet used for the plot
*
* @param xStart the start of the x-range
* @param xEnd the end of the x-range
* @param yStart the start of the y-range
* @param yEnd the end of the y-range
* @param drawables list of Drawables that shall be drawn onto the sheet
*/
constructor(
xStart: Double,
xEnd: Double,
yStart: Double,
yEnd: Double,
drawables: Vector<Drawable>
) {
val xRange = doubleArrayOf(xStart, xEnd)
val yRange = doubleArrayOf(yStart, yEnd)
screenParts.add(0, MultiScreenPart(xRange, yRange, drawables))
}
/**
* Create a virtual sheet used for the plot
*
* @param xStart the start of the x-range
* @param xEnd the end of the x-range
* @param yStart the start of the y-range
* @param yEnd the end of the y-range
*/
constructor(xStart: Double, xEnd: Double, yStart: Double, yEnd: Double) {
val xRange = doubleArrayOf(xStart, xEnd)
val yRange = doubleArrayOf(yStart, yEnd)
screenParts.add(0, MultiScreenPart(xRange, yRange))
}
/**
* add another Drawable object that shall be drawn onto the sheet
* this adds only drawables for the first screen in multimode plots for
*
* @param draw Drawable object which will be addet to plot sheet
*/
fun addDrawable(draw: Drawable?) {
screenParts[0].addDrawable(draw!!)
mDrawablesPrepared = false
}
/**
* Converts a given x coordinate from plotting field coordinate to a graphic field coordinate
*
* @param x given graphic x coordinate
* @param field the graphic field
* @return the converted x value
*/
fun xToGraphic(x: Double, field: RectangleWrap): Float {
val xQuotient = (field.width - leftFrameThickness - rightFrameThickness) /
Math.abs(
screenParts[currentScreen].getxRange()[1] -
screenParts[currentScreen].getxRange()[0]
)
val xDistanceFromLeft = x - screenParts[currentScreen].getxRange()[0]
return field.x + leftFrameThickness + (xDistanceFromLeft * xQuotient).toFloat()
}
/**
* Converts a given y coordinate from plotting field coordinate to a graphic field coordinate.
*
* @param y given graphic y coordinate
* @param field the graphic field
* @return the converted y value
*/
fun yToGraphic(y: Double, field: RectangleWrap): Float {
val yQuotient = (field.height - upperFrameThickness - bottomFrameThickness) /
Math.abs(
screenParts[currentScreen].getyRange()[1] -
screenParts[currentScreen].getyRange()[0]
)
val yDistanceFromTop = screenParts[currentScreen].getyRange()[1] - y
return (field.y + upperFrameThickness + yDistanceFromTop * yQuotient).toFloat()
}
/**
* Convert a coordinate system point to a point used for graphical processing (with hole pixels)
*
* @param x given x-coordinate
* @param y given y-coordinate
* @param field clipping bounds for drawing
* @return the point in graphical coordinates
*/
fun toGraphicPoint(x: Double, y: Double, field: RectangleWrap): FloatArray {
return floatArrayOf(xToGraphic(x, field), yToGraphic(y, field))
}
override fun paint(g: GraphicsWrap) {
val field = g.clipBounds
prepareDrawables()
val offFrameDrawables = Vector<Drawable>()
val onFrameDrawables = Vector<Drawable>()
g.typeface = typeface
g.color = backgroundColor
g.fillRect(0f, 0f, field.width.toFloat(), field.height.toFloat())
g.color = ColorWrap.BLACK
if (fontSizeSet) {
g.fontSize = fontSize
}
if (screenParts[0].drawables.size != 0) {
for (draw in screenParts[0].drawables) {
if (!draw.isOnFrame()) {
offFrameDrawables.add(draw)
} else {
onFrameDrawables.add(draw)
}
}
}
for (offFrameDrawing in offFrameDrawables) {
offFrameDrawing.paint(g)
}
// paint white frame to over paint everything that was drawn over the border
val oldColor = g.color
if (leftFrameThickness > 0 || rightFrameThickness > 0 || upperFrameThickness > 0 || bottomFrameThickness > 0) {
g.color = backgroundColor
// upper frame
g.fillRect(0f, 0f, field.width.toFloat(), upperFrameThickness)
// left frame
g.fillRect(0f, upperFrameThickness, leftFrameThickness, field.height.toFloat())
// right frame
g.fillRect(
field.width + 1 - rightFrameThickness, upperFrameThickness,
rightFrameThickness +
leftFrameThickness,
field.height - bottomFrameThickness
)
// bottom frame
g.fillRect(
leftFrameThickness, field.height - bottomFrameThickness,
field.width - rightFrameThickness, bottomFrameThickness + 1
)
// make small black border frame
if (isBordered) {
drawBorder(g, field)
}
g.color = oldColor
if (hasTitle) {
drawTitle(g, field)
}
val keyList: List<String?> = Vector(mLegendMap.keys)
if (isBackwards) {
Collections.reverse(keyList)
}
val oldFontSize = g.fontSize
g.fontSize = oldFontSize * 0.9f
val fm = g.fontMetrics
val height = fm.height
val spacerValue = height * 0.5f
var xPointer = spacerValue
var ySpacer = spacerValue
var legendCnt = 0
Timber.d("should draw legend now, number of legend entries: %d", mLegendMap.size)
for (legendName in keyList) {
val stringWidth = fm.stringWidth(" : $legendName")
val color = mLegendMap[legendName]
g.color = color!!
if (legendCnt++ != 0 && xPointer + height * 2.0f + stringWidth >= field.width) {
xPointer = spacerValue
ySpacer += height + spacerValue
}
g.fillRect(xPointer, ySpacer, height, height)
g.color = textColor
g.drawString(" : $legendName", xPointer + height, ySpacer + height)
xPointer += height * 1.3f + stringWidth
Timber.d(
"drawing a legend Item: (%s) %d, x: %,.2f , y: %,.2f",
legendName,
legendCnt,
xPointer + height,
ySpacer + height
)
}
g.fontSize = oldFontSize
g.color = textColor
}
for (onFrameDrawing in onFrameDrawables) {
onFrameDrawing.paint(g)
}
}
private fun drawBorder(g: GraphicsWrap, field: RectangleWrap) {
g.color = ColorWrap.black
// upper border
val borderThickness = 1
g.fillRect(
leftFrameThickness - borderThickness + 1,
upperFrameThickness - borderThickness + 1,
field.width - leftFrameThickness - rightFrameThickness + 2 * borderThickness - 2,
borderThickness.toFloat()
)
// lower border
g.fillRect(
leftFrameThickness - borderThickness + 1,
field.height - bottomFrameThickness,
field.width - leftFrameThickness - rightFrameThickness + 2 * borderThickness - 2,
borderThickness.toFloat()
)
// left border
g.fillRect(
leftFrameThickness - borderThickness + 1,
upperFrameThickness - borderThickness + 1,
borderThickness.toFloat(),
field.height - upperFrameThickness - bottomFrameThickness + 2 * borderThickness - 2
)
// right border
g.fillRect(
field.width - rightFrameThickness,
upperFrameThickness - borderThickness + 1,
borderThickness.toFloat(),
field.height - upperFrameThickness - bottomFrameThickness + 2 * borderThickness - 2
)
}
private fun drawTitle(g: GraphicsWrap, field: RectangleWrap) {
val oldFontSize = g.fontSize
val newFontSize = oldFontSize * 2
g.fontSize = newFontSize
val fm = g.fontMetrics
val height = fm.height
val width = fm.stringWidth(title)
g.drawString(title, field.width / 2 - width / 2, upperFrameThickness - 10 - height)
g.fontSize = oldFontSize
}
/**
* sort runnables and group them together to use lesser threads
*/
private fun prepareDrawables() {
if (!mDrawablesPrepared) {
mDrawablesPrepared = true
val drawables = screenParts[0].drawables
val onFrameDrawables = Vector<Drawable>()
val offFrameDrawables = Vector<Drawable>()
var onFrameContainer = DrawableContainer(true, false)
var offFrameContainer = DrawableContainer(false, false)
for (drawable in drawables) {
if (drawable is Legendable && (drawable as Legendable).nameIsSet()) {
val color = (drawable as Legendable).color!!
val name = (drawable as Legendable).name
mLegendMap[name] = color
}
if (drawable.isOnFrame()) {
if (drawable.isClusterable()) {
if (onFrameContainer.isCritical() != drawable.isCritical()) {
if (onFrameContainer.size > 0) {
onFrameDrawables.add(onFrameContainer)
}
onFrameContainer = DrawableContainer(true, drawable.isCritical())
}
onFrameContainer.addDrawable(drawable)
} else {
if (onFrameContainer.size > 0) {
onFrameDrawables.add(onFrameContainer)
}
onFrameDrawables.add(drawable)
onFrameContainer = DrawableContainer(true, false)
}
} else {
if (drawable.isClusterable()) {
if (offFrameContainer.isCritical() != drawable.isCritical()) {
if (offFrameContainer.size > 0) {
offFrameDrawables.add(offFrameContainer)
}
offFrameContainer = DrawableContainer(false, drawable.isCritical())
}
offFrameContainer.addDrawable(drawable)
} else {
if (offFrameContainer.size > 0) {
offFrameDrawables.add(offFrameContainer)
}
offFrameDrawables.add(drawable)
offFrameContainer = DrawableContainer(false, false)
}
}
}
if (onFrameContainer.size > 0) {
onFrameDrawables.add(onFrameContainer)
}
if (offFrameContainer.size > 0) {
offFrameDrawables.add(offFrameContainer)
}
screenParts[0].drawables.removeAllElements()
screenParts[0].drawables.addAll(offFrameDrawables)
screenParts[0].drawables.addAll(onFrameDrawables)
}
}
/**
* the x-range for the plot
*
* @return double array in the length of two with the first element beeingt left and the second element being the right border
*/
fun getxRange(): DoubleArray {
return screenParts[0].getxRange()
}
/**
* the <-range for the plot
*
* @return double array in the length of two with the first element being lower and the second element being the upper border
*/
fun getyRange(): DoubleArray {
return screenParts[0].getyRange()
}
/**
* returns the size in pixel of the outer frame
*
* @return the size of the outer frame for left, right, upper and bottom frame
*/
val frameThickness: FloatArray
get() = floatArrayOf(
leftFrameThickness,
rightFrameThickness,
upperFrameThickness,
bottomFrameThickness
)
/**
* set the size of the outer frame in pixel
*/
fun setFrameThickness(
leftFrameThickness: Float,
rightFrameThickness: Float,
upperFrameThickness: Float,
bottomFrameThickness: Float
) {
if (leftFrameThickness < 0 || rightFrameThickness < 0 || upperFrameThickness < 0 || bottomFrameThickness < 0) {
Timber.e("PlotSheet:Error::Wrong Frame size (smaller than 0)")
this.bottomFrameThickness = 0f
this.upperFrameThickness = this.bottomFrameThickness
this.rightFrameThickness = this.upperFrameThickness
this.leftFrameThickness = this.rightFrameThickness
}
this.leftFrameThickness = leftFrameThickness
this.rightFrameThickness = rightFrameThickness
this.upperFrameThickness = upperFrameThickness
this.bottomFrameThickness = bottomFrameThickness
}
/**
* deactivates the border between outer frame and plot
*/
fun unsetBorder() {
isBordered = false
}
override fun isOnFrame(): Boolean {
return false
}
override fun isClusterable(): Boolean {
return true
}
override fun isCritical(): Boolean {
return false
}
/**
* Show the legend items in reverse order of the order in which they were added.
*
* @param isBackwards If true, the legend items are shown in reverse order.
*/
fun setIsBackwards(isBackwards: Boolean) {
this.isBackwards = isBackwards
}
fun setFontSize(fontSize: Float) {
fontSizeSet = true
this.fontSize = fontSize
}
fun setBackgroundColor(backgroundColor: ColorWrap) {
this.backgroundColor = backgroundColor
}
companion object {
const val LEFT_FRAME_THICKNESS_INDEX = 0
const val RIGHT_FRAME_THICKNESS_INDEX = 1
const val UPPER_FRAME_THICKNESS_INDEX = 2
const val BOTTOM_FRAME_THICKNESS_INDEX = 3
}
}
| gpl-3.0 | bee9078ece32df19e736b09e427b4e2f | 37.075157 | 130 | 0.569141 | 4.898738 | false | false | false | false |
randombyte-developer/holograms | src/main/kotlin/de/randombyte/holograms/HologramsServiceImpl.kt | 1 | 3720 | package de.randombyte.holograms
import de.randombyte.holograms.api.HologramsService
import de.randombyte.holograms.api.HologramsService.Hologram
import de.randombyte.holograms.data.HologramData
import de.randombyte.holograms.data.HologramKeys
import de.randombyte.kosp.extensions.getWorld
import de.randombyte.kosp.extensions.orNull
import de.randombyte.kosp.extensions.toOptional
import org.spongepowered.api.data.key.Keys
import org.spongepowered.api.entity.Entity
import org.spongepowered.api.entity.EntityTypes
import org.spongepowered.api.entity.living.ArmorStand
import org.spongepowered.api.text.Text
import org.spongepowered.api.world.Location
import org.spongepowered.api.world.World
import org.spongepowered.api.world.extent.Extent
import java.util.*
class HologramsServiceImpl : HologramsService {
class HologramImpl internal constructor(uuid: UUID, worldUuid: UUID) : Hologram(uuid, worldUuid) {
init {
// Check for existence by trying to get the ArmorStand
// If it can't be found a detailed exception is thrown
getArmorStand()
}
override var location: Location<World>
get() = getArmorStand().location
set(value) { getArmorStand().location = value }
override var text: Text
get() = getArmorStand().get(Keys.DISPLAY_NAME).orElse(Text.EMPTY)
set(value) { getArmorStand().offer(Keys.DISPLAY_NAME, value) }
override fun exists() = worldUuid.getWorld()?.getEntity(uuid)?.orNull()?.isHologram() ?: false
override fun remove() = getArmorStand().remove()
override fun getArmorStand(): ArmorStand {
val world = worldUuid.getWorld() ?: throw RuntimeException("Can't find world '$worldUuid'!")
val entity = world.getEntity(uuid).orNull() ?: throw RuntimeException("Can't find Entity '$uuid' in world '$worldUuid'!")
val armorStand = (entity as? ArmorStand) ?: throw RuntimeException("Entity '$uuid' in world '$worldUuid' is not an ArmorStand!")
if (!armorStand.isHologram()) throw RuntimeException("ArmorStand '$uuid' in world '$worldUuid' is not a Hologram!")
return armorStand
}
}
override fun createHologram(location: Location<out Extent>, text: Text): Optional<Hologram> {
val armorStand = location.createEntity(EntityTypes.ARMOR_STAND)
if (!location.extent.spawnEntity(armorStand)) return Optional.empty()
armorStand.offer(Keys.DISPLAY_NAME, text)
armorStand.offer(Keys.CUSTOM_NAME_VISIBLE, true)
armorStand.offer(Keys.HAS_GRAVITY, false)
armorStand.offer(Keys.ARMOR_STAND_MARKER, true)
armorStand.offer(Keys.INVISIBLE, true)
val data = armorStand.getOrCreate(HologramData::class.java).get().set(HologramKeys.IS_HOLOGRAM, true)
armorStand.offer(data)
return HologramImpl(armorStand.uniqueId, location.extent.uniqueId).toOptional()
}
override fun getHologram(extent: Extent, hologramUuid: UUID) = getHolograms(extent)
.firstOrNull { it.uuid == hologramUuid }
.toOptional()
override fun getHolograms(center: Location<out Extent>, radius: Double) = getHolograms(center.extent)
.associateBy(keySelector = { it }, valueTransform = { center.position.distance(it.location.position) })
.filter { it.value <= radius }
.toList()
.sortedBy { it.second }
override fun getHolograms(extent: Extent) = extent.entities
.filter(Entity::isHologram)
.map { HologramImpl(it.uniqueId, extent.uniqueId) }
}
private fun Entity.isHologram() = this is ArmorStand && get(HologramKeys.IS_HOLOGRAM).orElse(false) | gpl-2.0 | 537cd7a74d91079a057caef1812fd717 | 44.378049 | 140 | 0.699194 | 4.227273 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/data/osmnotes/NoteDao.kt | 1 | 4021 | package de.westnordost.streetcomplete.data.osmnotes
import javax.inject.Inject
import de.westnordost.streetcomplete.data.CursorPosition
import de.westnordost.streetcomplete.data.Database
import de.westnordost.streetcomplete.data.osm.mapdata.BoundingBox
import de.westnordost.streetcomplete.data.osm.mapdata.LatLon
import de.westnordost.streetcomplete.data.osmnotes.NoteTable.Columns.CLOSED
import de.westnordost.streetcomplete.data.osmnotes.NoteTable.Columns.COMMENTS
import de.westnordost.streetcomplete.data.osmnotes.NoteTable.Columns.CREATED
import de.westnordost.streetcomplete.data.osmnotes.NoteTable.Columns.ID
import de.westnordost.streetcomplete.data.osmnotes.NoteTable.Columns.LAST_SYNC
import de.westnordost.streetcomplete.data.osmnotes.NoteTable.Columns.LATITUDE
import de.westnordost.streetcomplete.data.osmnotes.NoteTable.Columns.LONGITUDE
import de.westnordost.streetcomplete.data.osmnotes.NoteTable.Columns.STATUS
import de.westnordost.streetcomplete.data.osmnotes.NoteTable.NAME
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import java.lang.System.currentTimeMillis
/** Stores OSM notes */
class NoteDao @Inject constructor(private val db: Database) {
fun put(note: Note) {
db.replace(NAME, note.toPairs())
}
fun get(id: Long): Note? =
db.queryOne(NAME, where = "$ID = $id") { it.toNote() }
fun delete(id: Long): Boolean =
db.delete(NAME, "$ID = $id") == 1
fun putAll(notes: Collection<Note>) {
if (notes.isEmpty()) return
db.replaceMany(NAME,
arrayOf(ID, LATITUDE, LONGITUDE, STATUS, CREATED, CLOSED, COMMENTS, LAST_SYNC),
notes.map { arrayOf(
it.id,
it.position.latitude,
it.position.longitude,
it.status.name,
it.timestampCreated,
it.timestampClosed,
Json.encodeToString(it.comments),
currentTimeMillis()
) }
)
}
fun getAll(bbox: BoundingBox): List<Note> =
db.query(NAME, where = inBoundsSql(bbox)) { it.toNote() }
fun getAllPositions(bbox: BoundingBox): List<LatLon> =
db.query(NAME,
columns = arrayOf(LATITUDE, LONGITUDE),
where = inBoundsSql(bbox),
) { LatLon(it.getDouble(LATITUDE), it.getDouble(LONGITUDE)) }
fun getAll(ids: Collection<Long>): List<Note> {
if (ids.isEmpty()) return emptyList()
return db.query(NAME, where = "$ID IN (${ids.joinToString(",")})") { it.toNote() }
}
fun getIdsOlderThan(timestamp: Long, limit: Int? = null): List<Long> {
if (limit != null && limit <= 0) return emptyList()
else return db.query(NAME,
columns = arrayOf(ID),
where = "$LAST_SYNC < $timestamp",
limit = limit?.toString()
) { it.getLong(ID) }
}
fun deleteAll(ids: Collection<Long>): Int {
if (ids.isEmpty()) return 0
return db.delete(NAME, "$ID IN (${ids.joinToString(",")})")
}
fun clear() {
db.delete(NAME)
}
private fun Note.toPairs() = listOf(
ID to id,
LATITUDE to position.latitude,
LONGITUDE to position.longitude,
STATUS to status.name,
CREATED to timestampCreated,
CLOSED to timestampClosed,
COMMENTS to Json.encodeToString(comments),
LAST_SYNC to currentTimeMillis()
)
private fun CursorPosition.toNote() = Note(
LatLon(getDouble(LATITUDE), getDouble(LONGITUDE)),
getLong(ID),
getLong(CREATED),
getLongOrNull(CLOSED),
Note.Status.valueOf(getString(STATUS)),
Json.decodeFromString(getString(COMMENTS))
)
private fun inBoundsSql(bbox: BoundingBox): String = """
($LATITUDE BETWEEN ${bbox.min.latitude} AND ${bbox.max.latitude}) AND
($LONGITUDE BETWEEN ${bbox.min.longitude} AND ${bbox.max.longitude})
""".trimIndent()
}
| gpl-3.0 | 20d55538bcfaa41cff99687a84172c09 | 35.554545 | 91 | 0.660532 | 4.255026 | false | false | false | false |
pdvrieze/ProcessManager | java-common/src/javaMain/kotlin/net/devrieze/util/ObservableCollections.kt | 1 | 6838 | /*
* Copyright (c) 2019.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package net.devrieze.util
import net.devrieze.util.collection.replaceBy
import java.util.*
import java.util.function.Predicate
actual abstract class ObservableCollectionBase<C : MutableCollection<T>, T, S : ObservableCollectionBase<C, T, S>>
constructor(protected val delegate: C, observers: Iterable<(S) -> Unit> = emptyList()) : Collection<T> by delegate,
MutableCollection<T> {
val observers = observers.toMutableArraySet()
protected open class ObservableIterator<T>(protected val base: ObservableCollectionBase<*,T,*>, protected open val delegate: MutableIterator<T>) :
Iterator<T> by delegate, MutableIterator<T> {
override fun remove() {
delegate.remove()
base.triggerObservers()
}
}
abstract fun triggerObservers()
actual fun replaceBy(elements: Iterable<T>): Boolean {
var hasChanges = false
val oldElements = delegate.toMutableList()
delegate.clear()
for (element in elements) {
if (hasChanges) {
delegate.add(element)
} else {
if (!oldElements.remove(element)) {
hasChanges = true
}
delegate.add(element)
}
}
if (!hasChanges && oldElements.isNotEmpty()) hasChanges = true
if (hasChanges) {
triggerObservers()
}
return hasChanges
}
override fun addAll(elements: Collection<T>) = delegate.addAll(elements).apply { if (this) triggerObservers() }
override fun removeIf(filter: Predicate<in T>) = delegate.removeIf(filter).apply { if (this) triggerObservers() }
override fun add(element: T) = delegate.add(element).apply { if (this) triggerObservers() }
override fun clear() {
if (delegate.isNotEmpty()) {
delegate.clear(); triggerObservers()
}
}
override fun iterator(): MutableIterator<T> = ObservableIterator(this, delegate.iterator())
override fun remove(element: T) = delegate.remove(element).apply { if (this) triggerObservers() }
override fun removeAll(elements: Collection<T>) =
delegate.removeAll(elements).apply { if (this) triggerObservers() }
override fun retainAll(elements: Collection<T>): Boolean =
delegate.retainAll(elements).apply { if (this) triggerObservers() }
}
actual class ObservableCollection<T>
actual constructor(delegate: MutableCollection<T>, observers: Iterable<(ObservableCollection<T>) -> Unit>) :
ObservableCollectionBase<MutableCollection<T>, T, ObservableCollection<T>>(delegate, observers) {
actual constructor(delegate: MutableCollection<T>, vararg observers: (ObservableCollection<T>) -> Unit) :
this(delegate, observers.toList())
override fun triggerObservers() {
observers.forEach { it(this) }
}
}
actual class ObservableSet<T>
actual constructor(delegate: MutableSet<T>, observers: Iterable<(ObservableSet<T>) -> Unit>) :
ObservableCollectionBase<MutableSet<T>, T, ObservableSet<T>>(delegate, observers), MutableSet<T> {
actual constructor(delegate: MutableSet<T>, vararg observers: (ObservableSet<T>) -> Unit) :
this(delegate, observers.toList())
override fun triggerObservers() {
observers.forEach { it(this) }
}
override fun spliterator(): Spliterator<T> = delegate.spliterator()
override fun toString(): String = joinToString(prefix = "ObservableSet[", postfix = "]")
}
actual class ObservableList<T>
actual constructor(delegate: MutableList<T>, observers: Iterable<(ObservableList<T>) -> Unit>) :
ObservableCollectionBase<MutableList<T>, T, ObservableList<T>>(delegate, observers), List<T> by delegate,
MutableList<T> {
private inner class ObservableListIterator(delegate: MutableListIterator<T>) :
ObservableIterator<T>(this, delegate),
ListIterator<T> by delegate,
MutableListIterator<T> {
override val delegate: MutableListIterator<T> get() = super.delegate as MutableListIterator
override fun add(element: T) {
delegate.add(element)
triggerObservers()
}
override fun set(element: T) {
delegate.set(element)
triggerObservers()
}
override fun hasNext() = super.hasNext()
override fun next() = super.next()
}
actual constructor(delegate: MutableList<T>, vararg observers: (ObservableList<T>) -> Unit) :
this(delegate, observers.toList())
override fun triggerObservers() {
observers.forEach { it(this) }
}
override fun spliterator(): Spliterator<T> = delegate.spliterator()
override fun iterator() = super.iterator()
override fun listIterator(): MutableListIterator<T> = ObservableListIterator(delegate.listIterator())
override fun listIterator(index: Int): MutableListIterator<T> = ObservableListIterator(delegate.listIterator(index))
override fun subList(fromIndex: Int, toIndex: Int): MutableList<T> {
return ObservableList(
delegate.subList(
fromIndex,
toIndex
)
).apply { observers.replaceBy([email protected]) }
}
override fun add(index: Int, element: T) {
delegate.add(index, element)
triggerObservers()
}
override fun addAll(index: Int, elements: Collection<T>) =
delegate.addAll(index, elements).apply { if (this) triggerObservers() }
override fun removeAt(index: Int) = delegate.removeAt(index).apply { triggerObservers() }
override fun set(index: Int, element: T) = delegate.set(index, element).apply { triggerObservers() }
override fun contains(element: T) = delegate.contains(element)
override fun containsAll(elements: Collection<T>) = delegate.containsAll(elements)
override val size: Int get() = delegate.size
override fun isEmpty() = delegate.isEmpty()
override fun toString(): String = joinToString(prefix = "ObservableList[", postfix = "]")
}
| lgpl-3.0 | 472c25fc1df364b56544e65aeb50b49b | 36.36612 | 150 | 0.661889 | 4.696429 | false | false | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/provider/BaseProvider.kt | 1 | 4007 | package com.boardgamegeek.provider
import android.content.ContentResolver
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.database.SQLException
import android.database.sqlite.SQLiteDatabase
import android.net.Uri
import android.os.ParcelFileDescriptor
import androidx.core.app.NotificationCompat
import com.boardgamegeek.R
import com.boardgamegeek.extensions.*
import java.io.FileNotFoundException
abstract class BaseProvider {
open fun getType(uri: Uri): String? {
throw UnsupportedOperationException("Unknown uri getting type: $uri")
}
abstract val path: String
open fun query(
resolver: ContentResolver,
db: SQLiteDatabase,
uri: Uri,
projection: Array<String>?,
selection: String?,
selectionArgs: Array<String>?,
sortOrder: String?
): Cursor? {
val builder = buildExpandedSelection(uri, projection).where(selection, *(selectionArgs.orEmpty()))
builder.limit(uri.getQueryParameter(BggContract.QUERY_KEY_LIMIT))
return builder.query(db, projection, getSortOrder(sortOrder))
}
protected fun getSortOrder(sortOrder: String?): String? {
return sortOrder?.ifBlank { defaultSortOrder } ?: defaultSortOrder
}
protected open val defaultSortOrder: String?
get() = null
protected open fun buildExpandedSelection(uri: Uri, projection: Array<String>?): SelectionBuilder {
return buildExpandedSelection(uri)
}
protected open fun buildExpandedSelection(uri: Uri): SelectionBuilder {
return buildSimpleSelection(uri)
}
protected open fun buildSimpleSelection(uri: Uri): SelectionBuilder {
throw UnsupportedOperationException("Unknown uri: $uri")
}
@Suppress("RedundantNullableReturnType")
open fun insert(context: Context, db: SQLiteDatabase, uri: Uri, values: ContentValues): Uri? {
throw UnsupportedOperationException("Unknown uri inserting: $uri")
}
fun update(context: Context, db: SQLiteDatabase, uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>?): Int {
val rowCount = buildSimpleSelection(uri).where(selection, *(selectionArgs.orEmpty())).update(db, values)
if (rowCount > 0) notifyChange(context, uri)
return rowCount
}
open fun delete(context: Context, db: SQLiteDatabase, uri: Uri, selection: String?, selectionArgs: Array<String>?): Int {
val rowCount = buildSimpleSelection(uri).where(selection, *(selectionArgs.orEmpty())).delete(db)
if (rowCount > 0) notifyChange(context, uri)
return rowCount
}
private fun notifyChange(context: Context, uri: Uri) {
context.contentResolver.notifyChange(uri, null)
}
@Throws(FileNotFoundException::class)
open fun openFile(context: Context, uri: Uri, mode: String): ParcelFileDescriptor? {
throw FileNotFoundException("Unknown uri opening file: $uri")
}
protected fun queryInt(db: SQLiteDatabase, builder: SelectionBuilder, columnName: String, defaultValue: Int = BggContract.INVALID_ID): Int {
builder.query(db, arrayOf(columnName), null).use {
if (it.moveToFirst()) {
return it.getInt(0)
}
}
return defaultValue
}
protected fun notifyException(context: Context?, e: SQLException) {
val prefs = context?.preferences()
if (prefs != null && prefs[KEY_SYNC_NOTIFICATIONS, false] == true) {
val builder = context
.createNotificationBuilder(R.string.title_error, NotificationChannels.ERROR)
.setContentText(e.localizedMessage)
.setCategory(NotificationCompat.CATEGORY_ERROR)
.setStyle(NotificationCompat.BigTextStyle().bigText(e.toString()) .setSummaryText(e.localizedMessage))
context.notify(builder, NotificationTags.PROVIDER_ERROR)
}
}
}
| gpl-3.0 | 582ea0a71b32b055898137abed22247d | 38.284314 | 144 | 0.690791 | 4.946914 | false | false | false | false |
fossasia/open-event-android | app/src/main/java/org/fossasia/openevent/general/sessions/SessionRecyclerAdapter.kt | 2 | 1209 | package org.fossasia.openevent.general.sessions
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import org.fossasia.openevent.general.R
import org.fossasia.openevent.general.common.SessionClickListener
class SessionRecyclerAdapter : RecyclerView.Adapter<SessionViewHolder>() {
private val sessionList = ArrayList<Session>()
var onSessionClick: SessionClickListener? = null
fun addAll(sessionList: List<Session>) {
if (sessionList.isNotEmpty())
this.sessionList.clear()
this.sessionList.addAll(sessionList)
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SessionViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_session, parent, false)
return SessionViewHolder(view)
}
override fun onBindViewHolder(holder: SessionViewHolder, position: Int) {
val session = sessionList[position]
holder.apply {
bind(session)
sessionClickListener = onSessionClick
}
}
override fun getItemCount(): Int {
return sessionList.size
}
}
| apache-2.0 | acfb71cc41b7e21555d30bd6d578541e | 31.675676 | 100 | 0.718776 | 4.894737 | false | false | false | false |
googleapis/gapic-generator-kotlin | generator/src/main/kotlin/com/google/api/kotlin/util/RequestObject.kt | 1 | 5695 | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.api.kotlin.util
import com.google.api.kotlin.GeneratorContext
import com.google.api.kotlin.config.PropertyPath
import com.google.api.kotlin.config.SampleMethod
import com.google.api.kotlin.config.asPropertyPath
import com.google.api.kotlin.config.merge
import com.google.protobuf.DescriptorProtos
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.CodeBlock
/**
* Utility to build a request object for an API method call.
*/
internal object RequestObject {
/**
* A [builder] CodeBlock that can construct an proto object as a Kotlin type
* along with it's corresponding [parameters].
*/
data class BuilderCodeBlock(
val parameters: List<ParameterInfo>,
val builder: CodeBlock
)
/**
* Get a builder CodeBlock for constructing the [messageType] via it's [kotlinType]
* with the given [propertyPaths] setters filled out.
*
* If [sample] is non-null and it contains a property path that matches an entry in
* [propertyPaths] it's value is used for the setter. Otherwise, the property name
* is used as the variable name given to the setter.
*/
fun getBuilder(
context: GeneratorContext,
messageType: DescriptorProtos.DescriptorProto,
kotlinType: ClassName,
propertyPaths: List<PropertyPath>,
sample: SampleMethod? = null
): BuilderCodeBlock {
// params for the method signature
lateinit var parameters: List<ParameterInfo>
// the set of builders to be used to create the request object
val builders = mutableMapOf<String, CodeBlockBuilder>()
// add outermost builder
val code = CodeBlock.builder()
.add("%T {\n", builderName(kotlinType))
.indent()
Flattening.visitType(
context,
messageType,
propertyPaths.merge(sample),
object : Flattening.Visitor() {
override fun onBegin(params: List<ParameterInfo>) {
parameters = params
}
override fun onTerminalParam(paramName: String, currentPath: PropertyPath, fieldInfo: ProtoFieldInfo) {
// check if an explicit value was set for this property
// if not use the parameter name
val explicitValue = sample?.parameters?.find {
it.parameterPath == currentPath.toString()
}
val value = explicitValue?.value ?: paramName
// set value or add to appropriate builder
val setterCode =
FieldNamer.getDslSetterCode(context.typeMap, fieldInfo, value)
if (currentPath.size == 1) {
code.addStatement("%L", setterCode)
} else {
val key = currentPath.takeSubPath(currentPath.size - 1).toString()
builders[key]!!.code.addStatement("%L", setterCode)
}
}
override fun onNestedParam(paramName: String, currentPath: PropertyPath, fieldInfo: ProtoFieldInfo) {
// create a builder for this param, if first time
val key = currentPath.toString()
if (!builders.containsKey(key)) {
val nestedBuilder = CodeBlock.builder()
.add(
"%T {\n",
builderName(context.typeMap.getKotlinType(fieldInfo.field.typeName))
)
.indent()
builders[key] = CodeBlockBuilder(nestedBuilder, fieldInfo)
}
}
override fun onEnd() {
// close the nested builders
builders.forEach { _, builder ->
builder.code
.add("}\n")
.unindent()
}
// build from innermost to outermost
builders.keys.map { it.split(".") }.sortedBy { it.size }.reversed()
.map { it.asPropertyPath() }
.forEach { currentPath ->
val builder = builders[currentPath.toString()]!!
code.add(
FieldNamer.getDslSetterCode(
context.typeMap, builder.fieldInfo, builder.code.build()
)
)
}
}
})
// close outermost builder
code.unindent().add("}")
return BuilderCodeBlock(parameters, code.build())
}
private fun builderName(className: ClassName) = className.peerClass(className.simpleName.decapitalize())
private class CodeBlockBuilder(
val code: CodeBlock.Builder,
val fieldInfo: ProtoFieldInfo
)
} | apache-2.0 | a7f8935a6c53cc34d39bf4a75298da09 | 38.555556 | 119 | 0.562423 | 5.398104 | false | false | false | false |
andreyfomenkov/green-cat | plugin/src/ru/fomenkov/plugin/repository/JetifiedJarRepository.kt | 1 | 4240 | package ru.fomenkov.plugin.repository
import ru.fomenkov.plugin.repository.parser.JetifiedResourceParser
import ru.fomenkov.plugin.util.Telemetry
import ru.fomenkov.plugin.util.noTilda
import ru.fomenkov.plugin.util.timeMillis
import java.io.File
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
class JetifiedJarRepository(
private val parser: JetifiedResourceParser,
) : JarRepository() {
private val cacheDir = "~/.gradle/caches/transforms-3".noTilda() // TODO: search between transforms-X
private val artifactVersions = mutableMapOf<String, Set<String>>() // artifact ID -> available versions
private val artifactPaths = mutableMapOf<Entry, Set<String>>() // artifact entry -> available JARs and AARs
init {
if (!File(cacheDir).exists()) {
error("Gradle cache path doesn't exist: $cacheDir")
}
}
fun getAvailableVersions(artifactId: String) = artifactVersions[artifactId] ?: emptySet()
fun getArtifactPaths(artifactId: String, version: String): Set<String> {
val entry = Entry(artifactId, version)
return artifactPaths[entry] ?: emptySet()
}
override fun scan() {
val cpus = Runtime.getRuntime().availableProcessors()
val executor = Executors.newFixedThreadPool(cpus)
val allResources = mutableSetOf<String>()
val time = timeMillis {
val files = File(cacheDir).listFiles()!! // TODO
val latch = CountDownLatch(files.size)
files.forEach { dir ->
executor.submit {
val dirResources = mutableSetOf<String>()
val transformedDir = File(dir, "transformed")
val dirScanTask = { dir: File ->
if (dir.exists()) {
(dir.list() ?: emptyArray()).forEach { path ->
if (path.endsWith(".jar")) {
dirResources += File(dir, path).absolutePath
}
}
}
}
if (transformedDir.exists()) {
(transformedDir.list() ?: emptyArray()).forEach { resPath ->
if (resPath.endsWith(".jar") || resPath.endsWith(".aar")) {
dirResources += File(transformedDir, resPath).absolutePath
} else {
val jarsDir = File(transformedDir, "$resPath/jars")
val libsDir = File(jarsDir, "libs")
dirScanTask(jarsDir)
dirScanTask(libsDir)
}
}
}
synchronized(allResources) { allResources += dirResources }
latch.countDown()
}
}
latch.await()
executor.shutdown()
parseArtifactPaths(allResources)
}
optimizePaths()
Telemetry.log("Scan jetified JAR files: $time ms")
}
// AAR for a particular artifact already contains JAR => keep JAR, remove AAR
private fun optimizePaths() {
val optimizedPaths = mutableMapOf<Entry, Set<String>>()
artifactPaths.forEach { (entry, paths) ->
val classesJar = paths.firstOrNull { path -> path.endsWith("/classes.jar") }
if (classesJar == null) {
optimizedPaths[entry] = paths
} else {
optimizedPaths[entry] = setOf(classesJar)
}
}
artifactPaths.clear()
artifactPaths += optimizedPaths
}
private fun parseArtifactPaths(allPaths: Set<String>) {
allPaths.forEach { path ->
val entry = parser.parse(path)
val versions = artifactVersions[entry.artifactId] ?: mutableSetOf()
val paths = artifactPaths[entry] ?: emptySet()
artifactVersions[entry.artifactId] = versions + entry.version
artifactPaths[entry] = paths + path
}
}
data class Entry(val artifactId: String, val version: String)
} | apache-2.0 | 615a407708379dc64bc2bee45c7db6b6 | 38.635514 | 111 | 0.550943 | 5.083933 | false | false | false | false |
PtrTeixeira/cookbook | cookbook/server/src/test/kotlin/data/Helpers.kt | 2 | 741 | package cookbook.server.src.test.kotlin.data
import liquibase.Contexts
import liquibase.Liquibase
import liquibase.database.jvm.JdbcConnection
import liquibase.resource.ClassLoaderResourceAccessor
import org.jdbi.v3.core.Jdbi
import org.mockito.Mockito
internal fun jdbi(): Jdbi = Jdbi
.create("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1")
.installPlugins()
.registerArrayType(String::class.java, "varchar")
internal fun migrate(jdbi: Jdbi) = jdbi.inTransaction<Unit, Nothing> {
val connection = JdbcConnection(it.connection)
val liquibase = Liquibase("migrations.xml", ClassLoaderResourceAccessor(), connection)
liquibase.update(Contexts())
}
internal inline fun <reified T : Any> mock(): T = Mockito.mock(T::class.java) | mit | 9c1b551dce5d4a6f75aea5c64ceed217 | 34.333333 | 90 | 0.769231 | 3.614634 | false | true | false | false |
bravelocation/yeltzland-android | app/src/main/java/com/bravelocation/yeltzlandnew/dataproviders/YouTubeChannelXmlParser.kt | 1 | 6251 | package com.bravelocation.yeltzlandnew.dataproviders
import android.util.Log
import android.util.Xml
import com.bravelocation.yeltzlandnew.models.YouTubeVideo
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserException
import java.io.IOException
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
// Adapted from example code at https://developer.android.com/training/basics/network-ops/xml
// We don't use namespaces
private val ns: String? = null
class YouTubeChannelXmlParser {
@Throws(XmlPullParserException::class, IOException::class)
fun parse(xml: String): List<YouTubeVideo> {
xml.byteInputStream().use { inputStream ->
val parser: XmlPullParser = Xml.newPullParser()
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false)
parser.setInput(inputStream, null)
parser.nextTag()
return readFeed(parser)
}
}
@Throws(XmlPullParserException::class, IOException::class)
private fun readFeed(parser: XmlPullParser): List<YouTubeVideo> {
val videos = mutableListOf<YouTubeVideo>()
parser.require(XmlPullParser.START_TAG, ns, "feed")
while (parser.next() != XmlPullParser.END_DOCUMENT) {
if (parser.eventType != XmlPullParser.START_TAG) {
continue
}
// Starts by looking for the entry tag
if (parser.name == "entry") {
val parsedVideo = readEntry(parser)
parsedVideo?.let {
videos.add(parsedVideo)
}
} else {
skip(parser)
}
}
return videos
}
@Throws(XmlPullParserException::class, IOException::class)
private fun readEntry(parser: XmlPullParser): YouTubeVideo? {
parser.require(XmlPullParser.START_TAG, ns, "entry")
var title: String? = null
var videoId: String? = null
var thumbnail: String? = null
var description: String? = null
var published: Date? = null
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.eventType != XmlPullParser.START_TAG) {
continue
}
when (parser.name) {
"title" -> title = readTitle(parser)
"yt:videoId" -> videoId = readVideoId(parser)
"media:group" -> {
val pair = readThumbnailAndDescriptionFromGroup(parser)
thumbnail = pair.first
description = pair.second
}
"published" -> published = readPublished(parser)
else -> skip(parser)
}
}
return if (title != null && videoId != null && thumbnail != null && description != null && published != null) {
YouTubeVideo(title, videoId, thumbnail, description, published)
} else {
Log.d("YouTubeChannelXmlParser", "Not all video attributes are not null")
null
}
}
// Processes title tags in the feed
@Throws(IOException::class, XmlPullParserException::class)
private fun readTitle(parser: XmlPullParser): String {
parser.require(XmlPullParser.START_TAG, ns, "title")
val title = readText(parser)
parser.require(XmlPullParser.END_TAG, ns, "title")
Log.d("YouTubeChannelXmlParser", "Parsed title: $title")
return title
}
// Processes videoId tags in the feed.
@Throws(IOException::class, XmlPullParserException::class)
private fun readVideoId(parser: XmlPullParser): String {
parser.require(XmlPullParser.START_TAG, ns, "yt:videoId")
val videoId = readText(parser)
parser.require(XmlPullParser.END_TAG, ns, "yt:videoId")
Log.d("YouTubeChannelXmlParser", "Parsed videoId: $videoId")
return videoId
}
// Processes thumbnail tags in the feed.
@Throws(IOException::class, XmlPullParserException::class)
private fun readThumbnailAndDescriptionFromGroup(parser: XmlPullParser): Pair<String, String> {
// Read through the media:group nodes
var thumbnail = ""
var description = ""
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.eventType != XmlPullParser.START_TAG) {
continue
}
when (parser.name) {
"media:thumbnail" -> {
thumbnail = parser.getAttributeValue(null, "url")
skip(parser)
}
"media:description" -> description = readText(parser)
else -> skip(parser)
}
}
return Pair(thumbnail, description)
}
// Processes published tags in the feed.
@Throws(IOException::class, XmlPullParserException::class)
private fun readPublished(parser: XmlPullParser): Date? {
parser.require(XmlPullParser.START_TAG, ns, "published")
val published = readText(parser)
parser.require(XmlPullParser.END_TAG, ns, "published")
// Parse the date from the tag text
val dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.UK)
return try {
dateFormat.parse(published)
} catch (e: ParseException) {
Log.d("YouTubeChannelXmlParser", "Date parse exception on $published")
null
}
}
// For the tags extracts their text values.
@Throws(IOException::class, XmlPullParserException::class)
private fun readText(parser: XmlPullParser): String {
var result = ""
if (parser.next() == XmlPullParser.TEXT) {
result = parser.text
parser.nextTag()
}
return result
}
@Throws(XmlPullParserException::class, IOException::class)
private fun skip(parser: XmlPullParser) {
if (parser.eventType != XmlPullParser.START_TAG) {
throw IllegalStateException()
}
var depth = 1
while (depth != 0) {
when (parser.next()) {
XmlPullParser.END_TAG -> depth--
XmlPullParser.START_TAG -> depth++
}
}
}
} | mit | c45a4dac622dbd855d86760776aeb87e | 33.351648 | 119 | 0.599424 | 4.782708 | false | false | false | false |
didi/DoraemonKit | Android/dokit-autotest/src/main/java/com/didichuxing/doraemonkit/kit/autotest/ui/DoKitAutotestConnectFragment.kt | 1 | 2349 | package com.didichuxing.doraemonkit.kit.autotest.ui
import android.os.Bundle
import android.view.View
import android.widget.TextView
import com.didichuxing.doraemonkit.DoKit
import com.didichuxing.doraemonkit.autotest.R
import com.didichuxing.doraemonkit.kit.autotest.AutoTestManager
import com.didichuxing.doraemonkit.kit.connect.ConnectAddress
import com.didichuxing.doraemonkit.kit.connect.ConnectAddressStore
import com.didichuxing.doraemonkit.kit.connect.DoKitConnectFragment
import com.didichuxing.doraemonkit.kit.core.BaseFragment
import com.didichuxing.doraemonkit.util.ToastUtils
/**
* didi Create on 2022/4/14 .
*
* Copyright (c) 2022/4/14 by didiglobal.com.
*
* @author <a href="[email protected]">zhangjun</a>
* @version 1.0
* @Date 2022/4/14 4:40 下午
* @Description 用一句话说明文件功能
*/
class DoKitAutotestConnectFragment : BaseFragment() {
private var urlTextView: TextView? = null
private var address: ConnectAddress? = null
override fun onRequestLayout(): Int {
return R.layout.dk_fragment_autotest_connect
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
urlTextView = view.findViewById<TextView>(R.id.url)
view.findViewById<View>(R.id.connect).setOnClickListener {
starConnect()
}
view.findViewById<View>(R.id.change).setOnClickListener {
startChange()
}
}
override fun onResume() {
super.onResume()
updateUrl()
}
private fun updateUrl() {
val list = ConnectAddressStore.loadAddress()
if (list.size > 0) {
address = list[list.size - 1]
}
address?.let {
urlTextView?.text = "可使用地址:${it.url}"
} ?: run {
urlTextView?.text = "可使用地址:--}"
}
}
private fun starConnect() {
if (address == null) {
ToastUtils.showShort("无可用地址,请添加")
} else {
address?.let {
AutoTestManager.startConnect(it)
finish()
}
}
}
private fun startChange() {
//使用统一的链接管理
DoKit.launchFullScreen(DoKitConnectFragment::class.java, context, null, false)
}
}
| apache-2.0 | 6d85ae050a1a547ed74446cda7c0ad7a | 25.694118 | 86 | 0.651388 | 4.125455 | false | true | false | false |
wiltonlazary/kotlin-native | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/llvm/coverage/LLVMCoverageWriter.kt | 1 | 3834 | /*
* Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package org.jetbrains.kotlin.backend.konan.llvm.coverage
import kotlinx.cinterop.*
import llvm.*
import org.jetbrains.kotlin.backend.konan.Context
import org.jetbrains.kotlin.backend.konan.llvm.name
import org.jetbrains.kotlin.backend.konan.llvm.symbolName
import org.jetbrains.kotlin.ir.declarations.IrFile
import org.jetbrains.kotlin.ir.declarations.name
import org.jetbrains.kotlin.ir.declarations.path
import org.jetbrains.kotlin.konan.file.File
private fun RegionKind.toLLVMCoverageRegionKind(): LLVMCoverageRegionKind = when (this) {
RegionKind.Code -> LLVMCoverageRegionKind.CODE
RegionKind.Gap -> LLVMCoverageRegionKind.GAP
is RegionKind.Expansion -> LLVMCoverageRegionKind.EXPANSION
}
private fun LLVMCoverageRegion.populateFrom(region: Region, regionId: Int, filesIndex: Map<IrFile, Int>) = apply {
fileId = filesIndex.getValue(region.file)
lineStart = region.startLine
columnStart = region.startColumn
lineEnd = region.endLine
columnEnd = region.endColumn
counterId = regionId
kind = region.kind.toLLVMCoverageRegionKind()
expandedFileId = if (region.kind is RegionKind.Expansion) filesIndex.getValue(region.kind.expandedFile) else 0
}
/**
* Writes all of the coverage information to the [org.jetbrains.kotlin.backend.konan.Context.llvmModule].
* See http://llvm.org/docs/CoverageMappingFormat.html for the format description.
*/
internal class LLVMCoverageWriter(
private val context: Context,
private val filesRegionsInfo: List<FileRegionInfo>
) {
fun write() {
if (filesRegionsInfo.isEmpty()) return
val module = context.llvmModule
?: error("LLVM module should be initialized.")
val filesIndex = filesRegionsInfo.mapIndexed { index, fileRegionInfo -> fileRegionInfo.file to index }.toMap()
val coverageGlobal = memScoped {
val (functionMappingRecords, functionCoverages) = filesRegionsInfo.flatMap { it.functions }.map { functionRegions ->
val regions = (functionRegions.regions.values).map { region ->
alloc<LLVMCoverageRegion>().populateFrom(region, functionRegions.regionEnumeration.getValue(region), filesIndex).ptr
}
val fileIds = functionRegions.regions.map { filesIndex.getValue(it.value.file) }.toSet().toIntArray()
val functionCoverage = LLVMWriteCoverageRegionMapping(
fileIds.toCValues(), fileIds.size.signExtend(),
regions.toCValues(), regions.size.signExtend())
val functionName = context.llvmDeclarations.forFunction(functionRegions.function).llvmFunction.name
val functionMappingRecord = LLVMAddFunctionMappingRecord(LLVMGetModuleContext(context.llvmModule),
functionName, functionRegions.structuralHash, functionCoverage)!!
Pair(functionMappingRecord, functionCoverage)
}.unzip()
val (filenames, fileIds) = filesIndex.entries.toList().map { File(it.key.path).absolutePath to it.value }.unzip()
val retval = LLVMCoverageEmit(module, functionMappingRecords.toCValues(), functionMappingRecords.size.signExtend(),
filenames.toCStringArray(this), fileIds.toIntArray().toCValues(), fileIds.size.signExtend(),
functionCoverages.map { it }.toCValues(), functionCoverages.size.signExtend())!!
// TODO: Is there a better way to cleanup fields of T* type in `memScoped`?
functionCoverages.forEach { LLVMFunctionCoverageDispose(it) }
retval
}
context.llvm.usedGlobals.add(coverageGlobal)
}
}
| apache-2.0 | 548deb7ca040abc3f5d106fc1556c319 | 48.792208 | 136 | 0.708659 | 4.526564 | false | false | false | false |
wiltonlazary/kotlin-native | shared/src/main/kotlin/org/jetbrains/kotlin/konan/target/KonanTargetExtenstions.kt | 1 | 930 | package org.jetbrains.kotlin.konan.target
fun KonanTarget.supportsCodeCoverage(): Boolean =
this == KonanTarget.MINGW_X64 ||
this == KonanTarget.LINUX_X64 ||
this == KonanTarget.MACOS_X64 ||
this == KonanTarget.IOS_X64
fun KonanTarget.supportsMimallocAllocator(): Boolean =
when(this) {
is KonanTarget.LINUX_X64 -> true
is KonanTarget.MINGW_X86 -> true
is KonanTarget.MINGW_X64 -> true
is KonanTarget.MACOS_X64 -> true
is KonanTarget.LINUX_ARM64 -> true
is KonanTarget.LINUX_ARM32_HFP -> true
is KonanTarget.ANDROID_X64 -> true
is KonanTarget.ANDROID_ARM64 -> true
is KonanTarget.IOS_ARM32 -> true
is KonanTarget.IOS_ARM64 -> true
is KonanTarget.IOS_X64 -> true
else -> false // watchOS/tvOS/android_x86/android_arm32 aren't tested; linux_mips32/linux_mipsel32 need linking with libatomic.
} | apache-2.0 | 487a5f65a030dafed32e9ba899ba5198 | 39.478261 | 135 | 0.653763 | 3.974359 | false | false | false | false |
goodwinnk/intellij-community | platform/platform-impl/src/com/intellij/openapi/application/impl/AppUIExecutorEx.kt | 1 | 2241 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.application.impl
import com.intellij.openapi.application.AppUIExecutor
import kotlinx.coroutines.experimental.Runnable
import kotlinx.coroutines.experimental.async
import kotlinx.coroutines.experimental.launch
import kotlinx.coroutines.experimental.withContext
import org.jetbrains.concurrency.AsyncPromise
import org.jetbrains.concurrency.CancellablePromise
import java.util.concurrent.Callable
import kotlin.coroutines.experimental.coroutineContext
/**
* @author eldar
*/
interface AppUIExecutorEx : AppUIExecutor, AsyncExecution<AppUIExecutorEx> {
override fun execute(command: Runnable) {
// Note, that launch() is different from async() used by submit():
//
// - processing of async() errors thrown by the command are deferred
// until the Deferred.await() is called on the result,
//
// - errors thrown within launch() are not caught, and usually result in an error
// message with a stack trace to be logged on the corresponding thread.
//
launch(createJobContext()) {
command.run()
}
}
override fun submit(task: Runnable): CancellablePromise<*> {
return submit<Any> {
task.run()
null
}
}
override fun <T> submit(task: Callable<T>): CancellablePromise<T> {
val deferred = async(createJobContext()) {
task.call()
}
return AsyncPromise<T>().apply {
onError { cause -> deferred.cancel(cause) }
deferred.invokeOnCompletion {
try {
val result = deferred.getCompleted()
setResult(result)
}
catch (e: Throwable) {
setError(e)
}
}
}
}
fun inUndoTransparentAction(): AppUIExecutor
fun inWriteAction(): AppUIExecutor
}
fun AppUIExecutor.inUndoTransparentAction() =
(this as AppUIExecutorEx).inUndoTransparentAction()
fun AppUIExecutor.inWriteAction() =
(this as AppUIExecutorEx).inWriteAction()
suspend fun <T> AppUIExecutor.runCoroutine(block: suspend () -> T): T =
withContext((this as AsyncExecution<*>).createJobContext(coroutineContext)) {
block()
}
| apache-2.0 | 789f9b488d886af48195f518385b9ccb | 30.56338 | 140 | 0.705042 | 4.564155 | false | false | false | false |
DankBots/Mega-Gnar | src/main/kotlin/gg/octave/bot/music/sources/spotify/SpotifyAudioSourceManager.kt | 1 | 6806 | package gg.octave.bot.music.sources.spotify
import com.sedmelluq.discord.lavaplayer.player.DefaultAudioPlayerManager
import com.sedmelluq.discord.lavaplayer.source.AudioSourceManager
import com.sedmelluq.discord.lavaplayer.source.youtube.YoutubeAudioSourceManager
import com.sedmelluq.discord.lavaplayer.tools.FriendlyException
import com.sedmelluq.discord.lavaplayer.tools.io.HttpClientTools
import com.sedmelluq.discord.lavaplayer.track.AudioItem
import com.sedmelluq.discord.lavaplayer.track.AudioReference
import com.sedmelluq.discord.lavaplayer.track.AudioTrack
import com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo
import gg.octave.bot.music.sources.spotify.loaders.SpotifyAlbumLoader
import gg.octave.bot.music.sources.spotify.loaders.SpotifyPlaylistLoader
import gg.octave.bot.music.sources.spotify.loaders.SpotifyTrackLoader
import org.apache.http.HttpStatus
import org.apache.http.client.methods.CloseableHttpResponse
import org.apache.http.client.methods.HttpGet
import org.apache.http.client.methods.HttpPost
import org.apache.http.client.methods.RequestBuilder
import org.apache.http.entity.StringEntity
import org.apache.http.util.EntityUtils
import org.json.JSONObject
import org.slf4j.LoggerFactory
import java.io.DataInput
import java.io.DataOutput
import java.util.*
import java.util.concurrent.CompletableFuture
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
class SpotifyAudioSourceManager(
private val clientId: String?,
private val clientSecret: String?,
private val youtubeAudioSourceManager: YoutubeAudioSourceManager
) : AudioSourceManager {
private val sched = Executors.newSingleThreadScheduledExecutor()
private val trackLoaderPool = Executors.newFixedThreadPool(10)
private val httpInterfaceManager = HttpClientTools.createDefaultThreadLocalManager()!!
internal var accessToken: String = ""
private set
val enabled: Boolean
get() = "" != clientId && "" != clientSecret
init {
if (enabled) {
refreshAccessToken()
}
}
/**
* Source manager shizzle
*/
override fun getSourceName() = "spotify"
override fun isTrackEncodable(track: AudioTrack) = false
override fun decodeTrack(trackInfo: AudioTrackInfo, input: DataInput): AudioTrack {
throw UnsupportedOperationException("${this::class.java.simpleName} does not support track decoding.")
}
override fun encodeTrack(track: AudioTrack, output: DataOutput) {
throw UnsupportedOperationException("${this::class.java.simpleName} does not support track encoding.")
}
override fun shutdown() {
httpInterfaceManager.close()
}
override fun loadItem(manager: DefaultAudioPlayerManager, reference: AudioReference): AudioItem? {
if (accessToken.isEmpty()) {
return null
}
return try {
loadItemOnce(manager, reference.identifier)
} catch (exception: FriendlyException) {
// In case of a connection reset exception, try once more.
if (HttpClientTools.isRetriableNetworkException(exception.cause)) {
loadItemOnce(manager, reference.identifier)
} else {
throw exception
}
}
}
private fun loadItemOnce(manager: DefaultAudioPlayerManager, identifier: String): AudioItem? {
for (loader in loaders) {
val matcher = loader.pattern().matcher(identifier)
if (matcher.find()) {
return loader.load(manager, this, matcher)
}
}
return null
}
internal fun doYoutubeSearch(manager: DefaultAudioPlayerManager, identifier: String): AudioItem? {
val reference = AudioReference(identifier, null)
return youtubeAudioSourceManager.loadItem(manager, reference)
}
internal fun queueYoutubeSearch(manager: DefaultAudioPlayerManager, identifier: String): CompletableFuture<AudioItem?> {
val future = CompletableFuture<AudioItem?>()
trackLoaderPool.submit {
val reference = AudioReference(identifier, null)
try {
val result = youtubeAudioSourceManager.loadItem(manager, reference)
future.complete(result)
} catch (e: Exception) {
future.completeExceptionally(e)
}
}
return future
}
/**
* Spotify shizzle
*/
private fun refreshAccessToken() {
if (!enabled) {
return
}
val base64Auth = Base64.getEncoder().encodeToString("$clientId:$clientSecret".toByteArray())
request(HttpPost.METHOD_NAME, "https://accounts.spotify.com/api/token") {
addHeader("Authorization", "Basic $base64Auth")
addHeader("Content-Type", "application/x-www-form-urlencoded")
entity = StringEntity("grant_type=client_credentials")
}.use {
if (it.statusLine.statusCode != HttpStatus.SC_OK) {
log.warn("Received code ${it.statusLine.statusCode} from Spotify while trying to update access token!")
sched.schedule(::refreshAccessToken, 1, TimeUnit.MINUTES)
return
}
val content = EntityUtils.toString(it.entity)
val json = JSONObject(content)
if (json.has("error") && json.getString("error").startsWith("invalid_")) {
log.error("Spotify API access disabled (${json.getString("error")})")
accessToken = ""
return
}
val refreshIn = json.getInt("expires_in")
accessToken = json.getString("access_token")
sched.schedule(::refreshAccessToken, ((refreshIn * 1000) - 10000).toLong(), TimeUnit.MILLISECONDS)
val snippet = accessToken.substring(0..4).padEnd(accessToken.length - 5, '*') // lol imagine printing the entire token
log.info("Updated access token to $snippet")
}
}
/**
* Utils boiiii
*/
internal fun request(url: String, requestBuilder: RequestBuilder.() -> Unit): CloseableHttpResponse {
return request(HttpGet.METHOD_NAME, url, requestBuilder)
}
internal fun request(method: String, url: String, requestBuilder: RequestBuilder.() -> Unit): CloseableHttpResponse {
return httpInterfaceManager.`interface`.use {
it.execute(RequestBuilder.create(method).setUri(url).apply(requestBuilder).build())
}
}
companion object {
private val log = LoggerFactory.getLogger(SpotifyAudioSourceManager::class.java)
private val loaders = listOf(
SpotifyAlbumLoader(),
SpotifyPlaylistLoader(),
SpotifyTrackLoader()
)
}
}
| mit | 0a4731c785ff36859a57bd7dfa0e4aa5 | 35.395722 | 130 | 0.677197 | 4.864904 | false | false | false | false |
ohmae/mmupnp | mmupnp/src/test/java/net/mm2d/upnp/internal/server/MulticastEventReceiverListTest.kt | 1 | 2252 | /*
* Copyright (c) 2019 大前良介 (OHMAE Ryosuke)
*
* This software is released under the MIT License.
* http://opensource.org/licenses/MIT
*/
package net.mm2d.upnp.internal.server
import com.google.common.truth.Truth.assertThat
import io.mockk.every
import io.mockk.mockk
import io.mockk.mockkObject
import io.mockk.mockkStatic
import io.mockk.unmockkObject
import io.mockk.unmockkStatic
import io.mockk.verify
import net.mm2d.upnp.Protocol
import net.mm2d.upnp.util.isAvailableInet4Interface
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import java.net.NetworkInterface
@Suppress("TestFunctionName", "NonAsciiCharacters")
@RunWith(JUnit4::class)
class MulticastEventReceiverListTest {
private lateinit var nif: NetworkInterface
@Before
fun setUp() {
nif = mockk(relaxed = true)
mockkStatic("net.mm2d.upnp.util.NetworkUtilsKt")
every { nif.isAvailableInet4Interface() } returns true
}
@After
fun tearDown() {
unmockkStatic("net.mm2d.upnp.util.NetworkUtilsKt")
}
@Test
fun start() {
mockkObject(MulticastEventReceiverList.Companion)
val receiver: MulticastEventReceiver = mockk(relaxed = true)
every { MulticastEventReceiverList.newReceiver(any(), any(), any(), any()) } returns receiver
val list = MulticastEventReceiverList(mockk(), Protocol.DEFAULT, listOf(nif), mockk())
list.start()
verify(exactly = 1) { receiver.start() }
unmockkObject(MulticastEventReceiverList.Companion)
}
@Test
fun stop() {
mockkObject(MulticastEventReceiverList.Companion)
val receiver: MulticastEventReceiver = mockk(relaxed = true)
every { MulticastEventReceiverList.newReceiver(any(), any(), any(), any()) } returns receiver
val list = MulticastEventReceiverList(mockk(), Protocol.DEFAULT, listOf(nif), mockk())
list.stop()
verify(exactly = 1) { receiver.stop() }
unmockkObject(MulticastEventReceiverList.Companion)
}
@Test
fun newReceiver() {
assertThat(MulticastEventReceiverList.newReceiver(mockk(), Address.IP_V4, nif, mockk())).isNull()
}
}
| mit | 055eac3633ae11a1e7840a78c2e6fb98 | 29.324324 | 105 | 0.708556 | 4.210131 | false | true | false | false |
soywiz/korge | korge/src/nativeCommonMain/kotlin/com/soywiz/korge/native/KorgeSimpleNativeSyncIO.kt | 1 | 1496 | package com.soywiz.korge.native
import kotlinx.cinterop.*
import platform.posix.*
object KorgeSimpleNativeSyncIO {
fun mkdirs(file: String) {
com.soywiz.korio.doMkdir(file, "0777".toInt(8))
}
fun writeBytes(file: String, bytes: ByteArray) {
val fd = fopen(file, "wb") ?: error("Can't open file '$file' for writing")
try {
if (bytes.isNotEmpty()) {
memScoped {
bytes.usePinned { pin ->
fwrite(pin.addressOf(0), 1.convert(), bytes.size.convert(), fd)
}
}
}
} finally {
fclose(fd)
}
}
fun readBytes(file: String): ByteArray {
val fd = fopen(file, "rb") ?: error("Can't open file '$file' for reading")
try {
fseek(fd, 0L.convert(), SEEK_END)
val fileSize = ftell(fd)
fseek(fd, 0L.convert(), SEEK_SET)
val out = ByteArray(fileSize.toInt())
if (out.isNotEmpty()) {
memScoped {
out.usePinned { pin ->
@Suppress("UNUSED_VARIABLE")
val readCount = fread(pin.addressOf(0), 1.convert(), out.size.convert(), fd)
//println("readCount: $readCount, out.size=${out.size}, fileSize=$fileSize")
}
}
}
return out
} finally {
fclose(fd)
}
}
}
| apache-2.0 | 26eba85e028c274059361435ac67eb3b | 30.166667 | 100 | 0.472594 | 4.274286 | false | false | false | false |
ojacquemart/spring-kotlin-euro-bets | src/test/kotlin/org/ojacquemart/eurobets/firebase/management/table/DatasourceForTest.kt | 2 | 5681 | package org.ojacquemart.eurobets.firebase.management.table
import org.ojacquemart.eurobets.firebase.management.match.Match
import org.ojacquemart.eurobets.firebase.management.match.Phase
import org.ojacquemart.eurobets.firebase.management.match.Team
import org.ojacquemart.eurobets.firebase.management.user.User
import org.ojacquemart.eurobets.firebase.support.PhaseType
class DatasourceForTest {
companion object {
val phaseGroup = Phase(state = PhaseType.GROUP.state)
val phaseRound16 = Phase(state = PhaseType.ROUND_16.state)
val phaseQuarter = Phase(state = PhaseType.QUARTER.state)
val phaseSemi = Phase(state = PhaseType.SEMI.state)
val phaseFinal = Phase(state = PhaseType.FINAL.state)
val homeWinner_1_0 = Match(number = 1, phase = phaseGroup, home = Team(goals = 1), away = Team(goals = 0))
val awayWinner_0_1 = Match(number = 2, phase = phaseGroup, home = Team(goals = 0), away = Team(goals = 1))
val draw_1_1 = Match(number = 3, phase = phaseGroup, home = Team(goals = 1), away = Team(goals = 1))
val match1_1_0 = homeWinner_1_0
val match2_0_1 = awayWinner_0_1
val match3_1_1 = draw_1_1
val match4_2_4 = homeWinner_1_0.copy(number = 4, home = Team(goals = 2), away = Team(goals = 4))
val match5_2_2 = homeWinner_1_0.copy(number = 5, home = Team(goals = 2), away = Team(goals = 2))
val match6_1_0 = homeWinner_1_0.copy(number = 6, phase = phaseRound16, home = Team(goals = 1), away = Team(goals = 0))
val match7_2_0 = homeWinner_1_0.copy(number = 7, phase = phaseRound16, home = Team(goals = 2), away = Team(goals = 0))
val matches = listOf(match1_1_0, match2_0_1, match3_1_1, match4_2_4, match5_2_2, match6_1_0, match7_2_0)
// baz: start game on round16, 2 round16 perfect matches = 50 pts
val baz = User(uid = "baz", displayName = "Baz", profileImageURL = "baz.png")
// foo: perfect bets on 5 first matches = 50pts
val foo = User(uid = "foo", displayName = "Foo", profileImageURL = "foo.png")
// bar: only good bets on 5 first matches = 15pts
val bar = User(uid = "bar", displayName = "Bar", profileImageURL = "bar.png")
// qix: always losing... = 0pt
val qix = User(uid = "qix", displayName = "Qix", profileImageURL = "qix.png")
// bee: never betting = not in the table
val bee = User(uid = "bee", displayName = "Bee", profileImageURL = "bee.png")
// foo should be first because of its number of perfect bets
val bets = listOf(
// foo
BetData(match = match1_1_0, user = foo, bet = Bet(homeGoals = 1, awayGoals = 0)),
BetData(match = match2_0_1, user = foo, bet = Bet(homeGoals = 0, awayGoals = 1)),
BetData(match = match3_1_1, user = foo, bet = Bet(homeGoals = 1, awayGoals = 1)),
BetData(match = match4_2_4, user = foo, bet = Bet(homeGoals = 2, awayGoals = 4)),
BetData(match = match5_2_2, user = foo, bet = Bet(homeGoals = 2, awayGoals = 2)),
BetData(match = match6_1_0, user = foo, bet = null),
BetData(match = match7_2_0, user = foo, bet = null),
// baz
BetData(match = match1_1_0, user = baz, bet = null),
BetData(match = match2_0_1, user = baz, bet = null),
BetData(match = match3_1_1, user = baz, bet = null),
BetData(match = match4_2_4, user = baz, bet = null),
BetData(match = match5_2_2, user = baz, bet = null),
BetData(match = match6_1_0, user = baz, bet = Bet(homeGoals = 1, awayGoals = 0)),
BetData(match = match7_2_0, user = baz, bet = Bet(homeGoals = 2, awayGoals = 0)),
// bar
BetData(match = match1_1_0, user = bar, bet = Bet(homeGoals = 2, awayGoals = 0)),
BetData(match = match2_0_1, user = bar, bet = Bet(homeGoals = 0, awayGoals = 2)),
BetData(match = match3_1_1, user = bar, bet = Bet(homeGoals = 2, awayGoals = 2)),
BetData(match = match4_2_4, user = bar, bet = Bet(homeGoals = 0, awayGoals = 1)),
BetData(match = match5_2_2, user = bar, bet = Bet(homeGoals = 0, awayGoals = 0)),
BetData(match = match6_1_0, user = bar, bet = null),
BetData(match = match7_2_0, user = bar, bet = null),
// qix
BetData(match = match1_1_0, user = qix, bet = Bet(homeGoals = 0, awayGoals = 1)),
BetData(match = match2_0_1, user = qix, bet = Bet(homeGoals = 1, awayGoals = 0)),
BetData(match = match3_1_1, user = qix, bet = Bet(homeGoals = 1, awayGoals = 0)),
BetData(match = match4_2_4, user = qix, bet = Bet(homeGoals = 1, awayGoals = 0)),
BetData(match = match5_2_2, user = qix, bet = Bet(homeGoals = 1, awayGoals = 0)),
BetData(match = match6_1_0, user = qix, bet = Bet(homeGoals = 0, awayGoals = 1)),
BetData(match = match7_2_0, user = qix, bet = Bet(homeGoals = 0, awayGoals = 1)),
// bee
BetData(match = match1_1_0, user = bee, bet = null),
BetData(match = match2_0_1, user = bee, bet = null),
BetData(match = match3_1_1, user = bee, bet = null),
BetData(match = match4_2_4, user = bee, bet = null),
BetData(match = match5_2_2, user = bee, bet = null),
BetData(match = match6_1_0, user = bee, bet = null),
BetData(match = match7_2_0, user = bee, bet = null)
)
}
}
| unlicense | 39877527570d60e160d584a7f1eb0328 | 60.086022 | 126 | 0.57085 | 3.405875 | false | false | false | false |
android/security-samples | BiometricLoginKotlin/app/src/main/java/com/example/biometricloginsample/CryptographyManager.kt | 1 | 5713 | /*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package com.example.biometricloginsample
import android.content.Context
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import com.google.gson.Gson
import java.nio.charset.Charset
import java.security.KeyStore
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec
/**
* Handles encryption and decryption
*/
interface CryptographyManager {
fun getInitializedCipherForEncryption(keyName: String): Cipher
fun getInitializedCipherForDecryption(keyName: String, initializationVector: ByteArray): Cipher
/**
* The Cipher created with [getInitializedCipherForEncryption] is used here
*/
fun encryptData(plaintext: String, cipher: Cipher): CiphertextWrapper
/**
* The Cipher created with [getInitializedCipherForDecryption] is used here
*/
fun decryptData(ciphertext: ByteArray, cipher: Cipher): String
fun persistCiphertextWrapperToSharedPrefs(
ciphertextWrapper: CiphertextWrapper,
context: Context,
filename: String,
mode: Int,
prefKey: String
)
fun getCiphertextWrapperFromSharedPrefs(
context: Context,
filename: String,
mode: Int,
prefKey: String
): CiphertextWrapper?
}
fun CryptographyManager(): CryptographyManager = CryptographyManagerImpl()
/**
* To get an instance of this private CryptographyManagerImpl class, use the top-level function
* fun CryptographyManager(): CryptographyManager = CryptographyManagerImpl()
*/
private class CryptographyManagerImpl : CryptographyManager {
private val KEY_SIZE = 256
private val ANDROID_KEYSTORE = "AndroidKeyStore"
private val ENCRYPTION_BLOCK_MODE = KeyProperties.BLOCK_MODE_GCM
private val ENCRYPTION_PADDING = KeyProperties.ENCRYPTION_PADDING_NONE
private val ENCRYPTION_ALGORITHM = KeyProperties.KEY_ALGORITHM_AES
override fun getInitializedCipherForEncryption(keyName: String): Cipher {
val cipher = getCipher()
val secretKey = getOrCreateSecretKey(keyName)
cipher.init(Cipher.ENCRYPT_MODE, secretKey)
return cipher
}
override fun getInitializedCipherForDecryption(
keyName: String,
initializationVector: ByteArray
): Cipher {
val cipher = getCipher()
val secretKey = getOrCreateSecretKey(keyName)
cipher.init(Cipher.DECRYPT_MODE, secretKey, GCMParameterSpec(128, initializationVector))
return cipher
}
override fun encryptData(plaintext: String, cipher: Cipher): CiphertextWrapper {
val ciphertext = cipher.doFinal(plaintext.toByteArray(Charset.forName("UTF-8")))
return CiphertextWrapper(ciphertext, cipher.iv)
}
override fun decryptData(ciphertext: ByteArray, cipher: Cipher): String {
val plaintext = cipher.doFinal(ciphertext)
return String(plaintext, Charset.forName("UTF-8"))
}
private fun getCipher(): Cipher {
val transformation = "$ENCRYPTION_ALGORITHM/$ENCRYPTION_BLOCK_MODE/$ENCRYPTION_PADDING"
return Cipher.getInstance(transformation)
}
private fun getOrCreateSecretKey(keyName: String): SecretKey {
// If Secretkey was previously created for that keyName, then grab and return it.
val keyStore = KeyStore.getInstance(ANDROID_KEYSTORE)
keyStore.load(null) // Keystore must be loaded before it can be accessed
keyStore.getKey(keyName, null)?.let { return it as SecretKey }
// if you reach here, then a new SecretKey must be generated for that keyName
val paramsBuilder = KeyGenParameterSpec.Builder(
keyName,
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
)
paramsBuilder.apply {
setBlockModes(ENCRYPTION_BLOCK_MODE)
setEncryptionPaddings(ENCRYPTION_PADDING)
setKeySize(KEY_SIZE)
setUserAuthenticationRequired(true)
}
val keyGenParams = paramsBuilder.build()
val keyGenerator = KeyGenerator.getInstance(
KeyProperties.KEY_ALGORITHM_AES,
ANDROID_KEYSTORE
)
keyGenerator.init(keyGenParams)
return keyGenerator.generateKey()
}
override fun persistCiphertextWrapperToSharedPrefs(
ciphertextWrapper: CiphertextWrapper,
context: Context,
filename: String,
mode: Int,
prefKey: String
) {
val json = Gson().toJson(ciphertextWrapper)
context.getSharedPreferences(filename, mode).edit().putString(prefKey, json).apply()
}
override fun getCiphertextWrapperFromSharedPrefs(
context: Context,
filename: String,
mode: Int,
prefKey: String
): CiphertextWrapper? {
val json = context.getSharedPreferences(filename, mode).getString(prefKey, null)
return Gson().fromJson(json, CiphertextWrapper::class.java)
}
}
data class CiphertextWrapper(val ciphertext: ByteArray, val initializationVector: ByteArray) | apache-2.0 | f2434fea7b65e29be04ff5c26db6b670 | 34.271605 | 99 | 0.712235 | 4.772765 | false | false | false | false |
doerfli/hacked | app/src/main/kotlin/li/doerf/hacked/ui/fragments/AllBreachesFragment.kt | 1 | 5225 | package li.doerf.hacked.ui.fragments
import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.*
import android.widget.EditText
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.navigation.fragment.navArgs
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.work.Constraints
import androidx.work.NetworkType
import androidx.work.OneTimeWorkRequest
import androidx.work.WorkManager
import li.doerf.hacked.R
import li.doerf.hacked.db.entities.BreachedSite
import li.doerf.hacked.remote.hibp.BreachedSitesWorker
import li.doerf.hacked.ui.HibpInfo
import li.doerf.hacked.ui.adapters.BreachedSitesAdapter
import li.doerf.hacked.ui.viewmodels.BreachedSitesViewModel
import java.util.*
/**
* A simple [Fragment] subclass.
* create an instance of this fragment.
*/
class AllBreachesFragment : Fragment() {
private val breachedSitesViewModel: BreachedSitesViewModel by viewModels()
private lateinit var layoutManager: LinearLayoutManager
private var breachedSiteId: Long = -1
private lateinit var breachedSitesAdapter: BreachedSitesAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
val args: AllBreachesFragmentArgs by navArgs()
breachedSiteId = args.breachedSiteId
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val fragmentRootView = inflater.inflate(R.layout.fragment_all_breaches, container, false)
val breachedSites: RecyclerView = fragmentRootView.findViewById(R.id.breached_sites_list)
// breachedSites.setHasFixedSize(true)
layoutManager = LinearLayoutManager(context)
breachedSites.layoutManager = layoutManager
breachedSitesAdapter = BreachedSitesAdapter(requireActivity().applicationContext, ArrayList(), false)
breachedSites.adapter = breachedSitesAdapter
HibpInfo.prepare(context, fragmentRootView.findViewById(R.id.hibp_info), breachedSites)
val filter = fragmentRootView.findViewById<EditText>(R.id.filter)
filter.addTextChangedListener { watcher ->
Log.d(LOGTAG, "breaches filter: $watcher")
breachedSitesViewModel.setFilter(watcher.toString())
}
return fragmentRootView
}
override fun onAttach(context: Context) {
super.onAttach(context)
breachedSitesViewModel.breachesSites!!.observe(this, Observer { sites: List<BreachedSite> ->
sites.find { it.id == breachedSiteId }?.detailsVisible = true
breachedSitesAdapter.addItems(sites)
if (breachedSiteId > -1 && sites.isNotEmpty()) {
val position = sites.indexOfFirst { it.id == breachedSiteId }
if (position > -1) {
layoutManager.scrollToPositionWithOffset(position, 0)
}
}
})
}
override fun onResume() {
super.onResume()
if (breachedSitesAdapter.itemCount == 0 ) {
reloadBreachedSites(requireActivity())
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
return inflater.inflate(R.menu.menu_fragment_allbreaches, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.sort_by_name) {
breachedSitesViewModel.orderByName()
return true
}
if (item.itemId == R.id.sort_by_count) {
breachedSitesViewModel.orderByCount()
return true
}
if (item.itemId == R.id.sort_by_date) {
breachedSitesViewModel.orderByDate()
return true
}
return super.onOptionsItemSelected(item)
}
companion object {
private const val LOGTAG = "AllBreachesFragment"
private const val PREF_KEY_LAST_BREACHED_SITES_SYNC = "PREF_KEY_LAST_BREACHED_SITES_SYNC"
private const val SIXHOURS = 6 * 60 * 60 * 1000
fun reloadBreachedSites(activity: Activity) {
val sharedPref = activity.getPreferences(Context.MODE_PRIVATE) ?: return
val lastSync = sharedPref.getLong(PREF_KEY_LAST_BREACHED_SITES_SYNC, 0)
if (System.currentTimeMillis() - lastSync > SIXHOURS) {
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.UNMETERED)
.build()
val checker = OneTimeWorkRequest.Builder(BreachedSitesWorker::class.java)
.setConstraints(constraints)
.build()
WorkManager.getInstance(activity.applicationContext).enqueue(checker)
with (sharedPref.edit()) {
putLong(PREF_KEY_LAST_BREACHED_SITES_SYNC, System.currentTimeMillis())
commit()
}
}
}
}
}
| apache-2.0 | 283b4a2cabc49bc6601722ebf3eda1cb | 37.703704 | 109 | 0.675789 | 4.6819 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/dataclient/okhttp/AvailableInputStream.kt | 1 | 2189 | package org.wikipedia.dataclient.okhttp
import java.io.IOException
import java.io.InputStream
/**
* This is a subclass of InputStream that implements the available() method reliably enough
* to satisfy WebResourceResponses or other consumers like BufferedInputStream that depend
* on available() to return a meaningful value.
*
* The problem is that the InputStream provided by OkHttp's body().byteStream() returns zero
* when calling available() prior to making any read() calls, which means that it will break
* any consumers that wrap a BufferedInputStream onto this stream, or any other wrapper that
* relies on a consistent implementation of available().
*
* This is initialized with the original InputStream plus its total size, which must be known
* at the time of instantiation. You may then call the read() and skip() methods in the usual
* way, and then be able to call available() and get the number of bytes left to read.
*/
class AvailableInputStream(private val stream: InputStream, private var available: Long) : InputStream() {
@Throws(IOException::class)
override fun read(): Int {
decreaseAvailable(1)
return stream.read()
}
@Throws(IOException::class)
override fun read(b: ByteArray): Int {
val ret = stream.read(b)
if (ret > 0) {
decreaseAvailable(ret.toLong())
}
return ret
}
@Throws(IOException::class)
override fun read(b: ByteArray, off: Int, len: Int): Int {
val ret = stream.read(b, off, len)
if (ret > 0) {
decreaseAvailable(ret.toLong())
}
return ret
}
@Throws(IOException::class)
override fun skip(n: Long): Long {
val ret = stream.skip(n)
if (ret > 0) {
decreaseAvailable(ret)
}
return ret
}
@Throws(IOException::class)
override fun available(): Int {
val ret = stream.available()
return if (ret == 0 && available > 0) {
available.toInt()
} else ret
}
private fun decreaseAvailable(n: Long) {
available -= n
if (available < 0) {
available = 0
}
}
}
| apache-2.0 | b586443729bfb1d0b247899f30dff76c | 30.724638 | 106 | 0.640018 | 4.404427 | false | false | false | false |
syrop/Victor-Events | events/src/main/kotlin/pl/org/seva/events/event/Event.kt | 1 | 3367 | /*
* Copyright (C) 2017 Wiktor Nizio
*
* 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/>.
*
* If you like this program, consider donating bitcoin: bc1qncxh5xs6erq6w4qz3a7xl7f50agrgn3w58dsfp
*/
package pl.org.seva.events.event
import androidx.room.PrimaryKey
import com.google.android.gms.maps.model.LatLng
import com.google.firebase.firestore.GeoPoint
import pl.org.seva.events.main.data.db.EventsDb
import java.time.LocalDateTime
import java.time.ZoneOffset
data class Event(
val comm: String,
val name: String = CREATION_NAME,
val time: LocalDateTime = LocalDateTime.now(),
val location: LatLng? = null,
val address: String? = null,
val desc: String? = null,
) {
val fsEvent get() = Fs(
comm = comm,
name = name,
time = time.toString(),
location = location?.let { GeoPoint(it.latitude, it.longitude) },
address = address,
desc = desc,
timestamp = time.toEpochSecond(ZoneOffset.UTC),
)
@Suppress("MemberVisibilityCanBePrivate")
data class Fs(
val comm: String,
val name: String,
val time: String,
val location: GeoPoint?,
val address: String?,
val desc: String?,
val timestamp: Long,
) {
fun value() = Event(
comm = comm,
name = name,
time = LocalDateTime.parse(time),
location = location?.let { LatLng(it.longitude, it.longitude) },
address = address,
desc = desc)
companion object {
const val TIMESTAMP = "timestamp"
}
}
@androidx.room.Entity(tableName = EventsDb.EVENT_TABLE)
class Entity() {
lateinit var comm: String
lateinit var name: String
@PrimaryKey
var time: String = ""
var lat: Double? = null
var lon: Double? = null
var address: String? = null
var desc: String? = null
constructor(event: Event) : this() {
comm = event.comm
name = event.name
time = event.time.toString()
lat = event.location?.latitude
lon = event.location?.longitude
address = event.address
desc = event.desc
}
fun value() = Event(
comm = comm,
name = name,
time = LocalDateTime.parse(time),
location = lat?.let { LatLng(it, checkNotNull(lon)) },
address = address,
desc = desc,
)
}
companion object {
private const val CREATION_NAME = ""
val creationEvent get() = Event(CREATION_NAME)
}
}
| gpl-3.0 | 0a53660ccb5b3978b675da5fc6102a6a | 30.764151 | 98 | 0.585982 | 4.424442 | false | false | false | false |
AndroidX/androidx | camera/integration-tests/avsynctestapp/src/main/java/androidx/camera/integration/avsync/model/CameraHelper.kt | 3 | 6050 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.camera.integration.avsync.model
import android.annotation.SuppressLint
import android.content.ContentResolver
import android.content.ContentValues
import android.content.Context
import android.os.Environment
import android.provider.MediaStore
import androidx.annotation.MainThread
import androidx.camera.core.CameraSelector
import androidx.camera.core.Logger
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.video.FileOutputOptions
import androidx.camera.video.MediaStoreOutputOptions
import androidx.camera.video.PendingRecording
import androidx.camera.video.Recorder
import androidx.camera.video.Recording
import androidx.camera.video.VideoCapture
import androidx.camera.video.VideoRecordEvent
import androidx.camera.video.internal.compat.quirk.DeviceQuirks
import androidx.camera.video.internal.compat.quirk.MediaStoreVideoCannotWrite
import androidx.concurrent.futures.await
import androidx.core.content.ContextCompat
import androidx.core.util.Consumer
import androidx.lifecycle.LifecycleOwner
import java.io.File
private const val TAG = "CameraHelper"
class CameraHelper {
private val cameraSelector = CameraSelector.DEFAULT_FRONT_CAMERA
private var videoCapture: VideoCapture<Recorder>? = null
private var activeRecording: Recording? = null
@MainThread
suspend fun bindCamera(context: Context, lifecycleOwner: LifecycleOwner): Boolean {
val cameraProvider = ProcessCameraProvider.getInstance(context).await()
val recorder = Recorder.Builder().build()
videoCapture = VideoCapture.withOutput(recorder)
return try {
cameraProvider.bindToLifecycle(lifecycleOwner, cameraSelector, videoCapture)
true
} catch (exception: Exception) {
Logger.e(TAG, "Camera binding failed", exception)
videoCapture = null
false
}
}
/**
* Start video recording.
*
* <p> For E2E test, permissions will be handled by the launch script.
*/
@SuppressLint("MissingPermission")
fun startRecording(context: Context, eventListener: Consumer<VideoRecordEvent>? = null) {
activeRecording = videoCapture!!.let {
val listener = eventListener ?: generateVideoRecordEventListener()
prepareRecording(context, it.output).withAudioEnabled().start(
ContextCompat.getMainExecutor(context),
listener
)
}
}
private fun prepareRecording(context: Context, recorder: Recorder): PendingRecording {
return if (canDeviceWriteToMediaStore()) {
recorder.prepareRecording(
context,
generateVideoMediaStoreOptions(context.contentResolver)
)
} else {
recorder.prepareRecording(
context,
generateVideoFileOutputOptions()
)
}
}
private fun canDeviceWriteToMediaStore(): Boolean {
return DeviceQuirks.get(MediaStoreVideoCannotWrite::class.java) == null
}
fun stopRecording() {
activeRecording!!.stop()
activeRecording = null
}
fun pauseRecording() {
activeRecording!!.pause()
}
fun resumeRecording() {
activeRecording!!.resume()
}
private fun generateVideoFileOutputOptions(): FileOutputOptions {
val videoFileName = "${generateVideoFileName()}.mp4"
val videoFolder = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_MOVIES
)
if (!videoFolder.exists() && !videoFolder.mkdirs()) {
Logger.e(TAG, "Failed to create directory: $videoFolder")
}
return FileOutputOptions.Builder(File(videoFolder, videoFileName)).build()
}
private fun generateVideoMediaStoreOptions(
contentResolver: ContentResolver
): MediaStoreOutputOptions {
val contentValues = generateVideoContentValues(generateVideoFileName())
return MediaStoreOutputOptions.Builder(
contentResolver,
MediaStore.Video.Media.EXTERNAL_CONTENT_URI
).setContentValues(contentValues).build()
}
private fun generateVideoFileName(): String {
return "video_" + System.currentTimeMillis()
}
private fun generateVideoContentValues(fileName: String): ContentValues {
val res = ContentValues()
res.put(MediaStore.MediaColumns.MIME_TYPE, "video/mp4")
res.put(MediaStore.Video.Media.TITLE, fileName)
res.put(MediaStore.Video.Media.DISPLAY_NAME, fileName)
res.put(MediaStore.Video.Media.DATE_ADDED, System.currentTimeMillis() / 1000)
res.put(MediaStore.Video.Media.DATE_TAKEN, System.currentTimeMillis())
return res
}
private fun generateVideoRecordEventListener(): Consumer<VideoRecordEvent> {
return Consumer<VideoRecordEvent> { videoRecordEvent ->
if (videoRecordEvent is VideoRecordEvent.Finalize) {
val uri = videoRecordEvent.outputResults.outputUri
if (videoRecordEvent.error == VideoRecordEvent.Finalize.ERROR_NONE) {
Logger.d(TAG, "Video saved to: $uri")
} else {
val msg = "save to uri $uri with error code (${videoRecordEvent.error})"
Logger.e(TAG, "Failed to save video: $msg")
}
}
}
}
} | apache-2.0 | b71c59345099fa42ff68a3815d8be0d5 | 35.672727 | 93 | 0.691074 | 4.963084 | false | false | false | false |
Xenoage/Zong | utils-kotlin/src/com/xenoage/utils/color/Color.kt | 1 | 2662 | package com.xenoage.utils.color
import com.xenoage.utils.Cache
import com.xenoage.utils.annotations.Optimized
import com.xenoage.utils.annotations.Reason.MemorySaving
import com.xenoage.utils.math.clamp
import com.xenoage.utils.math.toHex
/**
* A platform independent way to store a color.
* All values are between 0 and 255.
*/
data class Color private constructor(
val r: Int, val g: Int, val b: Int, val a: Int
) {
val value: Int
get() = rgba(r, g, b, a)
/**
* Adds the given value to the red, green and blue color. The values
* are clamped to the range between 0 and 255. The given summand may also be negative
* to remove light.
*/
fun addWhite(summand: Int): Color {
return Color((r + summand).clamp(0, 255), (g + summand).clamp(0, 255),
(b + summand).clamp(0, 255), a)
}
/**
* Gets the this color as a hex string in either the form
* "#aarrggbb" if [withAlpha] is true, or "#rrggbb" otherwise.
* a, r, g and b are lowercase.
*/
fun toHex(withAlpha: Boolean = true): String {
val s = StringBuilder("#")
if (withAlpha)
s.append(toHex2Digits(a))
s.append(toHex2Digits(r))
s.append(toHex2Digits(g))
s.append(toHex2Digits(b))
return s.toString()
}
private fun toHex2Digits(i: Int): String =
i.toHex().padStart(2, '0')
companion object {
val black = Color(0, 0, 0, 255)
val blue = Color(0, 0, 255, 255)
val gray = Color(128, 128, 128, 255)
val green = Color(0, 255, 0, 255)
val lightGray = Color(192, 192, 192, 255)
val red = Color(255, 0, 0, 255)
val white = Color(255, 255, 255, 255)
val yellow = Color(255, 255, 0, 255)
private val cache = Cache<Int, Color>(100)
private fun rgba(r: Int, g: Int, b: Int, a: Int): Int =
(a and 0xFF shl 24) or
(r and 0xFF shl 16) or
(g and 0xFF shl 8) or
(b and 0xFF)
/** Creates a new color or returns a shared instance. */
@Optimized(MemorySaving)
operator fun invoke(r: Int, g: Int, b: Int, a: Int = 255): Color =
cache[rgba(r, g, b, a), { Color(r, g, b, a) }]
}
}
/**
* Reads a hexadecimal color in either the form "#aarrggbb" or "#rrggbb".
* a, r, g and b may be lowercase or uppercase.
*/
fun String.toColor(): Color {
try {
val withAlpha = length == 9
if (length != 7 && !withAlpha)
throw IllegalArgumentException("Illegal length")
val a = if (withAlpha) substring(1, 3).toInt(16) else 0xFF
val offset = if (withAlpha) 2 else 0
val r = substring(offset + 1, offset + 3).toInt(16)
val g = substring(offset + 3, offset + 5).toInt(16)
val b = substring(offset + 5, offset + 7).toInt(16)
return Color.invoke(r, g, b, a)
} catch (ex: Exception) {
throw NumberFormatException()
}
}
| agpl-3.0 | b76dfe15d3058e1702560130985c52de | 27.623656 | 86 | 0.650639 | 2.93495 | false | false | false | false |
AndroidX/androidx | compose/ui/ui-unit/src/test/kotlin/androidx/compose/ui/unit/VelocityTest.kt | 3 | 2846 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.unit
import com.google.common.truth.Truth
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class VelocityTest {
private val velocity1 = Velocity(3f, -7f)
private val velocity2 = Velocity(5f, 13f)
@Test
fun operatorUnaryMinus() {
Truth.assertThat(-velocity1)
.isEqualTo(Velocity(-3f, 7f))
Truth.assertThat(-velocity2)
.isEqualTo(Velocity(-5f, -13f))
}
@Test
fun operatorPlus() {
Truth.assertThat(velocity2 + velocity1)
.isEqualTo(Velocity(8f, 6f))
Truth.assertThat(velocity1 + velocity2)
.isEqualTo(Velocity(8f, 6f))
}
@Test
fun operatorMinus() {
Truth.assertThat(velocity1 - velocity2)
.isEqualTo(Velocity(-2f, -20f))
Truth.assertThat(velocity2 - velocity1)
.isEqualTo(Velocity(2f, 20f))
}
@Test
fun operatorDivide() {
Truth.assertThat(velocity1 / 10f)
.isEqualTo(Velocity(0.3f, -0.7f))
}
@Test
fun operatorTimes() {
Truth.assertThat(velocity1 * 10f)
.isEqualTo(Velocity(30f, -70f))
}
@Test
fun operatorRem() {
Truth.assertThat(velocity1 % 3f)
.isEqualTo(Velocity(0f, -1f))
}
@Test
fun components() {
val (x, y) = velocity1
Truth.assertThat(x).isEqualTo(3f)
Truth.assertThat(y).isEqualTo(-7f)
}
@Test
fun xy() {
Truth.assertThat(velocity1.x).isEqualTo(3f)
Truth.assertThat(velocity1.y).isEqualTo(-7f)
}
@Test
fun testOffsetCopy() {
val offset = Velocity(100f, 200f)
Assert.assertEquals(offset, offset.copy())
}
@Test
fun testOffsetCopyOverwriteX() {
val offset = Velocity(100f, 200f)
val copy = offset.copy(x = 50f)
Assert.assertEquals(50f, copy.x)
Assert.assertEquals(200f, copy.y)
}
@Test
fun testOffsetCopyOverwriteY() {
val offset = Velocity(100f, 200f)
val copy = offset.copy(y = 300f)
Assert.assertEquals(100f, copy.x)
Assert.assertEquals(300f, copy.y)
}
} | apache-2.0 | a0802d7e2695a68ba3efa87262a56239 | 25.607477 | 75 | 0.629656 | 3.715405 | false | true | false | false |
ftomassetti/LangSandbox | src/main/kotlin/me/tomassetti/sandy/parsing/SandyParserFacade.kt | 1 | 3162 | package me.tomassetti.sandy.parsing
import me.tomassetti.langsandbox.SandyLexer
import me.tomassetti.langsandbox.SandyParser
import me.tomassetti.langsandbox.SandyParser.SandyFileContext
import me.tomassetti.sandy.ast.*
import org.antlr.v4.runtime.*
import org.antlr.v4.runtime.atn.ATNConfigSet
import org.antlr.v4.runtime.dfa.DFA
import java.io.ByteArrayInputStream
import java.io.File
import java.io.FileInputStream
import java.io.InputStream
import java.nio.charset.Charset
import java.util.*
data class AntlrParsingResult(val root : SandyFileContext?, val errors: List<Error>) {
fun isCorrect() = errors.isEmpty() && root != null
}
data class ParsingResult(val root : SandyFile?, val errors: List<Error>) {
fun isCorrect() = errors.isEmpty() && root != null
}
fun String.toStream(charset: Charset = Charsets.UTF_8) = ByteArrayInputStream(toByteArray(charset))
object SandyAntlrParserFacade {
fun parse(code: String) : AntlrParsingResult = parse(code.toStream())
fun parse(file: File) : AntlrParsingResult = parse(FileInputStream(file))
fun parse(inputStream: InputStream) : AntlrParsingResult {
val lexicalAndSyntaticErrors = LinkedList<Error>()
val errorListener = object : ANTLRErrorListener {
override fun reportAmbiguity(p0: Parser?, p1: DFA?, p2: Int, p3: Int, p4: Boolean, p5: BitSet?, p6: ATNConfigSet?) {
// Ignored for now
}
override fun reportAttemptingFullContext(p0: Parser?, p1: DFA?, p2: Int, p3: Int, p4: BitSet?, p5: ATNConfigSet?) {
// Ignored for now
}
override fun syntaxError(recognizer: Recognizer<*, *>?, offendingSymbol: Any?, line: Int, charPositionInline: Int, msg: String, ex: RecognitionException?) {
lexicalAndSyntaticErrors.add(Error(msg, Point(line, charPositionInline)))
}
override fun reportContextSensitivity(p0: Parser?, p1: DFA?, p2: Int, p3: Int, p4: Int, p5: ATNConfigSet?) {
// Ignored for now
}
}
val lexer = SandyLexer(ANTLRInputStream(inputStream))
lexer.removeErrorListeners()
lexer.addErrorListener(errorListener)
val parser = SandyParser(CommonTokenStream(lexer))
parser.removeErrorListeners()
parser.addErrorListener(errorListener)
val antlrRoot = parser.sandyFile()
return AntlrParsingResult(antlrRoot, lexicalAndSyntaticErrors)
}
}
object SandyParserFacade {
fun parse(code: String) : ParsingResult = parse(code.toStream())
fun parse(file: File) : ParsingResult = parse(FileInputStream(file))
fun parse(inputStream: InputStream) : ParsingResult {
val antlrParsingResult = SandyAntlrParserFacade.parse(inputStream)
val lexicalAnsSyntaticErrors = antlrParsingResult.errors
val antlrRoot = antlrParsingResult.root
val astRoot = if (lexicalAnsSyntaticErrors.isEmpty()) {antlrRoot?.toAst(considerPosition = true) } else { null }
val semanticErrors = astRoot?.validate() ?: emptyList()
return ParsingResult(astRoot, lexicalAnsSyntaticErrors + semanticErrors)
}
}
| apache-2.0 | 280d63482e96bc310f58e212f248ffc2 | 38.525 | 168 | 0.699873 | 3.923077 | false | false | false | false |
androidx/androidx | camera/integration-tests/uiwidgetstestapp/src/main/java/androidx/camera/integration/uiwidgets/compose/ui/navigation/ComposeCameraNavHost.kt | 3 | 2304 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.camera.integration.uiwidgets.compose.ui.navigation
import androidx.camera.integration.uiwidgets.compose.ui.screen.imagecapture.ImageCaptureScreen
import androidx.camera.integration.uiwidgets.compose.ui.screen.videocapture.VideoCaptureScreen
import androidx.camera.view.PreviewView
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
// Provides the ComposeCameraScreen needed for onStreamStateChange
// The Screen-level Composable will provide the StreamState changes
@Composable
fun ComposeCameraNavHost(
navController: NavHostController,
modifier: Modifier = Modifier,
onStreamStateChange: (ComposeCameraScreen, PreviewView.StreamState) -> Unit = { _, _ -> }
) {
NavHost(
navController = navController,
startDestination = ComposeCameraScreen.ImageCapture.name,
modifier = modifier
) {
composable(ComposeCameraScreen.ImageCapture.name) {
ImageCaptureScreen(
onStreamStateChange = { state ->
onStreamStateChange(
ComposeCameraScreen.ImageCapture,
state
)
}
)
}
composable(ComposeCameraScreen.VideoCapture.name) {
VideoCaptureScreen(
onStreamStateChange = { state ->
onStreamStateChange(
ComposeCameraScreen.VideoCapture,
state
)
}
)
}
}
} | apache-2.0 | ca41e508a6c9206fe5814f2191813731 | 35.587302 | 94 | 0.676649 | 5.154362 | false | false | false | false |
androidx/androidx | bluetooth/bluetooth-core/src/androidTest/java/androidx/bluetooth/core/AdvertiseDataTest.kt | 3 | 6479 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.bluetooth.core
import android.bluetooth.le.AdvertiseData as FwkAdvertiseData
import android.os.Build
import android.os.ParcelUuid
import android.util.SparseArray
import com.google.common.truth.Truth
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class AdvertiseDataTest {
companion object {
val TEST_SERVICE_UUID = ParcelUuid.fromString("FFFFFFF0-FFFF-FFFF-FFFF-FFFFFFFFFFFF")
val TEST_SERVICE_UUIDS = mutableListOf<ParcelUuid>(TEST_SERVICE_UUID)
val TEST_SERVICE_SOLICITATION_UUID =
ParcelUuid.fromString("CCCCCCC0-CCCC-CCCC-CCCC-CCCCCCCCCCCC")
val TEST_SERVICE_SOLICITATION_UUIDS = mutableListOf<ParcelUuid>(
TEST_SERVICE_SOLICITATION_UUID)
val TEST_MANUFACTURER_ID = 1000
val TEST_MANUFACTURER_SPECIFIC_DATUM = "MANUFACTURER-DATA".toByteArray()
val TEST_MANUFACTURER_SPECIFIC_DATA = SparseArray<ByteArray>().also {
it.put(TEST_MANUFACTURER_ID, TEST_MANUFACTURER_SPECIFIC_DATUM)
}
val TEST_SERVICE_DATA_UUID = ParcelUuid.fromString(
"DDDDDDD0-DDDD-DDDD-DDDD-DDDDDDDDDDDD")
val TEST_SERVICE_DATUM = "SERVICE-DATA".toByteArray()
val TEST_SERVICE_DATA = mutableMapOf<ParcelUuid, ByteArray>(
TEST_SERVICE_DATA_UUID to TEST_SERVICE_DATUM)
val TEST_INCLUDE_TX_POWER_LEVEL = false
val TEST_INCLUDE_DEVICE_NAME = false
internal fun <E> SparseArray<E>.compareContent(other: SparseArray<E>?) {
Truth.assertThat(other).isNotNull()
Truth.assertThat(size()).isEqualTo(other?.size())
if (other != null && size() == other.size()) {
for (index in 0 until size()) {
val key = keyAt(index)
val value = get(key)
Truth.assertThat(key).isEqualTo(other.keyAt(index))
Truth.assertThat(value).isEqualTo(other.get(key))
}
}
}
}
@Test
fun constructorWithValues_createsFrameworkInstanceCorrectly() {
val advertiseData = AdvertiseData(
serviceUuids = TEST_SERVICE_UUIDS,
serviceSolicitationUuids = TEST_SERVICE_SOLICITATION_UUIDS,
manufacturerSpecificData = TEST_MANUFACTURER_SPECIFIC_DATA,
serviceData = TEST_SERVICE_DATA,
includeTxPowerLevel = TEST_INCLUDE_TX_POWER_LEVEL,
includeDeviceName = TEST_INCLUDE_DEVICE_NAME
)
val fwkAdvertiseData = advertiseData.impl.fwkInstance
Truth.assertThat(fwkAdvertiseData.serviceUuids).isEqualTo(TEST_SERVICE_UUIDS)
TEST_MANUFACTURER_SPECIFIC_DATA.compareContent(fwkAdvertiseData.manufacturerSpecificData)
Truth.assertThat(fwkAdvertiseData.serviceData).isEqualTo(TEST_SERVICE_DATA)
Truth.assertThat(fwkAdvertiseData.includeTxPowerLevel).isEqualTo(
TEST_INCLUDE_TX_POWER_LEVEL)
Truth.assertThat(fwkAdvertiseData.includeDeviceName).isEqualTo(TEST_INCLUDE_DEVICE_NAME)
if (Build.VERSION.SDK_INT >= 31) {
Truth.assertThat(fwkAdvertiseData.serviceSolicitationUuids).isEqualTo(
TEST_SERVICE_SOLICITATION_UUIDS)
}
}
@Test
fun constructorWithFwkInstance_createsAdvertiseDataCorrectly() {
val fwkAdvertiseDataBuilder = FwkAdvertiseData.Builder()
.addServiceUuid(TEST_SERVICE_UUID)
.addManufacturerData(TEST_MANUFACTURER_ID, TEST_MANUFACTURER_SPECIFIC_DATUM)
.addServiceData(TEST_SERVICE_DATA_UUID, TEST_SERVICE_DATUM)
.setIncludeTxPowerLevel(TEST_INCLUDE_TX_POWER_LEVEL)
.setIncludeDeviceName(TEST_INCLUDE_DEVICE_NAME)
if (Build.VERSION.SDK_INT >= 31) {
fwkAdvertiseDataBuilder.addServiceSolicitationUuid(TEST_SERVICE_SOLICITATION_UUID)
}
val advertiseData = AdvertiseData(fwkAdvertiseDataBuilder.build())
Truth.assertThat(advertiseData.serviceUuids).isEqualTo(TEST_SERVICE_UUIDS)
TEST_MANUFACTURER_SPECIFIC_DATA.compareContent(advertiseData.manufacturerSpecificData)
Truth.assertThat(advertiseData.serviceData).isEqualTo(TEST_SERVICE_DATA)
Truth.assertThat(advertiseData.includeTxPowerLevel).isEqualTo(TEST_INCLUDE_TX_POWER_LEVEL)
Truth.assertThat(advertiseData.includeDeviceName).isEqualTo(TEST_INCLUDE_DEVICE_NAME)
if (Build.VERSION.SDK_INT >= 31) {
Truth.assertThat(advertiseData.serviceSolicitationUuids)
.isEqualTo(TEST_SERVICE_SOLICITATION_UUIDS)
}
}
@Test
fun advertiseDataBundleable() {
val advertiseData = AdvertiseData(
serviceUuids = TEST_SERVICE_UUIDS,
serviceSolicitationUuids = TEST_SERVICE_SOLICITATION_UUIDS,
manufacturerSpecificData = TEST_MANUFACTURER_SPECIFIC_DATA,
serviceData = TEST_SERVICE_DATA,
includeTxPowerLevel = TEST_INCLUDE_TX_POWER_LEVEL,
includeDeviceName = TEST_INCLUDE_DEVICE_NAME
)
val bundle = advertiseData.toBundle()
val advertiseDataFromBundle = AdvertiseData.CREATOR.fromBundle(bundle)
Truth.assertThat(advertiseDataFromBundle.serviceUuids).isEqualTo(TEST_SERVICE_UUIDS)
TEST_MANUFACTURER_SPECIFIC_DATA.compareContent(
advertiseDataFromBundle.manufacturerSpecificData)
Truth.assertThat(advertiseDataFromBundle.serviceData).isEqualTo(TEST_SERVICE_DATA)
Truth.assertThat(advertiseDataFromBundle.includeTxPowerLevel).isEqualTo(
TEST_INCLUDE_TX_POWER_LEVEL)
Truth.assertThat(advertiseDataFromBundle.includeDeviceName).isEqualTo(
TEST_INCLUDE_DEVICE_NAME)
Truth.assertThat(advertiseDataFromBundle.serviceSolicitationUuids).isEqualTo(
TEST_SERVICE_SOLICITATION_UUIDS)
}
} | apache-2.0 | 6d96a4f5b14728ef48281d53a3b22052 | 46.29927 | 98 | 0.697793 | 4.351242 | false | true | false | false |
edx/edx-app-android | OpenEdXMobile/src/main/java/org/edx/mobile/module/registration/view/RegistrationCheckBoxView.kt | 1 | 1762 | package org.edx.mobile.module.registration.view
import android.view.View
import com.google.gson.JsonElement
import com.google.gson.JsonPrimitive
import org.edx.mobile.databinding.ViewRegisterCheckboxBinding
import org.edx.mobile.module.registration.model.RegistrationFormField
import org.edx.mobile.module.registration.view.IRegistrationFieldView.IActionListener
class RegistrationCheckBoxView(
field: RegistrationFormField,
view: View
) : IRegistrationFieldView {
private val binding: ViewRegisterCheckboxBinding = ViewRegisterCheckboxBinding.bind(view)
private val mField: RegistrationFormField = field
private var actionListener: IActionListener? = null
init {
binding.registerCheckbox.text = field.label
binding.registerCheckbox.isChecked = field.defaultValue?.toBoolean() ?: true
binding.registerCheckbox.setOnCheckedChangeListener { _, _ ->
actionListener?.onClickAgreement()
}
}
override fun getCurrentValue(): JsonElement = JsonPrimitive(binding.registerCheckbox.isChecked)
override fun getField(): RegistrationFormField = mField
override fun getOnErrorFocusView(): View = binding.registerCheckbox
override fun getView(): View = binding.root
override fun hasValue(): Boolean = true
override fun isValidInput(): Boolean = true
override fun setRawValue(value: String?): Boolean = false
override fun setInstructions(instructions: String?) {
}
override fun handleError(errorMessage: String?) {
}
override fun setEnabled(enabled: Boolean) {
binding.registerCheckbox.isEnabled = enabled
}
override fun setActionListener(actionListener: IActionListener?) {
this.actionListener = actionListener
}
}
| apache-2.0 | ece2fb521322d1049fc031e2862352b0 | 31.62963 | 99 | 0.751419 | 4.991501 | false | false | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/errorreporter/ErrorReporter.kt | 1 | 5358 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.errorreporter
import com.demonwav.mcdev.update.PluginUtil
import com.intellij.diagnostic.DiagnosticBundle
import com.intellij.diagnostic.LogMessage
import com.intellij.ide.DataManager
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.idea.IdeaLogger
import com.intellij.notification.NotificationGroupManager
import com.intellij.notification.NotificationListener
import com.intellij.notification.NotificationType
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.diagnostic.ErrorReportSubmitter
import com.intellij.openapi.diagnostic.IdeaLoggingEvent
import com.intellij.openapi.diagnostic.SubmittedReportInfo
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.util.Consumer
import java.awt.Component
class ErrorReporter : ErrorReportSubmitter() {
private val ignoredErrorMessages = listOf(
"Key com.demonwav.mcdev.translations.TranslationFoldingSettings duplicated",
"Inspection #EntityConstructor has no description"
)
private val baseUrl = "https://github.com/minecraft-dev/mcdev-error-report/issues"
override fun getReportActionText() = "Report to Minecraft Dev GitHub Issue Tracker"
override fun submit(
events: Array<out IdeaLoggingEvent>,
additionalInfo: String?,
parentComponent: Component,
consumer: Consumer<in SubmittedReportInfo>
): Boolean {
val dataContext = DataManager.getInstance().getDataContext(parentComponent)
val project = CommonDataKeys.PROJECT.getData(dataContext)
val event = events[0]
val errorMessage = event.throwableText
if (errorMessage.isNotBlank() && ignoredErrorMessages.any(errorMessage::contains)) {
val task = object : Task.Backgroundable(project, "Ignored error") {
override fun run(indicator: ProgressIndicator) {
consumer.consume(SubmittedReportInfo(null, null, SubmittedReportInfo.SubmissionStatus.DUPLICATE))
}
}
if (project == null) {
task.run(EmptyProgressIndicator())
} else {
ProgressManager.getInstance().run(task)
}
return true
}
val errorData = ErrorData(event.throwable, IdeaLogger.ourLastActionId)
errorData.description = additionalInfo
errorData.message = event.message
PluginManagerCore.getPlugin(PluginUtil.PLUGIN_ID)?.let { plugin ->
errorData.pluginName = plugin.name
errorData.pluginVersion = plugin.version
}
val data = event.data
if (data is LogMessage) {
errorData.throwable = data.throwable
errorData.attachments = data.includedAttachments
}
val (reportValues, attachments) = errorData.formatErrorData()
val task = AnonymousFeedbackTask(
project,
"Submitting error report",
true,
reportValues,
attachments,
{ htmlUrl, token, isDuplicate ->
val type = if (isDuplicate) {
SubmittedReportInfo.SubmissionStatus.DUPLICATE
} else {
SubmittedReportInfo.SubmissionStatus.NEW_ISSUE
}
val message = if (!isDuplicate) {
"<html>Created Issue #$token successfully. <a href=\"$htmlUrl\">View issue.</a></html>"
} else {
"<html>Commented on existing Issue #$token successfully. " +
"<a href=\"$htmlUrl\">View comment.</a></html>"
}
NotificationGroupManager.getInstance().getNotificationGroup("Error Report").createNotification(
DiagnosticBundle.message("error.report.title"),
message,
NotificationType.INFORMATION
).setListener(NotificationListener.URL_OPENING_LISTENER).setImportant(false).notify(project)
val reportInfo = SubmittedReportInfo(htmlUrl, "Issue #$token", type)
consumer.consume(reportInfo)
},
{ e ->
val message = "<html>Error Submitting Issue: ${e.message}<br>Consider opening an issue on " +
"<a href=\"$baseUrl\">the GitHub issue tracker.</a></html>"
NotificationGroupManager.getInstance().getNotificationGroup("Error Report").createNotification(
DiagnosticBundle.message("error.report.title"),
message,
NotificationType.ERROR,
).setListener(NotificationListener.URL_OPENING_LISTENER).setImportant(false).notify(project)
consumer.consume(SubmittedReportInfo(null, null, SubmittedReportInfo.SubmissionStatus.FAILED))
}
)
if (project == null) {
task.run(EmptyProgressIndicator())
} else {
ProgressManager.getInstance().run(task)
}
return true
}
}
| mit | 8348b6eb500a19df5b948e36032e6089 | 38.688889 | 117 | 0.648003 | 5.384925 | false | false | false | false |
napperley/Code_Kata | src/main/kotlin/org/example/codekata/kata13/kata13.kt | 1 | 566 | package org.example.codekata.kata13
import java.io.File
@Suppress("VARIABLE_WITH_REDUNDANT_INITIALIZER")
fun countCodeLines(srcFile: File): Int {
var result = 0
val lines = mutableListOf<String>()
srcFile.forEachLine { l ->
lines += l.trim()
}
result = lines
.filterNot { it.startsWith(prefix = "//") }
.filterNot { it.startsWith(prefix = "/*") }
.filterNot { it.startsWith(prefix = "*/") }
.filterNot { it.startsWith(prefix = "*") }
.filterNot { it.isEmpty() }
.size
return result
} | apache-2.0 | 51ce509701256ed9ea744ed6f0b583e3 | 26 | 51 | 0.595406 | 3.930556 | false | false | false | false |
C6H2Cl2/SolidXp | src/main/java/c6h2cl2/solidxp/item/Tools/ItemXpDiamondSword.kt | 1 | 1873 | package c6h2cl2.solidxp.item.Tools
import c6h2cl2.YukariLib.EnumToolType
import c6h2cl2.YukariLib.EnumToolType.SWORD
import c6h2cl2.solidxp.item.ICraftResultEnchanted
import c6h2cl2.solidxp.MOD_ID
import c6h2cl2.solidxp.SolidXpRegistry
import net.minecraft.creativetab.CreativeTabs
import net.minecraft.enchantment.EnumEnchantmentType.WEAPON
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.init.Enchantments
import net.minecraft.item.Item
import net.minecraft.item.ItemStack
import net.minecraft.item.ItemSword
import net.minecraft.util.NonNullList
import net.minecraft.util.ResourceLocation
import net.minecraft.world.World
/**
* @author C6H2Cl2
*/
class ItemXpDiamondSword : ItemSword(SolidXpRegistry.materialXpDiamond), ICraftResultEnchanted {
init {
unlocalizedName = "XpDiamondSword"
registryName = ResourceLocation(MOD_ID, "xp_diamond_sword")
creativeTab = SolidXpRegistry.tabSolidXp
hasSubtypes = true
}
override fun getSubItems(itemIn: Item, tab: CreativeTabs?, subItems: NonNullList<ItemStack>) {
val itemStack = ItemStack(itemIn)
itemStack.addEnchantment(Enchantments.MENDING, 3)
itemStack.addEnchantment(SolidXpRegistry.xpBoost[WEAPON], 5)
subItems.add(itemStack)
}
override fun onCreated(stack: ItemStack, worldIn: World?, playerIn: EntityPlayer?) {
stack.addEnchantment(Enchantments.MENDING, 3)
stack.addEnchantment(SolidXpRegistry.xpBoost[WEAPON], 5)
playerIn?.addStat(SolidXpRegistry.achievementCraftXpIronSword)
}
override fun getEnchanted(): ItemStack {
val stack = ItemStack(this)
stack.addEnchantment(Enchantments.MENDING, 3)
stack.addEnchantment(SolidXpRegistry.xpBoost[WEAPON], 5)
return stack
}
override fun getToolType(): EnumToolType {
return SWORD
}
} | mpl-2.0 | 91fac7ba8ef503cc67d17d4d0a04f1ad | 34.358491 | 98 | 0.757074 | 3.799189 | false | false | false | false |
inorichi/tachiyomi-extensions | src/it/perveden/src/eu/kanade/tachiyomi/extension/it/perveden/Perveden.kt | 1 | 20042 | package eu.kanade.tachiyomi.extension.it.perveden
import eu.kanade.tachiyomi.annotations.Nsfw
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.source.model.Filter
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.ParsedHttpSource
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.Request
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
@Nsfw
class Perveden : ParsedHttpSource() {
override val name = "PervEden"
override val baseUrl = "https://www.perveden.com"
override val lang = "it"
override val supportsLatest = true
override fun latestUpdatesRequest(page: Int): Request = GET("$baseUrl/it/it-directory/?order=3&page=$page", headers)
override fun latestUpdatesSelector() = searchMangaSelector()
override fun latestUpdatesFromElement(element: Element): SManga = searchMangaFromElement(element)
override fun latestUpdatesNextPageSelector() = searchMangaNextPageSelector()
override fun popularMangaRequest(page: Int): Request = GET("$baseUrl/it/it-directory/?page=$page", headers)
override fun popularMangaSelector() = searchMangaSelector()
override fun popularMangaFromElement(element: Element): SManga = searchMangaFromElement(element)
override fun popularMangaNextPageSelector() = searchMangaNextPageSelector()
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request {
val url = "$baseUrl/it/it-directory/".toHttpUrlOrNull()?.newBuilder()!!.addQueryParameter("title", query)
(if (filters.isEmpty()) getFilterList() else filters).forEach { filter ->
when (filter) {
is StatusList ->
filter.state
.filter { it.state }
.map { it.id.toString() }
.forEach { url.addQueryParameter("status", it) }
is Types ->
filter.state
.filter { it.state }
.map { it.id.toString() }
.forEach { url.addQueryParameter("type", it) }
is TextField -> url.addQueryParameter(filter.key, filter.state)
is OrderBy -> filter.state?.let {
val sortId = it.index
url.addQueryParameter("order", if (it.ascending) "-$sortId" else "$sortId")
}
is GenreField -> filter.state.toLowerCase(Locale.ENGLISH).split(',', ';').forEach {
val id = genres[it.trim()]
if (id != null) url.addQueryParameter(filter.key, id)
}
}
}
url.addQueryParameter("page", page.toString())
return GET(url.toString(), headers)
}
override fun searchMangaSelector() = "table#mangaList > tbody > tr:has(td:gt(1))"
override fun searchMangaFromElement(element: Element) = SManga.create().apply {
element.select("td > a").first()?.let {
setUrlWithoutDomain(it.attr("href"))
title = it.text()
}
}
override fun searchMangaNextPageSelector() = "a:has(span.next)"
override fun mangaDetailsParse(document: Document) = SManga.create().apply {
val infos = document.select("div.rightbox")
author = infos.select("a[href^=/it/it-directory/?author]").first()?.text()
artist = infos.select("a[href^=/it/it-directory/?artist]").first()?.text()
genre = infos.select("a[href^=/it/it-directory/?categoriesInc]").joinToString { it.text() }
description = document.select("h2#mangaDescription").text()
status = parseStatus(infos.select("h4:containsOwn(Stato)").first()?.nextSibling().toString())
val img = infos.select("div.mangaImage2 > img").first()?.attr("src")
if (!img.isNullOrBlank()) thumbnail_url = img.let { "https:$it" }
}
private fun parseStatus(status: String) = when {
status.contains("In Corso", true) -> SManga.ONGOING
status.contains("Completato", true) -> SManga.COMPLETED
else -> SManga.UNKNOWN
}
override fun chapterListSelector() = "div#leftContent > table > tbody > tr"
override fun chapterFromElement(element: Element) = SChapter.create().apply {
val a = element.select("a[href^=/it/it-manga/]").first()
setUrlWithoutDomain(a?.attr("href").orEmpty())
name = a?.select("b")?.first()?.text().orEmpty()
date_upload = element.select("td.chapterDate").first()?.text()?.let { parseChapterDate(it.trim()) } ?: 0L
}
private fun parseChapterDate(date: String): Long =
when {
"Oggi" in date -> {
Calendar.getInstance().apply {
set(Calendar.HOUR_OF_DAY, 0)
set(Calendar.MINUTE, 0)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
}.timeInMillis
}
"Ieri" in date -> {
Calendar.getInstance().apply {
add(Calendar.DATE, -1)
set(Calendar.HOUR_OF_DAY, 0)
set(Calendar.MINUTE, 0)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
}.timeInMillis
}
else ->
try {
SimpleDateFormat("d MMM yyyy", Locale.ITALIAN).parse(date)?.time ?: 0L
} catch (e: ParseException) {
0L
}
}
override fun pageListParse(document: Document): List<Page> = mutableListOf<Page>().apply {
document.select("option[value^=/it/it-manga/]").forEach {
add(Page(size, "$baseUrl${it.attr("value")}"))
}
}
override fun imageUrlParse(document: Document): String = document.select("a#nextA.next > img").first()?.attr("src").let { "https:$it" }
private class NamedId(name: String, val id: Int) : Filter.CheckBox(name)
private class TextField(name: String, val key: String) : Filter.Text(name)
private class GenreField(name: String, val key: String) : Filter.Text(name)
private class OrderBy : Filter.Sort(
"Ordina per",
arrayOf("Titolo manga", "Visite", "Capitoli", "Ultimo capitolo"),
Selection(1, false)
)
private class StatusList(statuses: List<NamedId>) : Filter.Group<NamedId>("Stato", statuses)
private class Types(types: List<NamedId>) : Filter.Group<NamedId>("Tipo", types)
override fun getFilterList() = FilterList(
TextField("Autore", "author"),
TextField("Artista", "artist"),
GenreField("Generi inclusi", "categoriesInc"),
GenreField("Generi esclusi", "categoriesExcl"),
OrderBy(),
Types(types()),
StatusList(statuses())
)
private fun types() = listOf(
NamedId("Japanese Manga", 0),
NamedId("Korean Manhwa", 1),
NamedId("Chinese Manhua", 2),
NamedId("Comic", 3),
NamedId("Doujinshi", 4)
)
private fun statuses() = listOf(
NamedId("In corso", 1),
NamedId("Completato", 2),
NamedId("Sospeso", 0)
)
private val genres = mapOf(
Pair("commedia", "4e70ea9ac092255ef70075d8"),
Pair("ecchi", "4e70ea9ac092255ef70075d9"),
Pair("age progression", "5782b043719a16947390104a"),
Pair("ahegao", "577e6f90719a168e7d256a3f"),
Pair("anal", "577e6f90719a168e7d256a3b"),
Pair("angel", "577e724a719a168ef96a74d6"),
Pair("apron", "577e720a719a166f4719a7be"),
Pair("armpit licking", "577e71db719a166f4719a3e7"),
Pair("assjob", "58474a08719a1668eeeea29b"),
Pair("aunt", "577e6f8d719a168e7d256a20"),
Pair("bbw", "5782ae42719a1675f68a6e29"),
Pair("bdsm", "577e723d719a168ef96a7416"),
Pair("bestiality", "57ad8919719a1629a0a327cf"),
Pair("big areolae", "577e7226719a166f4719a9d0"),
Pair("big ass", "577e6f8d719a168e7d256a21"),
Pair("big balls", "577e7267719a168ef96a76ee"),
Pair("big breasts", "577e6f8d719a168e7d256a1c"),
Pair("big clit", "57ef0396719a163dffb8fdff"),
Pair("big nipples", "5782ae42719a1675f68a6e2a"),
Pair("big penis", "577e7267719a168ef96a76ef"),
Pair("bike shorts", "577e7210719a166f4719a820"),
Pair("bikini", "577e6f91719a168e7d256a77"),
Pair("birth", "577e7273719a168ef96a77cf"),
Pair("blackmail", "577e6f91719a168e7d256a78"),
Pair("blindfold", "577e7208719a166f4719a78d"),
Pair("blood", "577e7295719a168ef96a79e6"),
Pair("bloomers", "5782b051719a1694739010ee"),
Pair("blowjob", "577e6f8d719a168e7d256a22"),
Pair("blowjob face", "577e71eb719a166f4719a544"),
Pair("body modification", "577e6f93719a168e7d256a8e"),
Pair("bodystocking", "5782b05c719a169473901151"),
Pair("bodysuit", "577e6f90719a168e7d256a42"),
Pair("bondage", "577e6f90719a168e7d256a45"),
Pair("breast expansion", "577e71c3719a166f4719a235"),
Pair("bukkake", "577e7210719a166f4719a821"),
Pair("bunny girl", "577e7224719a166f4719a9b9"),
Pair("business suit", "577e71e5719a166f4719a4b2"),
Pair("catgirl", "577e71d5719a166f4719a366"),
Pair("centaur", "577e7297719a168ef96a7a06"),
Pair("cervix penetration", "577e7273719a168ef96a77d0"),
Pair("cheating", "577e71b5719a166f4719a13b"),
Pair("cheerleader", "57c0a6de719a1641240e9257"),
Pair("chikan", "5782b0c6719a1679528762ac"),
Pair("chinese dress", "5782b059719a169473901131"),
Pair("chloroform", "577e6f92719a168e7d256a7f"),
Pair("christmas", "5782af2b719a169473900752"),
Pair("clit growth", "57ef0396719a163dffb8fe00"),
Pair("collar", "577e6f93719a168e7d256a8f"),
Pair("condom", "577e71d5719a166f4719a36c"),
Pair("corruption", "577e6f90719a168e7d256a41"),
Pair("cosplaying", "5782b185719a167952876944"),
Pair("cousin", "577e7283719a168ef96a78c3"),
Pair("cow", "5865d767719a162cce299571"),
Pair("cunnilingus", "577e6f8d719a168e7d256a23"),
Pair("dark skin", "577e6f90719a168e7d256a55"),
Pair("daughter", "577e7250719a168ef96a7539"),
Pair("deepthroat", "577e6f90719a168e7d256a3c"),
Pair("defloration", "577e6f92719a168e7d256a82"),
Pair("demon girl", "577e7218719a166f4719a8c8"),
Pair("dick growth", "577e6f93719a168e7d256a90"),
Pair("dickgirl on dickgirl", "5782af0e719a16947390067a"),
Pair("dog girl", "577e7218719a166f4719a8c9"),
Pair("double penetration", "577e6f90719a168e7d256a3d"),
Pair("double vaginal", "577e7226719a166f4719a9d1"),
Pair("drugs", "577e71da719a166f4719a3cb"),
Pair("drunk", "577e7199719a16697b9853ea"),
Pair("elf", "577e6f93719a168e7d256a91"),
Pair("enema", "5782aff7719a169473900d8a"),
Pair("exhibitionism", "577e72a7719a168ef96a7b26"),
Pair("eyemask", "577e7208719a166f4719a78e"),
Pair("facesitting", "577e7230719a166f4719aa8c"),
Pair("females only", "577e6f90719a168e7d256a44"),
Pair("femdom", "577e6f8c719a168e7d256a13"),
Pair("filming", "577e7242719a168ef96a7465"),
Pair("fingering", "577e6f90719a168e7d256a5d"),
Pair("fisting", "57c349e1719a1625b42603f4"),
Pair("foot licking", "5782b152719a16795287677d"),
Pair("footjob", "577e6f8d719a168e7d256a17"),
Pair("freckles", "5782ae42719a1675f68a6e2b"),
Pair("fundoshi", "577e71d9719a166f4719a3bf"),
Pair("furry", "5782ae45719a1675f68a6e49"),
Pair("futanari", "577e6f92719a168e7d256a80"),
Pair("gag", "577e6f90719a168e7d256a56"),
Pair("gaping", "577e7210719a166f4719a822"),
Pair("garter belt", "577e7201719a166f4719a704"),
Pair("glasses", "577e6f90719a168e7d256a5e"),
Pair("gothic lolita", "577e7201719a166f4719a705"),
Pair("group", "577e726e719a168ef96a7764"),
Pair("gyaru", "577e6f91719a168e7d256a79"),
Pair("hairjob", "57bcea9f719a1687ea2bc092"),
Pair("hairy", "577e7250719a168ef96a753a"),
Pair("hairy armpits", "5782b13c719a16795287669c"),
Pair("handjob", "577e71c8719a166f4719a29b"),
Pair("harem", "577e71c3719a166f4719a239"),
Pair("heterochromia", "577e7201719a166f4719a706"),
Pair("hotpants", "585b302d719a1648da4f0389"),
Pair("huge breasts", "577e71d9719a166f4719a3c0"),
Pair("huge penis", "585b302d719a1648da4f038a"),
Pair("human on furry", "577e7203719a166f4719a722"),
Pair("human pet", "577e6f90719a168e7d256a57"),
Pair("humiliation", "577e7210719a166f4719a823"),
Pair("impregnation", "577e6f90719a168e7d256a47"),
Pair("incest", "577e6f93719a168e7d256a92"),
Pair("inflation", "577e7273719a168ef96a77d1"),
Pair("insect girl", "577e71fc719a166f4719a692"),
Pair("inverted nipples", "5813993a719a165f236ddacd"),
Pair("kimono", "577e723d719a168ef96a7417"),
Pair("kissing", "5782ae4f719a1675f68a6ece"),
Pair("lactation", "577e6f93719a168e7d256a93"),
Pair("latex", "577e6f90719a168e7d256a58"),
Pair("layer cake", "577e7230719a166f4719aa8d"),
Pair("leg lock", "57b7c0c2719a169265b768bd"),
Pair("leotard", "579b141e719a16881d14ccfe"),
Pair("lingerie", "577e71fc719a166f4719a693"),
Pair("living clothes", "577e6f90719a168e7d256a49"),
Pair("lizard girl", "5782b127719a1679528765e9"),
Pair("lolicon", "5782af84719a1694739009b5"),
Pair("long tongue", "5782b158719a1679528767d5"),
Pair("machine", "57ef0396719a163dffb8fe01"),
Pair("magical girl", "577e71c3719a166f4719a236"),
Pair("maid", "5782ae3f719a1675f68a6e19"),
Pair("male on dickgirl", "577e7267719a168ef96a76f0"),
Pair("masked face", "57c349e1719a1625b42603f5"),
Pair("masturbation", "577e71b5719a166f4719a13c"),
Pair("mermaid", "578d3c5b719a164fa798c09e"),
Pair("metal armor", "5782b158719a1679528767d6"),
Pair("miko", "577e726e719a168ef96a7765"),
Pair("milf", "577e6f8d719a168e7d256a24"),
Pair("military", "577e6f8d719a168e7d256a18"),
Pair("milking", "577e6f93719a168e7d256a94"),
Pair("mind break", "577e6f90719a168e7d256a4b"),
Pair("mind control", "577e6f90719a168e7d256a4d"),
Pair("monster girl", "577e6f90719a168e7d256a4f"),
Pair("monster girl", "577e6f90719a168e7d256a46"),
Pair("moral degeneration", "577e71da719a166f4719a3cc"),
Pair("mother", "577e71c7719a166f4719a293"),
Pair("mouse girl", "5782ae45719a1675f68a6e4a"),
Pair("multiple breasts", "5782ae45719a1675f68a6e4b"),
Pair("multiple penises", "577e722a719a166f4719aa29"),
Pair("muscle", "577e7250719a168ef96a753c"),
Pair("nakadashi", "577e6f8e719a168e7d256a26"),
Pair("netorare", "577e71c7719a166f4719a294"),
Pair("niece", "5782b10a719a1679528764b5"),
Pair("nurse", "577e6f8d719a168e7d256a1d"),
Pair("oil", "5782af5e719a1694739008b1"),
Pair("onahole", "582324e5719a1674f99b3444"),
Pair("orgasm denial", "577e725d719a168ef96a762f"),
Pair("paizuri", "577e6f90719a168e7d256a3e"),
Pair("pantyhose", "577e6f8d719a168e7d256a19"),
Pair("pantyjob", "577e7276719a168ef96a77f9"),
Pair("parasite", "577e6f90719a168e7d256a50"),
Pair("pasties", "5782b029719a169473900f3b"),
Pair("piercing", "577e6f90719a168e7d256a59"),
Pair("plant girl", "577e71f4719a166f4719a5fa"),
Pair("policewoman", "57af673b719a1655a6ca8b58"),
Pair("ponygirl", "577e6f90719a168e7d256a5a"),
Pair("possession", "5782aff7719a169473900d8b"),
Pair("pregnant", "577e71da719a166f4719a3cd"),
Pair("prolapse", "5782cc79719a165f600844e0"),
Pair("prostitution", "577e7242719a168ef96a7466"),
Pair("pubic stubble", "577e71da719a166f4719a3ce"),
Pair("public use", "5782cc79719a165f600844e1"),
Pair("rape", "577e6f90719a168e7d256a51"),
Pair("rimjob", "577e725f719a168ef96a765e"),
Pair("robot", "5782b144719a1679528766f3"),
Pair("ryona", "577e723e719a168ef96a7424"),
Pair("saliva", "5884ed6f719a1678dfbb2258"),
Pair("scar", "5782b081719a167952876168"),
Pair("school swimsuit", "5782b05f719a169473901177"),
Pair("schoolgirl uniform", "577e7199719a16697b9853e6"),
Pair("selfcest", "5782b152719a16795287677e"),
Pair("sex toys", "577e6f90719a168e7d256a5b"),
Pair("sheep girl", "5782affa719a169473900da2"),
Pair("shemale", "577e7267719a168ef96a76f1"),
Pair("shibari", "577e72a6719a168ef96a7b18"),
Pair("shimapan", "5782aebd719a1694739004c5"),
Pair("sister", "577e6f8c719a168e7d256a14"),
Pair("slave", "577e71b4719a166f4719a138"),
Pair("sleeping", "577e71e5719a166f4719a4b3"),
Pair("slime", "577e6f93719a168e7d256a95"),
Pair("slime girl", "577e6f90719a168e7d256a48"),
Pair("small breasts", "577e6f90719a168e7d256a5f"),
Pair("smell", "577e7210719a166f4719a824"),
Pair("snake girl", "577e721e719a166f4719a94b"),
Pair("sole dickgirl", "582324e5719a1674f99b3445"),
Pair("sole female", "577e6f91719a168e7d256a7a"),
Pair("solo action", "5782afbf719a169473900ba2"),
Pair("spanking", "577e7199719a16697b9853e7"),
Pair("squirting", "577e7250719a168ef96a753d"),
Pair("stockings", "577e6f8d719a168e7d256a1a"),
Pair("stomach deformation", "5782aef2719a169473900606"),
Pair("strap-on", "577e71d5719a166f4719a367"),
Pair("stuck in wall", "5782aecf719a16947390055b"),
Pair("sundress", "577e7216719a166f4719a8a2"),
Pair("sweating", "577e71b5719a166f4719a13d"),
Pair("swimsuit", "577e71d3719a166f4719a342"),
Pair("swinging", "577e7203719a166f4719a723"),
Pair("syringe", "577e71da719a166f4719a3cf"),
Pair("tall girl", "577e71d9719a166f4719a3c1"),
Pair("tanlines", "577e6f91719a168e7d256a7b"),
Pair("teacher", "577e7199719a16697b9853e8"),
Pair("tentacles", "577e6f90719a168e7d256a52"),
Pair("thigh high boots", "577e6f93719a168e7d256a96"),
Pair("tiara", "5782cc74719a165f600844d3"),
Pair("tights", "5782b059719a169473901132"),
Pair("tomboy", "577e7201719a166f4719a6fb"),
Pair("torture", "577e725d719a168ef96a7630"),
Pair("tracksuit", "5782b146719a167952876708"),
Pair("transformation", "577e6f90719a168e7d256a4a"),
Pair("tribadism", "577e6f90719a168e7d256a60"),
Pair("tube", "577e7208719a166f4719a78f"),
Pair("tutor", "5782af34719a1694739007a3"),
Pair("twins", "577e726a719a168ef96a7729"),
Pair("unusual pupils", "577e6f90719a168e7d256a53"),
Pair("urethra insertion", "5877c07f719a163627a2ceb0"),
Pair("urination", "577e7210719a166f4719a825"),
Pair("vaginal sticker", "577e721c719a166f4719a930"),
Pair("vomit", "5782ae45719a1675f68a6e4c"),
Pair("vore", "577e6f8c719a168e7d256a15"),
Pair("voyeurism", "583ca1ef719a161795a60847"),
Pair("waitress", "5782ae3f719a1675f68a6e1a"),
Pair("widow", "5782b13c719a16795287669d"),
Pair("wings", "5782b158719a1679528767d7"),
Pair("witch", "577e6f93719a168e7d256a97"),
Pair("wolf girl", "577e724c719a168ef96a74fd"),
Pair("wrestling", "577e7230719a166f4719aa8e"),
Pair("x-ray", "577e6f90719a168e7d256a40"),
Pair("yandere", "577e7295719a168ef96a79e7"),
Pair("yuri", "577e6f90719a168e7d256a4c")
)
}
| apache-2.0 | 55d9626c6d50440c376346189efb8b70 | 47.06235 | 139 | 0.643099 | 2.935267 | false | false | false | false |
inorichi/tachiyomi-extensions | src/id/komiku/src/eu/kanade/tachiyomi/extension/id/komiku/Komiku.kt | 1 | 11679 | package eu.kanade.tachiyomi.extension.id.komiku
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.source.model.Filter
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.ParsedHttpSource
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
class Komiku : ParsedHttpSource() {
override val name = "Komiku"
override val baseUrl = "https://komiku.id"
override val lang = "id"
override val supportsLatest = true
override val client: OkHttpClient = network.cloudflareClient
// popular
override fun popularMangaSelector() = "div.bge"
override fun popularMangaRequest(page: Int): Request {
if (page == 1) {
return GET("$baseUrl/other/hot/?orderby=meta_value_num", headers)
} else {
return GET("$baseUrl/other/hot/page/$page/?orderby=meta_value_num", headers)
}
}
private val coverRegex = Regex("""(/Manga-|/Manhua-|/Manhwa-)""")
private val coverUploadRegex = Regex("""/uploads/\d\d\d\d/\d\d/""")
override fun popularMangaFromElement(element: Element): SManga {
val manga = SManga.create()
manga.title = element.select("h3").text().trim()
manga.setUrlWithoutDomain(element.select("a:has(h3)").attr("href"))
// scraped image doesn't make for a good cover; so try to transform it
// make it take bad cover instead of null if it contains upload date as those URLs aren't very useful
if (element.select("img").attr("data-src").contains(coverUploadRegex)) {
manga.thumbnail_url = element.select("img").attr("data-src")
} else {
manga.thumbnail_url = element.select("img").attr("data-src").substringBeforeLast("?").replace(coverRegex, "/Komik-")
}
return manga
}
override fun popularMangaNextPageSelector() = ".pag-nav a.next"
// latest
override fun latestUpdatesSelector() = popularMangaSelector()
override fun latestUpdatesRequest(page: Int): Request {
if (page == 1) {
return GET("$baseUrl/pustaka/?orderby=modified", headers)
} else {
return GET("$baseUrl/pustaka/page/$page/?orderby=modified", headers)
}
}
override fun latestUpdatesFromElement(element: Element) = popularMangaFromElement(element)
override fun latestUpdatesNextPageSelector() = popularMangaNextPageSelector()
// search
override fun searchMangaSelector() = popularMangaSelector()
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request {
var url = "$baseUrl/pustaka/page/$page/".toHttpUrlOrNull()?.newBuilder()!!.addQueryParameter("s", query)
(if (filters.isEmpty()) getFilterList() else filters).forEach { filter ->
when (filter) {
is CategoryNames -> {
val category = filter.values[filter.state]
url.addQueryParameter("category_name", category.key)
}
is OrderBy -> {
val order = filter.values[filter.state]
url.addQueryParameter("orderby", order.key)
}
is GenreList1 -> {
val genre = filter.values[filter.state]
url.addQueryParameter("genre", genre.key)
}
is GenreList2 -> {
val genre = filter.values[filter.state]
url.addQueryParameter("genre2", genre.key)
}
is StatusList -> {
val status = filter.values[filter.state]
url.addQueryParameter("status", status.key)
}
is ProjectList -> {
val project = filter.values[filter.state]
if (project.key == "project-filter-on") {
url = ("$baseUrl/pustaka" + if (page > 1) "/page/$page/" else "" + "?tipe=projek").toHttpUrlOrNull()!!.newBuilder()
}
}
}
}
return GET(url.toString(), headers)
}
override fun searchMangaFromElement(element: Element) = popularMangaFromElement(element)
override fun searchMangaNextPageSelector() = "a.next"
private class Category(title: String, val key: String) : Filter.TriState(title) {
override fun toString(): String {
return name
}
}
private class Genre(title: String, val key: String) : Filter.TriState(title) {
override fun toString(): String {
return name
}
}
private class Order(title: String, val key: String) : Filter.TriState(title) {
override fun toString(): String {
return name
}
}
private class Status(title: String, val key: String) : Filter.TriState(title) {
override fun toString(): String {
return name
}
}
private class CategoryNames(categories: Array<Category>) : Filter.Select<Category>("Category", categories, 0)
private class OrderBy(orders: Array<Order>) : Filter.Select<Order>("Order", orders, 0)
private class GenreList1(genres: Array<Genre>) : Filter.Select<Genre>("Genre 1", genres, 0)
private class GenreList2(genres: Array<Genre>) : Filter.Select<Genre>("Genre 2", genres, 0)
private class StatusList(statuses: Array<Status>) : Filter.Select<Status>("Status", statuses, 0)
private class ProjectList(project: Array<Status>) : Filter.Select<Status>("Filter Project", project, 0)
override fun getFilterList() = FilterList(
CategoryNames(categoryNames),
OrderBy(orderBy),
GenreList1(genreList),
GenreList2(genreList),
StatusList(statusList),
Filter.Separator(),
Filter.Header("NOTE: cant be used with other filter!"),
Filter.Header("$name Project List page"),
ProjectList(ProjectFilter),
)
private val ProjectFilter = arrayOf(
Status("Show all manga", ""),
Status("Show only project manga", "project-filter-on")
)
private val categoryNames = arrayOf(
Category("All", ""),
Category("Manga", "manga"),
Category("Manhua", "manhua"),
Category("Manhwa", "manhwa")
)
private val orderBy = arrayOf(
Order("Ranking", "meta_value_num"),
Order("New Title", "date"),
Order("Updates", "modified"),
Order("Random", "rand")
)
private val genreList = arrayOf(
Genre("All", ""),
Genre("Action", "action"),
Genre("Adventure", "adventure"),
Genre("Comedy", "comedy"),
Genre("Cooking", "cooking"),
Genre("Crime", "crime"),
Genre("Demons", "demons"),
Genre("Drama", "drama"),
Genre("Ecchi", "ecchi"),
Genre("Fantasy", "fantasy"),
Genre("Game", "game"),
Genre("Gender Bender", "gender-bender"),
Genre("Harem", "harem"),
Genre("Historical", "historical"),
Genre("Horror", "horror"),
Genre("Isekai", "isekai"),
Genre("Josei", "josei"),
Genre("Magic", "magic"),
Genre("Martial Arts", "martial-arts"),
Genre("Mature", "mature"),
Genre("Mecha", "mecha"),
Genre("Medical", "medical"),
Genre("Military", "military"),
Genre("Music", "music"),
Genre("Mystery", "mystery"),
Genre("One Shot", "one-shot"),
Genre("Overpower", "overpower"),
Genre("Parodi", "parodi"),
Genre("Police", "police"),
Genre("Psychological", "psychological"),
Genre("Reincarnation", "reincarnation"),
Genre("Romance", "romance"),
Genre("School", "school"),
Genre("School life", "school-life"),
Genre("Sci-fi", "sci-fi"),
Genre("Seinen", "seinen"),
Genre("Shotacon", "shotacon"),
Genre("Shoujo", "shoujo"),
Genre("Shoujo Ai", "shoujo-ai"),
Genre("Shounen", "shounen"),
Genre("Shounen Ai", "shounen-ai"),
Genre("Slice of Life", "slice-of-life"),
Genre("Sport", "sport"),
Genre("Sports", "sports"),
Genre("Super Power", "super-power"),
Genre("Supernatural", "supernatural"),
Genre("Thriller", "thriller"),
Genre("Tragedy", "tragedy"),
Genre("Urban", "urban"),
Genre("Vampire", "vampire"),
Genre("Webtoons", "webtoons"),
Genre("Yuri", "yuri")
)
private val statusList = arrayOf(
Status("All", ""),
Status("Ongoing", "ongoing"),
Status("End", "end")
)
// manga details
override fun mangaDetailsParse(document: Document) = SManga.create().apply {
description = document.select("#Sinopsis > p").text().trim()
author = document.select("table.inftable td:contains(Komikus)+td").text()
genre = document.select("li[itemprop=genre] > a").joinToString { it.text() }
status = parseStatus(document.select("table.inftable tr > td:contains(Status) + td").text())
thumbnail_url = document.select("div.ims > img").attr("abs:src")
// add series type(manga/manhwa/manhua/other) thinggy to genre
val seriesTypeSelector = "table.inftable tr:contains(Jenis) a, table.inftable tr:has(a[href*=category\\/]) a, a[href*=category\\/]"
document.select(seriesTypeSelector).firstOrNull()?.ownText()?.let {
if (it.isEmpty().not() && genre!!.contains(it, true).not()) {
genre += if (genre!!.isEmpty()) it else ", $it"
}
}
}
private fun parseStatus(status: String) = when {
status.contains("Ongoing") -> SManga.ONGOING
status.contains("Completed") -> SManga.COMPLETED
else -> SManga.UNKNOWN
}
// chapters
override fun chapterListSelector() = "#Daftar_Chapter tr:has(td.judulseries)"
override fun chapterFromElement(element: Element) = SChapter.create().apply {
setUrlWithoutDomain(element.select("a").attr("href"))
name = element.select("a").text()
val timeStamp = element.select("td.tanggalseries")
if (timeStamp.text().contains("lalu")) {
date_upload = parseRelativeDate(timeStamp.text().trim()) ?: 0
} else {
date_upload = parseDate(timeStamp.last())
}
}
private fun parseDate(element: Element): Long = SimpleDateFormat("dd/MM/yyyy", Locale.US).parse(element.text())?.time ?: 0
// Used Google translate here
private fun parseRelativeDate(date: String): Long? {
val trimmedDate = date.substringBefore(" lalu").removeSuffix("s").split(" ")
val calendar = Calendar.getInstance()
when (trimmedDate[1]) {
"jam" -> calendar.apply { add(Calendar.HOUR_OF_DAY, -trimmedDate[0].toInt()) }
"menit" -> calendar.apply { add(Calendar.MINUTE, -trimmedDate[0].toInt()) }
"detik" -> calendar.apply { add(Calendar.SECOND, 0) }
}
return calendar.timeInMillis
}
// pages
override fun pageListParse(document: Document): List<Page> {
return document.select("#Baca_Komik img").mapIndexed { i, element ->
Page(i, "", element.attr("abs:src"))
}
}
override fun imageUrlParse(document: Document): String = throw UnsupportedOperationException("Not Used")
}
| apache-2.0 | 1dcecef356d88ca21dce75eaeca824aa | 37.291803 | 139 | 0.599966 | 4.37252 | false | false | false | false |
develar/mapsforge-tile-server | server/src/TileRequest.kt | 1 | 1558 | package org.develar.mapsforgeTileServer
import org.mapdb.DataInput2
import org.mapdb.DataOutput2
import org.mapdb.Serializer
import org.mapsforge.core.model.Tile
import java.io.DataInput
import java.io.DataOutput
import java.io.Serializable
private val DEFAULT_TILE_SIZE = 256
public val TILE_REQUEST_WEIGHT: Int = 8 + 8 + 1 + 1
class TileRequest(tileX: Int, tileY: Int, zoomLevel: Byte, private val imageFormat: Byte) : Tile(tileX, tileY, zoomLevel, DEFAULT_TILE_SIZE), Serializable {
override fun createNeighbourTile(y: Int, x: Int): Tile {
return TileRequest(x, y, zoomLevel, imageFormat)
}
public fun getImageFormat(): ImageFormat {
return if (imageFormat == 0.toByte()) ImageFormat.WEBP else ImageFormat.PNG
}
override fun hashCode(): Int {
return 31 * super<Tile>.hashCode() + imageFormat.toInt()
}
override fun equals(other: Any?): Boolean {
return super<Tile>.equals(other) && (other as TileRequest).imageFormat == imageFormat
}
class TileRequestSerializer() : Serializer<TileRequest>, Serializable {
override fun serialize(out: DataOutput, value: TileRequest) {
DataOutput2.packInt(out, value.tileX)
DataOutput2.packInt(out, value.tileY)
out.write(value.zoomLevel.toInt())
out.write(value.imageFormat.toInt())
}
override fun deserialize(`in`: DataInput, available: Int): TileRequest {
return TileRequest(DataInput2.unpackInt(`in`), DataInput2.unpackInt(`in`), `in`.readByte(), `in`.readByte())
}
override fun fixedSize(): Int {
return -1
}
}
}
| mit | 02fd38fbe9cf51e5b23a7a469bcff4df | 32.148936 | 156 | 0.715019 | 3.944304 | false | false | false | false |
PassionateWsj/YH-Android | app/src/main/java/com/intfocus/template/subject/seven/indicatorlist/IndicatorListFragment.kt | 1 | 5176 | package com.intfocus.template.subject.seven.indicatorlist
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.alibaba.fastjson.JSON
import com.intfocus.template.R
import com.intfocus.template.model.response.attention.ConcernedListData
import com.intfocus.template.model.response.attention.Test2
import com.intfocus.template.subject.one.entity.SingleValue
import com.intfocus.template.subject.seven.listener.EventRefreshIndicatorListItemData
import com.intfocus.template.ui.BaseFragment
import com.intfocus.template.util.LoadAssetsJsonUtil
import com.intfocus.template.util.LogUtil
import com.intfocus.template.util.OKHttpUtils
import com.intfocus.template.util.RxBusUtil
import kotlinx.android.synthetic.main.fragment_indicator_list.*
import okhttp3.Call
import rx.Subscriber
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import java.io.IOException
/**
* ****************************************************
* author jameswong
* created on: 17/12/18 下午5:23
* e-mail: [email protected]
* name: 关注详情列表
* desc: 关注单品 可拓展详情信息列表
* ****************************************************
*/
class IndicatorListFragment : BaseFragment(), IndicatorListContract.View {
override lateinit var presenter: IndicatorListContract.Presenter
companion object {
val CONFIG_JSON_DATA = "data"
}
var mData: List<Test2.DataBeanXX.AttentionedDataBean> = ArrayList()
val testApi = "https://api.douban.com/v2/book/search?q=%E7%BC%96%E7%A8%8B%E8%89%BA%E6%9C%AF"
fun newInstance(): IndicatorListFragment {
// val args = Bundle()
val fragment = IndicatorListFragment()
// args.putString(CONFIG_JSON_DATA, data)
// fragment.arguments = args
IndicatorListPresenter(IndicatorListModelImpl.getInstance(), fragment)
return fragment
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun showConcernedListData(data: ConcernedListData) {
}
override fun updateConcernedListTitle(title: String) {
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater.inflate(R.layout.fragment_indicator_list, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
presenter.loadConcernedList()
val indicatorListAdapter = IndicatorListAdapter(ctx, this, mData)
elv_indicator_list.setAdapter(indicatorListAdapter)
elv_indicator_list.setOnGroupExpandListener { pos ->
(0 until indicatorListAdapter.groupCount)
.filter { pos != it }
.forEach { elv_indicator_list.collapseGroup(it) }
}
elv_indicator_list.setGroupIndicator(null)
RxBusUtil.getInstance().toObservable(EventRefreshIndicatorListItemData::class.java)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : Subscriber<EventRefreshIndicatorListItemData>() {
override fun onCompleted() {
}
override fun onNext(event: EventRefreshIndicatorListItemData?) {
event?.let {
val data = mData[0].attention_item_data[it.childPosition]
if (data.isReal_time) {
// data.real_time_api?.let {
testApi.let {
OKHttpUtils.newInstance().getAsyncData(it, object : OKHttpUtils.OnReusltListener {
override fun onFailure(call: Call?, e: IOException?) {
}
override fun onSuccess(call: Call?, response: String?) {
val itemData = JSON.parseObject(LoadAssetsJsonUtil.getAssetsJsonData(data.real_time_api), SingleValue::class.java)
data.main_data = itemData.main_data
data.sub_data = itemData.sub_data
data.state = itemData.state
data.isReal_time = false
tv_indicator_list_single_value_title.text = data.main_data.name
}
})
}
} else {
tv_indicator_list_single_value_title.text = data.main_data.name
}
}
}
override fun onError(e: Throwable?) {
e?.let {
LogUtil.d(this@IndicatorListFragment, it.message)
}
}
})
}
} | gpl-3.0 | b4a23223741f8156b310bccd74161678 | 40.747967 | 185 | 0.586287 | 4.984466 | false | false | false | false |
caot/intellij-community | platform/configuration-store-impl/src/FileBasedStorage.kt | 2 | 5738 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.configurationStore
import com.intellij.notification.Notification
import com.intellij.notification.NotificationType
import com.intellij.notification.Notifications
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.RoamingType
import com.intellij.openapi.components.StoragePathMacros
import com.intellij.openapi.components.TrackingPathMacroSubstitutor
import com.intellij.openapi.components.impl.stores.FileStorage
import com.intellij.openapi.components.impl.stores.StorageUtil
import com.intellij.openapi.components.impl.stores.StreamProvider
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.io.systemIndependentPath
import com.intellij.openapi.vfs.CharsetToolkit
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.LineSeparator
import org.jdom.Element
import org.jdom.JDOMException
import java.io.File
import java.io.IOException
import java.nio.ByteBuffer
open class FileBasedStorage(file: File,
fileSpec: String,
rootElementName: String,
pathMacroManager: TrackingPathMacroSubstitutor? = null,
roamingType: RoamingType? = null,
provider: StreamProvider? = null) : XmlElementStorage(fileSpec, rootElementName, pathMacroManager, roamingType, provider), FileStorage {
private volatile var cachedVirtualFile: VirtualFile? = null
private var lineSeparator: LineSeparator? = null
private var blockSavingTheContent = false
volatile var file = file
private set
init {
if (ApplicationManager.getApplication().isUnitTestMode() && file.getPath().startsWith('$')) {
throw AssertionError("It seems like some macros were not expanded for path: $file")
}
}
protected open val isUseXmlProlog: Boolean = false
// we never set io file to null
override fun setFile(virtualFile: VirtualFile?, ioFileIfChanged: File?) {
cachedVirtualFile = virtualFile
if (ioFileIfChanged != null) {
file = ioFileIfChanged
}
}
override fun createSaveSession(states: StateMap) = FileSaveSession(states, this)
protected open class FileSaveSession(storageData: StateMap, storage: FileBasedStorage) : XmlElementStorage.XmlElementStorageSaveSession<FileBasedStorage>(storageData, storage) {
override fun save() {
if (!storage.blockSavingTheContent) {
super.save()
}
}
override fun saveLocally(element: Element?) {
if (storage.lineSeparator == null) {
storage.lineSeparator = if (storage.isUseXmlProlog) LineSeparator.LF else LineSeparator.getSystemLineSeparator()
}
val virtualFile = storage.getVirtualFile()
if (element == null) {
StorageUtil.deleteFile(storage.file, this, virtualFile)
storage.cachedVirtualFile = null
}
else {
storage.cachedVirtualFile = StorageUtil.writeFile(storage.file, this, virtualFile, element, if (storage.isUseXmlProlog) storage.lineSeparator!! else LineSeparator.LF, storage.isUseXmlProlog)
}
}
}
override fun getVirtualFile(): VirtualFile? {
var result = cachedVirtualFile
if (result == null) {
result = LocalFileSystem.getInstance().findFileByIoFile(file)
cachedVirtualFile = result
}
return cachedVirtualFile
}
override fun loadLocalData(): Element? {
blockSavingTheContent = false
try {
val file = getVirtualFile()
if (file == null || file.isDirectory() || !file.isValid()) {
if (LOG.isDebugEnabled()) {
LOG.debug("Document was not loaded for $fileSpec file is ${if (file == null) "null" else "directory"}")
}
}
else if (file.getLength() == 0L) {
processReadException(null)
}
else {
val charBuffer = CharsetToolkit.UTF8_CHARSET.decode(ByteBuffer.wrap(file.contentsToByteArray()))
lineSeparator = StorageUtil.detectLineSeparators(charBuffer, if (isUseXmlProlog) null else LineSeparator.LF)
return JDOMUtil.loadDocument(charBuffer).detachRootElement()
}
}
catch (e: JDOMException) {
processReadException(e)
}
catch (e: IOException) {
processReadException(e)
}
return null
}
private fun processReadException(e: Exception?) {
val contentTruncated = e == null
blockSavingTheContent = !contentTruncated && (StorageUtil.isProjectOrModuleFile(fileSpec) || fileSpec == StoragePathMacros.WORKSPACE_FILE)
if (!ApplicationManager.getApplication().isUnitTestMode() && !ApplicationManager.getApplication().isHeadlessEnvironment()) {
if (e != null) {
LOG.info(e)
}
Notification(Notifications.SYSTEM_MESSAGES_GROUP_ID, "Load Settings", "Cannot load settings from file '$file': ${if (contentTruncated) "content truncated" else e!!.getMessage()}\n${if (blockSavingTheContent) "Please correct the file content" else "File content will be recreated"}", NotificationType.WARNING).notify(null)
}
}
override fun toString() = file.systemIndependentPath
}
| apache-2.0 | 9a5c7a72f7490111c39b44cad156ecad | 39.408451 | 327 | 0.720112 | 4.925322 | false | false | false | false |
andrewoma/kwery | example/src/main/kotlin/com/github/andrewoma/kwery/example/film/jackson/JacksonExtensions.kt | 1 | 3476 | /*
* Copyright (c) 2015 Andrew O'Malley
*
* 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.github.andrewoma.kwery.example.film.jackson
import com.fasterxml.jackson.annotation.JsonFilter
import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.core.JsonToken
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.SerializerProvider
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonObjectFormatVisitor
import com.fasterxml.jackson.databind.node.ObjectNode
import com.fasterxml.jackson.databind.ser.PropertyFilter
import com.fasterxml.jackson.databind.ser.PropertyWriter
import com.github.andrewoma.kwery.example.film.model.AttributeSet
import com.github.andrewoma.kwery.example.film.model.HasAttributeSet
import java.net.URL
inline fun <reified T : Any> ObjectMapper.withObjectStream(url: URL, f: (Sequence<T>) -> Unit) {
val parser = this.factory.createParser(url)
check(parser.nextToken() == JsonToken.START_ARRAY) { "Expected an array" }
check(parser.nextToken() == JsonToken.START_OBJECT) { "Expected an object" }
try {
val iterator = this.readValues<T>(parser, T::class.java)
f(object : Sequence<T> {
override fun iterator() = iterator
})
} finally {
parser.close()
}
}
// TODO ... sort out how to handle deserialisation of unspecified values into non-null fields
class AttributeSetFilter : PropertyFilter {
override fun serializeAsField(pojo: Any, generator: JsonGenerator, provider: SerializerProvider, writer: PropertyWriter) {
val partial = pojo as HasAttributeSet
if (partial.attributeSet() == AttributeSet.All || writer.name == "id") {
writer.serializeAsField(pojo, generator, provider)
} else {
writer.serializeAsOmittedField(pojo, generator, provider)
}
}
override fun serializeAsElement(p0: Any?, p1: JsonGenerator?, p2: SerializerProvider?, p3: PropertyWriter?) {
throw UnsupportedOperationException()
}
override fun depositSchemaProperty(p0: PropertyWriter?, p1: ObjectNode?, p2: SerializerProvider?) {
throw UnsupportedOperationException()
}
override fun depositSchemaProperty(p0: PropertyWriter?, p1: JsonObjectFormatVisitor?, p2: SerializerProvider?) {
throw UnsupportedOperationException()
}
}
@JsonFilter("Attribute set filter")
class AttributeSetFilterMixIn
| mit | 86c5afcdb5184b0edd3f39e1995725bb | 43 | 126 | 0.747699 | 4.4 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.