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
afollestad/material-cab
sample/src/main/java/com/afollestad/materialcabsample/MainActivity.kt
1
3631
/** * Designed and developed by Aidan Follestad (@afollestad) * * 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.afollestad.materialcabsample import android.os.Bundle import android.view.Menu import androidx.appcompat.app.AppCompatActivity import com.afollestad.materialcab.attached.AttachedCab import com.afollestad.materialcab.attached.destroy import com.afollestad.materialcab.attached.isActive import com.afollestad.materialcab.createCab import com.afollestad.recyclical.datasource.emptySelectableDataSource import com.afollestad.recyclical.setup import com.afollestad.recyclical.viewholder.isSelected import com.afollestad.recyclical.withItem import kotlinx.android.synthetic.main.activity_main.list /** @author Aidan Follestad (afollestad) */ class MainActivity : AppCompatActivity() { private val dataSource = emptySelectableDataSource().apply { onSelectionChange { invalidateCab() } } private var mainCab: AttachedCab? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(findViewById(R.id.main_toolbar)) dataSource.set( IntArray(100) { it + 1 } .map { MainItem("Item #$it") } ) list.setup { withDataSource(dataSource) withItem<MainItem, MainViewHolder>(R.layout.listitem_main) { onBind(::MainViewHolder) { index, item -> itemView.isActivated = isSelected() title.text = item.title icon.setOnClickListener { dataSource.toggleSelectionAt(index) } } onClick { if (hasSelection()) { toggleSelection() } else { toast("Clicked $item") } } onLongClick { toggleSelection() } } } } private fun invalidateCab() { if (!dataSource.hasSelection()) { mainCab?.destroy() return } if (mainCab.isActive()) { mainCab?.apply { title(literal = getString(R.string.x_selected, dataSource.getSelectionCount())) } } else { mainCab = createCab(R.id.cab_stub) { title(literal = getString(R.string.x_selected, dataSource.getSelectionCount())) menu(R.menu.menu_cab) popupTheme(R.style.ThemeOverlay_AppCompat_Light) slideDown() onCreate { _, menu -> onCabCreated(menu) } onSelection { toast(it.title as String) true } onDestroy { dataSource.deselectAll() true } } } } private fun onCabCreated(menu: Menu): Boolean { // Makes the icons in the overflow menu visible if (menu.javaClass.simpleName == "MenuBuilder") { try { val field = menu.javaClass.getDeclaredField("mOptionalIconsVisible") field.isAccessible = true field.setBoolean(menu, true) } catch (ignored: Exception) { ignored.printStackTrace() } } return true // allow creation } override fun onBackPressed() { if (!mainCab.destroy()) { super.onBackPressed() } } }
apache-2.0
22105aec1be322798e863a18aa97a53d
29.512605
87
0.666208
4.411908
false
false
false
false
alygin/intellij-rust
src/main/kotlin/org/rust/ide/inspections/RsApproxConstantInspection.kt
5
2482
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.inspections import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.PsiElement import org.rust.lang.core.psi.RsLitExpr import org.rust.lang.core.psi.RsLiteralKind import org.rust.lang.core.psi.RsVisitor import org.rust.lang.core.psi.kind class RsApproxConstantInspection : RsLocalInspectionTool() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitLitExpr(o: RsLitExpr) { val literal = o.kind if (literal is RsLiteralKind.Float) { val value = literal.value ?: return val constant = KNOWN_CONSTS.find { it.matches(value) } ?: return holder.registerProblem(o, literal.suffix ?: "f64", constant) } } } private companion object { val KNOWN_CONSTS = listOf( PredefinedConstant("E", Math.E, 4), PredefinedConstant("FRAC_1_PI", 1.0 / Math.PI, 4), PredefinedConstant("FRAC_1_SQRT_2", 1.0 / Math.sqrt(2.0), 5), PredefinedConstant("FRAC_2_PI", 2.0 / Math.PI, 5), PredefinedConstant("FRAC_2_SQRT_PI", 2.0 / Math.sqrt(Math.PI), 5), PredefinedConstant("FRAC_PI_2", Math.PI / 2.0, 5), PredefinedConstant("FRAC_PI_3", Math.PI / 3.0, 5), PredefinedConstant("FRAC_PI_4", Math.PI / 4.0, 5), PredefinedConstant("FRAC_PI_6", Math.PI / 6.0, 5), PredefinedConstant("FRAC_PI_8", Math.PI / 8.0, 5), PredefinedConstant("LN_10", Math.log(10.0), 5), PredefinedConstant("LN_2", Math.log(2.0), 5), PredefinedConstant("LOG10_E", Math.log10(Math.E), 5), PredefinedConstant("LOG2_E", Math.log(Math.E) / Math.log(2.0), 5), PredefinedConstant("PI", Math.PI, 3), PredefinedConstant("SQRT_2", Math.sqrt(2.0), 5) ) } } data class PredefinedConstant(val name: String, val value: Double, val minDigits: Int) { val accuracy = Math.pow(0.1, minDigits.toDouble()) fun matches(value: Double) = Math.abs(value - this.value) < accuracy } private fun ProblemsHolder.registerProblem(element: PsiElement, type: String, constant: PredefinedConstant) { registerProblem(element, "Approximate value of `std::$type::consts::${constant.name}` found. Consider using it directly.") }
mit
0d37470ec9e7ceee88ba9428010b3591
42.54386
126
0.63336
3.607558
false
false
false
false
kotlin-everywhere/TodoMVC.kt
client-browser/src/main/kotlin/com/github/kotlin_everywhere/todomvc/store/todo.kt
1
2391
package com.github.kotlin_everywhere.todomvc.store data class Todos(val list: List<Todo>, val listFilter: TodoListFilter) { val activeList by lazy { filterList(TodoState.ACTIVE) } val completeList by lazy { filterList(TodoState.COMPLETE) } val filteredList by lazy { when (listFilter) { TodoListFilter.ALL -> list TodoListFilter.ACTIVE -> activeList TodoListFilter.COMPLETE -> completeList } } private fun filterList(state: TodoState) = list.filter { it.state == state } companion object { private val todos: Todos get() = store.state.todos fun addTodo(text: String) { if (text.isBlank()) { return } setList(todos.list + Todo(Todo.nextSequence(), text, TodoState.ACTIVE, false)) } private fun setList(list: List<Todo>) { store.setTodos(todos.copy(list = list)) } private fun setTodo(todo: Todo, body: Todo.() -> Todo) { setList(todos.list.map { when (it) { todo -> todo.body() else -> it } }) } fun completeAllTodos() { setList(todos.list.map { it.copy(state = TodoState.COMPLETE) }) } fun setTodoState(todo: Todo, state: TodoState) { setTodo(todo) { copy(state = state) } } fun setTodoEditing(todo: Todo, editing: Boolean) { setTodo(todo) { copy(editing = editing) } } fun deleteTodo(todo: Todo) { setList(todos.list.filter { it !== todo }) } fun setTodoText(todo: Todo, text: String) { if (todo.text != text) { setTodo(todo) { copy(text = text) } } } fun setListFilter(listFilter: TodoListFilter) { store.setTodos(todos.copy(listFilter = listFilter)) } fun deleteAllCompleteTodos() { setList(todos.list.filter { it.state != TodoState.COMPLETE }) } } } enum class TodoListFilter { ALL, ACTIVE, COMPLETE } data class Todo(val pk: String, val text: String, val state: TodoState, val editing: Boolean) { companion object { fun nextSequence() = Date().getTime().toString(); } } enum class TodoState { ACTIVE, COMPLETE }
mit
9e2fc1cbe7b99222e1169c9afc6ef16b
26.802326
95
0.551234
4.187391
false
false
false
false
jtransc/jtransc
benchmark_kotlin_mpp/src/commonMain/kotlin/Benchmark.kt
1
18797
@file:Suppress("unused", "DuplicatedCode") import simd.* import kotlin.jvm.JvmStatic import kotlin.random.Random fun main() = Benchmark.main(arrayOf()) class Benchmark { companion object { @JvmStatic fun main(args: Array<String>) { Benchmark().main() } } fun main() { println( """Kotlin ${KotlinVersion.CURRENT} - $kotlinTarget""" ) //println("Java " + System.getProperty("java.version") + " - " + System.getProperty("java.vm.version") + " - " + System.getProperty("java.runtime.version")) //println("freeMemory: " + runtime.freeMemory() + ", maxMemory: " + runtime.maxMemory() + ", totalMemory: " + runtime.totalMemory()) println("Benchmarking:") benchmark("plain loops", object : Task { override fun run(): Int { var m = 0 for (n in 0..999999) { m += n } return m } }) benchmark("shift left constant", object : Task { override fun run(): Int { var m = 0x12345678 for (n in 0..999999) { m += m shl 1 } return m } }) benchmark("shift right constant", object : Task { override fun run(): Int { var m = 0x12345678 for (n in 0..999999) { m += m shr 1 } return m } }) benchmark("shift unsigned right constant", object : Task { override fun run(): Int { var m = 0x12345678 for (n in 0..999999) { m += m ushr 1 } return m } }) benchmark("shift left constant long", object : Task { override fun run(): Int { var m: Long = 0x12345678 for (n in 0..999999) { m += m shl 1 } return m.toInt() } }) benchmark("shift right constant long", object : Task { override fun run(): Int { var m: Long = 0x12345678 for (n in 0..999999) { m += m shr 1 } return m.toInt() } }) benchmark("shift unsigned right constant long", object : Task { override fun run(): Int { var m: Long = 0x12345678 for (n in 0..999999) { m += m ushr 1 } return m.toInt() } }) benchmark("left shift", object : Task { override fun run(): Int { var m = 0x12345678 for (n in 0..999999) { m += (m shl n) + (m shl -n) } return m } }) benchmark("right shift", object : Task { override fun run(): Int { var m = 0x12345678 for (n in 0..999999) { m += (m shr n) + (m shr -n) } return m } }) benchmark("right unsigned shift", object : Task { override fun run(): Int { var m = 0x12345678 for (n in 0..999999) { m += (m ushr n) + (m ushr -n) } return m } }) benchmark("call static mult", object : Task { override fun run(): Int { var m = 0 for (n in 0..999999) { m += calc(m, n) } return m } }) benchmark("call instance mult", object : Task { override fun run(): Int { var m = 0 for (n in 0..999999) { m += calc(m, n) } return m } private fun calc(a: Int, b: Int): Int { return (a + b) * (a + b) } }) benchmark("call instance div", object : Task { override fun run(): Int { var m = 1 for (n in 1..999999) { m += calc(m, n) } return m } private fun calc(a: Int, b: Int): Int { return (a - b) / (a + b) } }) benchmark("instanceof classes", object : Task { override fun run(): Int { var m = 1 val rand = rand(2) val test1 = genObj((rand + 0) % 2) val test2 = genObj((rand + 1) % 2) for (n in 1..999999) { if (test1 is Test1) { m += n - 1 } else if (test1 is Test2) { m += n + 2 } if (test2 is Test1) { m += n - 3 } else if (test2 is Test2) { m += n + 4 } } return m } private fun rand(count: Int): Int { return (currentTimeMillis().toLong() % count.toLong()).toInt() } private fun genObj(index: Int): Any { return when (index) { 0 -> Test1() else -> Test2() } } }) val srcI = IntArray(16 * 1024) val dstI = IntArray(16 * 1024) benchmark("arraycopy int", object : Task { override fun run(): Int { for (n in 0..1023) { arraycopy(srcI, 0, dstI, n, 8 * 1024) } return 0 } }) val barray = ByteArray(1000000) val sarray = ShortArray(1000000) val carray = CharArray(1000000) val iarray = IntArray(1000000) val farray = FloatArray(1000000) val darray = DoubleArray(1000000) benchmark("write byte[]", object : Task { override fun run(): Int { for (n in 0..999999) { barray[n] = (n * 123456711).toByte() } return barray[7].toInt() } }) benchmark("write short[]", object : Task { override fun run(): Int { for (n in 0..999999) { sarray[n] = (n * 1000).toShort() } return sarray[7].toInt() } }) benchmark("write char[]", object : Task { override fun run(): Int { for (n in 0..999999) { carray[n] = (n * 1000).toChar() } return carray[7].toInt() } }) benchmark("write int[]", object : Task { override fun run(): Int { for (n in 0..999999) { iarray[n] = n * 1000 } return iarray[7] } }) benchmark("write float[]", object : Task { override fun run(): Int { for (n in 0..999999) { farray[n] = (n * 1000).toFloat() } return farray[7].toInt() } }) benchmark("write double[]", object : Task { override fun run(): Int { for (n in 0..999999) { darray[n] = (n * 1000).toDouble() } return darray[7].toInt() } }) benchmark("String Builder 1", object : Task { override fun run(): Int { val out = StringBuilder() for (n in 0..99999) { out.append(n) } return out.toString().hashCode() } }) benchmark("String Builder 2", object : Task { override fun run(): Int { val out = StringBuilder() for (n in 0..99999) { out.append("a") } return out.toString().hashCode() } }) benchmark("long arithmetic", object : Task { override fun run(): Int { var a: Long = 0 for (n in 0..99999) { a = 17777L * n.toLong() + a / 3 } return a.toInt() } }) benchmark("simd mutable", object : Task { override fun run(): Int { val a: MutableFloat32x4 = MutableFloat32x4.create() val b: MutableFloat32x4 = MutableFloat32x4.create(2f, 3f, 4f, 5f) for (n in 0..999999) { a.setToAdd(a, b) } return a.x.toInt() + a.y.toInt() + a.z.toInt() + a.w.toInt() } }) benchmark("simd immutable", object : Task { override fun run(): Int { var a: Float32x4 = Float32x4.create(0f, 0f, 0f, 0f) val b: Float32x4 = Float32x4.create(2f, 3f, 4f, 5f) for (n in 0..999999) { a = Float32x4.add(a, b) } return Float32x4.getX(a).toInt() + Float32x4.getY(a).toInt() + Float32x4.getZ(a).toInt() + Float32x4.getW(a).toInt() } }) benchmark("simd mutable matrix mult", object : Task { override fun run(): Int { val a: MutableMatrixFloat32x4x4 = MutableMatrixFloat32x4x4.create() a.setTo( 1f, 9f, 1f, 7f, 3f, 2f, 4f, 5f, 3f, 7f, 3f, 3f, 3f, 8f, 4f, 4f ) val b: MutableMatrixFloat32x4x4 = MutableMatrixFloat32x4x4.create() b.setTo( 2f, 3f, 4f, 5f, 2f, 3f, 4f, 5f, 2f, 3f, 4f, 5f, 2f, 3f, 4f, 5f ) for (n in 0..99999) { a.setToMul44(a, b) } return a.sumAll.toInt() } }) benchmark("StringBuilder1", object : Task { override fun run(): Int { val sb = StringBuilder() for (n in 0..99999) { sb.append("hello") sb.append('w') sb.append("orld") } return sb.toString().length } }) benchmark("StringBuilder2", object : Task { override fun run(): Int { val sb = StringBuilder() sb.ensureCapacity(1000000) for (n in 0..99999) { sb.append("hello") sb.append('w') sb.append("orld") } return sb.toString().length } }) /* benchmark("Non Direct Buffer", object : Task { override fun run(): Int { val bb = ByteBuffer.allocate(1024).order(ByteOrder.nativeOrder()) val ib = bb.asIntBuffer() val fb = bb.asFloatBuffer() var res = 0 for (n in 0..99999) { fb.put(0, n.toFloat()) res += ib[0] } return res } }) benchmark("Direct Buffer Int/float", object : Task { override fun run(): Int { val bb = ByteBuffer.allocateDirect(1024).order(ByteOrder.nativeOrder()) val ib = bb.asIntBuffer() val fb = bb.asFloatBuffer() var res = 0 for (n in 0..99999) { fb.put(0, n.toFloat()) res += ib[0] } return res } }) benchmark("Direct Buffer Short/Char", object : Task { override fun run(): Int { val bb = ByteBuffer.allocateDirect(1024).order(ByteOrder.nativeOrder()) val sb = bb.asShortBuffer() val cb = bb.asCharBuffer() var res = 0 for (n in 0..99999) { cb.put(0, n.toChar()) res += sb[0].toInt() } return res } }) benchmark("Direct Buffer Double/Long", object : Task { override fun run(): Int { val bb = ByteBuffer.allocateDirect(1024).order(ByteOrder.nativeOrder()) val sb = bb.asLongBuffer() val cb = bb.asDoubleBuffer() var res = 0 for (n in 0..99999) { cb.put(0, n.toDouble()) res += sb[0].toInt() } return res } }) */ /* benchmark("FastMemory", object : Task { override fun run(): Int { val mem: FastMemory = FastMemory.alloc(1024) var res = 0 for (n in 0..99999) { mem.setAlignedFloat32(0, n.toFloat()) res += mem.getAlignedInt32(0) } return res } }) */ benchmark("Create Instances1 local", object : Task { override fun run(): Int { var out = 0 for (n in 0..99999) { val myClass = MyClass("test") out += myClass.b } return out } }) gc() benchmark("Create Instances2 local", object : Task { override fun run(): Int { var out = 0 val s = "test" for (n in 0..99999) { val myClass = MyClass2(s, n * out) out += myClass.b } return out } }) val objects = arrayOfNulls<MyClass2>(100000) benchmark("Create Instances2 global", object : Task { override fun run(): Int { var out = 0 val s = "test" for (n in 0..99999) { val v = MyClass2(s, n * out) objects[n] = v out += v.b } return out } }) benchmark("Create Instances with builder", object : Task { override fun run(): Int { var out = 0 for (n in 0..99999) { val myClass = MyClass("test$n") out += myClass.b + myClass.d.hashCode() } return out } }) val hexDataChar = charArrayOf( 0x50.toChar(), 0x4B.toChar(), 0x03.toChar(), 0x04.toChar(), 0x0A.toChar(), 0x03.toChar(), 0x00.toChar(), 0x00.toChar(), 0x00.toChar(), 0x00.toChar(), 0x49.toChar(), 0x9E.toChar(), 0x74.toChar(), 0x48.toChar(), 0xA3.toChar(), 0x1C.toChar(), 0x29.toChar(), 0x1C.toChar(), 0x0C.toChar(), 0x00.toChar(), 0x00.toChar(), 0x00.toChar(), 0x0C.toChar(), 0x00.toChar(), 0x00.toChar(), 0x00.toChar(), 0x09.toChar(), 0x00.toChar(), 0x00.toChar(), 0x00.toChar(), 0x68.toChar(), 0x65.toChar(), 0x6C.toChar(), 0x6C.toChar(), 0x6F.toChar(), 0x2E.toChar(), 0x74.toChar(), 0x78.toChar(), 0x74.toChar(), 0x48.toChar(), 0x65.toChar(), 0x6C.toChar(), 0x6C.toChar(), 0x6F.toChar(), 0x20.toChar(), 0x57.toChar(), 0x6F.toChar(), 0x72.toChar(), 0x6C.toChar(), 0x64.toChar(), 0x21.toChar(), 0x50.toChar(), 0x4B.toChar(), 0x03.toChar(), 0x04.toChar(), 0x14.toChar(), 0x03.toChar(), 0x00.toChar(), 0x00.toChar(), 0x08.toChar(), 0x00.toChar(), 0x35.toChar(), 0xB5.toChar(), 0x74.toChar(), 0x48.toChar(), 0xAA.toChar(), 0xC0.toChar(), 0x69.toChar(), 0x3A.toChar(), 0x1D.toChar(), 0x00.toChar(), 0x00.toChar(), 0x00.toChar(), 0x38.toChar(), 0x07.toChar(), 0x00.toChar(), 0x00.toChar(), 0x0A.toChar(), 0x00.toChar(), 0x00.toChar(), 0x00.toChar(), 0x68.toChar(), 0x65.toChar(), 0x6C.toChar(), 0x6C.toChar(), 0x6F.toChar(), 0x32.toChar(), 0x2E.toChar(), 0x74.toChar(), 0x78.toChar(), 0x74.toChar(), 0xF3.toChar(), 0x48.toChar(), 0xCD.toChar(), 0xC9.toChar(), 0xC9.toChar(), 0x57.toChar(), 0x08.toChar(), 0xCF.toChar(), 0x2F.toChar(), 0xCA.toChar(), 0x49.toChar(), 0x51.toChar(), 0x1C.toChar(), 0x65.toChar(), 0x8F.toChar(), 0xB2.toChar(), 0x47.toChar(), 0xD9.toChar(), 0xA3.toChar(), 0xEC.toChar(), 0x51.toChar(), 0xF6.toChar(), 0x28.toChar(), 0x7B.toChar(), 0x94.toChar(), 0x8D.toChar(), 0x9F.toChar(), 0x0D.toChar(), 0x00.toChar(), 0x50.toChar(), 0x4B.toChar(), 0x01.toChar(), 0x02.toChar(), 0x3F.toChar(), 0x03.toChar(), 0x0A.toChar(), 0x03.toChar(), 0x00.toChar(), 0x00.toChar(), 0x00.toChar(), 0x00.toChar(), 0x49.toChar(), 0x9E.toChar(), 0x74.toChar(), 0x48.toChar(), 0xA3.toChar(), 0x1C.toChar(), 0x29.toChar(), 0x1C.toChar(), 0x0C.toChar(), 0x00.toChar(), 0x00.toChar(), 0x00.toChar(), 0x0C.toChar(), 0x00.toChar(), 0x00.toChar(), 0x00.toChar(), 0x09.toChar(), 0x00.toChar(), 0x00.toChar(), 0x00.toChar(), 0x00.toChar(), 0x00.toChar(), 0x00.toChar(), 0x00.toChar(), 0x00.toChar(), 0x00.toChar(), 0x20.toChar(), 0x80.toChar(), 0xA4.toChar(), 0x81.toChar(), 0x00.toChar(), 0x00.toChar(), 0x00.toChar(), 0x00.toChar(), 0x68.toChar(), 0x65.toChar(), 0x6C.toChar(), 0x6C.toChar(), 0x6F.toChar(), 0x2E.toChar(), 0x74.toChar(), 0x78.toChar(), 0x74.toChar(), 0x50.toChar(), 0x4B.toChar(), 0x01.toChar(), 0x02.toChar(), 0x3F.toChar(), 0x03.toChar(), 0x14.toChar(), 0x03.toChar(), 0x00.toChar(), 0x00.toChar(), 0x08.toChar(), 0x00.toChar(), 0x35.toChar(), 0xB5.toChar(), 0x74.toChar(), 0x48.toChar(), 0xAA.toChar(), 0xC0.toChar(), 0x69.toChar(), 0x3A.toChar(), 0x1D.toChar(), 0x00.toChar(), 0x00.toChar(), 0x00.toChar(), 0x38.toChar(), 0x07.toChar(), 0x00.toChar(), 0x00.toChar(), 0x0A.toChar(), 0x00.toChar(), 0x00.toChar(), 0x00.toChar(), 0x00.toChar(), 0x00.toChar(), 0x00.toChar(), 0x00.toChar(), 0x00.toChar(), 0x00.toChar(), 0x20.toChar(), 0x80.toChar(), 0xA4.toChar(), 0x81.toChar(), 0x33.toChar(), 0x00.toChar(), 0x00.toChar(), 0x00.toChar(), 0x68.toChar(), 0x65.toChar(), 0x6C.toChar(), 0x6C.toChar(), 0x6F.toChar(), 0x32.toChar(), 0x2E.toChar(), 0x74.toChar(), 0x78.toChar(), 0x74.toChar(), 0x50.toChar(), 0x4B.toChar(), 0x05.toChar(), 0x06.toChar(), 0x00.toChar(), 0x00.toChar(), 0x00.toChar(), 0x00.toChar(), 0x02.toChar(), 0x00.toChar(), 0x02.toChar(), 0x00.toChar(), 0x6F.toChar(), 0x00.toChar(), 0x00.toChar(), 0x00.toChar(), 0x78.toChar(), 0x00.toChar(), 0x00.toChar(), 0x00.toChar(), 0x00.toChar(), 0x00 .toChar() ) val hexData = ByteArray(hexDataChar.size) for (n in hexDataChar.indices) hexData[n] = hexDataChar[n].toByte() benchmark("Java's CRC32", object : Task { override fun run(): Int { var out = 0 val crc32 = CRC32() for (n in 0..9999) { crc32.reset() crc32.update(hexData, 0, hexData.size) out += crc32.value } return out } }) benchmark("jzlib's CRC32", object : Task { override fun run(): Int { var out = 0 val crc32 = CRC32() for (n in 0..9999) { crc32.reset() crc32.update(hexData, 0, hexData.size) out += crc32.value } return out } }) //benchmark("decompress zlib", new Task() { // @Override // public int run() { // // //new ZipFile("memory://hex") // //com.jtransc.compression.JTranscZlib.inflate(hexData, 1848); // return -1; // //try { // // InflaterInputStream is = new InflaterInputStream(new ByteArrayInputStream(hexData)); // // ByteArrayOutputStream out = new ByteArrayOutputStream(); // // com.jtransc.io.JTranscIoTools.copy(is, out); // // return (int) out.size(); // //} catch (Throwable t) { // // t.printStackTrace(); // // return 0; // //} // } //}); val random = Random(0L) val bytes = ByteArray(64 * 1024) for (n in bytes.indices) bytes[n] = random.nextInt().toByte() /* benchmark("compress java's Deflate", object : Task { override fun run(): Int { return try { val out = ByteArray(128 * 1024) val deflater = Deflater(9, false) deflater.setInput(bytes, 0, bytes.size) deflater.deflate(out, 0, out.size, Deflater.FULL_FLUSH) } catch (t: Throwable) { t.printStackTrace() 0 } } }) benchmark("compress jzlib", object : Task { override fun run(): Int { return try { val out = ByteArray(128 * 1024) val deflater = Deflater(9, false) deflater.setInput(bytes, 0, bytes.size, false) deflater.setOutput(out, 0, out.size) deflater.deflate(3) } catch (t: Throwable) { t.printStackTrace() 0 } } }) */ benchmark("random", object : Task { override fun run(): Int { val rand = Random(0L) val len = 64 * 1024 val bytes2 = ByteArray(len) var sum = 0 for (n in bytes2.indices) { bytes2[n] = rand.nextInt().toByte() sum += bytes2[n] } return sum } }) benchmark("exception", object : Task { override fun run(): Int { var m = 0 for (n in 0..999) { try { throw Throwable() } catch (e: Throwable) { m++ } } return m } }) println("TOTAL time: " + totalTime) //try { // throw new Throwable(); //} catch (Throwable e) { // e.printStackTrace(); //} //new Throwable().printStackTrace(); } private var totalTime = 0.0 private fun benchmark(name: String, run: Task) { print("$name...") try { //val t1: Double = currentTimeMillis() for (n in 0..9) run.run() // warming up gc() val t2: Double = currentTimeMillis() for (n in 0..9) run.run() val t3: Double = currentTimeMillis() //System.out.println("( " + (t2 - t1) + " ) :: ( " + (t3 - t2) + " )"); //System.out.println((double)(t3 - t2) / 1000000.0); val elapsedTime: Double = t3 - t2 println(elapsedTime) totalTime += elapsedTime } catch (t: Throwable) { t.printStackTrace() //System.out.println(t.getMessage()); } } fun calc(a: Int, b: Int): Int { return (a + b) * (a + b) } internal interface Task { fun run(): Int } private class Test1 private class Test2 internal class MyClass(var d: String) { var a = 10 var b = 20 var c = "hello" } internal class MyClass2(var d: String, b: Int) { var a = 10 var b = 20 var c = "hello" init { this.b = b } } }
apache-2.0
3b6a708c43b3d0532c6d5757348185a4
20.730636
158
0.558706
2.686821
false
false
false
false
http4k/http4k
http4k-core/src/test/kotlin/org/http4k/core/UriTemplateTest.kt
1
5410
package org.http4k.core import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import org.http4k.core.UriTemplate.Companion.from import org.junit.jupiter.api.Disabled import org.junit.jupiter.api.Test class UriTemplateTest { @Test fun encodesOnlyPathParamsWhichDontContainForwardSlashes() { val template = from("properties/{name}") assertThat( template.generate(pathParameters(pair("name", "a name with spaces"))), equalTo("properties/a%20name%20with%20spaces")) assertThat( template.generate(pathParameters(pair("name", "a/name/with/slashes"))), equalTo("properties/a/name/with/slashes")) } @Test fun supportsMultiplePathParams() { val template = from("properties/{id}/{name}") assertThat(template.matches("properties/123/bob"), equalTo(true)) val parameters = template.extract("properties/123/bob") assertThat(parameters.getValue("id"), equalTo("123")) assertThat(parameters.getValue("name"), equalTo("bob")) assertThat(template.generate(pathParameters(pair("id", "123"), pair("name", "bob"))), equalTo("properties/123/bob")) } @Test fun doesNotCaptureEnd() { val template1 = from("path") assertThat(template1.matches("path/123"), equalTo(false)) val template = from("path/{id}") assertThat(template.matches("path/123/someotherpath"), equalTo(false)) assertThat(template.matches("path/123"), equalTo(true)) assertThat(template.generate(pathParameters(pair("id", "123"))), equalTo("path/123")) } @Test fun supportsCustomRegex() { val template = from("path/{id:\\d}") assertThat(template.matches("path/foo"), equalTo(false)) assertThat(template.matches("path/1"), equalTo(true)) assertThat(template.extract("path/1").getValue("id"), equalTo("1")) } @Test fun canMatch() { assertThat(from("path/{id}").matches("path/foo"), equalTo(true)) assertThat(from("/path/{id}").matches("/path/foo"), equalTo(true)) assertThat(from("/path/{id}/").matches("/path/foo"), equalTo(true)) assertThat(from("/path/{id}/").matches("path/foo"), equalTo(true)) assertThat(from("path/{id}").matches("/path/foo"), equalTo(true)) } @Test fun canExtractFromUri() { val template = from("path/{id}") assertThat(template.extract("path/foo").getValue("id"), equalTo("foo")) } @Test fun fallbackDoesNotWork() { val template = from("/b/c") assertThat(template.matches("/b/c/e/f"), equalTo(false)) } @Test fun canExtractFromUri_withLeadingSlash() { val template = from("/{id:.+}/{id2:.+}") val extracted = template.extract("/foo/bar") assertThat(extracted.getValue("id"), equalTo("foo")) assertThat(extracted.getValue("id2"), equalTo("bar")) } @Test fun canExtractFromUri_withTrailingSlash() { val template = from("/{id:.+}/{id2:.+}/") val extracted = template.extract("/foo/bar/") assertThat(extracted.getValue("id"), equalTo("foo")) assertThat(extracted.getValue("id2"), equalTo("bar")) val extractedNoTrailing = template.extract("/foo/bar/") assertThat(extractedNoTrailing.getValue("id"), equalTo("foo")) assertThat(extractedNoTrailing.getValue("id2"), equalTo("bar")) } @Test fun canExtractFromUriWithEncodedSpace() { val template = from("path/{id1}") assertThat(template.extract("path/foo%20bar").getValue("id1"), equalTo("foo bar")) } @Test fun canGenerateUri() { val template = from("path/{id}") assertThat(template.generate(pathParameters(pair("id", "foo"))), equalTo("path/foo")) } @Test fun doesNotDecodeSlashesWhenCapturing() { val extracted = from("path/{first}/{second}").extract("path/1%2F2/3") assertThat(extracted.getValue("first"), equalTo("1/2")) assertThat(extracted.getValue("second"), equalTo("3")) } @Test fun matchedValuesArePathDecoded() { val extracted = from("path/{band}").extract("path/Earth%2C%20Wind%20%26%20Fire") assertThat(extracted.getValue("band"), equalTo("Earth, Wind & Fire")) } @Test fun capturingPathVariableWithSlashes() { val template = from("/{anything:.*}") assertThat(template.matches("/foo/bar"), equalTo(true)) assertThat(template.extract("/foo/bar").getValue("anything"), equalTo("foo/bar")) } @Test fun doesNotMatchPathWithSlashesForUnnamedVariable() { assertThat(from("/{:.*}").matches("/foo/bar"), equalTo(false)) assertThat(from("/{something:.*}").matches("/foo/bar"), equalTo(true)) } @Test fun doesNotMatchEmptyPathSegment() { assertThat(from("/foo/{bar:.*}").matches("/foo/bar"), equalTo(true)) assertThat(from("/foo/{bar:.*}").matches("/foo"), equalTo(false)) } @Test @Disabled fun greedyQualifiersAreNotReplaced() { val patternWithGreedyQualifier = "[a-z]{3}" assertThat(from("/foo/{bar:$patternWithGreedyQualifier}").matches("/foo/abc"), equalTo(true)) } private fun pathParameters(vararg pairs: Pair<String, String>): Map<String, String> = mapOf(*pairs) private fun pair(v1: String, v2: String) = v1 to v2 }
apache-2.0
a519124306694f55bdc331951bb4c726
36.054795
124
0.630869
4.073795
false
true
false
false
laurencegw/jenjin
jenjin-spine/src/main/kotlin/com/binarymonks/jj/spine/components/SpineComponent.kt
1
6447
package com.binarymonks.jj.spine.components import com.badlogic.gdx.utils.Array import com.badlogic.gdx.utils.ObjectMap import com.binarymonks.jj.core.JJ import com.binarymonks.jj.core.components.Component import com.binarymonks.jj.core.scenes.Scene import com.binarymonks.jj.core.scenes.ScenePath import com.binarymonks.jj.spine.render.SpineRenderNode import com.binarymonks.jj.spine.specs.SpineAnimations import com.esotericsoftware.spine.AnimationState import com.esotericsoftware.spine.AnimationStateData import com.esotericsoftware.spine.Event import com.esotericsoftware.spine.attachments.Attachment val SPINE_RENDER_NAME = "SPINE_RENDER_NODE" class SpineComponent( var animations: SpineAnimations ) : Component() { constructor() : this(SpineAnimations()) internal var spineBoneComponents: ObjectMap<String, SpineBoneComponent> = ObjectMap() internal var rootBone: SpineBoneComponent? = null internal var animationListener = JJSpineAnimationStateListener(this) lateinit internal var spineRenderNode: SpineRenderNode lateinit internal var animationState: AnimationState internal var ragDoll = false var bonePaths: ObjectMap<String, ScenePath> = ObjectMap() private var hiddenSlotAttachments: ObjectMap<String, Attachment> = ObjectMap() override fun onAddToWorld() { spineRenderNode = me().renderRoot.getNode(SPINE_RENDER_NAME) as SpineRenderNode initialiseAnimations() bonePaths.forEach { it.value.from(me()).getComponent(SpineBoneComponent::class).first().setSpineComponent(me()) if (it.value.path.size == 1) { rootBone = it.value.from(me()).getComponent(SpineBoneComponent::class).first() } } val shows = Array<String>() hiddenSlotAttachments.forEach { shows.add(it.key) } shows.forEach { show(it) } if (ragDoll) { reverseRagDoll() } } override fun update() { animationState.update(JJ.clock.deltaFloat) animationState.apply(spineRenderNode.skeleton) } private fun initialiseAnimations() { //FIXME: There must be a problem with pooling and doing this! val stateData = AnimationStateData(spineRenderNode.skeletonData) stateData.defaultMix = animations.defaultMix animations.mixes.forEach { stateData.setMix(it.fromName, it.toName, it.duration) } animationState = AnimationState(stateData) if (animations.startingAnimation != null) { animationState.setAnimation(0, animations.startingAnimation, true) } animationListener.spineAnimations = animations animationState.addListener(animationListener) } fun animationState(): AnimationState { return animationState } fun applyToBones(sceneOperation: (Scene) -> Unit) { bonePaths.forEach { sceneOperation(it.value.from(me())) } } fun hide(slotName: String) { if (!hiddenSlotAttachments.containsKey(slotName)) { spineRenderNode.skeleton.slots.forEach { if (it.data.name == slotName) { hiddenSlotAttachments.put(slotName, it.attachment) it.attachment = null } } } } fun show(slotName: String) { if (hiddenSlotAttachments.containsKey(slotName)) { spineRenderNode.skeleton.slots.forEach { if (it.data.name == slotName) { it.attachment = hiddenSlotAttachments.get(slotName) hiddenSlotAttachments.remove(slotName) } } } } fun transitionToAnimation(animationName: String) { animationState.setAnimation(0, animationName, true) } fun triggerRagDollBelow(rootBoneName: String, gravity: Float = 1f) { val component = spineBoneComponents.get(rootBoneName) component.triggerRagDoll(gravity) } internal fun addBone(name: String, spineBoneComponent: SpineBoneComponent) { spineBoneComponents.put(name, spineBoneComponent) spineBoneComponent.spineParent = this } fun getBone(name: String): SpineBoneComponent { return spineBoneComponents.get(name) } override fun onRemoveFromWorld() { spineBoneComponents.clear() animationState.removeListener(animationListener) animationListener.spineAnimations = null } fun myRender(): SpineRenderNode { return checkNotNull(spineRenderNode) } fun reverseRagDoll() { if (ragDoll) { ragDoll = false rootBone!!.reverseRagDoll() } } fun triggerRagDoll(gravity: Float = 1f) { if (!ragDoll) { ragDoll = true rootBone!!.triggerRagDoll(gravity) } } override fun clone(): Component { return super.clone() } } class JJSpineAnimationStateListener( val spineComponent: SpineComponent, var spineAnimations: SpineAnimations? = null ) : AnimationState.AnimationStateListener { override fun start(entry: AnimationState.TrackEntry) { } override fun interrupt(entry: AnimationState.TrackEntry) { } override fun end(entry: AnimationState.TrackEntry) { } override fun dispose(entry: AnimationState.TrackEntry) { } override fun complete(entry: AnimationState.TrackEntry) { } override fun event(entry: AnimationState.TrackEntry, event: Event) { val name = event.data.name if (spineAnimations!!.handlers.containsKey(name)) { spineAnimations!!.handlers.get(name)(spineComponent, event) } if (spineAnimations!!.functions.containsKey(name)) { spineAnimations!!.functions.get(name)() } if (spineAnimations!!.componentHandlers.containsKey(name)) { val mapping = spineAnimations!!.componentHandlers.get(name) spineComponent.me().getComponent(mapping.componentType).forEach { mapping.componentFunction.invoke(it, event) } } if (spineAnimations!!.componentFunctions.containsKey(name)) { val mapping = spineAnimations!!.componentFunctions.get(name) spineComponent.me().getComponent(mapping.componentType).forEach { mapping.componentFunction.invoke(it) } } } }
apache-2.0
e7e7821c6429e0212ba05567e612610d
31.897959
103
0.661083
4.671739
false
false
false
false
blackbbc/Tucao
app/src/main/kotlin/me/sweetll/tucao/widget/HorizontalDivider.kt
1
1668
package me.sweetll.tucao.widget import android.graphics.Canvas import android.graphics.Rect import android.graphics.drawable.Drawable import androidx.recyclerview.widget.RecyclerView import android.view.View class HorizontalDivider(private val divider: Drawable, private val drawFirstItemTop: Boolean, private val leftPadding: Int, private val rightPadding: Int) : RecyclerView.ItemDecoration() { override fun onDraw(canvas: Canvas, parent: RecyclerView, state: RecyclerView.State) { val left = parent.paddingLeft val right = parent.width - parent.paddingRight val childCount = parent.childCount for (i in 0 until childCount) { val child = parent.getChildAt(i) //获得child的布局信息 val params = child.layoutParams as RecyclerView.LayoutParams var top = child.bottom + params.bottomMargin var bottom = top + divider.intrinsicHeight divider.setBounds(left + leftPadding, top, right - rightPadding, bottom) divider.draw(canvas) if (drawFirstItemTop && i == 1) { bottom = child.top + params.topMargin top = bottom - divider.intrinsicHeight divider.setBounds(left, top, right, bottom) divider.draw(canvas) } } } override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) { outRect.bottom = divider.intrinsicHeight if (drawFirstItemTop && parent.getChildAdapterPosition(view) == 0) { outRect.top = divider.intrinsicHeight } } }
mit
8e2c4e398646e1ff89598f00ba73f35e
40.35
118
0.654776
4.937313
false
false
false
false
Vavassor/Tusky
app/src/main/java/com/keylesspalace/tusky/fragment/AccountMediaFragment.kt
1
13175
/* Copyright 2017 Andrew Dawson * * This file is a part of Tusky. * * 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. * * Tusky 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 Tusky; if not, * see <http://www.gnu.org/licenses>. */ package com.keylesspalace.tusky.fragment import android.graphics.Color import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import androidx.core.app.ActivityOptionsCompat import androidx.core.content.ContextCompat import androidx.core.view.ViewCompat import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView import com.keylesspalace.tusky.R import com.keylesspalace.tusky.ViewMediaActivity import com.keylesspalace.tusky.di.Injectable import com.keylesspalace.tusky.entity.Attachment import com.keylesspalace.tusky.entity.Status import com.keylesspalace.tusky.network.MastodonApi import com.keylesspalace.tusky.util.ThemeUtils import com.keylesspalace.tusky.util.hide import com.keylesspalace.tusky.util.show import com.keylesspalace.tusky.view.SquareImageView import com.keylesspalace.tusky.viewdata.AttachmentViewData import com.squareup.picasso.Picasso import kotlinx.android.synthetic.main.fragment_timeline.* import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.io.IOException import java.util.* import javax.inject.Inject /** * Created by charlag on 26/10/2017. * * Fragment with multiple columns of media previews for the specified account. */ class AccountMediaFragment : BaseFragment(), Injectable { companion object { @JvmStatic fun newInstance(accountId: String): AccountMediaFragment { val fragment = AccountMediaFragment() val args = Bundle() args.putString(ACCOUNT_ID_ARG, accountId) fragment.arguments = args return fragment } private const val ACCOUNT_ID_ARG = "account_id" private const val TAG = "AccountMediaFragment" } @Inject lateinit var api: MastodonApi private val adapter = MediaGridAdapter() private var currentCall: Call<List<Status>>? = null private val statuses = mutableListOf<Status>() private var fetchingStatus = FetchingStatus.NOT_FETCHING private var isVisibleToUser: Boolean = false private val callback = object : Callback<List<Status>> { override fun onFailure(call: Call<List<Status>>?, t: Throwable?) { fetchingStatus = FetchingStatus.NOT_FETCHING if(isAdded) { swipeRefreshLayout.isRefreshing = false progressBar.visibility = View.GONE statusView.show() if (t is IOException) { statusView.setup(R.drawable.elephant_offline, R.string.error_network) { doInitialLoadingIfNeeded() } } else { statusView.setup(R.drawable.elephant_error, R.string.error_generic) { doInitialLoadingIfNeeded() } } } Log.d(TAG, "Failed to fetch account media", t) } override fun onResponse(call: Call<List<Status>>, response: Response<List<Status>>) { fetchingStatus = FetchingStatus.NOT_FETCHING if(isAdded) { swipeRefreshLayout.isRefreshing = false progressBar.visibility = View.GONE val body = response.body() body?.let { fetched -> statuses.addAll(0, fetched) // flatMap requires iterable but I don't want to box each array into list val result = mutableListOf<AttachmentViewData>() for (status in fetched) { result.addAll(AttachmentViewData.list(status)) } adapter.addTop(result) if (statuses.isEmpty()) { statusView.show() statusView.setup(R.drawable.elephant_friend_empty, R.string.message_empty, null) } } } } } private val bottomCallback = object : Callback<List<Status>> { override fun onFailure(call: Call<List<Status>>?, t: Throwable?) { fetchingStatus = FetchingStatus.NOT_FETCHING Log.d(TAG, "Failed to fetch account media", t) } override fun onResponse(call: Call<List<Status>>, response: Response<List<Status>>) { fetchingStatus = FetchingStatus.NOT_FETCHING val body = response.body() body?.let { fetched -> Log.d(TAG, "fetched ${fetched.size} statuses") if (fetched.isNotEmpty()) Log.d(TAG, "first: ${fetched.first().id}, last: ${fetched.last().id}") statuses.addAll(fetched) Log.d(TAG, "now there are ${statuses.size} statuses") // flatMap requires iterable but I don't want to box each array into list val result = mutableListOf<AttachmentViewData>() for (status in fetched) { result.addAll(AttachmentViewData.list(status)) } adapter.addBottom(result) } } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_timeline, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val columnCount = view.context.resources.getInteger(R.integer.profile_media_column_count) val layoutManager = GridLayoutManager(view.context, columnCount) val bgRes = ThemeUtils.getColorId(view.context, R.attr.window_background) adapter.baseItemColor = ContextCompat.getColor(recyclerView.context, bgRes) recyclerView.layoutManager = layoutManager recyclerView.adapter = adapter val accountId = arguments?.getString(ACCOUNT_ID_ARG) swipeRefreshLayout.setOnRefreshListener { statusView.hide() if (fetchingStatus != FetchingStatus.NOT_FETCHING) return@setOnRefreshListener currentCall = if (statuses.isEmpty()) { fetchingStatus = FetchingStatus.INITIAL_FETCHING api.accountStatuses(accountId, null, null, null, null, true, null) } else { fetchingStatus = FetchingStatus.REFRESHING api.accountStatuses(accountId, null, statuses[0].id, null, null, true, null) } currentCall?.enqueue(callback) } swipeRefreshLayout.setColorSchemeResources(R.color.tusky_blue) swipeRefreshLayout.setProgressBackgroundColorSchemeColor(ThemeUtils.getColor(view.context, android.R.attr.colorBackground)) statusView.visibility = View.GONE recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrolled(recycler_view: RecyclerView, dx: Int, dy: Int) { if (dy > 0) { val itemCount = layoutManager.itemCount val lastItem = layoutManager.findLastCompletelyVisibleItemPosition() if (itemCount <= lastItem + 3 && fetchingStatus == FetchingStatus.NOT_FETCHING) { statuses.lastOrNull()?.let { last -> Log.d(TAG, "Requesting statuses with max_id: ${last.id}, (bottom)") fetchingStatus = FetchingStatus.FETCHING_BOTTOM currentCall = api.accountStatuses(accountId, last.id, null, null, null, true, null) currentCall?.enqueue(bottomCallback) } } } } }) if (isVisibleToUser) doInitialLoadingIfNeeded() } // That's sort of an optimization to only load media once user has opened the tab // Attention: can be called before *any* lifecycle method! override fun setUserVisibleHint(isVisibleToUser: Boolean) { super.setUserVisibleHint(isVisibleToUser) this.isVisibleToUser = isVisibleToUser if (isVisibleToUser && isAdded) doInitialLoadingIfNeeded() } private fun doInitialLoadingIfNeeded() { if (isAdded) { statusView.hide() } val accountId = arguments?.getString(ACCOUNT_ID_ARG) if (fetchingStatus == FetchingStatus.NOT_FETCHING && statuses.isEmpty()) { fetchingStatus = FetchingStatus.INITIAL_FETCHING currentCall = api.accountStatuses(accountId, null, null, null, null, true, null) currentCall?.enqueue(callback) } } private fun viewMedia(items: List<AttachmentViewData>, currentIndex: Int, view: View?) { val type = items[currentIndex].attachment.type when (type) { Attachment.Type.IMAGE, Attachment.Type.GIFV, Attachment.Type.VIDEO -> { val intent = ViewMediaActivity.newIntent(context, items, currentIndex) if (view != null && activity != null) { val url = items[currentIndex].attachment.url ViewCompat.setTransitionName(view, url) val options = ActivityOptionsCompat.makeSceneTransitionAnimation(activity!!, view, url) startActivity(intent, options.toBundle()) } else { startActivity(intent) } } Attachment.Type.UNKNOWN -> { }/* Intentionally do nothing. This case is here is to handle when new attachment * types are added to the API before code is added here to handle them. So, the * best fallback is to just show the preview and ignore requests to view them. */ } } private enum class FetchingStatus { NOT_FETCHING, INITIAL_FETCHING, FETCHING_BOTTOM, REFRESHING } inner class MediaGridAdapter : RecyclerView.Adapter<MediaGridAdapter.MediaViewHolder>() { var baseItemColor = Color.BLACK private val items = mutableListOf<AttachmentViewData>() private val itemBgBaseHSV = FloatArray(3) private val random = Random() fun addTop(newItems: List<AttachmentViewData>) { items.addAll(0, newItems) notifyItemRangeInserted(0, newItems.size) } fun addBottom(newItems: List<AttachmentViewData>) { if (newItems.isEmpty()) return val oldLen = items.size items.addAll(newItems) notifyItemRangeInserted(oldLen, newItems.size) } override fun onAttachedToRecyclerView(recycler_view: RecyclerView) { val hsv = FloatArray(3) Color.colorToHSV(baseItemColor, hsv) super.onAttachedToRecyclerView(recycler_view) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MediaViewHolder { val view = SquareImageView(parent.context) view.scaleType = ImageView.ScaleType.CENTER_CROP return MediaViewHolder(view) } override fun getItemCount(): Int = items.size override fun onBindViewHolder(holder: MediaViewHolder, position: Int) { itemBgBaseHSV[2] = random.nextFloat() * (1f - 0.3f) + 0.3f holder.imageView.setBackgroundColor(Color.HSVToColor(itemBgBaseHSV)) val item = items[position] val maxW = holder.imageView.context.resources.getInteger(R.integer.media_max_width) val maxH = holder.imageView.context.resources.getInteger(R.integer.media_max_height) Picasso.with(holder.imageView.context) .load(item.attachment.previewUrl) .resize(maxW, maxH) .onlyScaleDown() .centerInside() .into(holder.imageView) } inner class MediaViewHolder(val imageView: ImageView) : RecyclerView.ViewHolder(imageView), View.OnClickListener { init { itemView.setOnClickListener(this) } // saving some allocations override fun onClick(v: View?) { viewMedia(items, adapterPosition, imageView) } } } }
gpl-3.0
a68c2a0552258af97561a4b705a5f3f0
38.927273
131
0.624061
5.051764
false
false
false
false
googlecodelabs/android-paging
advanced/start/app/src/main/java/com/example/android/codelabs/paging/data/GithubRepository.kt
1
4083
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.codelabs.paging.data import android.util.Log import com.example.android.codelabs.paging.api.GithubService import com.example.android.codelabs.paging.api.IN_QUALIFIER import com.example.android.codelabs.paging.model.Repo import com.example.android.codelabs.paging.model.RepoSearchResult import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableSharedFlow import retrofit2.HttpException import java.io.IOException // GitHub page API is 1 based: https://developer.github.com/v3/#pagination private const val GITHUB_STARTING_PAGE_INDEX = 1 /** * Repository class that works with local and remote data sources. */ class GithubRepository(private val service: GithubService) { // keep the list of all results received private val inMemoryCache = mutableListOf<Repo>() // shared flow of results, which allows us to broadcast updates so // the subscriber will have the latest data private val searchResults = MutableSharedFlow<RepoSearchResult>(replay = 1) // keep the last requested page. When the request is successful, increment the page number. private var lastRequestedPage = GITHUB_STARTING_PAGE_INDEX // avoid triggering multiple requests in the same time private var isRequestInProgress = false /** * Search repositories whose names match the query, exposed as a stream of data that will emit * every time we get more data from the network. */ suspend fun getSearchResultStream(query: String): Flow<RepoSearchResult> { Log.d("GithubRepository", "New query: $query") lastRequestedPage = 1 inMemoryCache.clear() requestAndSaveData(query) return searchResults } suspend fun requestMore(query: String) { if (isRequestInProgress) return val successful = requestAndSaveData(query) if (successful) { lastRequestedPage++ } } suspend fun retry(query: String) { if (isRequestInProgress) return requestAndSaveData(query) } private suspend fun requestAndSaveData(query: String): Boolean { isRequestInProgress = true var successful = false val apiQuery = query + IN_QUALIFIER try { val response = service.searchRepos(apiQuery, lastRequestedPage, NETWORK_PAGE_SIZE) Log.d("GithubRepository", "response $response") val repos = response.items ?: emptyList() inMemoryCache.addAll(repos) val reposByName = reposByName(query) searchResults.emit(RepoSearchResult.Success(reposByName)) successful = true } catch (exception: IOException) { searchResults.emit(RepoSearchResult.Error(exception)) } catch (exception: HttpException) { searchResults.emit(RepoSearchResult.Error(exception)) } isRequestInProgress = false return successful } private fun reposByName(query: String): List<Repo> { // from the in memory cache select only the repos whose name or description matches // the query. Then order the results. return inMemoryCache.filter { it.name.contains(query, true) || (it.description != null && it.description.contains(query, true)) }.sortedWith(compareByDescending<Repo> { it.stars }.thenBy { it.name }) } companion object { const val NETWORK_PAGE_SIZE = 30 } }
apache-2.0
58f60cf8b551aa16d1e3da2347db8de1
36.118182
98
0.695812
4.650342
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/libanki/sync/Tls12SocketFactory.kt
1
6710
/**************************************************************************************** * Copyright (c) 2019 Mike Hardy <[email protected]> * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 3 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************************/ package com.ichi2.libanki.sync import android.os.Build import com.ichi2.anki.AnkiDroidApp import com.ichi2.utils.KotlinCleanup import okhttp3.ConnectionSpec import okhttp3.OkHttpClient import okhttp3.TlsVersion import timber.log.Timber import java.io.IOException import java.net.InetAddress import java.net.Socket import java.security.KeyStore import java.security.cert.Certificate import java.security.cert.CertificateException import java.security.cert.CertificateFactory import javax.net.ssl.SSLContext import javax.net.ssl.SSLSocket import javax.net.ssl.SSLSocketFactory import javax.net.ssl.TrustManager /** * Enables TLS v1.2 when creating SSLSockets. * * * This hack is currently only maintained with API >= 21 for some Samsung API21 phones * * @link https://developer.android.com/reference/javax/net/ssl/SSLSocket.html * @see SSLSocketFactory */ class Tls12SocketFactory private constructor( private val delegate: SSLSocketFactory ) : SSLSocketFactory() { override fun getDefaultCipherSuites(): Array<String> { return delegate.defaultCipherSuites } override fun getSupportedCipherSuites(): Array<String> { return delegate.supportedCipherSuites } @Throws(IOException::class) override fun createSocket(s: Socket, host: String, port: Int, autoClose: Boolean): Socket { return patch(delegate.createSocket(s, host, port, autoClose)) } @Throws(IOException::class) override fun createSocket(host: String, port: Int): Socket { return patch(delegate.createSocket(host, port)) } @Throws(IOException::class) override fun createSocket( host: String, port: Int, localHost: InetAddress, localPort: Int ): Socket { return patch(delegate.createSocket(host, port, localHost, localPort)) } @Throws(IOException::class) override fun createSocket(host: InetAddress, port: Int): Socket { return patch(delegate.createSocket(host, port)) } @Throws(IOException::class) override fun createSocket( address: InetAddress, port: Int, localAddress: InetAddress, localPort: Int ): Socket { return patch(delegate.createSocket(address, port, localAddress, localPort)) } private fun patch(s: Socket): Socket { if (s is SSLSocket) { s.enabledProtocols = TLS_V12_ONLY } // Note if progress tracking needs to be more granular than default OkHTTP buffer, do this: // try { // s.setSendBufferSize(16 * 1024); // // We will only know if this is a problem if people complain about progress bar going to 100% // // on small transfers (indicating buffer ate all contents) before transfer finishes (because buffer is still flushing) // // Important to say that this can slow things down dramatically though so needs tuning. With 16kb throughput was 40kb/s // // By default throughput was maxing my 50Mbit line out (!) // } catch (SocketException se) { // Timber.e(se, "Unable to set socket send buffer size"); // } return s } companion object { private val TLS_V12_ONLY = arrayOf("TLSv1.2") fun enableTls12OnPreLollipop(client: OkHttpClient.Builder): OkHttpClient.Builder { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1 && "Samsung" == Build.MANUFACTURER) { try { Timber.d("Creating unified TrustManager") val cert = userTrustRootCertificate val keyStoreType = KeyStore.getDefaultType() val keyStore = KeyStore.getInstance(keyStoreType) keyStore.load(null, null) keyStore.setCertificateEntry("ca", cert) val trustManager = UnifiedTrustManager(keyStore) Timber.d("Finished: Creating unified TrustManager") val sc = SSLContext.getInstance("TLSv1.2") sc.init(null, arrayOf<TrustManager>(trustManager), null) val socketFactory = Tls12SocketFactory(sc.socketFactory) client.sslSocketFactory(socketFactory, trustManager) val cs: ConnectionSpec = ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) .tlsVersions(TlsVersion.TLS_1_2) .build() val specs: MutableList<ConnectionSpec> = ArrayList(3) specs.add(cs) specs.add(ConnectionSpec.COMPATIBLE_TLS) specs.add(ConnectionSpec.CLEARTEXT) client.connectionSpecs(specs) } catch (exc: Exception) { Timber.e(exc, "Error while setting TLS 1.2") } } return client } @get:Throws(CertificateException::class, IOException::class) @KotlinCleanup("has one usage inside this class, try to inline this property") private val userTrustRootCertificate: Certificate get() { val cf = CertificateFactory.getInstance("X.509") AnkiDroidApp.getResourceAsStream("assets/USERTrust_RSA.crt") .use { crt -> return cf.generateCertificate(crt) } } } }
gpl-3.0
2be8503717e3cf8f4640371d38cf682d
41.738854
133
0.588972
5.045113
false
false
false
false
Samourai-Wallet/samourai-wallet-android
app/src/main/java/com/samourai/wallet/tor/TorSettings.kt
1
4141
package com.samourai.wallet.tor import io.matthewnelson.topl_service_base.ApplicationDefaultTorSettings /** * samourai-wallet-android * * @author Sarath */ class TorSettings : ApplicationDefaultTorSettings() { override val dormantClientTimeout: Int? get() = DEFAULT__DORMANT_CLIENT_TIMEOUT override val disableNetwork: Boolean get() = DEFAULT__DISABLE_NETWORK override val dnsPort: String get() = PortOption.DISABLED override val dnsPortIsolationFlags: List<@IsolationFlag String>? get() = arrayListOf( IsolationFlag.ISOLATE_CLIENT_PROTOCOL ) override val customTorrc: String? get() = null override val entryNodes: String? get() = DEFAULT__ENTRY_NODES override val excludeNodes: String? get() = DEFAULT__EXCLUDED_NODES override val exitNodes: String? get() = DEFAULT__EXIT_NODES override val httpTunnelPort: String get() = PortOption.DISABLED override val httpTunnelPortIsolationFlags: List<@IsolationFlag String>? get() = arrayListOf( IsolationFlag.ISOLATE_CLIENT_PROTOCOL ) override val listOfSupportedBridges: List<@SupportedBridgeType String> get() = arrayListOf(SupportedBridgeType.MEEK, SupportedBridgeType.OBFS4) override val proxyHost: String? get() = DEFAULT__PROXY_HOST override val proxyPassword: String? get() = DEFAULT__PROXY_PASSWORD override val proxyPort: Int? get() = null override val proxySocks5Host: String? get() = DEFAULT__PROXY_SOCKS5_HOST override val proxySocks5ServerPort: Int? get() = null override val proxyType: @ProxyType String get() = ProxyType.DISABLED override val proxyUser: String? get() = DEFAULT__PROXY_USER override val reachableAddressPorts: String get() = DEFAULT__REACHABLE_ADDRESS_PORTS override val relayNickname: String? get() = DEFAULT__RELAY_NICKNAME override val relayPort: String get() = PortOption.DISABLED override val socksPort: String get() = PortOption.AUTO override val socksPortIsolationFlags: List<@IsolationFlag String>? get() = arrayListOf( IsolationFlag.KEEP_ALIVE_ISOLATE_SOCKS_AUTH, IsolationFlag.IPV6_TRAFFIC, IsolationFlag.PREFER_IPV6, IsolationFlag.ISOLATE_CLIENT_PROTOCOL ) override val virtualAddressNetwork: String? get() = "10.192.0.2/10" override val hasBridges: Boolean get() = DEFAULT__HAS_BRIDGES override val connectionPadding: @ConnectionPadding String get() = ConnectionPadding.OFF override val hasCookieAuthentication: Boolean get() = DEFAULT__HAS_COOKIE_AUTHENTICATION override val hasDebugLogs: Boolean get() = DEFAULT__HAS_DEBUG_LOGS override val hasDormantCanceledByStartup: Boolean get() = DEFAULT__HAS_DORMANT_CANCELED_BY_STARTUP override val hasOpenProxyOnAllInterfaces: Boolean get() = DEFAULT__HAS_OPEN_PROXY_ON_ALL_INTERFACES override val hasReachableAddress: Boolean get() = DEFAULT__HAS_REACHABLE_ADDRESS override val hasReducedConnectionPadding: Boolean get() = DEFAULT__HAS_REDUCED_CONNECTION_PADDING override val hasSafeSocks: Boolean get() = DEFAULT__HAS_SAFE_SOCKS override val hasStrictNodes: Boolean get() = DEFAULT__HAS_STRICT_NODES override val hasTestSocks: Boolean get() = DEFAULT__HAS_TEST_SOCKS override val isAutoMapHostsOnResolve: Boolean get() = DEFAULT__IS_AUTO_MAP_HOSTS_ON_RESOLVE override val isRelay: Boolean get() = DEFAULT__IS_RELAY override val runAsDaemon: Boolean get() = DEFAULT__RUN_AS_DAEMON override val transPort: String get() = PortOption.DISABLED override val transPortIsolationFlags: List<@IsolationFlag String>? get() = arrayListOf( IsolationFlag.ISOLATE_CLIENT_PROTOCOL ) override val useSocks5: Boolean get() = DEFAULT__USE_SOCKS5 }
unlicense
28a639151806c7e7980e9801529a990e
27.565517
80
0.667713
4.457481
false
false
false
false
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/data/elementfilter/filters/NotHasKeyLike.kt
1
690
package de.westnordost.streetcomplete.data.elementfilter.filters import de.westnordost.streetcomplete.data.osm.mapdata.Element /** !~key(word)? */ class NotHasKeyLike(val key: String) : ElementFilter { private val regex = RegexOrSet.from(key) override fun toOverpassQLString(): String { // not supported (conveniently) by overpass (yet): https://github.com/drolbr/Overpass-API/issues/589 //return "[" + "!~" + "^(${key.pattern})$".quoteIfNecessary() + " ~ '.*']" throw UnsupportedOperationException() } override fun toString() = toOverpassQLString() override fun matches(obj: Element?) = obj?.tags?.keys?.find { regex.matches(it) } == null }
gpl-3.0
29a1a96d4fb9cb66d61c435913de78d0
39.588235
108
0.681159
4.035088
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/provider/BggContract.kt
1
40723
@file:Suppress("SpellCheckingInspection") package com.boardgamegeek.provider import android.net.Uri class BggContract { object Thumbnails { val CONTENT_URI: Uri = BASE_CONTENT_URI.buildUpon().appendPath(PATH_THUMBNAILS).build() fun buildUri(fileName: String?): Uri = CONTENT_URI.buildUpon().appendPath(fileName).build() } object Avatars { val CONTENT_URI: Uri = BASE_CONTENT_URI.buildUpon().appendPath(PATH_AVATARS).build() fun buildUri(avatarFileName: String?): Uri = CONTENT_URI.buildUpon().appendPath(avatarFileName).build() } object Games { object Columns { const val GAME_ID = "game_id" const val GAME_NAME = "game_name" const val GAME_SORT_NAME = "game_sort_name" const val YEAR_PUBLISHED = "year_published" const val IMAGE_URL = "image_url" const val THUMBNAIL_URL = "thumbnail_url" const val MIN_PLAYERS = "min_players" const val MAX_PLAYERS = "max_players" const val PLAYING_TIME = "playing_time" const val MIN_PLAYING_TIME = "min_playing_time" const val MAX_PLAYING_TIME = "max_playing_time" const val NUM_PLAYS = "num_of_plays" const val MINIMUM_AGE = "age" const val DESCRIPTION = "description" const val SUBTYPE = "subtype" const val STATS_USERS_RATED = "usersrated" const val STATS_AVERAGE = "average" const val STATS_BAYES_AVERAGE = "bayes_average" const val STATS_STANDARD_DEVIATION = "standard_deviation" const val STATS_MEDIAN = "median" const val STATS_NUMBER_OWNED = "number_owned" const val STATS_NUMBER_TRADING = "number_trading" const val STATS_NUMBER_WANTING = "number_wanting" const val STATS_NUMBER_WISHING = "number_wishing" const val STATS_NUMBER_COMMENTS = "number_commenting" const val STATS_NUMBER_WEIGHTS = "number_weighting" const val STATS_AVERAGE_WEIGHT = "average_weight" const val LAST_VIEWED = "last_viewed" const val STARRED = "starred" const val UPDATED_PLAYS = "updated_plays" const val CUSTOM_PLAYER_SORT = "custom_player_sort" const val GAME_RANK = "game_rank" const val SUGGESTED_PLAYER_COUNT_POLL_VOTE_TOTAL = "suggested_player_count_poll_vote_total" const val PLAYER_COUNT_RECOMMENDATION_PREFIX = "player_count_recommendation_" const val HERO_IMAGE_URL = "hero_image_url" const val ICON_COLOR = "ICON_COLOR" const val DARK_COLOR = "DARK_COLOR" const val WINS_COLOR = "WINS_COLOR" const val WINNABLE_PLAYS_COLOR = "WINNABLE_PLAYS_COLOR" const val ALL_PLAYS_COLOR = "ALL_PLAYS_COLOR" const val PLAYER_COUNTS_BEST = "player_counts_best" const val PLAYER_COUNTS_RECOMMENDED = "player_counts_recommended" const val PLAYER_COUNTS_NOT_RECOMMENDED = "player_count_nots_recommended" const val UPDATED = "updated" const val UPDATED_LIST = "updated_list" const val POLLS_COUNT = "polls_count" } val CONTENT_URI: Uri = BASE_CONTENT_URI.buildUpon().appendPath(PATH_GAMES).build() val CONTENT_PLAYS_URI: Uri = CONTENT_URI.buildUpon().fragment(FRAGMENT_PLAYS).build() const val CONTENT_TYPE = "vnd.android.cursor.dir/vnd.boardgamegeek.game" const val CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.boardgamegeek.game" const val DEFAULT_SORT = Columns.GAME_SORT_NAME + COLLATE_NOCASE + " ASC" fun buildGameUri(gameId: Int): Uri { return getUriBuilder(gameId).build() } fun buildRanksUri(gameId: Int): Uri { return getUriBuilder(gameId, PATH_RANKS).build() } fun buildRanksUri(gameId: Int, rankId: Int): Uri { return getUriBuilder(gameId, PATH_RANKS, rankId).build() } fun buildDesignersUri(gameId: Int, limitCount: Int = 0): Uri { return getLimitedUriBuilder(gameId, PATH_DESIGNERS, limitCount).build() } fun buildDesignersUri(rowId: Long): Uri { return getUriBuilder().appendPath(PATH_DESIGNERS).appendPath(rowId.toString()).build() } fun buildArtistsUri(gameId: Int, limitCount: Int = 0): Uri { return getLimitedUriBuilder(gameId, PATH_ARTISTS, limitCount).build() } fun buildArtistUri(rowId: Long): Uri { return getUriBuilder().appendPath(PATH_ARTISTS).appendPath(rowId.toString()).build() } fun buildPublishersUri(gameId: Int, limitCount: Int = 0): Uri { return getLimitedUriBuilder(gameId, PATH_PUBLISHERS, limitCount).build() } fun buildPublisherUri(rowId: Long): Uri { return getUriBuilder().appendPath(PATH_PUBLISHERS).appendPath(rowId.toString()).build() } fun buildMechanicsUri(gameId: Int, limitCount: Int = 0): Uri { return getLimitedUriBuilder(gameId, PATH_MECHANICS, limitCount).build() } fun buildMechanicUri(rowId: Long): Uri { return getUriBuilder().appendPath(PATH_MECHANICS).appendPath(rowId.toString()).build() } fun buildCategoriesUri(gameId: Int, limitCount: Int = 0): Uri { return getLimitedUriBuilder(gameId, PATH_CATEGORIES, limitCount).build() } fun buildCategoryUri(rowId: Long): Uri { return getUriBuilder().appendPath(PATH_CATEGORIES).appendPath(rowId.toString()).build() } fun buildExpansionsUri(gameId: Int, limitCount: Int = 0): Uri { return getLimitedUriBuilder(gameId, PATH_EXPANSIONS, limitCount).build() } fun buildExpansionUri(rowId: Long): Uri { return getUriBuilder().appendPath(PATH_EXPANSIONS).appendPath(rowId.toString()).build() } fun buildPollsUri(gameId: Int): Uri { return getUriBuilder(gameId, PATH_POLLS).build() } fun buildPollsUri(gameId: Int, pollName: String?): Uri { return getUriBuilder(gameId, PATH_POLLS).appendPath(pollName).build() } fun buildPollResultsUri(gameId: Int, pollName: String?): Uri { return getUriBuilder(gameId, PATH_POLLS).appendPath(pollName).appendPath(PATH_POLL_RESULTS).build() } fun buildPollResultsUri(gameId: Int, pollName: String?, key: String?): Uri { return getUriBuilder(gameId, PATH_POLLS).appendPath(pollName).appendPath(PATH_POLL_RESULTS).appendPath(key) .build() } fun buildPollResultsResultUri(gameId: Int, pollName: String?): Uri { return getUriBuilder(gameId, PATH_POLLS).appendPath(pollName).appendPath(PATH_POLL_RESULTS) .appendPath(PATH_POLL_RESULTS_RESULT).build() } fun buildPollResultsResultUri(gameId: Int, pollName: String?, key: String?): Uri { return getUriBuilder(gameId, PATH_POLLS).appendPath(pollName).appendPath(PATH_POLL_RESULTS).appendPath(key) .appendPath(PATH_POLL_RESULTS_RESULT).build() } fun buildPollResultsResultUri(gameId: Int, pollName: String?, key: String?, key2: String?): Uri { return getUriBuilder(gameId, PATH_POLLS).appendPath(pollName) .appendPath(PATH_POLL_RESULTS).appendPath(key) .appendPath(PATH_POLL_RESULTS_RESULT).appendPath(key2).build() } fun buildSuggestedPlayerCountPollResultsUri(gameId: Int): Uri { return getUriBuilder(gameId, PATH_SUGGESTED_PLAYER_COUNT_POLL_RESULTS).build() } fun buildSuggestedPlayerCountPollResultsUri(gameId: Int, playerCount: String?): Uri { return getUriBuilder(gameId, PATH_SUGGESTED_PLAYER_COUNT_POLL_RESULTS).appendPath(playerCount).build() } fun buildColorsUri(gameId: Int): Uri { return getUriBuilder(gameId, PATH_COLORS).build() } fun buildColorsUri(gameId: Int, color: String?): Uri { return getUriBuilder(gameId, PATH_COLORS).appendPath(color).build() } private fun getUriBuilder(): Uri.Builder = CONTENT_URI.buildUpon() private fun getUriBuilder(gameId: Int): Uri.Builder { return CONTENT_URI.buildUpon().appendPath(gameId.toString()) } private fun getUriBuilder(gameId: Int, path: String): Uri.Builder { return getLimitedUriBuilder(gameId, path, 0) } private fun getUriBuilder(gameId: Int, path: String, id: Int): Uri.Builder { return getUriBuilder(gameId, path).appendPath(id.toString()) } fun buildPathUri(gameId: Int, path: String?): Uri { return CONTENT_URI.buildUpon().appendPath(gameId.toString()).appendPath(path).build() } fun buildPathUri(gameId: Int, path: String?, id: Int): Uri { return CONTENT_URI.buildUpon().appendPath(gameId.toString()).appendPath(path) .appendPath(id.toString()).build() } private fun getLimitedUriBuilder(gameId: Int, path: String, limit: Int = 0): Uri.Builder { val builder = CONTENT_URI.buildUpon().appendPath(gameId.toString()).appendPath(path) if (limit > 0) { builder.appendQueryParameter(QUERY_KEY_LIMIT, limit.toString()) } return builder } fun getGameId(uri: Uri?): Int { // TODO use generic function return uri?.pathSegments?.let { if (it.size > 1 && it.getOrNull(0) == PATH_GAMES) it.getOrNull(1)?.toIntOrNull() else null } ?: INVALID_ID } fun getPollName(uri: Uri): String { return getPathValue(uri, PATH_POLLS) } fun getPollResultsKey(uri: Uri): String { return getPathValue(uri, PATH_POLL_RESULTS) } fun getPollResultsResultKey(uri: Uri): String { return getPathValue(uri, PATH_POLL_RESULTS_RESULT) } fun getPollPlayerCount(uri: Uri): String { return getPathValue(uri, PATH_SUGGESTED_PLAYER_COUNT_POLL_RESULTS) } private fun getPathValue(uri: Uri, path: String): String { // TODO use find() if (path.isEmpty()) { return "" } var isNextValue = false for (segment in uri.pathSegments) { if (isNextValue) { return segment } if (path == segment) { isNextValue = true } } return "" } fun createRecommendedPlayerCountColumn(playerCount: String): String { return Columns.PLAYER_COUNT_RECOMMENDATION_PREFIX + playerCount } fun getRecommendedPlayerCountFromColumn(column: String): String? { if (column.startsWith(Columns.PLAYER_COUNT_RECOMMENDATION_PREFIX)) { val delimiter = Columns.PLAYER_COUNT_RECOMMENDATION_PREFIX.substring(Columns.PLAYER_COUNT_RECOMMENDATION_PREFIX.length - 1) val parts = column.split(delimiter.toRegex()).toTypedArray() return parts[parts.size - 1] } return null } } object GameRanks { object Columns { const val GAME_ID = Games.Columns.GAME_ID const val GAME_RANK_ID = "gamerank_id" const val GAME_RANK_TYPE = "gamerank_type" const val GAME_RANK_NAME = "gamerank_name" const val GAME_RANK_FRIENDLY_NAME = "gamerank_friendly_name" const val GAME_RANK_VALUE = "gamerank_value" const val GAME_RANK_BAYES_AVERAGE = "gamerank_bayes_average" } val CONTENT_URI: Uri = Games.CONTENT_URI.buildUpon().appendPath(PATH_RANKS).build() const val CONTENT_TYPE = "vnd.android.cursor.dir/vnd.boardgamegeek.rank" const val CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.boardgamegeek.rank" const val DEFAULT_SORT = ("${Columns.GAME_RANK_TYPE} DESC,${Columns.GAME_RANK_VALUE},${Columns.GAME_RANK_FRIENDLY_NAME}") fun buildGameRankUri(gameRankId: Int): Uri { return CONTENT_URI.buildUpon().appendPath(gameRankId.toString()).build() } fun getRankId(uri: Uri) = uri.lastPathSegment?.toIntOrNull() ?: INVALID_ID } object Designers { object Columns { const val DESIGNER_ID = "designer_id" const val DESIGNER_NAME = "designer_name" const val DESIGNER_DESCRIPTION = "designer_description" const val DESIGNER_IMAGE_URL = "designer_image_url" const val DESIGNER_THUMBNAIL_URL = "designer_thumbnail_url" const val DESIGNER_HERO_IMAGE_URL = "designer_hero_image_url" const val DESIGNER_IMAGES_UPDATED_TIMESTAMP = "designer_images_updated_timestamp" const val WHITMORE_SCORE = "whitmore_score" const val DESIGNER_STATS_UPDATED_TIMESTAMP = "designer_stats_updated_timestamp" const val ITEM_COUNT = "item_count" //TODO const val UPDATED = "updated" } val CONTENT_URI: Uri = BASE_CONTENT_URI.buildUpon().appendPath(PATH_DESIGNERS).build() const val CONTENT_TYPE = "vnd.android.cursor.dir/vnd.boardgamegeek.designer" const val CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.boardgamegeek.designer" const val DEFAULT_SORT = "${Columns.DESIGNER_NAME}$COLLATE_NOCASE ASC" fun buildDesignerUri(designerId: Int): Uri { return CONTENT_URI.buildUpon().appendPath(designerId.toString()).build() } fun buildDesignerCollectionUri(designerId: Int): Uri { return CONTENT_URI.buildUpon().appendPath(designerId.toString()).appendPath(PATH_COLLECTION).build() } fun getDesignerId(uri: Uri) = uri.pathSegments.getOrNull(1)?.toIntOrNull() ?: INVALID_ID } object Artists { object Columns { const val GAME_ID = Games.Columns.GAME_ID const val ARTIST_ID = "artist_id" const val ARTIST_NAME = "artist_name" const val ARTIST_DESCRIPTION = "artist_description" const val ARTIST_IMAGE_URL = "artist_image_url" const val ARTIST_THUMBNAIL_URL = "artist_thumbnail_url" const val ARTIST_HERO_IMAGE_URL = "artist_hero_image_url" const val ARTIST_IMAGES_UPDATED_TIMESTAMP = "artist_images_updated_timestamp" const val WHITMORE_SCORE = "whitmore_score" const val ARTIST_STATS_UPDATED_TIMESTAMP = "artist_stats_updated_timestamp" const val ITEM_COUNT = "item_count" //TODO const val UPDATED = "updated" } val CONTENT_URI: Uri = BASE_CONTENT_URI.buildUpon().appendPath(PATH_ARTISTS).build() const val CONTENT_TYPE = "vnd.android.cursor.dir/vnd.boardgamegeek.artist" const val CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.boardgamegeek.artist" const val DEFAULT_SORT = Columns.ARTIST_NAME + COLLATE_NOCASE + " ASC" fun buildArtistUri(artistId: Int): Uri { return CONTENT_URI.buildUpon().appendPath(artistId.toString()).build() } fun buildArtistCollectionUri(artistId: Int): Uri { return CONTENT_URI.buildUpon().appendPath(artistId.toString()).appendPath(PATH_COLLECTION).build() } fun getArtistId(uri: Uri) = uri.pathSegments.getOrNull(1)?.toIntOrNull() ?: INVALID_ID } object Publishers { object Columns { const val PUBLISHER_ID = "publisher_id" const val PUBLISHER_NAME = "publisher_name" const val PUBLISHER_DESCRIPTION = "publisher_description" const val PUBLISHER_IMAGE_URL = "publisher_image_url" const val PUBLISHER_THUMBNAIL_URL = "publisher_thumbnail_url" const val PUBLISHER_HERO_IMAGE_URL = "publisher_hero_image_url" const val PUBLISHER_SORT_NAME = "publisher_sort_name" const val WHITMORE_SCORE = "whitmore_score" const val PUBLISHER_STATS_UPDATED_TIMESTAMP = "publisher_stats_updated_timestamp" const val ITEM_COUNT = "item_count" //TODO const val UPDATED = "updated" } val CONTENT_URI: Uri = BASE_CONTENT_URI.buildUpon().appendPath(PATH_PUBLISHERS).build() const val CONTENT_TYPE = "vnd.android.cursor.dir/vnd.boardgamegeek.publisher" const val CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.boardgamegeek.publisher" const val DEFAULT_SORT = "${Columns.PUBLISHER_NAME}$COLLATE_NOCASE ASC" fun buildPublisherUri(publisherId: Int): Uri { return CONTENT_URI.buildUpon().appendPath(publisherId.toString()).build() } fun getPublisherId(uri: Uri): Int { return uri.pathSegments.getOrNull(1)?.toIntOrNull() ?: INVALID_ID } fun buildCollectionUri(publisherId: Int): Uri { return CONTENT_URI.buildUpon().appendPath(publisherId.toString()).appendPath(PATH_COLLECTION).build() } } object Mechanics { object Columns { const val MECHANIC_ID = "mechanic_id" const val MECHANIC_NAME = "mechanic_name" const val ITEM_COUNT = "item_count" const val UPDATED = "updated" } val CONTENT_URI: Uri = BASE_CONTENT_URI.buildUpon().appendPath(PATH_MECHANICS).build() const val CONTENT_TYPE = "vnd.android.cursor.dir/vnd.boardgamegeek.mechanic" const val CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.boardgamegeek.mechanic" const val DEFAULT_SORT = "${Columns.MECHANIC_NAME}$COLLATE_NOCASE ASC" @Suppress("unused") fun buildMechanicUri(mechanicId: Int): Uri { return createMechanicUri(mechanicId).build() } private fun createMechanicUri(mechanicId: Int): Uri.Builder { return CONTENT_URI.buildUpon().appendPath(mechanicId.toString()) } fun getMechanicId(uri: Uri): Int { return uri.pathSegments.getOrNull(1)?.toIntOrNull() ?: INVALID_ID } fun buildCollectionUri(mechanicId: Int): Uri { return createMechanicUri(mechanicId).appendPath(PATH_COLLECTION).build() } } object Categories { object Columns { const val CATEGORY_ID = "category_id" const val CATEGORY_NAME = "category_name" const val ITEM_COUNT = "item_count" const val UPDATED = "updated" } val CONTENT_URI: Uri = BASE_CONTENT_URI.buildUpon().appendPath(PATH_CATEGORIES).build() const val CONTENT_TYPE = "vnd.android.cursor.dir/vnd.boardgamegeek.category" const val CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.boardgamegeek.category" const val DEFAULT_SORT = "${Columns.CATEGORY_NAME}$COLLATE_NOCASE ASC" @Suppress("unused") fun buildCategoryUri(categoryId: Int): Uri { return createCategoryUri(categoryId).build() } fun buildCollectionUri(categoryId: Int): Uri { return createCategoryUri(categoryId).appendPath(PATH_COLLECTION).build() } fun getCategoryId(uri: Uri): Int { return uri.pathSegments.getOrNull(1)?.toIntOrNull() ?: INVALID_ID } private fun createCategoryUri(categoryId: Int): Uri.Builder { return CONTENT_URI.buildUpon().appendPath(categoryId.toString()) } } object GamesExpansions { object Columns { const val GAME_ID = Games.Columns.GAME_ID const val EXPANSION_ID = "expansion_id" const val EXPANSION_NAME = "expansion_name" const val INBOUND = "inbound" } val CONTENT_URI: Uri = Games.CONTENT_URI.buildUpon().appendPath(PATH_EXPANSIONS).build() const val CONTENT_TYPE = "vnd.android.cursor.dir/vnd.boardgamegeek.expansion" const val CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.boardgamegeek.expansion" const val DEFAULT_SORT = "${Columns.EXPANSION_NAME}$COLLATE_NOCASE ASC" } object Collection { object Columns { const val GAME_ID = Games.Columns.GAME_ID const val COLLECTION_ID = "collection_id" const val COLLECTION_NAME = "collection_name" const val COLLECTION_SORT_NAME = "collection_sort_name" const val STATUS_OWN = "own" const val STATUS_PREVIOUSLY_OWNED = "previously_owned" const val STATUS_FOR_TRADE = "for_trade" const val STATUS_WANT = "want" const val STATUS_WANT_TO_PLAY = "want_to_play" const val STATUS_WANT_TO_BUY = "want_to_buy" const val STATUS_WISHLIST = "wishlist" const val STATUS_WISHLIST_PRIORITY = "wishlist_priority" const val STATUS_PREORDERED = "preordered" const val COLLECTION_YEAR_PUBLISHED = "collection_year_published" const val RATING = "rating" const val COMMENT = "comment" const val CONDITION = "conditiontext" const val WANTPARTS_LIST = "wantpartslist" const val HASPARTS_LIST = "haspartslist" const val WISHLIST_COMMENT = "wishlistcomment" const val COLLECTION_THUMBNAIL_URL = "collection_thumbnail_url" const val COLLECTION_IMAGE_URL = "collection_image_url" const val LAST_MODIFIED = "last_modified" const val PRIVATE_INFO_PRICE_PAID_CURRENCY = "price_paid_currency" const val PRIVATE_INFO_PRICE_PAID = "price_paid" const val PRIVATE_INFO_CURRENT_VALUE_CURRENCY = "current_value_currency" const val PRIVATE_INFO_CURRENT_VALUE = "current_value" const val PRIVATE_INFO_QUANTITY = "quantity" const val PRIVATE_INFO_ACQUISITION_DATE = "acquisition_date" const val PRIVATE_INFO_ACQUIRED_FROM = "acquired_from" const val PRIVATE_INFO_COMMENT = "private_comment" const val STATUS_DIRTY_TIMESTAMP = "status_dirty_timestamp" const val RATING_DIRTY_TIMESTAMP = "rating_dirty_timestamp" const val COMMENT_DIRTY_TIMESTAMP = "comment_dirty_timestamp" const val PRIVATE_INFO_DIRTY_TIMESTAMP = "private_info_dirty_timestamp" const val COLLECTION_DIRTY_TIMESTAMP = "collection_dirty_timestamp" const val COLLECTION_DELETE_TIMESTAMP = "collection_delete_timestamp" const val WISHLIST_COMMENT_DIRTY_TIMESTAMP = "wishlist_comment_dirty_timestamp" const val TRADE_CONDITION_DIRTY_TIMESTAMP = "trade_condition_dirty_timestamp" const val WANT_PARTS_DIRTY_TIMESTAMP = "want_parts_dirty_timestamp" const val HAS_PARTS_DIRTY_TIMESTAMP = "has_parts_dirty_timestamp" const val COLLECTION_HERO_IMAGE_URL = "collection_hero_image_url" const val PRIVATE_INFO_INVENTORY_LOCATION = "inventory_location" // TODO use constants const val UPDATED = "updated" const val UPDATED_LIST = "updated_list" } val CONTENT_URI: Uri = BASE_CONTENT_URI.buildUpon().appendPath(PATH_COLLECTION).build() const val CONTENT_TYPE = "vnd.android.cursor.dir/vnd.boardgamegeek.collection" const val CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.boardgamegeek.collection" const val DEFAULT_SORT = Columns.COLLECTION_SORT_NAME + COLLATE_NOCASE + " ASC" const val SORT_ACQUIRED_FROM = Columns.PRIVATE_INFO_ACQUIRED_FROM + COLLATE_NOCASE + " ASC" const val SORT_INVENTORY_LOCATION = Columns.PRIVATE_INFO_INVENTORY_LOCATION + COLLATE_NOCASE + " ASC" fun buildUri(id: Long): Uri { return CONTENT_URI.buildUpon().appendPath(id.toString()).build() } fun buildAcquiredFromUri(): Uri { return CONTENT_URI.buildUpon().appendPath(PATH_ACQUIRED_FROM).build() } fun buildInventoryLocationUri(): Uri { return CONTENT_URI.buildUpon().appendPath(PATH_INVENTORY_LOCATION).build() } fun getId(uri: Uri): Long { return uri.pathSegments.getOrNull(1)?.toLongOrNull() ?: INVALID_ID.toLong() } } object Buddies { object Columns { const val BUDDY_ID = "buddy_id" const val BUDDY_NAME = "buddy_name" const val BUDDY_FIRSTNAME = "buddy_firtname" // TODO no "S"?! const val BUDDY_LASTNAME = "buddy_lastname" const val AVATAR_URL = "avatar_url" const val PLAY_NICKNAME = "play_nickname" const val BUDDY_FLAG = "buddy_flag" const val SYNC_HASH_CODE = "sync_hash_code" // TODO use constants const val UPDATED = "updated" const val UPDATED_LIST = "updated_list" } val CONTENT_URI: Uri = BASE_CONTENT_URI.buildUpon().appendPath(PATH_BUDDIES).build() const val CONTENT_TYPE = "vnd.android.cursor.dir/vnd.boardgamegeek.buddy" const val CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.boardgamegeek.buddy" const val DEFAULT_SORT = "${Columns.BUDDY_LASTNAME}$COLLATE_NOCASE ASC, ${Columns.BUDDY_FIRSTNAME}$COLLATE_NOCASE ASC" fun buildBuddyUri(buddyName: String?): Uri { return CONTENT_URI.buildUpon().appendPath(buddyName).build() } fun getBuddyName(uri: Uri): String { // TODO null-able? return uri.pathSegments[1] } } object PlayerColors { object Columns { const val PLAYER_NAME = "player_name" const val PLAYER_TYPE = "player_type" const val PLAYER_COLOR = "player_color" const val PLAYER_COLOR_SORT_ORDER = "player_color_sort" } val CONTENT_URI: Uri = BASE_CONTENT_URI.buildUpon().appendPath(PATH_PLAYER_COLORS).build() const val CONTENT_TYPE = "vnd.android.cursor.dir/vnd.boardgamegeek.playercolor" const val CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.boardgamegeek.playercolor" const val TYPE_USER = 1 const val TYPE_PLAYER = 2 const val DEFAULT_SORT = "${Columns.PLAYER_TYPE} ASC, ${Columns.PLAYER_NAME} ASC, ${Columns.PLAYER_COLOR_SORT_ORDER} ASC" fun buildUserUri(username: String?): Uri { return BASE_CONTENT_URI.buildUpon().appendPath(PATH_USERS).appendPath(username).appendPath(PATH_COLORS).build() } fun buildPlayerUri(playerName: String?): Uri { return BASE_CONTENT_URI.buildUpon().appendPath(PATH_PLAYERS).appendPath(playerName).appendPath(PATH_COLORS).build() } fun buildUserUri(username: String?, sortOrder: Int): Uri { return buildUserUri(username).buildUpon().appendPath(sortOrder.toString()).build() } fun getUsername(uri: Uri?) = uri.getSegmentAfterPath(PATH_USERS) fun getPlayerName(uri: Uri?) = uri.getSegmentAfterPath(PATH_PLAYERS) fun getSortOrder(uri: Uri?) = uri.getSegmentAfterPath(PATH_COLORS)?.toIntOrNull() ?: 0 private fun Uri?.getSegmentAfterPath(pathSegment: String, pathIndex: Int = 0): String? { return this?.pathSegments?.let { if (it.getOrNull(pathIndex) == pathSegment) it.getOrNull(pathIndex + 1) else null } } } object GameSuggestedPlayerCountPollPollResults { object Columns { const val GAME_ID = Games.Columns.GAME_ID const val PLAYER_COUNT = "player_count" const val SORT_INDEX = "sort_index" const val BEST_VOTE_COUNT = "best_vote_count" const val RECOMMENDED_VOTE_COUNT = "recommended_vote_count" const val NOT_RECOMMENDED_VOTE_COUNT = "not_recommended_vote_count" const val RECOMMENDATION = "recommendation" } const val CONTENT_TYPE = "vnd.android.cursor.dir/vnd.boardgamegeek.boardgamepoll.playercount" const val CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.boardgamegeek.boardgamepoll.playercount" const val DEFAULT_SORT = "${Columns.SORT_INDEX} ASC" } object GamePolls { object Columns { const val GAME_ID = Games.Columns.GAME_ID const val POLL_NAME = "poll_name" const val POLL_TITLE = "poll_title" const val POLL_TOTAL_VOTES = "poll_total_votes" } val CONTENT_URI: Uri = Games.CONTENT_URI.buildUpon().appendPath(PATH_POLLS).build() const val CONTENT_TYPE = "vnd.android.cursor.dir/vnd.boardgamegeek.boardgamepoll" const val CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.boardgamegeek.boardgamepoll" const val DEFAULT_SORT = "${Columns.POLL_TITLE}$COLLATE_NOCASE ASC" } object GamePollResults { object Columns { const val POLL_ID = "poll_id" const val POLL_RESULTS_KEY = "pollresults_key" const val POLL_RESULTS_PLAYERS = "pollresults_players" const val POLL_RESULTS_SORT_INDEX = "pollresults_sortindex" } val CONTENT_URI: Uri = GamePolls.CONTENT_URI.buildUpon().appendPath(PATH_POLL_RESULTS).build() const val CONTENT_TYPE = "vnd.android.cursor.dir/vnd.boardgamegeek.boardgamepollresult" const val CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.boardgamegeek.boardgamepollresult" const val DEFAULT_SORT = "${Columns.POLL_RESULTS_SORT_INDEX} ASC" } object GamePollResultsResult { object Columns { const val POLL_RESULTS_ID = "pollresults_id" const val POLL_RESULTS_RESULT_KEY = "pollresultsresult_key" const val POLL_RESULTS_RESULT_LEVEL = "pollresultsresult_level" const val POLL_RESULTS_RESULT_VALUE = "pollresultsresult_value" const val POLL_RESULTS_RESULT_VOTES = "pollresultsresult_votes" const val POLL_RESULTS_RESULT_SORT_INDEX = "pollresultsresult_sortindex" } val CONTENT_URI: Uri = GamePollResults.CONTENT_URI.buildUpon().appendPath(PATH_POLL_RESULTS_RESULT).build() const val CONTENT_TYPE = "vnd.android.cursor.dir/vnd.boardgamegeek.boardgamepollresultsresult" const val CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.boardgamegeek.boardgamepollresultsresult" const val DEFAULT_SORT = "${GamePollResults.Columns.POLL_RESULTS_SORT_INDEX} ASC, ${Columns.POLL_RESULTS_RESULT_SORT_INDEX} ASC" } object GameColors { object Columns { const val GAME_ID = Games.Columns.GAME_ID const val COLOR = "color" } val CONTENT_URI: Uri = Games.CONTENT_URI.buildUpon().appendPath(PATH_COLORS).build() const val CONTENT_TYPE = "vnd.android.cursor.dir/vnd.boardgamegeek.boardgamecolor" const val CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.boardgamegeek.boardgamecolor" const val DEFAULT_SORT = Columns.COLOR + COLLATE_NOCASE + " ASC" } object Plays { object Columns { const val PLAY_ID = "play_id" const val DATE = "date" const val QUANTITY = "quantity" const val LENGTH = "length" const val INCOMPLETE = "incomplete" const val NO_WIN_STATS = "no_win_stats" const val LOCATION = "location" const val COMMENTS = "comments" const val START_TIME = "start_time" const val PLAYER_COUNT = "player_count" const val SYNC_HASH_CODE = "sync_hash_code" const val ITEM_NAME = "item_name" const val OBJECT_ID = "object_id" const val DELETE_TIMESTAMP = "delete_timestamp" const val UPDATE_TIMESTAMP = "update_timestamp" const val DIRTY_TIMESTAMP = "dirty_timestamp" const val SYNC_TIMESTAMP = "updated_list" const val SUM_QUANTITY = "sum_quantity" const val SUM_WINS = "sum_wins" const val MAX_DATE = "max_date" } val CONTENT_URI: Uri = BASE_CONTENT_URI.buildUpon().appendPath(PATH_PLAYS).build() private val CONTENT_SIMPLE_URI: Uri = CONTENT_URI.buildUpon().fragment(FRAGMENT_SIMPLE).build() const val CONTENT_TYPE = "vnd.android.cursor.dir/vnd.boardgamegeek.play" const val CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.boardgamegeek.play" // TODO define table name in a better spot const val DEFAULT_SORT = "${Columns.DATE} DESC, plays.${Columns.PLAY_ID} DESC" /** * content://com.boardgamegeek/plays/# */ fun buildPlayUri(internalId: Long): Uri { return CONTENT_SIMPLE_URI.buildUpon().appendPath(internalId.toString()).build() } fun buildPlayWithGameUri(internalId: Long): Uri { return CONTENT_URI.buildUpon().appendPath(internalId.toString()).build() } fun buildPlayerUri(): Uri { return CONTENT_URI.buildUpon() .appendPath(PATH_PLAYERS) .build() } fun buildPlayerUri(internalId: Long): Uri { return CONTENT_URI.buildUpon() .appendPath(internalId.toString()) .appendPath(PATH_PLAYERS) .build() } fun buildPlayerUri(internalPlayId: Long, internalPlayerId: Long): Uri { return CONTENT_URI.buildUpon() .appendPath(internalPlayId.toString()) .appendPath(PATH_PLAYERS) .appendPath(internalPlayerId.toString()) .build() } fun buildLocationsUri(): Uri { return CONTENT_URI.buildUpon().appendPath(PATH_LOCATIONS).build() } fun buildPlayersUri(): Uri { return CONTENT_URI.buildUpon().appendPath(PATH_PLAYERS).build() } fun buildPlayersByPlayUri(): Uri { return buildPlayersUri().buildUpon().appendQueryParameter(QUERY_KEY_GROUP_BY, QUERY_VALUE_PLAY).build() } fun buildPlayersByUniquePlayerUri(): Uri { return buildPlayersUri().buildUpon().appendQueryParameter(QUERY_KEY_GROUP_BY, QUERY_VALUE_UNIQUE_PLAYER).build() } fun buildPlayersByUniqueUserUri(): Uri { return buildPlayersUri().buildUpon().appendQueryParameter(QUERY_KEY_GROUP_BY, QUERY_VALUE_UNIQUE_USER).build() } fun buildPlayersByUniqueNameUri(): Uri { return buildPlayersUri().buildUpon().appendQueryParameter(QUERY_KEY_GROUP_BY, QUERY_VALUE_UNIQUE_NAME).build() } fun buildPlayersByColor(): Uri { return buildPlayersUri().buildUpon().appendQueryParameter(QUERY_KEY_GROUP_BY, QUERY_VALUE_COLOR).build() } fun getInternalId(uri: Uri) = uri.pathSegments[1].toLong() } object PlayPlayers { object Columns { @Suppress("ObjectPropertyName") const val _PLAY_ID = "_play_id" const val USER_NAME = "user_name" const val USER_ID = "user_id" const val NAME = "name" const val START_POSITION = "start_position" const val COLOR = "color" const val SCORE = "score" const val NEW = "new" const val RATING = "rating" const val WIN = "win" const val COUNT = "count" const val DESCRIPTION = "description" const val UNIQUE_NAME = "unique_name" } const val CONTENT_TYPE = "vnd.android.cursor.dir/vnd.boardgamegeek.playplayer" const val CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.boardgamegeek.playplayer" const val DEFAULT_SORT = "${Columns.START_POSITION} ASC, play_players.${Columns.NAME}$COLLATE_NOCASE ASC" const val SORT_BY_SUM_QUANTITY = "${Plays.Columns.SUM_QUANTITY} DESC, $DEFAULT_SORT" fun getPlayPlayerId(uri: Uri?) = uri?.lastPathSegment?.toLongOrNull() ?: INVALID_ID.toLong() } object PlayLocations { const val DEFAULT_SORT = "${Plays.Columns.LOCATION}$COLLATE_NOCASE ASC" } object CollectionViews { object Columns { const val NAME = "name" const val STARRED = "starred" const val SORT_TYPE = "sort_type" const val SELECTED_COUNT = "selected_count" const val SELECTED_TIMESTAMP = "selected_timestamp" } val CONTENT_URI: Uri = BASE_CONTENT_URI.buildUpon().appendPath(PATH_COLLECTION_VIEWS).build() const val CONTENT_TYPE = "vnd.android.cursor.dir/vnd.boardgamegeek.collectionview" const val CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.boardgamegeek.collectionview" const val DEFAULT_SORT = "${Columns.STARRED} DESC, ${Columns.NAME}$COLLATE_NOCASE ASC" fun buildViewUri(viewId: Long): Uri = build(viewId).build() // TODO move to next object fun buildViewFilterUri(viewId: Long): Uri = build2(viewId).build() fun buildViewFilterUri(viewId: Long, filterId: Long): Uri = build2(viewId).appendPath(filterId.toString()).build() private fun build(viewId: Long): Uri.Builder = CONTENT_URI.buildUpon().appendPath(viewId.toString()) private fun build2(viewId: Long) = build(viewId).appendPath(PATH_FILTERS) fun getViewId(uri: Uri?) = uri?.pathSegments?.getOrNull(1)?.toIntOrNull() ?: INVALID_ID } object CollectionViewFilters { object Columns { const val VIEW_ID = "filter_id" const val TYPE = "type" const val DATA = "data" } const val CONTENT_TYPE = "vnd.android.cursor.dir/vnd.boardgamegeek.collectionviewfilter" const val CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.boardgamegeek.collectionviewfilter" const val DEFAULT_SORT = "${CollectionViews.Columns.STARRED} DESC, ${CollectionViews.Columns.NAME}$COLLATE_NOCASE ASC, ${Columns.TYPE} ASC" fun getFilterType(uri: Uri?) = uri?.lastPathSegment?.toIntOrNull() ?: INVALID_ID } companion object { const val INVALID_ID = -1 const val INVALID_URL = "N/A" const val CONTENT_AUTHORITY = "com.boardgamegeek" private val BASE_CONTENT_URI = Uri.parse("content://$CONTENT_AUTHORITY") const val COLLATE_NOCASE = " COLLATE NOCASE" // TODO prefix with COL_ const val UPDATED = "updated" const val UPDATED_LIST = "updated_list" const val PATH_GAMES = "games" const val PATH_RANKS = "ranks" const val PATH_DESIGNERS = "designers" const val PATH_ARTISTS = "artists" const val PATH_PUBLISHERS = "publishers" const val PATH_MECHANICS = "mechanics" const val PATH_CATEGORIES = "categories" const val PATH_EXPANSIONS = "expansions" const val PATH_COLLECTION = "collection" const val PATH_BUDDIES = "buddies" const val PATH_USERS = "users" const val PATH_POLLS = "polls" const val PATH_POLL_RESULTS = "results" const val PATH_POLL_RESULTS_RESULT = "result" const val PATH_SUGGESTED_PLAYER_COUNT_POLL_RESULTS = "suggestedplayercountpollresults" const val PATH_THUMBNAILS = "thumbnails" const val PATH_AVATARS = "avatars" const val PATH_COLORS = "colors" const val PATH_PLAYER_COLORS = "playercolors" const val PATH_ACQUIRED_FROM = "acquiredfrom" const val PATH_INVENTORY_LOCATION = "inventorylocation" const val PATH_PLAYS = "plays" const val PATH_PLAYERS = "players" const val PATH_LOCATIONS = "locations" const val PATH_COLLECTION_VIEWS = "collectionviews" const val PATH_FILTERS = "filters" const val QUERY_KEY_GROUP_BY = "groupby" const val QUERY_VALUE_NAME_NOT_USER = "namenotuser" const val QUERY_VALUE_UNIQUE_NAME = "uniquename" const val QUERY_VALUE_UNIQUE_PLAYER = "uniqueplayer" const val QUERY_VALUE_UNIQUE_USER = "uniqueuser" const val QUERY_VALUE_COLOR = "color" const val QUERY_VALUE_PLAY = "play" const val QUERY_KEY_HAVING = "having" const val QUERY_KEY_LIMIT = "limit" const val FRAGMENT_SIMPLE = "simple" const val FRAGMENT_PLAYS = "plays" const val POLL_TYPE_LANGUAGE_DEPENDENCE = "language_dependence" const val POLL_TYPE_SUGGESTED_PLAYER_AGE = "suggested_playerage" fun buildBasicUri(path: String?, id: Long): Uri? { return BASE_CONTENT_URI.buildUpon().appendPath(path).appendPath(id.toString()).build() } } }
gpl-3.0
4b6803479a9ba5668f043f62dc0a88aa
43.603505
147
0.628294
4.277177
false
false
false
false
shkschneider/android_Skeleton
core/src/main/kotlin/me/shkschneider/skeleton/helper/PermissionsHelper.kt
1
6426
package me.shkschneider.skeleton.helper import android.Manifest import android.annotation.SuppressLint // <http://developer.android.com/reference/android/Manifest.permission.html> object PermissionsHelper { // Useless: only used to keep track of new features const val ACCESS_COARSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION // DANGEROUS const val ACCESS_FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION // DANGEROUS const val ACCESS_LOCATION_EXTRA_COMMANDS = Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS const val ACCESS_NETWORK_STATE = Manifest.permission.ACCESS_NETWORK_STATE @SuppressLint("InlinedApi") // API-23+ const val ACCESS_NOTIFICATION_POLICY = Manifest.permission.ACCESS_NOTIFICATION_POLICY const val ACCESS_WIFI_STATE = Manifest.permission.ACCESS_WIFI_STATE const val ADD_VOICEMAIL = Manifest.permission.ADD_VOICEMAIL // DANGEROUS @SuppressLint("InlinedApi") // API-26+ const val ANSWER_PHONE_CALLS = Manifest.permission.ANSWER_PHONE_CALLS // DANGEROUS const val BLUETOOTH = Manifest.permission.BLUETOOTH const val BLUETOOTH_ADMIN = Manifest.permission.BLUETOOTH_ADMIN @SuppressLint("InlinedApi") // API-20+ const val BODY_SENSORS = Manifest.permission.BODY_SENSORS // DANGEROUS const val BROADCAST_STICKY = Manifest.permission.BROADCAST_STICKY const val CALL_PHONE = Manifest.permission.CALL_PHONE // DANGEROUS const val CAMERA = Manifest.permission.CAMERA // DANGEROUS const val CHANGE_NETWORK_STATE = Manifest.permission.CHANGE_NETWORK_STATE const val CHANGE_WIFI_MULTICAST_STATE = Manifest.permission.CHANGE_WIFI_MULTICAST_STATE const val CHANGE_WIFI_STATE = Manifest.permission.CHANGE_WIFI_STATE const val DISABLE_KEYGUARD = Manifest.permission.DISABLE_KEYGUARD const val EXPAND_STATUS_BAR = Manifest.permission.EXPAND_STATUS_BAR const val GET_ACCOUNTS = Manifest.permission.GET_ACCOUNTS // DANGEROUS @SuppressLint("InlinedApi") // API-23+ const val GET_ACCOUNTS_PRIVILEGED = Manifest.permission.GET_ACCOUNTS_PRIVILEGED const val GET_PACKAGE_SIZE = Manifest.permission.GET_PACKAGE_SIZE @SuppressLint("InlinedApi") // API-19+ const val INSTALL_SHORTCUT = Manifest.permission.INSTALL_SHORTCUT @SuppressLint("InlinedApi") // API-26+ const val INSTANT_APP_FOREGROUND_SERVICE = Manifest.permission.INSTANT_APP_FOREGROUND_SERVICE const val INTERNET = Manifest.permission.INTERNET const val KILL_BACKGROUND_PROCESSES = Manifest.permission.KILL_BACKGROUND_PROCESSES @SuppressLint("InlinedApi") // API-26+ const val MANAGE_OWN_CALLS = Manifest.permission.MANAGE_OWN_CALLS const val MODIFY_AUDIO_SETTINGS = Manifest.permission.MODIFY_AUDIO_SETTINGS const val NFC = Manifest.permission.NFC @SuppressLint("InlinedApi") // API-23+ const val PROCESS_OUTGOING_CALLS = Manifest.permission.PROCESS_OUTGOING_CALLS // DANGEROUS const val READ_CALENDAR = Manifest.permission.READ_CALENDAR // DANGEROUS @SuppressLint("InlinedApi") // API-16+ const val READ_CALL_LOG = Manifest.permission.READ_CALL_LOG // DANGEROUS const val READ_CONTACTS = Manifest.permission.READ_CONTACTS // DANGEROUS @SuppressLint("InlinedApi") // API-16+ const val READ_EXTERNAL_STORAGE = Manifest.permission.READ_EXTERNAL_STORAGE // DANGEROUS @SuppressLint("InlinedApi") // API-26+ const val READ_PHONE_NUMBERS = Manifest.permission.READ_PHONE_NUMBERS // DANGEROUS const val READ_PHONE_STATE = Manifest.permission.READ_PHONE_STATE // DANGEROUS const val READ_SMS = Manifest.permission.READ_SMS // DANGEROUS @SuppressLint("InlinedApi") // API-15+ const val READ_SYNC_SETTINGS = Manifest.permission.READ_SYNC_SETTINGS const val READ_SYNC_STATS = Manifest.permission.READ_SYNC_STATS const val RECEIVE_BOOT_COMPLETED = Manifest.permission.RECEIVE_BOOT_COMPLETED const val RECEIVE_MMS = Manifest.permission.RECEIVE_MMS // DANGEROUS const val RECEIVE_SMS = Manifest.permission.RECEIVE_SMS // DANGEROUS const val RECEIVE_WAP_PUSH = Manifest.permission.RECEIVE_WAP_PUSH // DANGEROUS const val RECORD_AUDIO = Manifest.permission.RECORD_AUDIO // DANGEROUS const val REORDER_TASKS = Manifest.permission.REORDER_TASKS @SuppressLint("InlinedApi") // API-26+ const val REQUEST_COMPANION_RUN_IN_BACKGROUND = Manifest.permission.REQUEST_COMPANION_RUN_IN_BACKGROUND @SuppressLint("InlinedApi") // API-26+ const val REQUEST_COMPANION_USE_DATA_IN_BACKGROUND = Manifest.permission.REQUEST_COMPANION_USE_DATA_IN_BACKGROUND @SuppressLint("InlinedApi") // API-26+ const val REQUEST_DELETE_PACKAGES = Manifest.permission.REQUEST_DELETE_PACKAGES @SuppressLint("InlinedApi") // API-23+ const val REQUEST_IGNORE_BATTERY_OPTIMIZATIONS = Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS @SuppressLint("InlinedApi") // API-23+ const val REQUEST_INSTALL_PACKAGES = Manifest.permission.REQUEST_INSTALL_PACKAGES const val SEND_SMS = Manifest.permission.SEND_SMS // DANGEROUS const val SET_ALARM = Manifest.permission.SET_ALARM const val SET_TIME_ZONE = Manifest.permission.SET_TIME_ZONE const val SET_WALLPAPER = Manifest.permission.SET_WALLPAPER const val SET_WALLPAPER_HINTS = Manifest.permission.SET_WALLPAPER_HINTS @SuppressLint("InlinedApi") // API-19+ const val TRANSMIT_IR = Manifest.permission.TRANSMIT_IR @SuppressLint("InlinedApi") // API-19+ const val UNINSTALL_SHORTCUT = Manifest.permission.UNINSTALL_SHORTCUT @SuppressLint("InlinedApi") // API-28+ const val USE_BIOMETRIC = Manifest.permission.USE_BIOMETRIC @Suppress("DEPRECATION") @Deprecated("Use USE_BIOMETRIC instead.") @SuppressLint("InlinedApi") // API-23+ const val USE_FINGERPRINT = Manifest.permission.USE_FINGERPRINT const val USE_SIP = Manifest.permission.USE_SIP // DANGEROUS const val VIBRATE = Manifest.permission.VIBRATE const val WAKE_LOCK = Manifest.permission.WAKE_LOCK const val WRITE_CALENDAR = Manifest.permission.WRITE_CALENDAR // DANGEROUS @SuppressLint("InlinedApi") // API-16+ const val WRITE_CALL_LOG = Manifest.permission.WRITE_CALL_LOG // DANGEROUS const val WRITE_CONTACTS = Manifest.permission.WRITE_CONTACTS // DANGEROUS const val WRITE_EXTERNAL_STORAGE = Manifest.permission.WRITE_EXTERNAL_STORAGE // DANGEROUS const val WRITE_SYNC_SETTINGS = Manifest.permission.WRITE_SYNC_SETTINGS }
apache-2.0
615aaeb283ef042dcc10f389aef6a520
62
117
0.758326
4.098214
false
false
false
false
MichaelRocks/Sunny
app/src/main/kotlin/io/michaelrocks/forecast/model/repository/sqlite/SqliteForecastStorage.kt
1
9961
/* * Copyright 2016 Michael Rozumyanskiy * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.michaelrocks.forecast.model.repository.sqlite import android.content.ContentValues import android.content.Context import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper import io.michaelrocks.forecast.model.City import io.michaelrocks.forecast.model.Forecast import io.michaelrocks.forecast.model.Temperature import io.michaelrocks.forecast.model.Weather import io.michaelrocks.forecast.model.WeatherType import rx.Observable import rx.schedulers.Schedulers import java.util.ArrayList import java.util.Date import java.util.UUID import java.util.concurrent.Executors import javax.inject.Inject const val CURRENT_LOCATION_ID = -1 val CURRENT_LOCATION_UUID = UUID(0L, 0L) private const val DATABASE_NAME = "forecasts" private const val DATABASE_VERSION = 1 private const val FORECASTS_TABLE = "forecasts" private const val UUID_MSB_COLUMN = "uuid_msb" private const val UUID_LSB_COLUMN = "uuid_lsb" private const val CITY_ID_COLUMN = "city_id" private const val CITY_NAME_COLUMN = "city_name" private const val COUNTRY_COLUMN = "country" private const val DATE_COLUMN = "date" private const val TEMPERATURE_CURRENT_COLUMN = "temperature_current" private const val TEMPERATURE_MORNING_COLUMN = "temperature_morning" private const val TEMPERATURE_DAY_COLUMN = "temperature_day" private const val TEMPERATURE_EVENING_COLUMN = "temperature_evening" private const val TEMPERATURE_NIGHT_COLUMN = "temperature_night" private const val WEATHER_TYPE_COLUMN = "weather_type" private const val WEATHER_DESCRIPTION_COLUMN = "weather_description" private const val FORECAST_UUID_INDEX = "forecast_uuid" private val FORECAST_PROJECTION = arrayOf( UUID_MSB_COLUMN, UUID_LSB_COLUMN, CITY_ID_COLUMN, CITY_NAME_COLUMN, COUNTRY_COLUMN, DATE_COLUMN, TEMPERATURE_CURRENT_COLUMN, TEMPERATURE_MORNING_COLUMN, TEMPERATURE_DAY_COLUMN, TEMPERATURE_EVENING_COLUMN, TEMPERATURE_NIGHT_COLUMN, WEATHER_TYPE_COLUMN, WEATHER_DESCRIPTION_COLUMN ) private const val UUID_SELECTION = "$UUID_MSB_COLUMN = ? and $UUID_LSB_COLUMN = ?" internal class SqliteForecastStorage @Inject private constructor( context: Context ) { private val scheduler = Schedulers.from(Executors.newSingleThreadExecutor()) private val helper = object : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) { override fun onCreate(database: SQLiteDatabase) { database.execSQL( """ create table $FORECASTS_TABLE( $UUID_MSB_COLUMN integer not null, $UUID_LSB_COLUMN integer not null, $CITY_ID_COLUMN integer not null, $CITY_NAME_COLUMN text not null, $COUNTRY_COLUMN text(2) not null, $DATE_COLUMN integer not null default 0, $TEMPERATURE_CURRENT_COLUMN real not null default 0, $TEMPERATURE_MORNING_COLUMN real not null default 0, $TEMPERATURE_DAY_COLUMN real not null default 0, $TEMPERATURE_EVENING_COLUMN real not null default 0, $TEMPERATURE_NIGHT_COLUMN real not null default 0, $WEATHER_TYPE_COLUMN integer not null default 0, $WEATHER_DESCRIPTION_COLUMN text not null default '' ); """) database.execSQL( "create unique index $FORECAST_UUID_INDEX on $FORECASTS_TABLE($UUID_MSB_COLUMN, $UUID_LSB_COLUMN);" ) database.beginTransaction() database.insert(FORECASTS_TABLE, null, newCityContentValues(CURRENT_LOCATION_ID, "", "", CURRENT_LOCATION_UUID)) database.insert(FORECASTS_TABLE, null, newCityContentValues(2643743, "London", "GB")) database.insert(FORECASTS_TABLE, null, newCityContentValues(1850147, "Tokyo", "JP")) database.insert(FORECASTS_TABLE, null, newCityContentValues(5128581, "New York", "US")) database.setTransactionSuccessful() database.endTransaction() } override fun onUpgrade(database: SQLiteDatabase, oldVersion: Int, newVersion: Int) { database.execSQL("drop table $FORECASTS_TABLE;") onCreate(database) } private fun newCityContentValues(id: Int, name: String, country: String, uuid: UUID = UUID.randomUUID()) = ContentValues(5).apply { put(UUID_MSB_COLUMN, uuid.mostSignificantBits) put(UUID_LSB_COLUMN, uuid.leastSignificantBits) put(CITY_ID_COLUMN, id) put(CITY_NAME_COLUMN, name) put(COUNTRY_COLUMN, country) } } fun getForecasts(): Observable<List<Forecast>> = Observable .create<List<Forecast>> { subscriber -> val forecasts = queryForecasts() subscriber.onNext(forecasts) subscriber.onCompleted() } .subscribeOn(scheduler) private fun queryForecasts(): List<Forecast> = helper.readableDatabase.query(FORECASTS_TABLE, FORECAST_PROJECTION, null, null, null, null, null)?.let { cursor -> ArrayList<Forecast>(cursor.count).apply { val uuidMsbIndex = cursor.getColumnIndexOrThrow(UUID_MSB_COLUMN) val uuidLsbIndex = cursor.getColumnIndexOrThrow(UUID_LSB_COLUMN) val cityIdIndex = cursor.getColumnIndexOrThrow(CITY_ID_COLUMN) val cityNameIndex = cursor.getColumnIndexOrThrow(CITY_NAME_COLUMN) val countryIndex = cursor.getColumnIndexOrThrow(COUNTRY_COLUMN) val dateIndex = cursor.getColumnIndexOrThrow(DATE_COLUMN) val temperatureCurrentIndex = cursor.getColumnIndexOrThrow(TEMPERATURE_CURRENT_COLUMN) val temperatureMorningIndex = cursor.getColumnIndexOrThrow(TEMPERATURE_MORNING_COLUMN) val temperatureDayIndex = cursor.getColumnIndexOrThrow(TEMPERATURE_DAY_COLUMN) val temperatureEveningIndex = cursor.getColumnIndexOrThrow(TEMPERATURE_EVENING_COLUMN) val temperatureNightIndex = cursor.getColumnIndexOrThrow(TEMPERATURE_NIGHT_COLUMN) val weatherTypeIndex = cursor.getColumnIndexOrThrow(WEATHER_TYPE_COLUMN) val weatherDescriptionIndex = cursor.getColumnIndexOrThrow(WEATHER_DESCRIPTION_COLUMN) val weatherTypes = WeatherType.values() while (cursor.moveToNext()) { val uuidMsb = cursor.getLong(uuidMsbIndex) val uuidLsb = cursor.getLong(uuidLsbIndex) val id = UUID(uuidMsb, uuidLsb) val city = City( cursor.getInt(cityIdIndex), cursor.getString(cityNameIndex), cursor.getString(countryIndex) ) val date = Date(cursor.getLong(dateIndex)) val temperature = Temperature( cursor.getFloat(temperatureCurrentIndex), cursor.getFloat(temperatureMorningIndex), cursor.getFloat(temperatureDayIndex), cursor.getFloat(temperatureEveningIndex), cursor.getFloat(temperatureNightIndex) ) val weather = Weather( weatherTypes[cursor.getInt(weatherTypeIndex)], cursor.getString(weatherDescriptionIndex) ) val forecast = Forecast(id, date, city, temperature, weather) add(forecast) } } } ?: emptyList() fun createForecast(id: UUID, city: City): Observable<Unit> = Observable .create<Unit> { subscriber -> val values = ContentValues().apply { put(UUID_MSB_COLUMN, id.mostSignificantBits) put(UUID_LSB_COLUMN, id.leastSignificantBits) put(CITY_ID_COLUMN, city.id) put(CITY_NAME_COLUMN, city.name) put(COUNTRY_COLUMN, city.country) } helper.writableDatabase.insert(FORECASTS_TABLE, null, values) subscriber.onCompleted() } .subscribeOn(scheduler) fun updateForecast(forecast: Forecast): Observable<Unit> = Observable .create<Unit> { subscriber -> val values = ContentValues().apply { put(DATE_COLUMN, forecast.date.time) put(CITY_ID_COLUMN, forecast.city.id) put(CITY_NAME_COLUMN, forecast.city.name) put(COUNTRY_COLUMN, forecast.city.country) put(TEMPERATURE_CURRENT_COLUMN, forecast.temperature.current) put(TEMPERATURE_MORNING_COLUMN, forecast.temperature.morning) put(TEMPERATURE_DAY_COLUMN, forecast.temperature.day) put(TEMPERATURE_EVENING_COLUMN, forecast.temperature.evening) put(TEMPERATURE_NIGHT_COLUMN, forecast.temperature.night) put(WEATHER_TYPE_COLUMN, forecast.weather.type.ordinal) put(WEATHER_DESCRIPTION_COLUMN, forecast.weather.description) } helper.writableDatabase.update(FORECASTS_TABLE, values, UUID_SELECTION, forecast.id.toSelectionArgs()) subscriber.onCompleted() } .subscribeOn(scheduler) fun removeForecast(id: UUID): Observable<Unit> = Observable .create<Unit> { subscriber -> helper.writableDatabase.delete(FORECASTS_TABLE, UUID_SELECTION, id.toSelectionArgs()) subscriber.onCompleted() } .subscribeOn(scheduler) private fun UUID.toSelectionArgs(): Array<String> = arrayOf(mostSignificantBits.toString(), leastSignificantBits.toString()) }
apache-2.0
9b9c004d727896e464c10ccd62f4abf6
42.121212
120
0.683365
4.482898
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/io/ExponentialBackOff.kt
1
1942
package com.boardgamegeek.io import kotlin.random.Random class ExponentialBackOff( private var initialIntervalMillis: Int = 500, private var randomizationFactor: Double = 0.5, private var multiplier: Double = 1.5, private var maxIntervalMillis: Int = 60_000, private var maxElapsedTimeMillis: Int = 900_000 ) : BackOff { private var currentIntervalMillis: Int = 0 private var startTimeNanos: Long = 0 init { if (initialIntervalMillis <= 0) initialIntervalMillis = 500 if (randomizationFactor < 0 || randomizationFactor >= 1) randomizationFactor = 0.5 if (multiplier < 1) multiplier = 1.5 if (maxIntervalMillis < initialIntervalMillis) maxIntervalMillis = initialIntervalMillis if (maxElapsedTimeMillis <= 0) maxElapsedTimeMillis = 900000 reset() } override fun reset() { currentIntervalMillis = initialIntervalMillis startTimeNanos = System.nanoTime() } override fun nextBackOffMillis(): Long { if (calculateElapsedTimeMillis() > maxElapsedTimeMillis) return BackOff.STOP val delta = randomizationFactor * currentIntervalMillis val minInterval = currentIntervalMillis - delta val maxInterval = currentIntervalMillis + delta val randomizedInterval = (minInterval + Random.nextDouble() * (maxInterval - minInterval + 1)).toInt() incrementCurrentInterval() return randomizedInterval.toLong() } private fun calculateElapsedTimeMillis() = ((System.nanoTime() - startTimeNanos) / 1_000_000L).toInt() private fun incrementCurrentInterval() { // Check for overflow, if overflow is detected set the current interval to the max interval. currentIntervalMillis = if (currentIntervalMillis >= maxIntervalMillis / multiplier) { maxIntervalMillis } else { (currentIntervalMillis * multiplier).toInt() } } }
gpl-3.0
c7579108b5f297023df8541320d3d8f5
37.078431
110
0.69207
4.725061
false
false
false
false
raatiniemi/worker
app/src/main/java/me/raatiniemi/worker/features/project/timesheet/model/TimesheetGroup.kt
1
4054
/* * Copyright (C) 2018 Tobias Raatiniemi * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 2 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package me.raatiniemi.worker.features.project.timesheet.model import me.raatiniemi.worker.domain.model.HoursMinutes import me.raatiniemi.worker.domain.model.TimesheetItem import me.raatiniemi.worker.domain.model.accumulated import me.raatiniemi.worker.domain.util.HoursMinutesFormat import me.raatiniemi.worker.features.shared.model.ExpandableItem import java.text.SimpleDateFormat import java.util.* class TimesheetGroup private constructor( private val date: Date, private val items: MutableList<TimesheetItem> ) : ExpandableItem<TimesheetItem> { private val dateFormat = SimpleDateFormat("EEE (MMM d)", Locale.forLanguageTag(LANGUAGE_TAG)) val id: Long val title: String get() = dateFormat.format(date) val firstLetterFromTitle: String get() = title.first().toString() val isRegistered: Boolean get() { return items.any { it.isRegistered } } init { id = calculateDaysSinceUnixEpoch(date) } private fun calculateTimeDifference(accumulated: HoursMinutes): HoursMinutes { return accumulated.minus(HoursMinutes(8, 0)) } fun getTimeSummaryWithDifference(formatter: HoursMinutesFormat): String { val accumulated = accumulatedHoursMinutes() val timeSummary = formatter.apply(accumulated) val calculatedDifference = calculateTimeDifference(accumulated) val timeDifference = formatTimeDifference( getTimeDifferenceFormat(calculatedDifference), formatter.apply(calculatedDifference) ) return timeSummary + timeDifference } private fun accumulatedHoursMinutes(): HoursMinutes { return items.map { it.hoursMinutes } .accumulated() } fun buildItemResultsWithGroupIndex(groupIndex: Int): List<TimesheetAdapterResult> { return items.mapIndexedTo(ArrayList()) { childIndex, item -> TimesheetAdapterResult(groupIndex, childIndex, item) } } override fun get(index: Int): TimesheetItem { return items[index] } override fun set(index: Int, item: TimesheetItem) { items[index] = item } override fun remove(index: Int): TimesheetItem { return items.removeAt(index) } override fun size(): Int { return items.size } companion object { private const val LANGUAGE_TAG = "en_US" fun build(date: Date, timesheetItems: SortedSet<TimesheetItem>): TimesheetGroup { val items = ArrayList<TimesheetItem>() items.addAll(timesheetItems) return TimesheetGroup(date, items) } private fun calculateDaysSinceUnixEpoch(date: Date): Long { val milliseconds = date.time val seconds = milliseconds / 1000 val minutes = seconds / 60 val hours = minutes / 60 return hours / 24 } private fun formatTimeDifference(format: String, difference: String): String { return String.format(Locale.forLanguageTag(LANGUAGE_TAG), format, difference) } private fun getTimeDifferenceFormat(difference: HoursMinutes): String { if (difference.empty) { return "" } if (difference.positive) { return " (+%s)" } return " (%s)" } } }
gpl-2.0
f805ca2c213368a873c54550bae2b96f
30.92126
97
0.664036
4.849282
false
false
false
false
ekager/focus-android
app/src/main/java/org/mozilla/focus/search/MultiselectSearchEngineListPreference.kt
1
2506
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.search import android.content.Context import android.support.v7.preference.PreferenceViewHolder import android.util.AttributeSet import android.widget.CompoundButton import org.mozilla.focus.R import org.mozilla.focus.utils.asActivity import java.util.HashSet class MultiselectSearchEngineListPreference(context: Context, attrs: AttributeSet) : SearchEngineListPreference(context, attrs) { override val itemResId: Int get() = R.layout.search_engine_checkbox_button val checkedEngineIds: Set<String> get() { val engineIdSet = HashSet<String>() for (i in 0 until searchEngineGroup!!.childCount) { val engineButton = searchEngineGroup!!.getChildAt(i) as CompoundButton if (engineButton.isChecked) { engineIdSet.add(engineButton.tag as String) } } return engineIdSet } override fun onBindViewHolder(holder: PreferenceViewHolder?) { super.onBindViewHolder(holder) this.bindEngineCheckboxesToMenu() } override fun updateDefaultItem(defaultButton: CompoundButton) { defaultButton.isClickable = false // Showing the default engine as disabled requires a StateListDrawable, but since there // is no state_clickable and state_enabled seems to require a default drawable state, // use state_activated instead to designate the default search engine. defaultButton.isActivated = true } // Whenever an engine is checked or unchecked, we notify the menu private fun bindEngineCheckboxesToMenu() { for (i in 0 until searchEngineGroup!!.childCount) { val engineButton = searchEngineGroup!!.getChildAt(i) as CompoundButton engineButton.setOnCheckedChangeListener { _, _ -> val context = context context?.asActivity()?.invalidateOptionsMenu() } } } fun atLeastOneEngineChecked(): Boolean { for (i in 0 until searchEngineGroup!!.childCount) { val engineButton = searchEngineGroup!!.getChildAt(i) as CompoundButton if (engineButton.isChecked) { return true } } return false } }
mpl-2.0
c86ed739215dca33b186531b9a039bf7
36.402985
95
0.665603
5.022044
false
false
false
false
pokk/mvp-magazine
app/src/main/kotlin/taiwan/no1/app/mvp/presenters/fragment/MovieListPresenter.kt
1
1697
package taiwan.no1.app.mvp.presenters.fragment import com.devrapid.kotlinknifer.loge import rx.lang.kotlin.subscriber import taiwan.no1.app.data.source.CloudDataStore import taiwan.no1.app.domain.usecase.MovieLists import taiwan.no1.app.mvp.contracts.fragment.MovieListContract import taiwan.no1.app.mvp.models.movie.MovieBriefModel import java.util.* /** * * @author Jieyi * @since 12/6/16 */ class MovieListPresenter constructor(val moviesCase: MovieLists): BasePresenter<MovieListContract.View>(), MovieListContract.Presenter { private var movieBriefModelList: List<MovieBriefModel> = emptyList() //region Presenter implementation override fun init(view: MovieListContract.View) { super.init(view) } override fun requestListMovies(category: CloudDataStore.Movies, page: Int) { val request = MovieLists.Requests(category, page) request.fragmentLifecycle = this.view.getLifecycle() // TODO: 4/4/17 Create a customize subscriber in [BasePresenter]. // If declaring [subscriber] as a variable, it won't be used again. this.moviesCase.execute(request, subscriber<List<MovieBriefModel>>().onError { loge(it.message) loge(it) this.view.showRetry() }.onNext { this.movieBriefModelList += it view.showMovieBriefList(this.movieBriefModelList) }.onCompleted { this.view.hideLoading() }) } override fun restoreMovieList(movieList: List<MovieBriefModel>) { this.movieBriefModelList = movieList.toList() } override fun getMovieList(): ArrayList<MovieBriefModel> = ArrayList(this.movieBriefModelList) //endregion }
apache-2.0
cffe36d98d7aece918c58dcee42fca82
35.106383
97
0.712434
4.149144
false
false
false
false
googlesamples/mlkit
android/material-showcase/app/src/main/java/com/google/mlkit/md/LiveObjectDetectionActivity.kt
1
17287
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.mlkit.md import android.animation.AnimatorInflater import android.animation.AnimatorSet import android.content.Intent import android.graphics.Bitmap import android.graphics.Color import android.hardware.Camera import android.os.Bundle import android.util.Log import android.view.View import android.view.View.OnClickListener import android.widget.ProgressBar import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.android.material.bottomsheet.BottomSheetBehavior import com.google.android.material.chip.Chip import com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton import com.google.common.base.Objects import com.google.common.collect.ImmutableList import com.google.mlkit.md.camera.GraphicOverlay import com.google.mlkit.md.camera.WorkflowModel import com.google.mlkit.md.camera.WorkflowModel.WorkflowState import com.google.mlkit.md.camera.CameraSource import com.google.mlkit.md.camera.CameraSourcePreview import com.google.mlkit.md.objectdetection.MultiObjectProcessor import com.google.mlkit.md.objectdetection.ProminentObjectProcessor import com.google.mlkit.md.productsearch.BottomSheetScrimView import com.google.mlkit.md.productsearch.ProductAdapter import com.google.mlkit.md.productsearch.SearchEngine import com.google.mlkit.md.settings.PreferenceUtils import com.google.mlkit.md.settings.SettingsActivity import java.io.IOException /** Demonstrates the object detection and visual search workflow using camera preview. */ class LiveObjectDetectionActivity : AppCompatActivity(), OnClickListener { private var cameraSource: CameraSource? = null private var preview: CameraSourcePreview? = null private var graphicOverlay: GraphicOverlay? = null private var settingsButton: View? = null private var flashButton: View? = null private var promptChip: Chip? = null private var promptChipAnimator: AnimatorSet? = null private var searchButton: ExtendedFloatingActionButton? = null private var searchButtonAnimator: AnimatorSet? = null private var searchProgressBar: ProgressBar? = null private var workflowModel: WorkflowModel? = null private var currentWorkflowState: WorkflowState? = null private var searchEngine: SearchEngine? = null private var bottomSheetBehavior: BottomSheetBehavior<View>? = null private var bottomSheetScrimView: BottomSheetScrimView? = null private var productRecyclerView: RecyclerView? = null private var bottomSheetTitleView: TextView? = null private var objectThumbnailForBottomSheet: Bitmap? = null private var slidingSheetUpFromHiddenState: Boolean = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) searchEngine = SearchEngine(applicationContext) setContentView(R.layout.activity_live_object) preview = findViewById(R.id.camera_preview) graphicOverlay = findViewById<GraphicOverlay>(R.id.camera_preview_graphic_overlay).apply { setOnClickListener(this@LiveObjectDetectionActivity) cameraSource = CameraSource(this) } promptChip = findViewById(R.id.bottom_prompt_chip) promptChipAnimator = (AnimatorInflater.loadAnimator(this, R.animator.bottom_prompt_chip_enter) as AnimatorSet).apply { setTarget(promptChip) } searchButton = findViewById<ExtendedFloatingActionButton>(R.id.product_search_button).apply { setOnClickListener(this@LiveObjectDetectionActivity) } searchButtonAnimator = (AnimatorInflater.loadAnimator(this, R.animator.search_button_enter) as AnimatorSet).apply { setTarget(searchButton) } searchProgressBar = findViewById(R.id.search_progress_bar) setUpBottomSheet() findViewById<View>(R.id.close_button).setOnClickListener(this) flashButton = findViewById<View>(R.id.flash_button).apply { setOnClickListener(this@LiveObjectDetectionActivity) } settingsButton = findViewById<View>(R.id.settings_button).apply { setOnClickListener(this@LiveObjectDetectionActivity) } setUpWorkflowModel() } override fun onResume() { super.onResume() workflowModel?.markCameraFrozen() settingsButton?.isEnabled = true bottomSheetBehavior?.state = BottomSheetBehavior.STATE_HIDDEN currentWorkflowState = WorkflowState.NOT_STARTED cameraSource?.setFrameProcessor( if (PreferenceUtils.isMultipleObjectsMode(this)) { MultiObjectProcessor(graphicOverlay!!, workflowModel!!) } else { ProminentObjectProcessor(graphicOverlay!!, workflowModel!!) } ) workflowModel?.setWorkflowState(WorkflowState.DETECTING) } override fun onPause() { super.onPause() currentWorkflowState = WorkflowState.NOT_STARTED stopCameraPreview() } override fun onDestroy() { super.onDestroy() cameraSource?.release() cameraSource = null searchEngine?.shutdown() } override fun onBackPressed() { if (bottomSheetBehavior?.state != BottomSheetBehavior.STATE_HIDDEN) { bottomSheetBehavior?.setState(BottomSheetBehavior.STATE_HIDDEN) } else { super.onBackPressed() } } override fun onClick(view: View) { when (view.id) { R.id.product_search_button -> { searchButton?.isEnabled = false workflowModel?.onSearchButtonClicked() } R.id.bottom_sheet_scrim_view -> bottomSheetBehavior?.setState(BottomSheetBehavior.STATE_HIDDEN) R.id.close_button -> onBackPressed() R.id.flash_button -> { if (flashButton?.isSelected == true) { flashButton?.isSelected = false cameraSource?.updateFlashMode(Camera.Parameters.FLASH_MODE_OFF) } else { flashButton?.isSelected = true cameraSource?.updateFlashMode(Camera.Parameters.FLASH_MODE_TORCH) } } R.id.settings_button -> { settingsButton?.isEnabled = false startActivity(Intent(this, SettingsActivity::class.java)) } } } private fun startCameraPreview() { val cameraSource = this.cameraSource ?: return val workflowModel = this.workflowModel ?: return if (!workflowModel.isCameraLive) { try { workflowModel.markCameraLive() preview?.start(cameraSource) } catch (e: IOException) { Log.e(TAG, "Failed to start camera preview!", e) cameraSource.release() this.cameraSource = null } } } private fun stopCameraPreview() { if (workflowModel?.isCameraLive == true) { workflowModel!!.markCameraFrozen() flashButton?.isSelected = false preview?.stop() } } private fun setUpBottomSheet() { bottomSheetBehavior = BottomSheetBehavior.from(findViewById(R.id.bottom_sheet)) bottomSheetBehavior?.setBottomSheetCallback( object : BottomSheetBehavior.BottomSheetCallback() { override fun onStateChanged(bottomSheet: View, newState: Int) { Log.d(TAG, "Bottom sheet new state: $newState") bottomSheetScrimView?.visibility = if (newState == BottomSheetBehavior.STATE_HIDDEN) View.GONE else View.VISIBLE graphicOverlay?.clear() when (newState) { BottomSheetBehavior.STATE_HIDDEN -> workflowModel?.setWorkflowState(WorkflowState.DETECTING) BottomSheetBehavior.STATE_COLLAPSED, BottomSheetBehavior.STATE_EXPANDED, BottomSheetBehavior.STATE_HALF_EXPANDED -> slidingSheetUpFromHiddenState = false BottomSheetBehavior.STATE_DRAGGING, BottomSheetBehavior.STATE_SETTLING -> { } } } override fun onSlide(bottomSheet: View, slideOffset: Float) { val searchedObject = workflowModel!!.searchedObject.value if (searchedObject == null || java.lang.Float.isNaN(slideOffset)) { return } val graphicOverlay = graphicOverlay ?: return val bottomSheetBehavior = bottomSheetBehavior ?: return val collapsedStateHeight = bottomSheetBehavior.peekHeight.coerceAtMost(bottomSheet.height) val bottomBitmap = objectThumbnailForBottomSheet ?: return if (slidingSheetUpFromHiddenState) { val thumbnailSrcRect = graphicOverlay.translateRect(searchedObject.boundingBox) bottomSheetScrimView?.updateWithThumbnailTranslateAndScale( bottomBitmap, collapsedStateHeight, slideOffset, thumbnailSrcRect ) } else { bottomSheetScrimView?.updateWithThumbnailTranslate( bottomBitmap, collapsedStateHeight, slideOffset, bottomSheet ) } } }) bottomSheetScrimView = findViewById<BottomSheetScrimView>(R.id.bottom_sheet_scrim_view).apply { setOnClickListener(this@LiveObjectDetectionActivity) } bottomSheetTitleView = findViewById(R.id.bottom_sheet_title) productRecyclerView = findViewById<RecyclerView>(R.id.product_recycler_view).apply { setHasFixedSize(true) layoutManager = LinearLayoutManager(this@LiveObjectDetectionActivity) adapter = ProductAdapter(ImmutableList.of()) } } private fun setUpWorkflowModel() { workflowModel = ViewModelProviders.of(this).get(WorkflowModel::class.java).apply { // Observes the workflow state changes, if happens, update the overlay view indicators and // camera preview state. workflowState.observe(this@LiveObjectDetectionActivity, Observer { workflowState -> if (workflowState == null || Objects.equal(currentWorkflowState, workflowState)) { return@Observer } currentWorkflowState = workflowState Log.d(TAG, "Current workflow state: ${workflowState.name}") if (PreferenceUtils.isAutoSearchEnabled(this@LiveObjectDetectionActivity)) { stateChangeInAutoSearchMode(workflowState) } else { stateChangeInManualSearchMode(workflowState) } }) // Observes changes on the object to search, if happens, fire product search request. objectToSearch.observe(this@LiveObjectDetectionActivity, Observer { detectObject -> searchEngine!!.search(detectObject) { detectedObject, products -> workflowModel?.onSearchCompleted(detectedObject, products) } }) // Observes changes on the object that has search completed, if happens, show the bottom sheet // to present search result. searchedObject.observe(this@LiveObjectDetectionActivity, Observer { nullableSearchedObject -> val searchedObject = nullableSearchedObject ?: return@Observer val productList = searchedObject.productList objectThumbnailForBottomSheet = searchedObject.getObjectThumbnail() bottomSheetTitleView?.text = resources .getQuantityString( R.plurals.bottom_sheet_title, productList.size, productList.size ) productRecyclerView?.adapter = ProductAdapter(productList) slidingSheetUpFromHiddenState = true bottomSheetBehavior?.peekHeight = preview?.height?.div(2) ?: BottomSheetBehavior.PEEK_HEIGHT_AUTO bottomSheetBehavior?.state = BottomSheetBehavior.STATE_COLLAPSED }) } } private fun stateChangeInAutoSearchMode(workflowState: WorkflowState) { val wasPromptChipGone = promptChip!!.visibility == View.GONE searchButton?.visibility = View.GONE searchProgressBar?.visibility = View.GONE when (workflowState) { WorkflowState.DETECTING, WorkflowState.DETECTED, WorkflowState.CONFIRMING -> { promptChip?.visibility = View.VISIBLE promptChip?.setText( if (workflowState == WorkflowState.CONFIRMING) R.string.prompt_hold_camera_steady else R.string.prompt_point_at_an_object ) startCameraPreview() } WorkflowState.CONFIRMED -> { promptChip?.visibility = View.VISIBLE promptChip?.setText(R.string.prompt_searching) stopCameraPreview() } WorkflowState.SEARCHING -> { searchProgressBar?.visibility = View.VISIBLE promptChip?.visibility = View.VISIBLE promptChip?.setText(R.string.prompt_searching) stopCameraPreview() } WorkflowState.SEARCHED -> { promptChip?.visibility = View.GONE stopCameraPreview() } else -> promptChip?.visibility = View.GONE } val shouldPlayPromptChipEnteringAnimation = wasPromptChipGone && promptChip?.visibility == View.VISIBLE if (shouldPlayPromptChipEnteringAnimation && promptChipAnimator?.isRunning == false) { promptChipAnimator?.start() } } private fun stateChangeInManualSearchMode(workflowState: WorkflowState) { val wasPromptChipGone = promptChip?.visibility == View.GONE val wasSearchButtonGone = searchButton?.visibility == View.GONE searchProgressBar?.visibility = View.GONE when (workflowState) { WorkflowState.DETECTING, WorkflowState.DETECTED, WorkflowState.CONFIRMING -> { promptChip?.visibility = View.VISIBLE promptChip?.setText(R.string.prompt_point_at_an_object) searchButton?.visibility = View.GONE startCameraPreview() } WorkflowState.CONFIRMED -> { promptChip?.visibility = View.GONE searchButton?.visibility = View.VISIBLE searchButton?.isEnabled = true searchButton?.setBackgroundColor(Color.WHITE) startCameraPreview() } WorkflowState.SEARCHING -> { promptChip?.visibility = View.GONE searchButton?.visibility = View.VISIBLE searchButton?.isEnabled = false searchButton?.setBackgroundColor(Color.GRAY) searchProgressBar!!.visibility = View.VISIBLE stopCameraPreview() } WorkflowState.SEARCHED -> { promptChip?.visibility = View.GONE searchButton?.visibility = View.GONE stopCameraPreview() } else -> { promptChip?.visibility = View.GONE searchButton?.visibility = View.GONE } } val shouldPlayPromptChipEnteringAnimation = wasPromptChipGone && promptChip?.visibility == View.VISIBLE promptChipAnimator?.let { if (shouldPlayPromptChipEnteringAnimation && !it.isRunning) it.start() } val shouldPlaySearchButtonEnteringAnimation = wasSearchButtonGone && searchButton?.visibility == View.VISIBLE searchButtonAnimator?.let { if (shouldPlaySearchButtonEnteringAnimation && !it.isRunning) it.start() } } companion object { private const val TAG = "LiveObjectActivity" } }
apache-2.0
4e24f4d35216d95fd0f5b497f8c8d7a7
42.875635
117
0.638399
5.508923
false
false
false
false
ademar111190/Studies
Template/core/src/test/java/ademar/study/template/core/repository/HelloWorldRepositoryTest.kt
1
6155
package ademar.study.template.core.repository import ademar.study.template.core.injection.ApplicationJsonAdapterFactory import ademar.study.template.core.repository.datasource.HelloWorldCloudRepository import ademar.study.template.core.repository.datasource.HelloWorldMemoryRepository import ademar.study.template.core.test.BaseTest import ademar.study.template.core.test.Fixture import com.nhaarman.mockito_kotlin.whenever import com.squareup.moshi.KotlinJsonAdapterFactory import com.squareup.moshi.Moshi import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import okhttp3.mockwebserver.MockResponse import org.assertj.core.api.Assertions.assertThat import org.junit.Test import org.mockito.Mock import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.moshi.MoshiConverterFactory class HelloWorldRepositoryTest : BaseTest() { private lateinit var mockRetrofit: Retrofit private lateinit var mockHelloWorldCloudRepository: HelloWorldCloudRepository private var nextCalls = 0 private var errorCalled = false private var successCalled = false @Mock lateinit var mockHelloWorldMemoryRepository: HelloWorldMemoryRepository override fun setUp() { super.setUp() nextCalls = 0 errorCalled = false successCalled = false mockWebServer.start() mockRetrofit = Retrofit.Builder() .baseUrl(mockWebServer.url("")) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(MoshiConverterFactory.create(Moshi.Builder() .add(KotlinJsonAdapterFactory()) .add(ApplicationJsonAdapterFactory.INSTANCE) .build())) .client(OkHttpClient.Builder() .addInterceptor(HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY }) .build()) .build() mockHelloWorldCloudRepository = mockRetrofit.create(HelloWorldCloudRepository::class.java) } override fun tearDown() { super.tearDown() mockWebServer.shutdown() } @Test fun testHellos_successService() { val mockResponse = MockResponse().setResponseCode(200) .setBody(readJson("helloWorlds")) mockWebServer.enqueue(mockResponse) whenever(mockHelloWorldMemoryRepository.hellos).thenReturn(null) val repository = HelloWorldRepository(mockHelloWorldCloudRepository, mockHelloWorldMemoryRepository) repository.getAllHelloWorld() .subscribe({ nextCalls++ }, { errorCalled = true }, { successCalled = true }) assertThat(nextCalls).isEqualTo(1) assertThat(errorCalled).isFalse() assertThat(successCalled).isTrue() } @Test fun testHellos_successCached_noUpdate() { val mockResponse = MockResponse().setResponseCode(200) .setBody(readJson("helloWorlds")) mockWebServer.enqueue(mockResponse) whenever(mockHelloWorldMemoryRepository.hellos).thenReturn(listOf(Fixture.helloWorld())) val repository = HelloWorldRepository(mockHelloWorldCloudRepository, mockHelloWorldMemoryRepository) repository.getAllHelloWorld() .subscribe({ nextCalls++ }, { errorCalled = true }, { successCalled = true }) assertThat(nextCalls).isEqualTo(1) assertThat(errorCalled).isFalse() assertThat(successCalled).isTrue() } @Test fun testHellos_successCached_update() { val mockResponse = MockResponse().setResponseCode(200) .setBody(readJson("helloWorldsUpdate")) mockWebServer.enqueue(mockResponse) whenever(mockHelloWorldMemoryRepository.hellos).thenReturn(listOf(Fixture.helloWorld())) val repository = HelloWorldRepository(mockHelloWorldCloudRepository, mockHelloWorldMemoryRepository) repository.getAllHelloWorld() .subscribe({ nextCalls++ }, { errorCalled = true }, { successCalled = true }) assertThat(nextCalls).isEqualTo(2) assertThat(errorCalled).isFalse() assertThat(successCalled).isTrue() } @Test fun testHellos_successCached_error() { val mockResponse = MockResponse().setResponseCode(0) mockWebServer.enqueue(mockResponse) whenever(mockHelloWorldMemoryRepository.hellos).thenReturn(listOf(Fixture.helloWorld())) val repository = HelloWorldRepository(mockHelloWorldCloudRepository, mockHelloWorldMemoryRepository) repository.getAllHelloWorld() .subscribe({ nextCalls++ }, { errorCalled = true }, { successCalled = true }) assertThat(nextCalls).isEqualTo(1) assertThat(errorCalled).isFalse() assertThat(successCalled).isTrue() } @Test fun testHellos_successError() { val mockResponse = MockResponse().setResponseCode(0) mockWebServer.enqueue(mockResponse) whenever(mockHelloWorldMemoryRepository.hellos).thenReturn(null) val repository = HelloWorldRepository(mockHelloWorldCloudRepository, mockHelloWorldMemoryRepository) repository.getAllHelloWorld() .subscribe({ nextCalls++ }, { error -> assertThat(error).isNotNull() errorCalled = true }, { successCalled = true }) assertThat(nextCalls).isEqualTo(0) assertThat(errorCalled).isTrue() assertThat(successCalled).isFalse() } }
mit
a0271dc082676a4f3665919777f6f517
33.194444
108
0.633469
5.651974
false
true
false
false
dafi/photoshelf
birthday/src/main/java/com/ternaryop/photoshelf/birthday/browser/adapter/BirthdayViewHolder.kt
1
3117
package com.ternaryop.photoshelf.birthday.browser.adapter import android.view.View import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.ternaryop.photoshelf.api.birthday.Birthday import com.ternaryop.photoshelf.birthday.R import com.ternaryop.utils.date.dayOfMonth import com.ternaryop.utils.date.month import com.ternaryop.utils.date.yearsBetweenDates import com.ternaryop.utils.text.fromHtml import com.ternaryop.utils.text.htmlHighlightPattern import java.text.ParseException import java.text.SimpleDateFormat import java.util.Calendar import java.util.Locale private val dateFormat = SimpleDateFormat("d MMMM, yyyy", Locale.US) class BirthdayViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val title: TextView = itemView.findViewById(android.R.id.text1) val subtitle: TextView = itemView.findViewById(android.R.id.text2) var onClickListeners: View.OnClickListener? = null set(value) { if (value != null) { val position = bindingAdapterPosition itemView.setOnClickListener(value) itemView.tag = position } } var onLongClickListener: View.OnLongClickListener? = null set(value) { if (value != null) { itemView.setOnLongClickListener(value) itemView.isLongClickable = true itemView.tag = bindingAdapterPosition } } fun bindModel(pattern: String, birthday: Birthday) { try { updateBackground(birthday) updateName(pattern, birthday) updateBirthdate(birthday) } catch (ignored: ParseException) { } } private fun updateBackground(birthday: Birthday) { val date = birthday.birthdate if (date == null) { itemView.setBackgroundResource(R.drawable.list_selector_post_group_even) return } val now = Calendar.getInstance() if (date.dayOfMonth == now.dayOfMonth && date.month == now.month) { itemView.setBackgroundResource(R.drawable.list_selector_post_never) } else { // group by day, not perfect by better than nothing val isEven = date.dayOfMonth and 1 == 0 itemView.setBackgroundResource( if (isEven) R.drawable.list_selector_post_group_even else R.drawable.list_selector_post_group_odd ) } } private fun updateName(pattern: String, birthday: Birthday) { title.text = birthday.name.htmlHighlightPattern(pattern).fromHtml() } private fun updateBirthdate(birthday: Birthday) { val date = birthday.birthdate if (date == null) { subtitle.visibility = View.GONE } else { subtitle.visibility = View.VISIBLE val age = date.yearsBetweenDates(Calendar.getInstance()).toString() val dateStr = dateFormat.format(date.time) subtitle.text = itemView.context.getString(R.string.name_with_age, dateStr, age) } } }
mit
b238f1522fb56542c18f25e68dd6b163
34.022472
92
0.654155
4.673163
false
false
false
false
jonalmeida/focus-android
app/src/main/java/org/mozilla/focus/fragment/BrowserFragment.kt
1
58107
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.fragment import android.Manifest import android.app.DownloadManager import android.app.PendingIntent import androidx.lifecycle.LifecycleObserver import androidx.lifecycle.Observer import androidx.lifecycle.ProcessLifecycleOwner import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.content.Intent import android.content.IntentFilter import android.content.pm.PackageManager import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.graphics.drawable.TransitionDrawable import android.net.Uri import android.os.Build import android.os.Bundle import android.os.Environment import android.preference.PreferenceManager import androidx.annotation.RequiresApi import com.google.android.material.appbar.AppBarLayout import androidx.coordinatorlayout.widget.CoordinatorLayout import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import android.text.Editable import android.text.TextUtils import android.text.TextWatcher import android.util.Log import android.view.Gravity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.WindowManager import android.view.accessibility.AccessibilityEvent import android.view.accessibility.AccessibilityManager import android.view.inputmethod.EditorInfo import android.webkit.CookieManager import android.webkit.URLUtil import android.widget.FrameLayout import android.widget.ImageButton import android.widget.ImageView import android.widget.TextView import android.widget.Toast import kotlinx.android.synthetic.main.browser_display_toolbar.* import kotlinx.android.synthetic.main.fragment_browser.* import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import mozilla.components.browser.session.Session import mozilla.components.browser.session.SessionManager import mozilla.components.concept.engine.content.blocking.Tracker import mozilla.components.lib.crash.Crash import mozilla.components.support.utils.ColorUtils import mozilla.components.support.utils.DownloadUtils import mozilla.components.support.utils.DrawableUtils import org.mozilla.focus.R import org.mozilla.focus.activity.InstallFirefoxActivity import org.mozilla.focus.activity.MainActivity import org.mozilla.focus.animation.TransitionDrawableGroup import org.mozilla.focus.biometrics.BiometricAuthenticationDialogFragment import org.mozilla.focus.biometrics.BiometricAuthenticationHandler import org.mozilla.focus.biometrics.Biometrics import org.mozilla.focus.broadcastreceiver.DownloadBroadcastReceiver import org.mozilla.focus.exceptions.ExceptionDomains import org.mozilla.focus.ext.isSearch import org.mozilla.focus.ext.requireComponents import org.mozilla.focus.ext.shouldRequestDesktopSite import org.mozilla.focus.findinpage.FindInPageCoordinator import org.mozilla.focus.gecko.NestedGeckoView import org.mozilla.focus.locale.LocaleAwareAppCompatActivity import org.mozilla.focus.menu.browser.BrowserMenu import org.mozilla.focus.menu.context.WebContextMenu import org.mozilla.focus.observer.LoadTimeObserver import org.mozilla.focus.open.OpenWithFragment import org.mozilla.focus.popup.PopupUtils import org.mozilla.focus.session.SessionCallbackProxy import org.mozilla.focus.session.removeAndCloseAllSessions import org.mozilla.focus.session.removeAndCloseSession import org.mozilla.focus.session.ui.SessionsSheetFragment import org.mozilla.focus.telemetry.CrashReporterWrapper import org.mozilla.focus.telemetry.TelemetryWrapper import org.mozilla.focus.utils.AppConstants import org.mozilla.focus.utils.Browsers import org.mozilla.focus.utils.Features import org.mozilla.focus.utils.StatusBarUtils import org.mozilla.focus.utils.SupportUtils import org.mozilla.focus.utils.UrlUtils import org.mozilla.focus.utils.ViewUtils import org.mozilla.focus.web.Download import org.mozilla.focus.web.HttpAuthenticationDialogBuilder import org.mozilla.focus.web.IWebView import org.mozilla.focus.widget.AnimatedProgressBar import org.mozilla.focus.widget.FloatingEraseButton import org.mozilla.focus.widget.FloatingSessionsButton import java.lang.ref.WeakReference import java.net.MalformedURLException import java.net.URL import kotlin.coroutines.CoroutineContext /** * Fragment for displaying the browser UI. */ @Suppress("LargeClass", "TooManyFunctions") class BrowserFragment : WebFragment(), LifecycleObserver, View.OnClickListener, DownloadDialogFragment.DownloadDialogListener, View.OnLongClickListener, BiometricAuthenticationDialogFragment.BiometricAuthenticationListener, CoroutineScope { private var pendingDownload: Download? = null private var backgroundTransitionGroup: TransitionDrawableGroup? = null private var urlView: TextView? = null private var progressView: AnimatedProgressBar? = null private var blockView: FrameLayout? = null private var securityView: ImageView? = null private var menuView: ImageButton? = null private var statusBar: View? = null private var urlBar: View? = null private var popupTint: FrameLayout? = null private var swipeRefresh: SwipeRefreshLayout? = null private var menuWeakReference: WeakReference<BrowserMenu>? = WeakReference<BrowserMenu>(null) /** * Container for custom video views shown in fullscreen mode. */ private var videoContainer: ViewGroup? = null private var isFullscreen: Boolean = false /** * Container containing the browser chrome and web content. */ private var browserContainer: View? = null private var forwardButton: View? = null private var backButton: View? = null private var refreshButton: View? = null private var stopButton: View? = null private var findInPageView: View? = null private var findInPageViewHeight: Int = 0 private var findInPageQuery: TextView? = null private var findInPageResultTextView: TextView? = null private var findInPageNext: ImageButton? = null private var findInPagePrevious: ImageButton? = null private var closeFindInPage: ImageButton? = null private var fullscreenCallback: IWebView.FullscreenCallback? = null private var manager: DownloadManager? = null private var downloadBroadcastReceiver: DownloadBroadcastReceiver? = null private val findInPageCoordinator = FindInPageCoordinator() private var biometricController: BiometricAuthenticationHandler? = null private var job = Job() override val coroutineContext: CoroutineContext get() = job + Dispatchers.Main // The url property is used for things like sharing the current URL. We could try to use the webview, // but sometimes it's null, and sometimes it returns a null URL. Sometimes it returns a data: // URL for error pages. The URL we show in the toolbar is (A) always correct and (B) what the // user is probably expecting to share, so lets use that here: val url: String get() = urlView!!.text.toString() var openedFromExternalLink: Boolean = false override lateinit var session: Session private set override val initialUrl: String? get() = session.url override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) ProcessLifecycleOwner.get().lifecycle.addObserver(this) val sessionUUID = arguments!!.getString(ARGUMENT_SESSION_UUID) ?: throw IllegalAccessError("No session exists") session = requireComponents.sessionManager.findSessionById(sessionUUID) ?: Session("about:blank") findInPageCoordinator.matches.observe( this, Observer { matches -> updateFindInPageResult(matches!!.first, matches.second) }) } override fun onPause() { super.onPause() if (Biometrics.isBiometricsEnabled(requireContext())) { biometricController?.stopListening() view!!.alpha = 0f } requireContext().unregisterReceiver(downloadBroadcastReceiver) if (isFullscreen) { getWebView()?.exitFullscreen() } val menu = menuWeakReference!!.get() if (menu != null) { menu.dismiss() menuWeakReference!!.clear() } } override fun onStop() { job.cancel() super.onStop() } @Suppress("LongMethod", "ComplexMethod") override fun inflateLayout(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { if (savedInstanceState != null && savedInstanceState.containsKey(RESTORE_KEY_DOWNLOAD)) { // If this activity was destroyed before we could start a download (e.g. because we were waiting for a // permission) then restore the download object. pendingDownload = savedInstanceState.getParcelable(RESTORE_KEY_DOWNLOAD) } val view = inflater.inflate(R.layout.fragment_browser, container, false) videoContainer = view.findViewById<View>(R.id.video_container) as ViewGroup browserContainer = view.findViewById(R.id.browser_container) urlBar = view.findViewById(R.id.urlbar) statusBar = view.findViewById(R.id.status_bar_background) popupTint = view.findViewById(R.id.popup_tint) urlView = view.findViewById<View>(R.id.display_url) as TextView urlView!!.setOnLongClickListener(this) progressView = view.findViewById<View>(R.id.progress) as AnimatedProgressBar swipeRefresh = view.findViewById<View>(R.id.swipe_refresh) as SwipeRefreshLayout swipeRefresh!!.setColorSchemeResources(R.color.colorAccent) swipeRefresh!!.isEnabled = Features.SWIPE_TO_REFRESH swipeRefresh!!.setOnRefreshListener { reload() TelemetryWrapper.swipeReloadEvent() } findInPageView = view.findViewById(R.id.find_in_page) findInPageQuery = view.findViewById(R.id.queryText) findInPageResultTextView = view.findViewById(R.id.resultText) findInPageQuery!!.addTextChangedListener( object : TextWatcher { override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {} override fun afterTextChanged(s: Editable) {} override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { if (!TextUtils.isEmpty(s)) { getWebView()?.findAllAsync(s.toString()) } } } ) findInPageQuery!!.setOnClickListener(this) findInPageQuery!!.setOnEditorActionListener { _, actionId, _ -> if (actionId == EditorInfo.IME_ACTION_DONE) { ViewUtils.hideKeyboard(findInPageQuery!!) findInPageQuery!!.isCursorVisible = false } false } findInPagePrevious = view.findViewById(R.id.previousResult) findInPagePrevious!!.setOnClickListener(this) findInPageNext = view.findViewById(R.id.nextResult) findInPageNext!!.setOnClickListener(this) closeFindInPage = view.findViewById(R.id.close_find_in_page) closeFindInPage!!.setOnClickListener(this) setShouldRequestDesktop(session.shouldRequestDesktopSite) LoadTimeObserver.addObservers(session, this) refreshButton = view.findViewById(R.id.refresh) refreshButton?.let { it.setOnClickListener(this) } stopButton = view.findViewById(R.id.stop) stopButton?.let { it.setOnClickListener(this) } forwardButton = view.findViewById(R.id.forward) forwardButton?.let { it.setOnClickListener(this) } backButton = view.findViewById(R.id.back) backButton?.let { it.setOnClickListener(this) } val blockIcon = view.findViewById<View>(R.id.block_image) as ImageView blockIcon.setImageResource(R.drawable.ic_tracking_protection_disabled) blockView = view.findViewById<View>(R.id.block) as FrameLayout securityView = view.findViewById(R.id.security_info) securityView!!.setImageResource(R.drawable.ic_internet) securityView!!.setOnClickListener(this) menuView = view.findViewById<View>(R.id.menuView) as ImageButton menuView!!.setOnClickListener(this) if (session.isCustomTabSession()) { initialiseCustomTabUi(view) } else { initialiseNormalBrowserUi(view) } // Pre-calculate the height of the find in page UI so that we can accurately add padding // to the WebView when we present it. findInPageView!!.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED) findInPageViewHeight = findInPageView!!.measuredHeight return view } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { session.register(sessionObserver, owner = this) // We need to update the views with the initial values. Other than LiveData an Observer doesn't get the initial // values automatically yet. // We want to change that in Android Components: https://github.com/mozilla-mobile/android-components/issues/665 sessionObserver.apply { onTrackerBlockingEnabledChanged(session, session.trackerBlockingEnabled) onLoadingStateChanged(session, session.loading) onUrlChanged(session, session.url) onSecurityChanged(session, session.securityInfo) } } private fun initialiseNormalBrowserUi(view: View) { val eraseButton = view.findViewById<FloatingEraseButton>(R.id.erase) eraseButton.setOnClickListener(this) urlView!!.setOnClickListener(this) val tabsButton = view.findViewById<FloatingSessionsButton>(R.id.tabs) tabsButton.setOnClickListener(this) val sessionManager = requireComponents.sessionManager sessionManager.register(object : SessionManager.Observer { override fun onSessionAdded(session: Session) { tabsButton.updateSessionsCount(sessionManager.sessions.size) eraseButton.updateSessionsCount(sessionManager.sessions.size) } override fun onSessionRemoved(session: Session) { tabsButton.updateSessionsCount(sessionManager.sessions.size) eraseButton.updateSessionsCount(sessionManager.sessions.size) } override fun onAllSessionsRemoved() { tabsButton.updateSessionsCount(sessionManager.sessions.size) eraseButton.updateSessionsCount(sessionManager.sessions.size) } }) tabsButton.updateSessionsCount(sessionManager.sessions.size) eraseButton.updateSessionsCount(sessionManager.sessions.size) } private fun initialiseCustomTabUi(view: View) { val customTabConfig = session.customTabConfig!! // Unfortunately there's no simpler way to have the FAB only in normal-browser mode. // - ViewStub: requires splitting attributes for the FAB between the ViewStub, and actual FAB layout file. // Moreover, the layout behaviour just doesn't work unless you set it programatically. // - View.GONE: doesn't work because the layout-behaviour makes the FAB visible again when scrolling. // - Adding at runtime: works, but then we need to use a separate layout file (and you need // to set some attributes programatically, same as ViewStub). val erase = view.findViewById<FloatingEraseButton>(R.id.erase) val eraseContainer = erase.parent as ViewGroup eraseContainer.removeView(erase) val sessions = view.findViewById<FloatingSessionsButton>(R.id.tabs) eraseContainer.removeView(sessions) val textColor: Int if (customTabConfig.toolbarColor != null) { urlBar!!.setBackgroundColor(customTabConfig.toolbarColor!!) textColor = ColorUtils.getReadableTextColor(customTabConfig.toolbarColor!!) urlView!!.setTextColor(textColor) } else { textColor = Color.WHITE } val closeButton = view.findViewById<View>(R.id.customtab_close) as ImageView closeButton.visibility = View.VISIBLE closeButton.setOnClickListener(this) if (customTabConfig.closeButtonIcon != null) { closeButton.setImageBitmap(customTabConfig.closeButtonIcon) } else { // Always set the icon in case it's been overridden by a previous CT invocation val closeIcon = DrawableUtils.loadAndTintDrawable(requireContext(), R.drawable.ic_close, textColor) closeButton.setImageDrawable(closeIcon) } if (!customTabConfig.enableUrlbarHiding) { val params = urlBar!!.layoutParams as AppBarLayout.LayoutParams params.scrollFlags = 0 } if (customTabConfig.actionButtonConfig != null) { val actionButton = view.findViewById<View>(R.id.customtab_actionbutton) as ImageButton actionButton.visibility = View.VISIBLE actionButton.setImageBitmap(customTabConfig.actionButtonConfig!!.icon) actionButton.contentDescription = customTabConfig.actionButtonConfig!!.description val pendingIntent = customTabConfig.actionButtonConfig!!.pendingIntent actionButton.setOnClickListener { try { val intent = Intent() intent.data = Uri.parse(url) pendingIntent.send(context, 0, intent) } catch (e: PendingIntent.CanceledException) { // There's really nothing we can do here... } TelemetryWrapper.customTabActionButtonEvent() } } else { // If the third-party app doesn't provide an action button configuration then we are // going to disable a "Share" button in the toolbar instead. val shareButton = view.findViewById<ImageButton>(R.id.customtab_actionbutton) shareButton.visibility = View.VISIBLE shareButton.setImageDrawable( DrawableUtils.loadAndTintDrawable( requireContext(), R.drawable.ic_share, textColor ) ) shareButton.contentDescription = getString(R.string.menu_share) shareButton.setOnClickListener { shareCurrentUrl() } } // We need to tint some icons.. We already tinted the close button above. Let's tint our other icons too. securityView!!.setColorFilter(textColor) val menuIcon = DrawableUtils.loadAndTintDrawable(requireContext(), R.drawable.ic_menu, textColor) menuView!!.setImageDrawable(menuIcon) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) if (pendingDownload != null) { // We were not able to start this download yet (waiting for a permission). Save this download // so that we can start it once we get restored and receive the permission. outState.putParcelable(RESTORE_KEY_DOWNLOAD, pendingDownload) } } @Suppress("ComplexMethod") override fun createCallback(): IWebView.Callback { return SessionCallbackProxy(session, object : IWebView.Callback { override fun onPageStarted(url: String) {} override fun onPageFinished(isSecure: Boolean) {} override fun onSecurityChanged(isSecure: Boolean, host: String, organization: String) {} override fun onURLChanged(url: String) {} override fun onTitleChanged(title: String) {} override fun onRequest(isTriggeredByUserGesture: Boolean) {} override fun onProgress(progress: Int) {} override fun countBlockedTracker() {} override fun resetBlockedTrackers() {} override fun onBlockingStateChanged(isBlockingEnabled: Boolean) {} override fun onHttpAuthRequest(callback: IWebView.HttpAuthCallback, host: String, realm: String) { val builder = HttpAuthenticationDialogBuilder.Builder(activity, host, realm) .setOkListener { _, _, username, password -> callback.proceed(username, password) } .setCancelListener { callback.cancel() } .build() builder.createDialog() builder.show() } override fun onRequestDesktopStateChanged(shouldRequestDesktop: Boolean) {} override fun onLongPress(hitTarget: IWebView.HitTarget) { WebContextMenu.show(requireActivity(), this, hitTarget, session) } override fun onEnterFullScreen(callback: IWebView.FullscreenCallback, view: View?) { fullscreenCallback = callback isFullscreen = true // View is passed in as null for GeckoView fullscreen if (view != null) { // Hide browser UI and web content browserContainer!!.visibility = View.INVISIBLE // Add view to video container and make it visible val params = FrameLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) videoContainer!!.addView(view, params) videoContainer!!.visibility = View.VISIBLE // Switch to immersive mode: Hide system bars other UI controls switchToImmersiveMode() } else { appbar?.setExpanded(false, true) (getWebView() as? NestedGeckoView)?.isNestedScrollingEnabled = false // Hide status bar when entering fullscreen with GeckoView statusBar!!.visibility = View.GONE // Switch to immersive mode: Hide system bars other UI controls switchToImmersiveMode() } } override fun onExitFullScreen() { if (AppConstants.isGeckoBuild) { appbar?.setExpanded(true, true) (getWebView() as? NestedGeckoView)?.isNestedScrollingEnabled = true } isFullscreen = false // Remove custom video views and hide container videoContainer!!.removeAllViews() videoContainer!!.visibility = View.GONE // Show browser UI and web content again browserContainer!!.visibility = View.VISIBLE // Show status bar again (hidden in GeckoView versions) statusBar!!.visibility = View.VISIBLE exitImmersiveModeIfNeeded() // Notify renderer that we left fullscreen mode. if (fullscreenCallback != null) { fullscreenCallback!!.fullScreenExited() fullscreenCallback = null } } override fun onDownloadStart(download: Download) { if (PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission( requireContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE ) ) { // Long press image displays its own dialog and we handle other download cases here if (!isDownloadFromLongPressImage(download)) { showDownloadPromptDialog(download) } else { // Download dialog has already been shown from long press on image. Proceed with download. queueDownload(download) } } else { // We do not have the permission to write to the external storage. Request the permission and start // the download from onRequestPermissionsResult(). val activity = activity ?: return pendingDownload = download ActivityCompat.requestPermissions( activity, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), REQUEST_CODE_STORAGE_PERMISSION ) } } }) } /** * Checks a download's destination directory to determine if it is being called from * a long press on an image or otherwise. */ private fun isDownloadFromLongPressImage(download: Download): Boolean { return download.destinationDirectory == Environment.DIRECTORY_PICTURES } /** * Hide system bars. They can be revealed temporarily with system gestures, such as swiping from * the top of the screen. These transient system bars will overlay app’s content, may have some * degree of transparency, and will automatically hide after a short timeout. */ private fun switchToImmersiveMode() { val activity = activity ?: return val window = activity.window window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) } /** * Show the system bars again. */ private fun exitImmersiveModeIfNeeded() { val activity = activity ?: return if (WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON and activity.window.attributes.flags == 0) { // We left immersive mode already. return } val window = activity.window window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN } override fun onDestroy() { super.onDestroy() // This fragment might get destroyed before the user left immersive mode (e.g. by opening another URL from an // app). In this case let's leave immersive mode now when the fragment gets destroyed. exitImmersiveModeIfNeeded() } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { if (requestCode != REQUEST_CODE_STORAGE_PERMISSION) { return } if (grantResults.isEmpty() || grantResults[0] != PackageManager.PERMISSION_GRANTED) { // We didn't get the storage permission: We are not able to start this download. pendingDownload = null } // The actual download dialog will be shown from onResume(). If this activity/fragment is // getting restored then we need to 'resume' first before we can show a dialog (attaching // another fragment). } internal fun showDownloadPromptDialog(download: Download) { val fragmentManager = childFragmentManager if (fragmentManager.findFragmentByTag(DownloadDialogFragment.FRAGMENT_TAG) != null) { // We are already displaying a download dialog fragment (Probably a restored fragment). // No need to show another one. return } val downloadDialogFragment = DownloadDialogFragment.newInstance(download) try { downloadDialogFragment.show(fragmentManager, DownloadDialogFragment.FRAGMENT_TAG) } catch (e: IllegalStateException) { // It can happen that at this point in time the activity is already in the background // and onSaveInstanceState() has already been called. Fragment transactions are not // allowed after that anymore. It's probably safe to guess that the user might not // be interested in the download at this point. So we could just *not* show the dialog. // Unfortunately we can't call commitAllowingStateLoss() because committing the // transaction is happening inside the DialogFragment code. Therefore we just swallow // the exception here. Gulp! } } private fun showCrashReporter(crash: Crash) { val fragmentManager = requireActivity().supportFragmentManager Log.e("crash:", crash.toString()) if (crashReporterIsVisible()) { // We are already displaying the crash reporter // No need to show another one. return } val crashReporterFragment = CrashReporterFragment.create() crashReporterFragment.onCloseTabPressed = { sendCrashReport -> if (sendCrashReport) { CrashReporterWrapper.submitCrash(crash) } erase() hideCrashReporter() } fragmentManager .beginTransaction() .addToBackStack(null) .add(R.id.crash_container, crashReporterFragment, CrashReporterFragment.FRAGMENT_TAG) .commit() crash_container.visibility = View.VISIBLE tabs.hide() erase.hide() securityView?.setImageResource(R.drawable.ic_firefox) menuView?.visibility = View.GONE urlView?.text = requireContext().getString(R.string.tab_crash_report_title) } private fun hideCrashReporter() { val fragmentManager = requireActivity().supportFragmentManager val fragment = fragmentManager.findFragmentByTag(CrashReporterFragment.FRAGMENT_TAG) ?: return fragmentManager .beginTransaction() .remove(fragment) .commit() crash_container.visibility = View.GONE tabs.show() erase.show() securityView?.setImageResource(R.drawable.ic_internet) menuView?.visibility = View.VISIBLE urlView?.text = session.let { if (it.isSearch) it.searchTerms else it.url } } fun crashReporterIsVisible(): Boolean = requireActivity().supportFragmentManager.let { it.findFragmentByTag(CrashReporterFragment.FRAGMENT_TAG)?.isVisible ?: false } internal fun showAddToHomescreenDialog(url: String, title: String) { val fragmentManager = childFragmentManager if (fragmentManager.findFragmentByTag(AddToHomescreenDialogFragment.FRAGMENT_TAG) != null) { // We are already displaying a homescreen dialog fragment (Probably a restored fragment). // No need to show another one. return } val addToHomescreenDialogFragment = AddToHomescreenDialogFragment.newInstance( url, title, session.trackerBlockingEnabled, session.shouldRequestDesktopSite ) try { addToHomescreenDialogFragment.show( fragmentManager, AddToHomescreenDialogFragment.FRAGMENT_TAG ) } catch (e: IllegalStateException) { // It can happen that at this point in time the activity is already in the background // and onSaveInstanceState() has already been called. Fragment transactions are not // allowed after that anymore. It's probably safe to guess that the user might not // be interested in adding to homescreen now. } } override fun onFinishDownloadDialog(download: Download?, shouldDownload: Boolean) { if (shouldDownload) { queueDownload(download) } } override fun biometricCreateNewSessionWithLink() { for (session in requireComponents.sessionManager.sessions) { if (session != requireComponents.sessionManager.selectedSession) { requireComponents.sessionManager.remove(session) } } // Purposefully not calling onAuthSuccess in case we add to that function in the future view!!.alpha = 1f } override fun biometricCreateNewSession() { requireComponents.sessionManager.removeAndCloseAllSessions() } override fun onAuthSuccess() { view!!.alpha = 1f } override fun onCreateViewCalled() { manager = requireContext().getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager downloadBroadcastReceiver = DownloadBroadcastReceiver(browserContainer, manager) val webView = getWebView() webView?.setFindListener(findInPageCoordinator) } override fun onResume() { super.onResume() if (job.isCancelled) { job = Job() } val filter = IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE) requireContext().registerReceiver(downloadBroadcastReceiver, filter) if (pendingDownload != null && PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission( requireContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE ) ) { // There's a pending download (waiting for the storage permission) and now we have the // missing permission: Show the dialog to ask whether the user wants to actually proceed // with downloading this file. showDownloadPromptDialog(pendingDownload!!) pendingDownload = null } StatusBarUtils.getStatusBarHeight(statusBar) { statusBarHeight -> statusBar!!.layoutParams.height = statusBarHeight } if (Biometrics.isBiometricsEnabled(requireContext())) { if (biometricController == null) { biometricController = BiometricAuthenticationHandler(context!!) } displayBiometricPromptIfNeeded() } else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { biometricController?.stopListening() } biometricController = null view!!.alpha = 1f } } @RequiresApi(api = Build.VERSION_CODES.M) private fun displayBiometricPromptIfNeeded() { val fragmentManager = childFragmentManager // Check that we need to auth and that the fragment isn't already displayed if (biometricController!!.needsAuth || openedFromExternalLink) { view!!.alpha = 0f biometricController!!.startAuthentication(openedFromExternalLink) openedFromExternalLink = false // Are we already displaying the biometric fragment? if (fragmentManager.findFragmentByTag(BiometricAuthenticationDialogFragment.FRAGMENT_TAG) != null) { return } try { biometricController!!.biometricFragment!!.show( fragmentManager, BiometricAuthenticationDialogFragment.FRAGMENT_TAG ) } catch (e: IllegalStateException) { // It can happen that at this point in time the activity is already in the background // and onSaveInstanceState() has already been called. Fragment transactions are not // allowed after that anymore. } } else { view!!.alpha = 1f } } /** * Use Android's Download Manager to queue this download. */ private fun queueDownload(download: Download?) { if (download == null) { return } val fileName = if (!TextUtils.isEmpty(download.fileName)) download.fileName else DownloadUtils.guessFileName( download.contentDisposition, download.url, download.mimeType ) val request = DownloadManager.Request(Uri.parse(download.url)) .addRequestHeader("Referer", url) .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED) .setMimeType(download.mimeType) if (!AppConstants.isGeckoBuild) { val cookie = CookieManager.getInstance().getCookie(download.url) request.addRequestHeader("Cookie", cookie) .addRequestHeader("User-Agent", download.userAgent) } try { request.setDestinationInExternalPublicDir(download.destinationDirectory, fileName) } catch (e: IllegalStateException) { Log.e(FRAGMENT_TAG, "Cannot create download directory") return } request.allowScanningByMediaScanner() @Suppress("TooGenericExceptionCaught") try { val downloadReference = manager!!.enqueue(request) downloadBroadcastReceiver!!.addQueuedDownload(downloadReference) } catch (e: RuntimeException) { Log.e(FRAGMENT_TAG, "Download failed: $e") } } @Suppress("ComplexMethod") fun onBackPressed(): Boolean { if (findInPageView!!.visibility == View.VISIBLE) { hideFindInPage() } else if (isFullscreen) { val webView = getWebView() webView?.exitFullscreen() } else if (canGoBack()) { // Go back in web history goBack() } else { if (session.source == Session.Source.ACTION_VIEW || session.isCustomTabSession()) { TelemetryWrapper.eraseBackToAppEvent() // This session has been started from a VIEW intent. Go back to the previous app // immediately and erase the current browsing session. erase() // If there are no other sessions then we remove the whole task because otherwise // the old session might still be partially visible in the app switcher. if (requireComponents.sessionManager.sessions.isEmpty()) { requireActivity().finishAndRemoveTask() } else { requireActivity().finish() } // We can't show a snackbar outside of the app. So let's show a toast instead. Toast.makeText(context, R.string.feedback_erase_custom_tab, Toast.LENGTH_SHORT).show() } else { // Just go back to the home screen. TelemetryWrapper.eraseBackToHomeEvent() erase() } } return true } fun erase() { val webView = getWebView() val context = context // Notify the user their session has been erased if Talk Back is enabled: if (context != null) { val manager = context.getSystemService(Context.ACCESSIBILITY_SERVICE) as AccessibilityManager if (manager.isEnabled) { val event = AccessibilityEvent.obtain() event.eventType = AccessibilityEvent.TYPE_ANNOUNCEMENT event.className = javaClass.name event.packageName = getContext()!!.packageName event.text.add(getString(R.string.feedback_erase)) } } webView?.cleanup() requireComponents.sessionManager.removeAndCloseSession(session) } private fun shareCurrentUrl() { val url = url val shareIntent = Intent(Intent.ACTION_SEND) shareIntent.type = "text/plain" shareIntent.putExtra(Intent.EXTRA_TEXT, url) // Use title from webView if it's content matches the url val webView = getWebView() if (webView != null) { val contentUrl = webView.url if (contentUrl != null && contentUrl == url) { val contentTitle = webView.title shareIntent.putExtra(Intent.EXTRA_SUBJECT, contentTitle) } } startActivity(Intent.createChooser(shareIntent, getString(R.string.share_dialog_title))) TelemetryWrapper.shareEvent() } @Suppress("ComplexMethod") override fun onClick(view: View) { when (view.id) { R.id.menuView -> { val menu = BrowserMenu(activity, this, session.customTabConfig) menu.show(menuView) menuWeakReference = WeakReference(menu) } R.id.display_url -> if ( !crashReporterIsVisible() && requireComponents.sessionManager.findSessionById(session.id) != null) { val urlFragment = UrlInputFragment .createWithSession(session, urlView!!) requireActivity().supportFragmentManager .beginTransaction() .add(R.id.container, urlFragment, UrlInputFragment.FRAGMENT_TAG) .commit() } R.id.erase -> { TelemetryWrapper.eraseEvent() erase() } R.id.tabs -> { requireActivity().supportFragmentManager .beginTransaction() .add(R.id.container, SessionsSheetFragment(), SessionsSheetFragment.FRAGMENT_TAG) .commit() TelemetryWrapper.openTabsTrayEvent() } R.id.back -> { goBack() } R.id.forward -> { val webView = getWebView() webView?.goForward() } R.id.refresh -> { reload() TelemetryWrapper.menuReloadEvent() } R.id.stop -> { val webView = getWebView() webView?.stopLoading() } R.id.open_in_firefox_focus -> { session.customTabConfig = null requireComponents.sessionManager.select(session) val webView = getWebView() webView?.releaseGeckoSession() webView?.saveWebViewState(session) val intent = Intent(context, MainActivity::class.java) intent.action = Intent.ACTION_MAIN intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP startActivity(intent) TelemetryWrapper.openFullBrowser() val activity = activity activity?.finish() } R.id.share -> { shareCurrentUrl() } R.id.settings -> (activity as LocaleAwareAppCompatActivity).openPreferences() R.id.open_default -> { val browsers = Browsers(requireContext(), url) val defaultBrowser = browsers.defaultBrowser ?: // We only add this menu item when a third party default exists, in // BrowserMenuAdapter.initializeMenu() throw IllegalStateException("<Open with \$Default> was shown when no default browser is set") val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)) intent.setPackage(defaultBrowser.packageName) startActivity(intent) if (browsers.isFirefoxDefaultBrowser) { TelemetryWrapper.openFirefoxEvent() } else { TelemetryWrapper.openDefaultAppEvent() } } R.id.open_select_browser -> { val browsers = Browsers(requireContext(), url) val apps = browsers.installedBrowsers val store = if (browsers.hasFirefoxBrandedBrowserInstalled()) null else InstallFirefoxActivity.resolveAppStore(requireContext()) val fragment = OpenWithFragment.newInstance( apps, url, store ) fragment.show(fragmentManager!!, OpenWithFragment.FRAGMENT_TAG) TelemetryWrapper.openSelectionEvent() } R.id.customtab_close -> { erase() requireActivity().finish() TelemetryWrapper.closeCustomTabEvent() } R.id.help -> { val session = Session(SupportUtils.HELP_URL, source = Session.Source.MENU) requireComponents.sessionManager.add(session, selected = true) } R.id.help_trackers -> { val url = SupportUtils.getSumoURLForTopic(context!!, SupportUtils.SumoTopic.TRACKERS) val session = Session(url, source = Session.Source.MENU) requireComponents.sessionManager.add(session, selected = true) } R.id.add_to_homescreen -> { val webView = getWebView() ?: return val url = webView.url val title = webView.title showAddToHomescreenDialog(url, title) } R.id.security_info -> if (!crashReporterIsVisible()) { showSecurityPopUp() } R.id.report_site_issue -> { val reportUrl = String.format(SupportUtils.REPORT_SITE_ISSUE_URL, url) val session = Session(reportUrl, source = Session.Source.MENU) requireComponents.sessionManager.add(session, selected = true) TelemetryWrapper.reportSiteIssueEvent() } R.id.find_in_page -> { showFindInPage() ViewUtils.showKeyboard(findInPageQuery) TelemetryWrapper.findInPageMenuEvent() } R.id.queryText -> findInPageQuery!!.isCursorVisible = true R.id.nextResult -> { ViewUtils.hideKeyboard(findInPageQuery!!) findInPageQuery!!.isCursorVisible = false getWebView()?.findNext(true) } R.id.previousResult -> { ViewUtils.hideKeyboard(findInPageQuery!!) findInPageQuery!!.isCursorVisible = false getWebView()?.findNext(false) } R.id.close_find_in_page -> { hideFindInPage() } else -> throw IllegalArgumentException("Unhandled menu item in BrowserFragment") } } @Suppress("MagicNumber") private fun updateToolbarButtonStates(isLoading: Boolean) { @Suppress("ComplexCondition") if (forwardButton == null || backButton == null || refreshButton == null || stopButton == null) { return } val webView = getWebView() ?: return val canGoForward = webView.canGoForward() val canGoBack = webView.canGoBack() forwardButton!!.isEnabled = canGoForward forwardButton!!.alpha = if (canGoForward) 1.0f else 0.5f backButton!!.isEnabled = canGoBack backButton!!.alpha = if (canGoBack) 1.0f else 0.5f refreshButton!!.visibility = if (isLoading) View.GONE else View.VISIBLE stopButton!!.visibility = if (isLoading) View.VISIBLE else View.GONE } fun canGoForward(): Boolean = getWebView()?.canGoForward() ?: false fun canGoBack(): Boolean = getWebView()?.canGoBack() ?: false fun goBack() = getWebView()?.goBack() fun loadUrl(url: String) { val webView = getWebView() if (webView != null && !TextUtils.isEmpty(url)) { webView.loadUrl(url) } } fun reload() = getWebView()?.reload() fun setBlockingUI(enabled: Boolean) { val webView = getWebView() webView?.setBlockingEnabled(enabled) statusBar!!.setBackgroundResource(if (enabled) R.drawable.animated_background else R.drawable.animated_background_disabled ) backgroundTransitionGroup = if (!session.isCustomTabSession()) { // Only update the toolbar background if this is not a custom tab. Custom tabs set their // own color and we do not want to override this here. urlBar!!.setBackgroundResource(if (enabled) R.drawable.animated_background else R.drawable.animated_background_disabled) TransitionDrawableGroup( urlBar!!.background as TransitionDrawable, statusBar!!.background as TransitionDrawable ) } else { TransitionDrawableGroup( statusBar!!.background as TransitionDrawable ) } } fun setShouldRequestDesktop(enabled: Boolean) { if (enabled) { PreferenceManager.getDefaultSharedPreferences(context).edit() .putBoolean( requireContext().getString(R.string.has_requested_desktop), true ).apply() } getWebView()?.setRequestDesktop(enabled) } private fun showSecurityPopUp() { // Don't show Security Popup if the page is loading if (session.loading) { return } val securityPopup = PopupUtils.createSecurityPopup(requireContext(), session) if (securityPopup != null) { securityPopup.setOnDismissListener { popupTint!!.visibility = View.GONE } securityPopup.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) securityPopup.animationStyle = android.R.style.Animation_Dialog securityPopup.isTouchable = true securityPopup.isFocusable = true securityPopup.elevation = resources.getDimension(R.dimen.menu_elevation) val offsetY = requireContext().resources.getDimensionPixelOffset(R.dimen.doorhanger_offsetY) securityPopup.showAtLocation(urlBar, Gravity.TOP or Gravity.CENTER_HORIZONTAL, 0, offsetY) popupTint!!.visibility = View.VISIBLE } } // In the future, if more badging icons are needed, this should be abstracted fun updateBlockingBadging(enabled: Boolean) { blockView!!.visibility = if (enabled) View.GONE else View.VISIBLE } override fun onLongClick(view: View): Boolean { // Detect long clicks on display_url if (view.id == R.id.display_url) { val context = activity ?: return false if (session.isCustomTabSession()) { val clipBoard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager val uri = Uri.parse(url) clipBoard.primaryClip = ClipData.newRawUri("Uri", uri) Toast.makeText(context, getString(R.string.custom_tab_copy_url_action), Toast.LENGTH_SHORT).show() } } return false } private fun showFindInPage() { findInPageView!!.visibility = View.VISIBLE findInPageQuery!!.requestFocus() val params = swipeRefresh!!.layoutParams as CoordinatorLayout.LayoutParams params.bottomMargin = findInPageViewHeight swipeRefresh!!.layoutParams = params } private fun hideFindInPage() { val webView = getWebView() ?: return webView.clearMatches() findInPageCoordinator.reset() findInPageView!!.visibility = View.GONE findInPageQuery!!.text = "" findInPageQuery!!.clearFocus() val params = swipeRefresh!!.layoutParams as CoordinatorLayout.LayoutParams params.bottomMargin = 0 swipeRefresh!!.layoutParams = params ViewUtils.hideKeyboard(findInPageQuery!!) } override fun applyLocale() { activity?.supportFragmentManager ?.beginTransaction() ?.replace( R.id.container, BrowserFragment.createForSession(requireNotNull(session)), BrowserFragment.FRAGMENT_TAG ) ?.commit() } private fun updateSecurityIcon(session: Session, securityInfo: Session.SecurityInfo = session.securityInfo) { if (crashReporterIsVisible()) return val securityView = securityView ?: return if (!session.loading) { if (securityInfo.secure) { securityView.setImageResource(R.drawable.ic_lock) } else { if (URLUtil.isHttpUrl(url)) { // HTTP site securityView.setImageResource(R.drawable.ic_internet) } else { // Certificate is bad securityView.setImageResource(R.drawable.ic_warning) } } } else { securityView.setImageResource(R.drawable.ic_internet) } } @Suppress("DEPRECATION", "MagicNumber") private fun updateFindInPageResult(activeMatchOrdinal: Int, numberOfMatches: Int) { var actualActiveMatchOrdinal = activeMatchOrdinal val context = context ?: return if (numberOfMatches > 0) { findInPageNext!!.setColorFilter(resources.getColor(R.color.photonWhite)) findInPageNext!!.alpha = 1.0f findInPagePrevious!!.setColorFilter(resources.getColor(R.color.photonWhite)) findInPagePrevious!!.alpha = 1.0f // We don't want the presentation of the activeMatchOrdinal to be zero indexed. So let's // increment it by one for WebView. if (!AppConstants.isGeckoBuild) { actualActiveMatchOrdinal++ } val visibleString = String.format( context.getString(R.string.find_in_page_result), actualActiveMatchOrdinal, numberOfMatches) val accessibleString = String.format( context.getString(R.string.find_in_page_result), actualActiveMatchOrdinal, numberOfMatches) findInPageResultTextView!!.text = visibleString findInPageResultTextView!!.contentDescription = accessibleString } else { findInPageNext!!.setColorFilter(resources.getColor(R.color.photonGrey10)) findInPageNext!!.alpha = 0.4f findInPagePrevious!!.setColorFilter(resources.getColor(R.color.photonWhite)) findInPagePrevious!!.alpha = 0.4f findInPageResultTextView!!.text = "" findInPageResultTextView!!.contentDescription = "" } } private val sessionObserver = object : Session.Observer { override fun onLoadingStateChanged(session: Session, loading: Boolean) { if (loading) { backgroundTransitionGroup!!.resetTransition() progressView!!.progress = INITIAL_PROGRESS progressView!!.visibility = View.VISIBLE } else { if (progressView!!.visibility == View.VISIBLE) { // We start a transition only if a page was just loading before // allowing to avoid issue #1179 backgroundTransitionGroup!!.startTransition(ANIMATION_DURATION) progressView!!.visibility = View.GONE } swipeRefresh!!.isRefreshing = false updateSecurityIcon(session) } updateBlockingBadging(loading || session.trackerBlockingEnabled) updateToolbarButtonStates(loading) val menu = menuWeakReference!!.get() menu?.updateLoading(loading) if (findInPageView?.visibility == View.VISIBLE) { hideFindInPage() } } override fun onUrlChanged(session: Session, url: String) { if (crashReporterIsVisible()) return val host = try { URL(url).host } catch (_: MalformedURLException) { url } val isException = host != null && ExceptionDomains.load(requireContext()).contains(host) getWebView()?.setBlockingEnabled(!isException) urlView?.text = UrlUtils.stripUserInfo(url) } override fun onProgress(session: Session, progress: Int) { progressView?.progress = progress } override fun onTrackerBlocked(session: Session, tracker: Tracker, all: List<Tracker>) { menuWeakReference?.let { val menu = it.get() menu?.updateTrackers(all.size) } } override fun onTrackerBlockingEnabledChanged(session: Session, blockingEnabled: Boolean) { setBlockingUI(blockingEnabled) } override fun onSecurityChanged(session: Session, securityInfo: Session.SecurityInfo) { updateSecurityIcon(session, securityInfo) } } fun handleTabCrash(crash: Crash) { showCrashReporter(crash) } companion object { const val FRAGMENT_TAG = "browser" private const val REQUEST_CODE_STORAGE_PERMISSION = 101 private const val ANIMATION_DURATION = 300 private const val ARGUMENT_SESSION_UUID = "sessionUUID" private const val RESTORE_KEY_DOWNLOAD = "download" private const val INITIAL_PROGRESS = 5 @JvmStatic fun createForSession(session: Session): BrowserFragment { val arguments = Bundle() arguments.putString(ARGUMENT_SESSION_UUID, session.id) val fragment = BrowserFragment() fragment.arguments = arguments return fragment } } }
mpl-2.0
61c733b7c1f27786d0bedce4ae031f69
37.582337
120
0.633887
5.486262
false
false
false
false
pedroSG94/rtmp-streamer-java
rtsp/src/main/java/com/pedro/rtsp/rtsp/RtspSender.kt
1
7189
/* * Copyright (C) 2021 pedroSG94. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pedro.rtsp.rtsp import android.media.MediaCodec import android.util.Log import com.pedro.rtsp.rtcp.BaseSenderReport import com.pedro.rtsp.rtp.packets.* import com.pedro.rtsp.rtp.sockets.BaseRtpSocket import com.pedro.rtsp.rtp.sockets.RtpSocketTcp import com.pedro.rtsp.utils.BitrateManager import com.pedro.rtsp.utils.ConnectCheckerRtsp import com.pedro.rtsp.utils.RtpConstants import java.io.OutputStream import java.nio.ByteBuffer import java.util.* import java.util.concurrent.* /** * Created by pedro on 7/11/18. */ open class RtspSender(private val connectCheckerRtsp: ConnectCheckerRtsp) : VideoPacketCallback, AudioPacketCallback { private var videoPacket: BasePacket? = null private var aacPacket: AacPacket? = null private var rtpSocket: BaseRtpSocket? = null private var baseSenderReport: BaseSenderReport? = null private var running = false @Volatile private var rtpFrameBlockingQueue: BlockingQueue<RtpFrame> = LinkedBlockingQueue(defaultCacheSize) private var thread: ExecutorService? = null private var audioFramesSent: Long = 0 private var videoFramesSent: Long = 0 var droppedAudioFrames: Long = 0 private set var droppedVideoFrames: Long = 0 private set private val bitrateManager: BitrateManager = BitrateManager(connectCheckerRtsp) private var isEnableLogs = true companion object { private const val TAG = "RtspSender" } fun setSocketsInfo(protocol: Protocol, videoSourcePorts: IntArray, audioSourcePorts: IntArray) { rtpSocket = BaseRtpSocket.getInstance(protocol, videoSourcePorts[0], audioSourcePorts[0]) baseSenderReport = BaseSenderReport.getInstance(protocol, videoSourcePorts[1], audioSourcePorts[1]) } fun setVideoInfo(sps: ByteArray, pps: ByteArray, vps: ByteArray?) { videoPacket = if (vps == null) H264Packet(sps, pps, this) else H265Packet(sps, pps, vps, this) } fun setAudioInfo(sampleRate: Int) { aacPacket = AacPacket(sampleRate, this) } /** * @return number of packets */ private val defaultCacheSize: Int get() = 10 * 1024 * 1024 / RtpConstants.MTU fun setDataStream(outputStream: OutputStream, host: String) { rtpSocket?.setDataStream(outputStream, host) baseSenderReport?.setDataStream(outputStream, host) } fun setVideoPorts(rtpPort: Int, rtcpPort: Int) { videoPacket?.setPorts(rtpPort, rtcpPort) } fun setAudioPorts(rtpPort: Int, rtcpPort: Int) { aacPacket?.setPorts(rtpPort, rtcpPort) } fun sendVideoFrame(h264Buffer: ByteBuffer, info: MediaCodec.BufferInfo) { if (running) videoPacket?.createAndSendPacket(h264Buffer, info) } fun sendAudioFrame(aacBuffer: ByteBuffer, info: MediaCodec.BufferInfo) { if (running) aacPacket?.createAndSendPacket(aacBuffer, info) } override fun onVideoFrameCreated(rtpFrame: RtpFrame) { try { rtpFrameBlockingQueue.add(rtpFrame) } catch (e: IllegalStateException) { Log.i(TAG, "Video frame discarded") droppedVideoFrames++ } } override fun onAudioFrameCreated(rtpFrame: RtpFrame) { try { rtpFrameBlockingQueue.add(rtpFrame) } catch (e: IllegalStateException) { Log.i(TAG, "Audio frame discarded") droppedAudioFrames++ } } fun start() { thread = Executors.newSingleThreadExecutor() running = true thread?.execute post@{ val ssrcVideo = Random().nextInt().toLong() val ssrcAudio = Random().nextInt().toLong() baseSenderReport?.setSSRC(ssrcVideo, ssrcAudio) videoPacket?.setSSRC(ssrcVideo) aacPacket?.setSSRC(ssrcAudio) val isTcp = rtpSocket is RtpSocketTcp while (!Thread.interrupted()) { try { val rtpFrame = rtpFrameBlockingQueue.poll(1, TimeUnit.SECONDS) if (rtpFrame == null) { Log.i(TAG, "Skipping iteration, frame null") continue } rtpSocket?.sendFrame(rtpFrame, isEnableLogs) //bytes to bits (4 is tcp header length) val packetSize = if (isTcp) rtpFrame.length + 4 else rtpFrame.length bitrateManager.calculateBitrate(packetSize * 8.toLong()) if (rtpFrame.isVideoFrame()) { videoFramesSent++ } else { audioFramesSent++ } if (baseSenderReport?.update(rtpFrame, isEnableLogs) == true) { //bytes to bits (4 is tcp header length) val reportSize = if (isTcp) baseSenderReport?.PACKET_LENGTH ?: 0 + 4 else baseSenderReport?.PACKET_LENGTH ?: 0 bitrateManager.calculateBitrate(reportSize * 8.toLong()) } } catch (e: Exception) { //InterruptedException is only when you disconnect manually, you don't need report it. if (e !is InterruptedException) { connectCheckerRtsp.onConnectionFailedRtsp("Error send packet, " + e.message) Log.e(TAG, "send error: ", e) } return@post } } } } fun stop() { running = false thread?.shutdownNow() try { thread?.awaitTermination(100, TimeUnit.MILLISECONDS) } catch (e: InterruptedException) { } thread = null rtpFrameBlockingQueue.clear() baseSenderReport?.reset() baseSenderReport?.close() rtpSocket?.close() aacPacket?.reset() videoPacket?.reset() resetSentAudioFrames() resetSentVideoFrames() resetDroppedAudioFrames() resetDroppedVideoFrames() } fun hasCongestion(): Boolean { val size = rtpFrameBlockingQueue.size.toFloat() val remaining = rtpFrameBlockingQueue.remainingCapacity().toFloat() val capacity = size + remaining return size >= capacity * 0.2f //more than 20% queue used. You could have congestion } fun resizeCache(newSize: Int) { if (newSize < rtpFrameBlockingQueue.size - rtpFrameBlockingQueue.remainingCapacity()) { throw RuntimeException("Can't fit current cache inside new cache size") } val tempQueue: BlockingQueue<RtpFrame> = LinkedBlockingQueue(newSize) rtpFrameBlockingQueue.drainTo(tempQueue) rtpFrameBlockingQueue = tempQueue } fun getCacheSize(): Int { return rtpFrameBlockingQueue.size } fun getSentAudioFrames(): Long { return audioFramesSent } fun getSentVideoFrames(): Long { return videoFramesSent } fun resetSentAudioFrames() { audioFramesSent = 0 } fun resetSentVideoFrames() { videoFramesSent = 0 } fun resetDroppedAudioFrames() { droppedAudioFrames = 0 } fun resetDroppedVideoFrames() { droppedVideoFrames = 0 } fun setLogs(enable: Boolean) { isEnableLogs = enable } }
apache-2.0
9c2e2f61ae2a068f421c8de6682f5b7f
30.535088
122
0.698845
4.059289
false
false
false
false
pedroSG94/rtmp-streamer-java
rtmp/src/main/java/com/pedro/rtmp/rtmp/Handshake.kt
1
5484
/* * Copyright (C) 2021 pedroSG94. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pedro.rtmp.rtmp import android.util.Log import com.pedro.rtmp.utils.readUntil import java.io.IOException import java.io.InputStream import java.io.OutputStream import kotlin.random.Random /** * Created by pedro on 8/04/21. * * The C0 and S0 packets are a single octet * * The version defined by this * specification is 3. Values 0-2 are deprecated values used by * earlier proprietary products; 4-31 are reserved for future * implementations; and 32-255 are not allowed * 0 1 2 3 4 5 6 7 * +-+-+-+-+-+-+-+-+ * | version | * +-+-+-+-+-+-+-+-+ * * The C1 and S1 packets are 1536 octets long * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | time (4 bytes) | local generated timestamp * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | zero (4 bytes) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | random bytes | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | random bytes | * | (cont) | * | .... | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * * The C2 and S2 packets are 1536 octets long, and nearly an echo of S1 and C1 (respectively). * * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | time (4 bytes) | s1 timestamp for c2 or c1 for s2. In this case s1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | time2 (4 bytes) | timestamp of previous packet (s1 or c1). In this case c1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | random echo | random data field sent by the peer in s1 for c2 or s2 for c1. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | random echo | random data field sent by the peer in s1 for c2 or s2 for c1. * | (cont) | * | .... | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ class Handshake { private val TAG = "Handshake" private val protocolVersion = 0x03 private val handshakeSize = 1536 private var timestampC1 = 0 @Throws(IOException::class) fun sendHandshake(input: InputStream, output: OutputStream): Boolean { writeC0(output) val c1 = writeC1(output) output.flush() readS0(input) val s1 = readS1(input) writeC2(output, s1) output.flush() readS2(input, c1) return true } @Throws(IOException::class) private fun writeC0(output: OutputStream) { Log.i(TAG, "writing C0") output.write(protocolVersion) Log.i(TAG, "C0 write successful") } @Throws(IOException::class) private fun writeC1(output: OutputStream): ByteArray { Log.i(TAG, "writing C1") val c1 = ByteArray(handshakeSize) timestampC1 = (System.currentTimeMillis() / 1000).toInt() Log.i(TAG, "writing time $timestampC1 to c1") val timestampData = ByteArray(4) timestampData[0] = (timestampC1 ushr 24).toByte() timestampData[1] = (timestampC1 ushr 16).toByte() timestampData[2] = (timestampC1 ushr 8).toByte() timestampData[3] = timestampC1.toByte() System.arraycopy(timestampData, 0, c1, 0, timestampData.size) Log.i(TAG, "writing zero to c1") val zeroData = byteArrayOf(0x00, 0x00, 0x00, 0x00) System.arraycopy(zeroData, 0, c1, timestampData.size, zeroData.size) Log.i(TAG, "writing random to c1") val random = Random.Default val randomData = ByteArray(handshakeSize - 8) for (i in randomData.indices step 1) { //step UInt8 size //random with UInt8 max value val uInt8 = random.nextInt().toByte() randomData[i] = uInt8 } System.arraycopy(randomData, 0, c1, 8, randomData.size) output.write(c1) Log.i(TAG, "C1 write successful") return c1 } @Throws(IOException::class) private fun writeC2(output: OutputStream, s1: ByteArray) { Log.i(TAG, "writing C2") output.write(s1) Log.i(TAG, "C2 write successful") } @Throws(IOException::class) private fun readS0(input: InputStream): ByteArray { Log.i(TAG, "reading S0") val response = input.read() if (response == protocolVersion || response == 72) { Log.i(TAG, "read S0 successful") return byteArrayOf(response.toByte()) } else { throw IOException("$TAG error, unexpected $response S0 received") } } @Throws(IOException::class) private fun readS1(input: InputStream): ByteArray { Log.i(TAG, "reading S1") val s1 = ByteArray(handshakeSize) input.readUntil(s1) Log.i(TAG, "read S1 successful") return s1 } @Throws(IOException::class) private fun readS2(input: InputStream, c1: ByteArray): ByteArray { Log.i(TAG, "reading S2") val s2 = ByteArray(handshakeSize) input.readUntil(s2) //S2 should be equals to C1 but we can skip this if (!s2.contentEquals(c1)) { Log.e(TAG, "S2 content is different that C1") } Log.i(TAG, "read S2 successful") return s2 } }
apache-2.0
b3e8ebcc06f03a5e9418515d8edce203
31.844311
94
0.587163
3.81098
false
false
false
false
fallGamlet/DnestrCinema
app/src/main/java/com/fallgamlet/dnestrcinema/domain/models/ImageUrl.kt
1
227
package com.fallgamlet.dnestrcinema.domain.models data class ImageUrl( var hight: String = "", var low: String = "" ) { fun isEmpty() = this == EMPTY companion object { val EMPTY = ImageUrl() } }
gpl-3.0
dfcf5e1f4fc6d0b461eb269d33bbf785
16.461538
49
0.603524
3.982456
false
false
false
false
nemerosa/ontrack
ontrack-extension-indicators/src/main/java/net/nemerosa/ontrack/extension/indicators/ui/graphql/GQLTypeIndicatorStats.kt
1
3157
package net.nemerosa.ontrack.extension.indicators.ui.graphql import graphql.Scalars.GraphQLInt import graphql.Scalars.GraphQLString import graphql.schema.GraphQLObjectType import net.nemerosa.ontrack.extension.indicators.model.IndicatorCompliance import net.nemerosa.ontrack.extension.indicators.model.Rating import net.nemerosa.ontrack.extension.indicators.stats.IndicatorStats import net.nemerosa.ontrack.graphql.schema.GQLType import net.nemerosa.ontrack.graphql.schema.GQLTypeCache import net.nemerosa.ontrack.graphql.support.intField import org.springframework.stereotype.Component import kotlin.reflect.KProperty1 @Component class GQLTypeIndicatorStats : GQLType { override fun createType(cache: GQLTypeCache): GraphQLObjectType = GraphQLObjectType.newObject() .name(typeName) .description("Aggregation of ratings over several items.") .intField(IndicatorStats::total, "Total number of items used for this stat") .intField(IndicatorStats::count, "Number of items having an actual usable value for stat computation") .statField(IndicatorStats::min, "Minimal value (undefined if no stat available)") .statField(IndicatorStats::avg, "Average value (undefined if no stat available)") .statField(IndicatorStats::max, "Maximal value (undefined if no stat available)") .intField(IndicatorStats::minCount, "Number of items having the minimum value") .intField(IndicatorStats::maxCount, "Number of items having the maximum value") .ratingField(IndicatorStats::min, "Rating for the min value") .ratingField(IndicatorStats::avg, "Rating for the min value") .ratingField(IndicatorStats::max, "Rating for the min value") .build() override fun getTypeName(): String = IndicatorStats::class.java.simpleName private fun GraphQLObjectType.Builder.statField(property: KProperty1<IndicatorStats, IndicatorCompliance?>, description: String): GraphQLObjectType.Builder = field { it.name(property.name) .description(description) .type(GraphQLInt) .dataFetcher { env -> val stats = env.getSource<IndicatorStats>() property.get(stats)?.value } } fun GraphQLObjectType.Builder.ratingField(property: KProperty1<IndicatorStats, IndicatorCompliance?>, description: String): GraphQLObjectType.Builder = field { it.name("${property.name}Rating") .description(description) .type(GraphQLString) .dataFetcher { env -> val stats = env.getSource<IndicatorStats>() property.get(stats)?.let { compliance -> Rating.asRating(compliance.value) } } } }
mit
08279455b41a84efccaacd1fad156499
51.616667
161
0.623377
5.471404
false
false
false
false
ibaton/3House
mobile/src/main/java/treehou/se/habit/util/DatabaseServerLoaderFactory.kt
1
6615
package treehou.se.habit.util import android.content.Context import android.util.Log import io.reactivex.Observable import io.reactivex.ObservableTransformer import io.reactivex.functions.Function import io.reactivex.schedulers.Schedulers import io.realm.Realm import se.treehou.ng.ohcommunicator.connector.models.OHServer import se.treehou.ng.ohcommunicator.connector.models.OHSitemap import treehou.se.habit.core.db.OHRealm import treehou.se.habit.core.db.model.ServerDB import treehou.se.habit.core.db.model.SitemapDB import treehou.se.habit.dagger.ServerLoaderFactory import java.util.* import javax.inject.Inject class DatabaseServerLoaderFactory @Inject constructor(private val realm: OHRealm, private val connectionFactory: ConnectionFactory) : ServerLoaderFactory { override fun loadServer(realm: Realm, id: Long): OHServer { return ServerDB.load(realm, id)!!.toGeneric() } override fun loadServersRx(): ObservableTransformer<Realm, OHServer> { return RxUtil.loadServers() } override fun loadAllServersRx(): ObservableTransformer<Realm, List<OHServer>> { return ObservableTransformer { observable -> observable.flatMap({ realmLocal -> realmLocal.where(ServerDB::class.java).isNotEmpty("localurl").or().isNotEmpty("remoteurl").greaterThan("id", 0).findAllAsync() .asFlowable().toObservable() }) .map({ serverDBS -> serverDBS.map { it.toGeneric() } }) .distinct() } } override fun serversToSitemap(context: Context?): ObservableTransformer<List<OHServer>, List<ServerLoaderFactory.ServerSitemapsResponse>> { return ObservableTransformer { observable -> observable .switchMap({ servers -> val sitemapResponseRx = ArrayList<Observable<ServerLoaderFactory.ServerSitemapsResponse>>() for (server in servers) { val serverSitemapsResponseRx = Observable.just<OHServer>(server) .compose<ServerLoaderFactory.ServerSitemapsResponse>(serverToSitemap(context!!)) .subscribeOn(Schedulers.io()) .startWith(ServerLoaderFactory.Companion.EMPTY_RESPONSE) sitemapResponseRx.add(serverSitemapsResponseRx) } Observable.combineLatest<ServerLoaderFactory.ServerSitemapsResponse, List<ServerLoaderFactory.ServerSitemapsResponse>>(sitemapResponseRx) { responsesObject -> val responses = ArrayList<ServerLoaderFactory.ServerSitemapsResponse>() for (responseObject in responsesObject) { val response = responseObject as ServerLoaderFactory.ServerSitemapsResponse responses.add(response) } responses } }) } } /** * Fetches sitemaps from server. * @param context the used to fetch sitemaps. * @return */ override fun serverToSitemap(context: Context): ObservableTransformer<OHServer, ServerLoaderFactory.ServerSitemapsResponse> { return ObservableTransformer { observable -> observable .flatMap({ server -> val serverHandler = connectionFactory.createServerHandler(server, context) serverHandler.requestSitemapRx() .map { SitemapResponse(it) } .subscribeOn(Schedulers.io()) .doOnError { e -> Log.e(TAG, "Failed to load sitemap", e) } .onErrorReturn { throwable -> SitemapResponse(ArrayList(), throwable) } }, { server, sitemapResponse -> for (sitemap in sitemapResponse.sitemaps) { sitemap.setServer(server) } ServerLoaderFactory.ServerSitemapsResponse(server, sitemapResponse.sitemaps, sitemapResponse.error) }) .doOnNext(RxUtil.saveSitemap()) } } override fun filterDisplaySitemaps(): ObservableTransformer<ServerLoaderFactory.ServerSitemapsResponse, ServerLoaderFactory.ServerSitemapsResponse> { return ObservableTransformer { observable -> observable.map(Function<ServerLoaderFactory.ServerSitemapsResponse, ServerLoaderFactory.ServerSitemapsResponse> { this.filterDisplaySitemaps(it) }) } } override fun filterDisplaySitemapsList(): ObservableTransformer<List<ServerLoaderFactory.ServerSitemapsResponse>, List<ServerLoaderFactory.ServerSitemapsResponse>> { return ObservableTransformer { observable -> observable.map({ serverSitemapsResponses: List<ServerLoaderFactory.ServerSitemapsResponse> -> val responses = ArrayList<ServerLoaderFactory.ServerSitemapsResponse>() for (sitemapsResponse in serverSitemapsResponses) { responses.add(filterDisplaySitemaps(sitemapsResponse)) } responses }) } } private fun filterDisplaySitemaps(response: ServerLoaderFactory.ServerSitemapsResponse): ServerLoaderFactory.ServerSitemapsResponse { val sitemaps = ArrayList<OHSitemap>() for (sitemap in response.sitemaps!!) { val sitemapDB = realm.realm().where(SitemapDB::class.java) .equalTo("name", sitemap.name) .equalTo("server.name", response.server!!.name) .findFirst() if (sitemapDB == null || sitemapDB.settingsDB == null || sitemapDB.settingsDB!!.display) { sitemaps.add(sitemap) } } return ServerLoaderFactory.ServerSitemapsResponse(response.server, sitemaps, response.error) } private class SitemapResponse { var error: Throwable? = null var sitemaps: List<OHSitemap> constructor(sitemaps: List<OHSitemap>) { this.sitemaps = sitemaps } constructor(sitemaps: List<OHSitemap>, error: Throwable) { this.error = error this.sitemaps = sitemaps } } companion object { private val TAG = DatabaseServerLoaderFactory::class.java.simpleName } }
epl-1.0
e3ff4c794cb5cb98af87c13be3aece91
44
202
0.618141
5.678112
false
false
false
false
RedstonerServer/Parcels
src/main/kotlin/io/dico/parcels2/command/ParcelCommandReceivers.kt
1
2965
package io.dico.parcels2.command import io.dico.dicore.command.CommandException import io.dico.dicore.command.ExecutionContext import io.dico.dicore.command.registration.reflect.ICommandReceiver import io.dico.dicore.command.Validate import io.dico.parcels2.* import io.dico.parcels2.Privilege.* import io.dico.parcels2.util.ext.hasPermAdminManage import io.dico.parcels2.util.ext.uuid import org.bukkit.entity.Player import java.lang.reflect.Method import kotlin.reflect.full.extensionReceiverParameter import kotlin.reflect.full.findAnnotation import kotlin.reflect.jvm.jvmErasure import kotlin.reflect.jvm.kotlinFunction @Target(AnnotationTarget.FUNCTION) @Retention(AnnotationRetention.RUNTIME) annotation class RequireParcelPrivilege(val privilege: Privilege) /* @Target(AnnotationTarget.FUNCTION) @Retention(AnnotationRetention.RUNTIME) annotation class SuspensionTimeout(val millis: Int) */ open class WorldScope(val world: ParcelWorld) : ICommandReceiver open class ParcelScope(val parcel: Parcel) : WorldScope(parcel.world) { fun checkCanManage(player: Player, action: String) = Validate.isTrue(parcel.canManage(player), "You must own this parcel to $action") } fun getParcelCommandReceiver(parcelProvider: ParcelProvider, context: ExecutionContext, method: Method, cmdName: String): ICommandReceiver { val player = context.sender as Player val function = method.kotlinFunction!! val receiverType = function.extensionReceiverParameter!!.type val require = function.findAnnotation<RequireParcelPrivilege>() return when (receiverType.jvmErasure) { ParcelScope::class -> ParcelScope(parcelProvider.getParcelRequired(player, require?.privilege)) WorldScope::class -> WorldScope(parcelProvider.getWorldRequired(player, require?.privilege == ADMIN)) else -> throw InternalError("Invalid command receiver type") } } fun ParcelProvider.getWorldRequired(player: Player, admin: Boolean = false): ParcelWorld { if (admin) Validate.isTrue(player.hasPermAdminManage, "You must have admin rights to use that command") return getWorld(player.world) ?: throw CommandException("You must be in a parcel world to use that command") } fun ParcelProvider.getParcelRequired(player: Player, privilege: Privilege? = null): Parcel { val parcel = getWorldRequired(player, admin = privilege == ADMIN).getParcelAt(player) ?: throw CommandException("You must be in a parcel to use that command") if (!player.hasPermAdminManage) { @Suppress("NON_EXHAUSTIVE_WHEN") when (privilege) { OWNER -> Validate.isTrue(parcel.isOwner(player.uuid), "You must own this parcel to use that command") CAN_MANAGE -> Validate.isTrue(parcel.canManage(player), "You must have management privileges on this parcel to use that command") } } return parcel }
gpl-2.0
345b1d10cdf87a2ac481b2c57d4ead85
41.602941
140
0.743676
4.278499
false
false
false
false
genobis/tornadofx
src/test/kotlin/tornadofx/testapps/PojoTreeTableColumns.kt
1
1978
package tornadofx.testapps import javafx.scene.control.TreeItem import tornadofx.* import tornadofx.tests.JavaPerson class PojoTreeTableColumnsApp : App(PojoTreeTableColumns::class) class PojoTreeTableColumns : View("Pojo Tree Table Columns") { val people = listOf( JavaPerson("Mary Hanes", "IT Administration", "[email protected]", "[email protected]", listOf( JavaPerson("Jacob Mays", "IT Help Desk", "[email protected]", "[email protected]"), JavaPerson("John Ramsy", "IT Help Desk", "[email protected]", "[email protected]"))), JavaPerson("Erin James", "Human Resources", "[email protected]", "[email protected]", listOf( JavaPerson("Erlick Foyes", "Customer Service", "[email protected]", "[email protected]"), JavaPerson("Steve Folley", "Customer Service", "[email protected]", "[email protected]"), JavaPerson("Larry Cable", "Customer Service", "[email protected]", "[email protected]"))) ).observable() // Create the root item that holds all top level employees val rootItem = TreeItem(JavaPerson().apply { name = "Employees by Manager"; employees = people }) override val root = treetableview(rootItem) { prefWidth = 800.0 column<JavaPerson, String>("Name", "name").contentWidth(50) // non type safe column("Department", JavaPerson::getDepartment).remainingWidth() nestedColumn("Email addresses") { column("Primary Email", JavaPerson::getPrimaryEmail) column("Secondary Email", JavaPerson::getSecondaryEmail) } // Always return employees under the current person populate { it.value.employees } // Expand the two first levels root.isExpanded = true root.children.forEach { it.isExpanded = true } smartResize() } }
apache-2.0
e51915422e163fe97d630f1ae3b5a010
46.119048
124
0.658241
3.711069
false
false
false
false
openHPI/android-app
app/src/main/java/de/xikolo/models/dao/CourseDao.kt
1
10553
package de.xikolo.models.dao import androidx.lifecycle.LiveData import com.google.gson.Gson import de.xikolo.App import de.xikolo.R import de.xikolo.extensions.asCopy import de.xikolo.extensions.asLiveData import de.xikolo.models.Course import de.xikolo.models.dao.base.BaseDao import io.realm.Case import io.realm.Realm import io.realm.Sort import io.realm.kotlin.where import java.util.* class CourseDao(realm: Realm) : BaseDao<Course>(Course::class, realm) { init { defaultSort = "startDate" to Sort.DESCENDING } fun all() = all("external" to false) fun allSortedByTitle(): LiveData<List<Course>> = query() .sort("title", Sort.ASCENDING) .findAllAsync() .asLiveData() override fun find(id: String?): LiveData<Course> = query() .beginGroup() .equalTo("id", id) .or() .equalTo("slug", id) .endGroup() .findFirstAsync() .asLiveData() class Unmanaged { companion object { @JvmStatic fun find(id: String?): Course? = Realm.getDefaultInstance().use { realm -> realm.where<Course>() .beginGroup() .equalTo("id", id) .or() .equalTo("slug", id) .endGroup() .findFirst() ?.asCopy() } fun allWithCertificates(): List<Course> = Realm.getDefaultInstance().use { realm -> realm.where<Course>() .sort("startDate", Sort.DESCENDING) .findAll() .asCopy() .filter { course -> EnrollmentDao.Unmanaged.findForCourse(course.id) ?.anyCertificateAchieved() == true } } fun filter(searchQuery: String?, filterMap: Map<String, String>, withEnrollment: Boolean): List<Course> = Realm.getDefaultInstance().use { realm -> val realmQuery = realm.where<Course>() .beginGroup() .like("title", "*$searchQuery*", Case.INSENSITIVE) .or() .like("shortAbstract", "*$searchQuery*", Case.INSENSITIVE) .or() .like("description", "*$searchQuery*", Case.INSENSITIVE) .or() .like("teachers", "*$searchQuery*", Case.INSENSITIVE) .endGroup() filterMap.forEach { if (it.value != App.instance.getString(R.string.course_filter_classifier_all)) { when (it.key) { App.instance.getString(R.string.course_filter_classifier_channel) -> { realmQuery.equalTo("channelId", it.value, Case.INSENSITIVE) } App.instance.getString(R.string.course_filter_classifier_language) -> { realmQuery.equalTo("language", it.value, Case.INSENSITIVE) } } } } if (withEnrollment) { realmQuery.isNotNull("enrollmentId") } return realmQuery .sort("startDate", Sort.DESCENDING) .findAll() .asCopy() .filter { course -> filterMap.all { it.value == App.instance.getString(R.string.course_filter_classifier_all) || it.key == App.instance.getString(R.string.course_filter_classifier_channel) || it.key == App.instance.getString(R.string.course_filter_classifier_language) || Gson().fromJson<Map<String, List<String>>>(course.classifiers, Map::class.java)[it.key]?.contains(it.value) == true } } } fun allCurrentAndFuture(): List<Course> = Realm.getDefaultInstance().use { realm -> realm.where<Course>() .beginGroup() .isNull("endDate") .or() .greaterThanOrEqualTo("endDate", Date()) .endGroup() .sort("startDate", Sort.ASCENDING) .findAll() .asCopy() } fun allCurrentAndPast(): List<Course> = Realm.getDefaultInstance().use { realm -> realm.where<Course>() .lessThanOrEqualTo("startDate", Date()) .sort("startDate", Sort.DESCENDING) .findAll() .asCopy() } fun allPast(): List<Course> = Realm.getDefaultInstance().use { realm -> realm.where<Course>() .beginGroup() .isNotNull("endDate") .and() .lessThan("endDate", Date()) .endGroup() .sort("startDate", Sort.DESCENDING) .findAll() .asCopy() } fun allFuture(): List<Course> = Realm.getDefaultInstance().use { realm -> realm.where<Course>() .greaterThan("startDate", Date()) .sort("startDate", Sort.ASCENDING) .findAll() .asCopy() } fun allCurrentAndPastWithEnrollment(): List<Course> = Realm.getDefaultInstance().use { realm -> realm.where<Course>() .equalTo("external", false) .isNotNull("enrollmentId") .lessThanOrEqualTo("startDate", Date()) .sort("startDate", Sort.DESCENDING) .findAll() .asCopy() } fun allFutureWithEnrollment(): List<Course> = Realm.getDefaultInstance().use { realm -> realm.where<Course>() .equalTo("external", false) .isNotNull("enrollmentId") .greaterThan("startDate", Date()) .sort("startDate", Sort.ASCENDING) .findAll() .asCopy() } fun allCurrentAndFutureForChannel(channelId: String?): List<Course> = Realm.getDefaultInstance().use { realm -> realm.where<Course>() .equalTo("channelId", channelId) .equalTo("external", false) .beginGroup() .isNull("endDate") .or() .greaterThanOrEqualTo("endDate", Date()) .endGroup() .sort("startDate", Sort.ASCENDING) .findAll() .asCopy() } fun allCurrentAndPastForChannel(channelId: String?): List<Course> = Realm.getDefaultInstance().use { realm -> realm.where<Course>() .equalTo("channelId", channelId) .equalTo("external", false) .lessThanOrEqualTo("startDate", Date()) .sort("startDate", Sort.DESCENDING) .findAll() .asCopy() } fun allPastForChannel(channelId: String?): List<Course> = Realm.getDefaultInstance().use { realm -> realm.where<Course>() .equalTo("channelId", channelId) .equalTo("external", false) .beginGroup() .isNotNull("endDate") .and() .lessThan("endDate", Date()) .endGroup() .sort("startDate", Sort.DESCENDING) .findAll() .asCopy() } fun allFutureForChannel(channelId: String?): List<Course> = Realm.getDefaultInstance().use { realm -> realm.where<Course>() .equalTo("channelId", channelId) .equalTo("external", false) .greaterThan("startDate", Date()) .sort("startDate", Sort.ASCENDING) .findAll() .asCopy() } fun languages(): List<String> = Realm.getDefaultInstance().use { realm -> realm.where<Course>() .findAll() .asCopy() } .map { it.language } .distinct() fun collectClassifier(name: String): List<String> = Realm.getDefaultInstance() .use { realm -> realm.where<Course>() .findAll() .asCopy() } .map { val map = Gson().fromJson<Map<String, List<String>>>( it.classifiers, Map::class.java ) map?.get(name) ?: listOf() } .fold(mutableListOf<String>(), { acc, list -> acc.apply { addAll(list) } }) .distinct() } } }
bsd-3-clause
0e278985b983a416c9c8ac61e615c64c
39.278626
154
0.404435
6.075417
false
false
false
false
equeim/tremotesf-android
torrentfile/src/test/kotlin/org/equeim/tremotesf/torrentfile/TorrentFileParserTest.kt
1
7309
package org.equeim.tremotesf.torrentfile import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.* import org.junit.After import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test @OptIn(ExperimentalCoroutinesApi::class) class TorrentFileParserTest { private val dispatcher = StandardTestDispatcher() private val dispatchers = TestDispatchers(dispatcher) private fun getResource(name: String) = requireNotNull(javaClass.getResourceAsStream(name)) { "Resource $name not found" } @Before fun before() { Dispatchers.setMain(dispatcher) } @After fun after() { Dispatchers.resetMain() } @Test fun `Parsing single file torrent`() = runTest { val actual = TorrentFileParser.parseFile(getResource(singleFileTorrent), dispatchers) assertEquals(singleFileTorrentParsed, actual) } @Test fun `Creating tree for single file torrent`() = runTest { val actual = TorrentFileParser.createFilesTree(singleFileTorrentParsed, dispatchers) assertTreeResultsAreSimilar(singleFileTorrentTreeResult, actual) } @Test fun `Parsing multiple file torrent`() = runTest { val actual = TorrentFileParser.parseFile(getResource(multipleFileTorrent), dispatchers) assertEquals(multipleFileTorrentParsed, actual) } @Test fun `Creating tree for multiple file torrent`() = runTest { val actual = TorrentFileParser.createFilesTree(multipleFileTorrentParsed, dispatchers) assertTreeResultsAreSimilar(multipleFileTorrentTreeResult, actual) } @Test fun `Parsing multiple file torrent with subdirectories`() = runTest { val actual = TorrentFileParser.parseFile( getResource(multipleFileTorrentWithSubdirectories), dispatchers ) assertEquals(multipleFileTorrentWithSubdirectoriesParsed, actual) } @Test fun `Creating tree for multiple file torrent with subdirectories`() = runTest { val actual = TorrentFileParser.createFilesTree( multipleFileTorrentWithSubdirectoriesParsed, dispatchers ) assertTreeResultsAreSimilar(multipleFileTorrentWithSubdirectoriesTreeResult, actual) } @Test fun `Parsing torrent that is too big`() = runTest { try { TorrentFileParser.parseFile(getResource(bigTorrent), dispatchers) } catch (ignore: FileIsTooLargeException) { return@runTest } throw AssertionError("FileIsTooLargeException exception is not thrown") } private fun assertTreeResultsAreSimilar(expected: TorrentFilesTreeBuildResult, actual: TorrentFilesTreeBuildResult) { assertNodesAreSimilar(expected.rootNode, actual.rootNode) assertNodesAreSimilar(expected.files, actual.files) } private companion object { const val singleFileTorrent = "debian-10.9.0-amd64-netinst.iso.torrent" val singleFileTorrentParsed by lazy { TorrentFileParser.TorrentFile( TorrentFileParser.TorrentFile.Info( files = null, length = 353370112, name = "debian-10.9.0-amd64-netinst.iso" ) ) } val singleFileTorrentTreeResult by lazy { buildTorrentFilesTree { addFile( 0, listOf("debian-10.9.0-amd64-netinst.iso"), 353370112, 0, TorrentFilesTree.Item.WantedState.Wanted, TorrentFilesTree.Item.Priority.Normal ) } } const val multipleFileTorrent = "Fedora-Workstation-Live-x86_64-34.torrent" val multipleFileTorrentParsed by lazy { TorrentFileParser.TorrentFile( TorrentFileParser.TorrentFile.Info( files = listOf( TorrentFileParser.TorrentFile.File( 1062, listOf("Fedora-Workstation-34-1.2-x86_64-CHECKSUM") ), TorrentFileParser.TorrentFile.File( 2007367680, listOf("Fedora-Workstation-Live-x86_64-34-1.2.iso") ) ), length = null, name = "Fedora-Workstation-Live-x86_64-34" ) ) } val multipleFileTorrentTreeResult by lazy { buildTorrentFilesTree { addFile( 0, listOf( "Fedora-Workstation-Live-x86_64-34", "Fedora-Workstation-34-1.2-x86_64-CHECKSUM" ), 1062, 0, TorrentFilesTree.Item.WantedState.Wanted, TorrentFilesTree.Item.Priority.Normal ) addFile( 1, listOf( "Fedora-Workstation-Live-x86_64-34", "Fedora-Workstation-Live-x86_64-34-1.2.iso" ), 2007367680, 0, TorrentFilesTree.Item.WantedState.Wanted, TorrentFilesTree.Item.Priority.Normal ) } } const val multipleFileTorrentWithSubdirectories = "with_subdirectories.torrent" val multipleFileTorrentWithSubdirectoriesParsed by lazy { TorrentFileParser.TorrentFile( TorrentFileParser.TorrentFile.Info( files = listOf( TorrentFileParser.TorrentFile.File( 153488, listOf("fedora", "Fedora-Workstation-Live-x86_64-34.torrent") ), TorrentFileParser.TorrentFile.File( 27506, listOf("debian", "debian-10.9.0-amd64-netinst.iso.torrent") ) ), length = null, name = "foo" ) ) } val multipleFileTorrentWithSubdirectoriesTreeResult by lazy { buildTorrentFilesTree { addFile( 0, listOf("foo", "fedora", "Fedora-Workstation-Live-x86_64-34.torrent"), 153488, 0, TorrentFilesTree.Item.WantedState.Wanted, TorrentFilesTree.Item.Priority.Normal ) addFile( 1, listOf("foo", "debian", "debian-10.9.0-amd64-netinst.iso.torrent"), 27506, 0, TorrentFilesTree.Item.WantedState.Wanted, TorrentFilesTree.Item.Priority.Normal ) } } const val bigTorrent = "big.torrent" } }
gpl-3.0
091d19e4b784b594f7013fc703085be6
35.004926
121
0.545218
5.273449
false
true
false
false
KyuBlade/kotlin-discord-bot
src/main/kotlin/com/omega/discord/bot/audio/AudioProvider.kt
1
893
package com.omega.discord.bot.audio import com.sedmelluq.discord.lavaplayer.player.AudioPlayer import com.sedmelluq.discord.lavaplayer.track.playback.AudioFrame import sx.blah.discord.handle.audio.AudioEncodingType import sx.blah.discord.handle.audio.IAudioProvider class AudioProvider(val audioPlayer: AudioPlayer) : IAudioProvider { private var lastFrame: AudioFrame? = null override fun isReady(): Boolean { if (lastFrame == null) { lastFrame = audioPlayer.provide() } return lastFrame != null } override fun provide(): ByteArray { if (lastFrame == null) { lastFrame = audioPlayer.provide() } val data: ByteArray = lastFrame?.data!! lastFrame = null return data } override fun getAudioEncodingType(): AudioEncodingType { return AudioEncodingType.OPUS } }
gpl-3.0
91a03dab948ac077cdf73ec099fa632c
23.162162
68
0.675252
4.442786
false
false
false
false
ojacquemart/spring-kotlin-euro-bets
src/main/kotlin/org/ojacquemart/eurobets/firebase/management/match/Team.kt
2
488
package org.ojacquemart.eurobets.firebase.management.match import com.fasterxml.jackson.annotation.JsonIgnoreProperties @JsonIgnoreProperties(ignoreUnknown = true) data class Team(val i18n: I18Nested? = null, val isoAlpha2Code: String? = null, val goals: Int? = -1, val winner: Boolean? = false) { fun getI18EnName(): String { return i18n!!.en } data class I18Nested(val en: String = "", val fr: String = "") {} }
unlicense
d5e65c6af933c364d9b634a0398e36d7
26.111111
69
0.633197
3.96748
false
false
false
false
androhi/AndroidDrawableViewer
src/main/kotlin/com/androhi/androiddrawableviewer/form/DetailDisplayDialog.kt
1
4493
package com.androhi.androiddrawableviewer.form import com.androhi.androiddrawableviewer.Constants.Companion.DRAWABLE_RESOURCE_NAME import com.androhi.androiddrawableviewer.Constants.Companion.MIPMAP_RESOURCE_NAME import com.androhi.androiddrawableviewer.model.DrawableModel import com.androhi.androiddrawableviewer.utils.IconUtils import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.ui.components.JBScrollPane import java.awt.BorderLayout import java.awt.Dimension import javax.swing.* import javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS import javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS import javax.swing.border.EmptyBorder import javax.swing.border.SoftBevelBorder class DetailDisplayDialog(project: Project, drawableModel: DrawableModel) : DialogWrapper(project, true) { private var mainPanel: JPanel? = null private val subPanel: JPanel = JPanel() private var springLayout: SpringLayout? = null init { springLayout = SpringLayout() subPanel.run { layout = springLayout } isAutoAdjustable = false setResizable(true) setSize(480, 360) title = drawableModel.fileName createContent(drawableModel) init() } private fun createContent(model: DrawableModel) { //addDisplayImage(model, model.fileName, Constants.DRAWABLE_PREFIX, model.drawableDensityList) //addDisplayImage(model, model.fileName, Constants.MIPMAP_PREFIX, model.mipmapDensityList) addDisplayImage(model) } // todo: すクローラブルにする。 private fun addDisplayImage(model: DrawableModel, fileName: String = "", densityPrefix: String = "", densityList: List<String>? = null) { if (densityList?.isEmpty() == true) { return } var oldPanel: JPanel? = null var panelWidth = HORIZONTAL_PADDING var panelHeight = 0 mainPanel?.add(createScrollPane(), BorderLayout.CENTER) model.filePathList.forEach { filePath -> val densityLabel = JLabel().apply { text = getDensityName(filePath) horizontalAlignment = JLabel.CENTER border = EmptyBorder(0, 0, 4, 0) } val iconLabel = JLabel().apply { icon = IconUtils.createOriginalIcon(filePath) border = SoftBevelBorder(SoftBevelBorder.LOWERED) } val panel = JPanel().apply { layout = BorderLayout() add(densityLabel, BorderLayout.PAGE_START) add(iconLabel, BorderLayout.CENTER) } updateContainer(panel, oldPanel) panelWidth += (panel.width + HORIZONTAL_PADDING) if (panelHeight < panel.height) { panelHeight = panel.height } oldPanel = panel } setContainerSize(panelWidth, panelHeight) } private fun getDensityName(filePath: String): String { val regex = Regex("$DRAWABLE_RESOURCE_NAME|$MIPMAP_RESOURCE_NAME|-") return filePath.split("/") .find { it.startsWith(DRAWABLE_RESOURCE_NAME) || it.startsWith(MIPMAP_RESOURCE_NAME) } ?.replace(regex, "") ?: "" } private fun createScrollPane(): JBScrollPane = JBScrollPane(VERTICAL_SCROLLBAR_ALWAYS, HORIZONTAL_SCROLLBAR_ALWAYS).apply { setViewportView(subPanel) } private fun updateContainer(newPanel: JPanel, oldPanel: JPanel?) { val e2 = if (oldPanel == null) SpringLayout.WEST else SpringLayout.EAST val c2 = if (oldPanel == null) subPanel else oldPanel springLayout?.run { putConstraint(SpringLayout.NORTH, newPanel, VERTICAL_PADDING, SpringLayout.NORTH, subPanel) putConstraint(SpringLayout.WEST, newPanel, HORIZONTAL_PADDING, e2, c2) } subPanel.add(newPanel) subPanel.doLayout() } private fun setContainerSize(width: Int, height: Int) { subPanel.preferredSize = Dimension(width, height + VERTICAL_PADDING * 2) } override fun createCenterPanel(): JComponent? = mainPanel override fun createActions(): Array<Action> = Array(1) { DialogWrapperExitAction("OK", OK_EXIT_CODE) } companion object { private const val VERTICAL_PADDING = 8 private const val HORIZONTAL_PADDING = 16 } }
apache-2.0
647cd08c9ac260f6c6a008d205f0c1a1
34.212598
141
0.658913
4.609278
false
false
false
false
jitsi/jicofo
jicofo/src/main/kotlin/org/jitsi/jicofo/conference/ConferenceMetrics.kt
1
3229
/* * Jicofo, the Jitsi Conference Focus. * * Copyright @ 2020 - 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.jicofo.conference import edu.umd.cs.findbugs.annotations.SuppressFBWarnings import org.jitsi.utils.stats.ConferenceSizeBuckets import org.jitsi.jicofo.metrics.JicofoMetricsContainer.Companion.instance as metricsContainer @SuppressFBWarnings("MS_CANNOT_BE_FINAL") class ConferenceMetrics { companion object { @JvmField val conferencesCreated = metricsContainer.registerCounter( "conferences_created", "The number of conferences created on this Jicofo since it was started" ) @JvmField val participants = metricsContainer.registerCounter( "participants", "The total number of participants that have connected to this Jicofo since it was started." ) @JvmField val participantsNoMultiStream = metricsContainer.registerCounter( "participants_no_multi_stream", "Number of participants with no support for receiving multiple streams." ) @JvmField val participantsNoSourceName = metricsContainer.registerCounter( "participants_no_source_name", "Number of participants with no support for source names." ) @JvmField val participantsMoved = metricsContainer.registerCounter( "participants_moved", "Number of participants moved away from a failed bridge" ) @JvmField val participantsIceFailed = metricsContainer.registerCounter( "participants_ice_failed", "Number of participants that reported an ICE failure" ) @JvmField val participantsRequestedRestart = metricsContainer.registerCounter( "participants_restart_requested", "Number of times a participant requested a restart via session-terminate" ) @JvmField val largestConference = metricsContainer.registerLongGauge( "largest_conference", "The current largest conference." ) @JvmField val currentParticipants = metricsContainer.registerLongGauge( "participants_current", "The current number of participants." ) /** * TODO: convert to a [Metric] */ @JvmField var conferenceSizes = ConferenceSizeBuckets() @JvmField val participantPairs = metricsContainer.registerLongGauge( "participants_pairs", "The number of pairs of participants (the sum of n*(n-1) for each conference)" ) } }
apache-2.0
f38ebcb54440955e6b5870a8a389153e
33.72043
103
0.664292
5.09306
false
false
false
false
vondear/RxTools
RxKit/src/main/java/com/tamsiree/rxkit/RxActivityTool.kt
1
8260
package com.tamsiree.rxkit import android.R import android.app.Activity import android.app.ActivityManager import android.app.ActivityOptions import android.content.Context import android.content.Intent import android.os.Bundle import android.util.Pair import android.view.View import androidx.core.app.ActivityCompat import androidx.core.app.ActivityOptionsCompat import java.util.* import kotlin.system.exitProcess /** * @author tamsiree * @date 2016/1/24 * * * 封装Activity相关工具类 */ object RxActivityTool { var activityStack: Stack<Activity?>? = null /** * 添加Activity 到栈 * * @param activity Activity */ @JvmStatic fun addActivity(activity: Activity?) { if (activityStack == null) { activityStack = Stack() } activityStack?.add(activity) } /** * 从List中移除活动 * * @param activity 活动 */ @JvmStatic fun removeActivity(activity: Activity?) { if (activity != null) { if (activityStack!!.contains(activity)) { activityStack?.remove(activity) } } } /** * 获取当前的Activity(堆栈中最后一个压入的) */ @JvmStatic fun currentActivity(): Activity? { return activityStack?.lastElement() } /** * 结束当前Activity(堆栈中最后一个压入的) */ @JvmStatic @JvmOverloads fun finishActivity(isTransition: Boolean = false) { val activity = activityStack?.lastElement() if (isTransition) { activity?.onBackPressed() } else { activity?.finish() } } /** * 结束指定类名的Activity */ @JvmStatic fun finishActivity(cls: Class<out Activity>) { for (activity in activityStack!!) { if (activity!!.javaClass == cls) { finishActivity(activity) } } } /** * 结束所有的Activity */ @JvmStatic fun finishAllActivity() { val size = activityStack!!.size for (i in 0 until size) { if (null != activityStack!![i]) { activityStack!![i]!!.finish() } } activityStack!!.clear() } @Suppress("DEPRECATION") @JvmStatic fun AppExit(context: Context) { try { finishAllActivity() val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager activityManager.restartPackage(context.packageName) exitProcess(0) } catch (e: Exception) { e.printStackTrace() } } /** * 判断是否存在指定Activity * * @param context 上下文 * @param packageName 包名 * @param className activity全路径类名 * @return `true`: 是<br></br>`false`: 否 */ @JvmStatic fun isExistActivity(context: Context, packageName: String?, className: String?): Boolean { val intent = Intent() intent.setClassName(packageName!!, className!!) return !(context.packageManager.resolveActivity(intent, 0) == null || intent.resolveActivity(context.packageManager) == null || context.packageManager.queryIntentActivities(intent, 0).size == 0) } /** * 打开指定的Activity * * @param context 上下文 * @param packageName 包名 * @param className 全类名 */ @JvmStatic fun launchActivity(context: Context, packageName: String?, className: String?, bundle: Bundle? = null) { context.startActivity(RxIntentTool.getComponentNameIntent(packageName, className, bundle)) } /** * 要求最低API为11 * Activity 跳转 * 跳转后Finish之前所有的Activity * * @param context Context * @param goal Activity */ /** * 要求最低API为11 * Activity 跳转 * 跳转后Finish之前所有的Activity * * @param context Context * @param goal Activity */ @JvmStatic @JvmOverloads fun skipActivityAndFinishAll(context: Context, goal: Class<out Activity>?, bundle: Bundle? = null, isFade: Boolean = false) { val intent = Intent(context, goal) if (bundle != null) { intent.putExtras(bundle) } intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK context.startActivity(intent) finishActivity(context, false) if (isFade) { fadeTransition(context) } } /** * Activity 跳转 * * @param context Context * @param goal Activity */ @JvmStatic fun skipActivityAndFinish(context: Context, goal: Class<out Activity>?, isFade: Boolean = false, isTransition: Boolean = false) { skipActivity(context, goal, null, isFade) finishActivity(context, isTransition) } /** * Activity 跳转 * * @param context Context * @param goal Activity */ @JvmStatic @JvmOverloads fun skipActivityAndFinish(context: Context, goal: Class<out Activity>?, bundle: Bundle? = null, isFade: Boolean = false, isTransition: Boolean = false) { skipActivity(context, goal, bundle, isFade) finishActivity(context, isTransition) } /** * Activity 跳转 * * @param context Context * @param goal Activity */ @JvmStatic @JvmOverloads fun skipActivity(context: Context, goal: Class<out Activity>?, bundle: Bundle? = null, isFade: Boolean = false) { val intent = Intent(context, goal) if (bundle != null) { intent.putExtras(bundle) } context.startActivity(intent) if (isFade) { fadeTransition(context) } } @JvmStatic @JvmOverloads fun skipActivityForResult(context: Activity, goal: Class<out Activity>?, bundle: Bundle? = null, requestCode: Int) { val intent = Intent(context, goal) if (bundle != null) { intent.putExtras(bundle) } context.startActivityForResult(intent, requestCode) } @JvmStatic @JvmOverloads fun skipActivityOnTransitions(mContext: Context?, goal: Class<out Activity>?, bundle: Bundle? = null, vararg pairs: Pair<View, String>?) { val intent = Intent(mContext, goal) val bundle1 = ActivityOptions.makeSceneTransitionAnimation(mContext as Activity?, *pairs).toBundle() if (bundle != null) { intent.putExtras(bundle) } ActivityCompat.startActivity(mContext!!, intent, bundle1) } @JvmStatic @JvmOverloads fun skipActivityTransition(mContext: Context, goal: Class<out Activity>?, bundle: Bundle? = null, view: View?, elementName: String?) { val intent = Intent(mContext, goal) val bundle1 = ActivityOptionsCompat.makeSceneTransitionAnimation((mContext as Activity), view!!, elementName!!).toBundle() if (bundle != null) { intent.putExtras(bundle) } mContext.startActivity(intent, bundle1) } /** * 获取launcher activity * * @param context 上下文 * @param packageName 包名 * @return launcher activity */ @JvmStatic fun getLauncherActivity(context: Context, packageName: String): String { val intent = Intent(Intent.ACTION_MAIN, null) intent.addCategory(Intent.CATEGORY_LAUNCHER) val pm = context.packageManager val infos = pm.queryIntentActivities(intent, 0) for (info in infos) { if (info.activityInfo.packageName == packageName) { return info.activityInfo.name } } return "no $packageName" } @JvmStatic @JvmOverloads fun finishActivity(mContext: Context, isTransition: Boolean = false) { removeActivity((mContext as Activity)) if (isTransition) { mContext.onBackPressed() } else { mContext.finish() } } @JvmStatic fun fadeTransition(mContext: Context) { (mContext as Activity).overridePendingTransition(R.anim.fade_in, R.anim.fade_out) } }
apache-2.0
1710d426a7c6645207a5067b5f1df455
26.71875
202
0.603608
4.494369
false
false
false
false
vondear/RxTools
RxUI/src/main/java/com/tamsiree/rxui/view/popupwindows/tools/RxPopupViewCoordinatesFinder.kt
1
9251
package com.tamsiree.rxui.view.popupwindows.tools import android.graphics.Point import android.view.View import android.view.ViewGroup import android.widget.TextView import com.tamsiree.rxui.view.popupwindows.tools.RxPopupViewTool.isRtl /** * @author Tamsiree */ internal object RxPopupViewCoordinatesFinder { /** * return the top left coordinates for positioning the tip * * @param tipView - the newly created tip view * @param popupView - tool tip object * @return point */ fun getCoordinates(tipView: TextView, popupView: RxPopupView): Point { var point = Point() val anchorViewRxCoordinates = RxCoordinates(popupView.anchorView) val rootRxCoordinates = RxCoordinates(popupView.rootView) tipView.measure(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) when (popupView.position) { RxPopupView.POSITION_ABOVE -> point = getPositionAbove(tipView, popupView, anchorViewRxCoordinates, rootRxCoordinates) RxPopupView.POSITION_BELOW -> point = getPositionBelow(tipView, popupView, anchorViewRxCoordinates, rootRxCoordinates) RxPopupView.POSITION_LEFT_TO -> point = getPositionLeftTo(tipView, popupView, anchorViewRxCoordinates, rootRxCoordinates) RxPopupView.POSITION_RIGHT_TO -> point = getPositionRightTo(tipView, popupView, anchorViewRxCoordinates, rootRxCoordinates) else -> { } } // add user defined offset values point.x += if (isRtl) -popupView.offsetX else popupView.offsetX point.y += popupView.offsetY // coordinates retrieved are relative to 0,0 of the root layout // added view to root is subject to root padding // we need to subtract the top and left padding of root from coordinates. to adjust // top left tip coordinates point.x -= popupView.rootView.paddingLeft point.y -= popupView.rootView.paddingTop return point } private fun getPositionRightTo(tipView: TextView, rxPopupView: RxPopupView, anchorViewRxCoordinates: RxCoordinates, rootLocation: RxCoordinates): Point { val point = Point() point.x = anchorViewRxCoordinates.right AdjustRightToOutOfBounds(tipView, rxPopupView.rootView, point, anchorViewRxCoordinates, rootLocation) point.y = anchorViewRxCoordinates.top + getYCenteringOffset(tipView, rxPopupView) return point } private fun getPositionLeftTo(tipView: TextView, rxPopupView: RxPopupView, anchorViewRxCoordinates: RxCoordinates, rootLocation: RxCoordinates): Point { val point = Point() point.x = anchorViewRxCoordinates.left - tipView.measuredWidth AdjustLeftToOutOfBounds(tipView, rxPopupView.rootView, point, anchorViewRxCoordinates, rootLocation) point.y = anchorViewRxCoordinates.top + getYCenteringOffset(tipView, rxPopupView) return point } private fun getPositionBelow(tipView: TextView, rxPopupView: RxPopupView, anchorViewRxCoordinates: RxCoordinates, rootLocation: RxCoordinates): Point { val point = Point() point.x = anchorViewRxCoordinates.left + getXOffset(tipView, rxPopupView) if (rxPopupView.alignedCenter()) { AdjustHorizontalCenteredOutOfBounds(tipView, rxPopupView.rootView, point, rootLocation) } else if (rxPopupView.alignedLeft()) { AdjustHorizontalLeftAlignmentOutOfBounds(tipView, rxPopupView.rootView, point, anchorViewRxCoordinates, rootLocation) } else if (rxPopupView.alignedRight()) { AdjustHorizotalRightAlignmentOutOfBounds(tipView, rxPopupView.rootView, point, anchorViewRxCoordinates, rootLocation) } point.y = anchorViewRxCoordinates.bottom return point } private fun getPositionAbove(tipView: TextView, rxPopupView: RxPopupView, anchorViewRxCoordinates: RxCoordinates, rootLocation: RxCoordinates): Point { val point = Point() point.x = anchorViewRxCoordinates.left + getXOffset(tipView, rxPopupView) if (rxPopupView.alignedCenter()) { AdjustHorizontalCenteredOutOfBounds(tipView, rxPopupView.rootView, point, rootLocation) } else if (rxPopupView.alignedLeft()) { AdjustHorizontalLeftAlignmentOutOfBounds(tipView, rxPopupView.rootView, point, anchorViewRxCoordinates, rootLocation) } else if (rxPopupView.alignedRight()) { AdjustHorizotalRightAlignmentOutOfBounds(tipView, rxPopupView.rootView, point, anchorViewRxCoordinates, rootLocation) } point.y = anchorViewRxCoordinates.top - tipView.measuredHeight return point } private fun AdjustRightToOutOfBounds(tipView: TextView, root: ViewGroup, point: Point, anchorViewRxCoordinates: RxCoordinates, rootLocation: RxCoordinates) { val params = tipView.layoutParams val availableSpace = rootLocation.right - root.paddingRight - anchorViewRxCoordinates.right if (point.x + tipView.measuredWidth > rootLocation.right - root.paddingRight) { params.width = availableSpace params.height = ViewGroup.LayoutParams.WRAP_CONTENT tipView.layoutParams = params measureViewWithFixedWidth(tipView, params.width) } } private fun AdjustLeftToOutOfBounds(tipView: TextView, root: ViewGroup, point: Point, anchorViewRxCoordinates: RxCoordinates, rootLocation: RxCoordinates) { val params = tipView.layoutParams val rootLeft = rootLocation.left + root.paddingLeft if (point.x < rootLeft) { val availableSpace = anchorViewRxCoordinates.left - rootLeft point.x = rootLeft params.width = availableSpace params.height = ViewGroup.LayoutParams.WRAP_CONTENT tipView.layoutParams = params measureViewWithFixedWidth(tipView, params.width) } } private fun AdjustHorizotalRightAlignmentOutOfBounds(tipView: TextView, root: ViewGroup, point: Point, anchorViewRxCoordinates: RxCoordinates, rootLocation: RxCoordinates) { val params = tipView.layoutParams val rootLeft = rootLocation.left + root.paddingLeft if (point.x < rootLeft) { val availableSpace = anchorViewRxCoordinates.right - rootLeft point.x = rootLeft params.width = availableSpace params.height = ViewGroup.LayoutParams.WRAP_CONTENT tipView.layoutParams = params measureViewWithFixedWidth(tipView, params.width) } } private fun AdjustHorizontalLeftAlignmentOutOfBounds(tipView: TextView, root: ViewGroup, point: Point, anchorViewRxCoordinates: RxCoordinates, rootLocation: RxCoordinates) { val params = tipView.layoutParams val rootRight = rootLocation.right - root.paddingRight if (point.x + tipView.measuredWidth > rootRight) { params.width = rootRight - anchorViewRxCoordinates.left params.height = ViewGroup.LayoutParams.WRAP_CONTENT tipView.layoutParams = params measureViewWithFixedWidth(tipView, params.width) } } private fun AdjustHorizontalCenteredOutOfBounds(tipView: TextView, root: ViewGroup, point: Point, rootLocation: RxCoordinates) { val params = tipView.layoutParams val rootWidth = root.width - root.paddingLeft - root.paddingRight if (tipView.measuredWidth > rootWidth) { point.x = rootLocation.left + root.paddingLeft params.width = rootWidth params.height = ViewGroup.LayoutParams.WRAP_CONTENT tipView.layoutParams = params measureViewWithFixedWidth(tipView, rootWidth) } } private fun measureViewWithFixedWidth(tipView: TextView, width: Int) { tipView.measure(View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY), ViewGroup.LayoutParams.WRAP_CONTENT) } /** * calculate the amount of movement need to be taken inorder to align tip * on X axis according to "align" parameter * @return int */ private fun getXOffset(tipView: View, rxPopupView: RxPopupView): Int { val offset: Int offset = when (rxPopupView.align) { RxPopupView.ALIGN_CENTER -> (rxPopupView.anchorView.width - tipView.measuredWidth) / 2 RxPopupView.ALIGN_LEFT -> 0 RxPopupView.ALIGN_RIGHT -> rxPopupView.anchorView.width - tipView.measuredWidth else -> 0 } return offset } /** * calculate the amount of movement need to be taken inorder to center tip * on Y axis * @return int */ private fun getYCenteringOffset(tipView: View, rxPopupView: RxPopupView): Int { return (rxPopupView.anchorView.height - tipView.measuredHeight) / 2 } }
apache-2.0
2692cd758390c30efee83aa157cb01d9
47.694737
161
0.672144
4.803219
false
false
false
false
kotlinz/kotlinz
src/main/kotlin/com/github/kotlinz/kotlinz/data/state/StateMonadOps.kt
1
1076
package com.github.kotlinz.kotlinz.data.state import com.github.kotlinz.kotlinz.K1 import com.github.kotlinz.kotlinz.type.monad.MonadOps interface StateMonadOps<S>: MonadOps<K1<State.T, S>>, StateMonad<S> { override fun <A, B> liftM(f: (A) -> B): (K1<K1<State.T, S>, A>) -> K1<K1<State.T, S>, B> { return { m -> val i = State.narrow(m) i bind { x -> State.pure<S, B>(f(x)) } } } override fun <A, B, C> liftM2(f: (A, B) -> C): (K1<K1<State.T, S>, A>, K1<K1<State.T, S>, B>) -> K1<K1<State.T, S>, C> { return { m1, m2 -> val i1 = State.narrow(m1) val i2 = State.narrow(m2) i1 bind { x1 -> i2 bind { x2 -> State.pure<S, C>(f(x1, x2)) } } } } override fun <A, B, C, D> liftM3(f: (A, B, C) -> D): (K1<K1<State.T, S>, A>, K1<K1<State.T, S>, B>, K1<K1<State.T, S>, C>) -> K1<K1<State.T, S>, D> { return { m1, m2, m3 -> val i1 = State.narrow(m1) val i2 = State.narrow(m2) val i3 = State.narrow(m3) i1 bind { x1 -> i2 bind { x2 -> i3 bind { x3 -> State.pure<S, D>(f(x1, x2, x3)) } } } } } }
apache-2.0
62429b168e6a8be169a2845c6bad589a
34.9
151
0.533457
2.237006
false
false
false
false
andimage/PCBridge
src/main/kotlin/com/projectcitybuild/core/infrastructure/network/clients/PCBClient.kt
1
2056
package com.projectcitybuild.core.infrastructure.network.clients import com.projectcitybuild.entities.requests.pcb.AuthAPIRequest import com.projectcitybuild.entities.requests.pcb.BalanceAPIRequest import com.projectcitybuild.entities.requests.pcb.BanAPIRequest import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory class PCBClient( private val oldAuthToken: String, // Deprecated private val authToken: String, private val baseUrl: String, private val withLogging: Boolean ) { private val instance: Retrofit = build() val banApi: BanAPIRequest = instance.create(BanAPIRequest::class.java) val authApi: AuthAPIRequest = instance.create(AuthAPIRequest::class.java) val balanceApi: BalanceAPIRequest = instance.create(BalanceAPIRequest::class.java) private fun build(): Retrofit { val authenticatedClient = makeAuthenticatedClient() return Retrofit.Builder() .baseUrl(baseUrl) .client(authenticatedClient) .addConverterFactory(GsonConverterFactory.create()) .build() } private fun makeAuthenticatedClient(): OkHttpClient { var clientFactory = OkHttpClient().newBuilder() .addInterceptor { chain -> // Add access token as header to each API request val request = chain.request() val token = if (request.url.toString().contains("balance")) authToken else oldAuthToken val requestBuilder = request.newBuilder().header("Authorization", "Bearer $token") val nextRequest = requestBuilder.build() chain.proceed(nextRequest) } if (withLogging) { val loggingInterceptor = HttpLoggingInterceptor() loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY clientFactory = clientFactory.addInterceptor(loggingInterceptor) } return clientFactory.build() } }
mit
7e7f06391a3b6b264fa1fbfbb3bb40c2
37.074074
103
0.700389
5.191919
false
false
false
false
stripe/stripe-android
payments-ui-core/src/main/java/com/stripe/android/ui/core/injection/FormControllerModule.kt
1
1929
package com.stripe.android.ui.core.injection import android.content.Context import androidx.annotation.RestrictTo import com.stripe.android.core.injection.INITIAL_VALUES import com.stripe.android.core.injection.SHIPPING_VALUES import com.stripe.android.model.PaymentIntent import com.stripe.android.model.StripeIntent import com.stripe.android.ui.core.Amount import com.stripe.android.ui.core.address.AddressRepository import com.stripe.android.ui.core.elements.IdentifierSpec import com.stripe.android.ui.core.forms.TransformSpecToElements import com.stripe.android.ui.core.forms.resources.ResourceRepository import dagger.Module import dagger.Provides import javax.inject.Named @Module @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) abstract class FormControllerModule { companion object { @Provides fun provideTransformSpecToElements( addressResourceRepository: ResourceRepository<AddressRepository>, context: Context, merchantName: String, stripeIntent: StripeIntent?, @Named(INITIAL_VALUES) initialValues: Map<IdentifierSpec, String?>, @Named(SHIPPING_VALUES) shippingValues: Map<IdentifierSpec, String?>?, viewOnlyFields: Set<IdentifierSpec> ) = TransformSpecToElements( addressResourceRepository = addressResourceRepository, initialValues = initialValues, shippingValues = shippingValues, amount = (stripeIntent as? PaymentIntent)?.let { val amount = it.amount val currency = it.currency if (amount != null && currency != null) { Amount(amount, currency) } null }, saveForFutureUseInitialValue = false, merchantName = merchantName, context = context, viewOnlyFields = viewOnlyFields ) } }
mit
13573f436257928e4fdf2af198efa025
36.823529
82
0.686366
5.049738
false
false
false
false
HochschuleHofStundenplanapp/AndroidStundenplanHof
app/src/main/java/de/hof/university/app/widget/data/AppWidgetDataCache.kt
1
10219
/* Copyright © 2018 Jan Gaida licensed under GNU GPLv3 */ @file:Suppress("SpellCheckingInspection") package de.hof.university.app.widget.data import de.hof.university.app.util.Define import de.hof.university.app.model.schedule.Changes import de.hof.university.app.model.schedule.LectureItem import de.hof.university.app.model.schedule.MySchedule import de.hof.university.app.model.schedule.Schedule import java.util.Date import android.util.Log import android.content.Context import de.hof.university.app.widget.AppWidgetBroadcastReceiver import java.io.File import java.io.ObjectOutputStream import java.io.ObjectInputStream import java.io.FileInputStream import java.io.FileOutputStream import java.io.InvalidClassException import java.lang.Exception /** * ************************************************************************** * * !! CAUTION !! * * * !! DO NOT USE THIS TO GET YOUR DATA !! * * * !! THIS WILL BE AND SHOULD ONLY AVAILABLE IF A WIDGET IS ACTIVE !! * * ************************************************************************** * * What is this? * Similar to [de.hof.university.app.data.DataManager] this is used to cache data which should be shown in a widget, * to supply x-amount of widgets it follows the singleton-pattern (see [getInstance]) * * Why is this? * If you look inside [de.hof.university.app.data.DataManager]-constructor you will find that the context used to set the SharedPreference-value * is based on [de.hof.university.app.MainActivity], since widgets do not require this Activity to be launched at all a [ExceptionInInitializerError] * is thrown since the context is null - which itself is to hard to handle without fundamental modifications to [de.hof.university.app.data.DataManager]. * Instead of doing these modifications this class fits the needs while being smaller. * * What does this? * Caching any Data needed to display a Widget including WidgetSettings ( which gets fully managed by this - including creation / saving / deleting / mapping ). * No Schedule, MySchedule, Changes - Data will and should be written by this - only read-access on these. * * @reacts_on [android.content.Intent.ACTION_SHUTDOWN] - see for more [AppWidgetBroadcastReceiver] * @reacts_on [android.content.Intent.ACTION_BOOT_COMPLETED] - see for more [AppWidgetBroadcastReceiver] * * @constructor Singleton-Pattern [getInstance] * * @author Jan Gaida * @since Version 4.8(37) * @date 18.02.2018 */ class AppWidgetDataCache private constructor() { /** * Data */ private var scheduleDataCache: ArrayList<LectureItem>? = null // cached scheduleLectureItems private var scheduleLastSaved: Date? = null // date of last modification to ^ private var myScheduleDataCache: ArrayList<LectureItem>? = null // cached myScheduleLectureItems private var myScheduleLastSaved: Date? = null // date of last modification to ^ private var changesDataCache: ArrayList<Any>? = null // cached lectureChangeItems private var changesLastSaved: Date? = null // date of last modification to ^ private lateinit var widgetSettings: MutableMap<Int, AppWidgetSettingsHolder> // a map full of AppWidgetSettingsHolder as #value where AppWidgetId is the #key /** * Companion */ companion object { private const val TAG = "AppWidgetDataCache" private const val CONFIG_FILE_NAME = "AppWidgetConfig" // the filename for WidgetSettings private var instance: AppWidgetDataCache? = null // the instance fun getInstance(): AppWidgetDataCache = instance ?: run { instance = AppWidgetDataCache(); instance!!} fun hasInstance() = instance != null // !! CAUTION !! // called to delete any WidgetSettings immediate, including cleaning up this -> will cause problems when called while a AppWidget is active internal fun cleanUp(context: Context) = instance?.apply { try { File(context.filesDir, CONFIG_FILE_NAME).delete() } catch (e: SecurityException) {/* fine */} scheduleDataCache = null; myScheduleDataCache = null; changesDataCache = null scheduleLastSaved = null; myScheduleLastSaved = null; changesLastSaved = null if(::widgetSettings.isInitialized) widgetSettings.clear() instance = null } } /** * Data-Modification from outside * * @see [de.hof.university.app.data.DataManager.getSchedule] * @see [de.hof.university.app.data.DataManager.getMySchedule] * @see [de.hof.university.app.data.DataManager.getChanges] */ fun shareScheduleData(context: Context, data: ArrayList<LectureItem>, lastSaved: Date) { scheduleDataCache = data scheduleLastSaved = lastSaved AppWidgetBroadcastReceiver.informAllWidgetsDataChanged(context) } fun shareMyScheduleData(context: Context, data: ArrayList<LectureItem>?, lastSaved: Date?) { myScheduleDataCache = data myScheduleLastSaved = lastSaved AppWidgetBroadcastReceiver.informAllWidgetsDataChanged(context) } fun shareChangesData(context: Context, data: ArrayList<Any>, lastSaved: Date) { changesDataCache = data changesLastSaved = lastSaved AppWidgetBroadcastReceiver.informAllWidgetsDataChanged(context) } /** * Data-Access from inside * * @see [de.hof.university.app.widget.adapters] */ internal fun getScheduleData(context: Context): ArrayList<LectureItem> = scheduleDataCache ?: grabScheduleData(context) internal fun getMyScheduleData(context: Context): ArrayList<LectureItem> = myScheduleDataCache ?: grabMyScheduleData(context) internal fun getChangesData(context: Context): ArrayList<Any> = changesDataCache ?: grabChangesData(context) internal fun getScheduleLastSaved(context: Context): Date? = scheduleLastSaved ?: grabScheduleData(context).run{scheduleLastSaved} internal fun getMyScheduleLastSaved(context: Context): Date? = myScheduleLastSaved ?: grabMyScheduleData(context).run{myScheduleLastSaved} internal fun getChangesLastSaved(context: Context): Date? = changesLastSaved ?: grabChangesData(context).run{changesLastSaved} private fun grabMyScheduleData(context: Context): ArrayList<LectureItem> = grabData < MySchedule, ArrayList<LectureItem> > ( context, Define.myScheduleFilename, success = { it.run{ myScheduleLastSaved = it.lastSaved; it.lectures }}, failure = { ArrayList() } ) private fun grabScheduleData(context: Context): ArrayList<LectureItem> = grabData < Schedule, ArrayList<LectureItem> > ( context, Define.scheduleFilename, success = { it.run{ scheduleLastSaved = it.lastSaved; it.lectures }}, failure = { ArrayList() } ) private fun grabChangesData(context: Context): ArrayList<Any> = grabData < Changes, ArrayList<Any> > ( context, Define.changesFilename, success = { it.run{ changesLastSaved = it.lastSaved; it.changes }}, failure = { ArrayList() } ) /** * Widget-Settings-Functionality * * @see [AppWidgetSettingsHolder] */ internal fun getWidgetSettingsFor(context: Context, appwidgetId: Int): AppWidgetSettingsHolder? = initWidgetSettingsIfNotAlreadyDone(context).run { widgetSettings[appwidgetId] } internal fun putWidgetSettingsFor(context: Context, appWidgetId: Int, settings: AppWidgetSettingsHolder) = initWidgetSettingsIfNotAlreadyDone(context).run { widgetSettings[appWidgetId] = settings // also inititate a write-cycle to ensure at least some data is available before shutdown saveWidgetSettings(context) } internal fun removeWidgetSettingsFor(context: Context, appWidgetId: Int) = initWidgetSettingsIfNotAlreadyDone(context).let { widgetSettings.remove(appWidgetId) } internal fun saveWidgetSettings(context: Context) { if(::widgetSettings.isInitialized) try { FileOutputStream(File(context.filesDir, CONFIG_FILE_NAME)).use { fos -> ObjectOutputStream(fos).use { oos -> oos.writeObject(widgetSettings) } } } catch (e: Exception) { Log.e(TAG, "Failed writing $CONFIG_FILE_NAME", e)} } private fun initWidgetSettingsIfNotAlreadyDone(context: Context) { if (!::widgetSettings.isInitialized || widgetSettings.isEmpty()) widgetSettings = grabData < MutableMap<Int,AppWidgetSettingsHolder> , MutableMap<Int,AppWidgetSettingsHolder> > ( context, CONFIG_FILE_NAME, success = { it }, failure = { mutableMapOf() } ) } /** * HELPER-FUN */ /** * Helper-Method to read a [File] from the [Context.getFilesDir]. * * @param context - The Context from which the requested file can be read * @param fileName - The name of the file * @param success - The function called if the read data is of [TARGET] * @param failure - The function called if the read data isn't [TARGET] * @param TARGET - The targetted Type to read * @param RESULT - The resulting Type of [success] and [failure] */ private inline fun <reified TARGET, RESULT> grabData(context: Context, fileName: String, success: (TARGET) -> RESULT, failure: () -> RESULT): RESULT{ try { File(context.filesDir, fileName).apply { if (exists()) FileInputStream(this).use { fis -> ObjectInputStream(fis).use { ois -> ois.readObject()?.let { if (it is TARGET) { return success(it) } } } } } } catch (invalid: InvalidClassException) { Log.e(TAG, "Failed identifying $fileName", invalid) if (fileName == CONFIG_FILE_NAME) { File(context.filesDir, fileName).delete() saveWidgetSettings(context) } } catch (e: Exception) { Log.e(TAG, "Failed reading $fileName", e) } return failure() } /** * NOT-SURE-WHEN-THIS-EVER-BE-CALLED-FUN */ internal fun remapWidgetIds(context: Context, oldWidgetIds: IntArray, newWidgetIds: IntArray) = initWidgetSettingsIfNotAlreadyDone(context).also { widgetSettings.apply { oldWidgetIds.forEachIndexed{ index, old-> put(newWidgetIds[index], get(old)!!) remove(old) } } } }
gpl-3.0
38769a160ed3f70aab0f03de8d2ff981
42.113924
160
0.69681
4.136842
false
false
false
false
Nunnery/MythicDrops
src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/commands/GiveCommands.kt
1
12842
/* * This file is part of MythicDrops, licensed under the MIT License. * * Copyright (C) 2019 Richard Harrah * * 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.tealcube.minecraft.bukkit.mythicdrops.commands import co.aikar.commands.BaseCommand import co.aikar.commands.annotation.CommandAlias import co.aikar.commands.annotation.CommandCompletion import co.aikar.commands.annotation.CommandPermission import co.aikar.commands.annotation.Conditions import co.aikar.commands.annotation.Default import co.aikar.commands.annotation.Dependency import co.aikar.commands.annotation.Description import co.aikar.commands.annotation.Flags import co.aikar.commands.annotation.Split import co.aikar.commands.annotation.Subcommand import com.tealcube.minecraft.bukkit.mythicdrops.api.MythicDrops import com.tealcube.minecraft.bukkit.mythicdrops.api.items.CustomItem import com.tealcube.minecraft.bukkit.mythicdrops.api.items.ItemGenerationReason import com.tealcube.minecraft.bukkit.mythicdrops.api.socketing.SocketGem import com.tealcube.minecraft.bukkit.mythicdrops.api.tiers.Tier import com.tealcube.minecraft.bukkit.mythicdrops.identification.IdentityTome import com.tealcube.minecraft.bukkit.mythicdrops.identification.UnidentifiedItem import com.tealcube.minecraft.bukkit.mythicdrops.items.builders.MythicDropBuilder import com.tealcube.minecraft.bukkit.mythicdrops.sendMythicMessage import com.tealcube.minecraft.bukkit.mythicdrops.socketing.SocketExtender import com.tealcube.minecraft.bukkit.mythicdrops.socketing.SocketItem import com.tealcube.minecraft.bukkit.mythicdrops.utils.GemUtil import io.pixeloutlaw.minecraft.spigot.bandsaw.JulLoggerFactory import io.pixeloutlaw.minecraft.spigot.mythicdrops.getMaterials import org.bukkit.command.CommandSender import org.bukkit.entity.Player @CommandAlias("mythicdrops|md") class GiveCommands : BaseCommand() { companion object { private val logger = JulLoggerFactory.getLogger(GiveCommands::class) } @Subcommand("give") class NestedGiveCommands(parent: BaseCommand) : BaseCommand() { @field:Dependency lateinit var mythicDrops: MythicDrops @Subcommand("custom") @CommandCompletion("@players @customItems *") @Description("Spawns a tiered item in the player's inventory. Use \"*\" to give any custom item.") @CommandPermission("mythicdrops.command.give.custom") fun giveCustomItemCommand( sender: CommandSender, @Flags("other") player: Player, @Default("*") customItem: CustomItem?, @Conditions("limits:min=0") @Default("1") amount: Int ) { var amountGiven = 0 repeat(amount) { val itemStack = customItem?.toItemStack(mythicDrops.customEnchantmentRegistry) ?: mythicDrops.customItemManager.randomByWeight() ?.toItemStack(mythicDrops.customEnchantmentRegistry) if (itemStack != null) { player.inventory.addItem(itemStack) amountGiven++ } } sender.sendMythicMessage( mythicDrops.settingsManager.languageSettings.command.giveCustom.senderSuccess, "%amount%" to amountGiven.toString(), "%receiver%" to player.displayName ) player.sendMythicMessage( mythicDrops.settingsManager.languageSettings.command.giveCustom.receiverSuccess, "%amount%" to amountGiven.toString() ) } @Subcommand("extender") @CommandCompletion("@players *") @Description("Spawns a Socket Extender in the player's inventory.") @CommandPermission("mythicdrops.command.give.extender") fun giveSocketExtenderCommand( sender: CommandSender, @Flags("other") player: Player, @Conditions("limits:min=0") @Default("1") amount: Int ) { var amountGiven = 0 repeat(amount) { mythicDrops.settingsManager.socketingSettings.options.socketExtenderMaterialIds.randomOrNull()?.let { val socketExtender = SocketExtender(it, mythicDrops.settingsManager.socketingSettings.items.socketExtender) player.inventory.addItem(socketExtender) amountGiven++ } } sender.sendMythicMessage( mythicDrops.settingsManager.languageSettings.command.giveExtender.senderSuccess, "%amount%" to amountGiven.toString(), "%receiver%" to player.displayName ) player.sendMythicMessage( mythicDrops.settingsManager.languageSettings.command.giveExtender.receiverSuccess, "%amount%" to amountGiven.toString() ) } @Subcommand("gem") @CommandCompletion("@players @socketGems *") @Description("Spawns a Socket Gem in the player's inventory. Use \"*\" to give any Socket Gem.") @CommandPermission("mythicdrops.command.give.gem") fun giveSocketGemCommand( sender: CommandSender, @Flags("other") player: Player, @Default("*") socketGem: SocketGem?, @Conditions("limits:min=0") @Default("1") amount: Int ) { var amountGiven = 0 repeat(amount) { val chosenSocketGem = socketGem ?: mythicDrops.socketGemManager.randomByWeight() ?: return@repeat GemUtil.getRandomSocketGemMaterial()?.let { val itemStack = SocketItem( it, chosenSocketGem, mythicDrops.settingsManager.socketingSettings.items.socketGem ) player.inventory.addItem(itemStack) amountGiven++ } } sender.sendMythicMessage( mythicDrops.settingsManager.languageSettings.command.giveGem.senderSuccess, "%amount%" to amountGiven.toString(), "%receiver%" to player.displayName ) player.sendMythicMessage( mythicDrops.settingsManager.languageSettings.command.giveGem.receiverSuccess, "%amount%" to amountGiven.toString() ) } @Subcommand("tier") @CommandCompletion("@players @tiers *") @Description("Spawns a tiered item in the player's inventory. Use \"*\" to give any tier.") @CommandPermission("mythicdrops.command.give.tier") fun giveTierCommand( sender: CommandSender, @Flags("other") player: Player, @Default("*") tier: Tier?, @Conditions("limits:min=0") @Default("1") amount: Int ) { var amountGiven = 0 val dropBuilder = MythicDropBuilder(mythicDrops) repeat(amount) { val chosenTier = tier ?: mythicDrops.tierManager.randomByWeight() ?: return@repeat val itemStack = dropBuilder.withItemGenerationReason(ItemGenerationReason.COMMAND) .withTier(chosenTier).useDurability(true).build() if (itemStack != null) { player.inventory.addItem(itemStack) amountGiven++ } } sender.sendMythicMessage( mythicDrops.settingsManager.languageSettings.command.giveRandom.senderSuccess, "%amount%" to amountGiven.toString(), "%receiver%" to player.displayName ) player.sendMythicMessage( mythicDrops.settingsManager.languageSettings.command.giveRandom.receiverSuccess, "%amount%" to amountGiven.toString() ) } @Subcommand("tome") @CommandCompletion("@players *") @Description("Spawns an Identity Tome in the player's inventory.") @CommandPermission("mythicdrops.command.give.tome") fun giveIdentityTomeCommand( sender: CommandSender, @Flags("other") player: Player, @Conditions("limits:min=0") @Default("1") amount: Int ) { var amountGiven = 0 repeat(amount) { val itemStack = IdentityTome(mythicDrops.settingsManager.identifyingSettings.items.identityTome) player.inventory.addItem(itemStack) amountGiven++ } sender.sendMythicMessage( mythicDrops.settingsManager.languageSettings.command.giveTome.senderSuccess, "%amount%" to amountGiven.toString(), "%receiver%" to player.displayName ) player.sendMythicMessage( mythicDrops.settingsManager.languageSettings.command.giveTome.receiverSuccess, "%amount%" to amountGiven.toString() ) } @Subcommand("unidentified") @CommandCompletion("@players * *") @Description("Spawns an Unidentified Item in the player's inventory.") @CommandPermission("mythicdrops.command.give.unidentified") fun giveUnidentifiedItem( sender: CommandSender, @Flags("other") player: Player, @Conditions("limits:min=0") @Default("1") amount: Int, @Default("") @Split(",") allowableTiers: Array<String> ) { val allowableTierList = allowableTiers.mapNotNull { mythicDrops.tierManager.getByName(it) } var amountGiven = 0 repeat(amount) { val randomAllowableTier = if (allowableTierList.isEmpty()) { null } else { allowableTierList.random() } val randomTierFromManager = mythicDrops.tierManager.randomByWeight() val tier = randomAllowableTier ?: randomTierFromManager // intentionally not folded for readability if (tier == null) { return@repeat } val materials = tier.getMaterials() if (materials.isEmpty()) { return@repeat } val material = materials.random() val itemStack = if (allowableTierList.isEmpty()) { UnidentifiedItem.build( mythicDrops.settingsManager.creatureSpawningSettings, mythicDrops.settingsManager.languageSettings.displayNames, material, mythicDrops.tierManager, mythicDrops.settingsManager.identifyingSettings.items.unidentifiedItem ) } else { UnidentifiedItem( material, mythicDrops.settingsManager.identifyingSettings.items.unidentifiedItem, mythicDrops.settingsManager.languageSettings.displayNames, allowableTierList ) } player.inventory.addItem(itemStack) amountGiven++ } sender.sendMythicMessage( mythicDrops.settingsManager.languageSettings.command.giveUnidentified.senderSuccess, "%amount%" to amountGiven.toString(), "%receiver%" to player.displayName ) player.sendMythicMessage( mythicDrops.settingsManager.languageSettings.command.giveUnidentified.receiverSuccess, "%amount%" to amountGiven.toString() ) } } }
mit
2121a6207e5e157a97360f6436bf531f
45.698182
117
0.621944
5.186591
false
false
false
false
hannesa2/owncloud-android
owncloudApp/src/main/java/com/owncloud/android/ui/helpers/ShareSheetHelper.kt
2
2337
/** * ownCloud Android client application * * @author Abel García de Prada * Copyright (C) 2020 ownCloud GmbH. * <p> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * <p> * 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. * <p> * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.owncloud.android.ui.helpers import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.content.pm.ResolveInfo import android.os.Build import android.os.Parcelable import androidx.annotation.RequiresApi import androidx.annotation.StringRes import java.util.ArrayList class ShareSheetHelper { @RequiresApi(Build.VERSION_CODES.N) fun getShareSheetIntent( intent: Intent, context: Context, @StringRes title: Int, packagesToExclude: Array<String> ): Intent { // Get excluding specific targets by component. We want to hide oC targets. val resInfo: List<ResolveInfo> = context.packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY) val excludeLists = ArrayList<ComponentName>() if (resInfo.isNotEmpty()) { for (info in resInfo) { val activityInfo = info.activityInfo for (packageToExclude in packagesToExclude) { if (activityInfo != null && activityInfo.packageName == packageToExclude) { excludeLists.add(ComponentName(activityInfo.packageName, activityInfo.name)) } } } } // Return a new ShareSheet intent return Intent.createChooser(intent, "").apply { putExtra(Intent.EXTRA_EXCLUDE_COMPONENTS, excludeLists.toArray(arrayOf<Parcelable>())) putExtra(Intent.EXTRA_TITLE, context.getString(title)) } } }
gpl-2.0
ae3969d642fc81162c0efa5d211560ca
35.5
100
0.686216
4.653386
false
false
false
false
valmaev/antforce
src/main/kotlin/com/aquivalabs/force/ant/reporters/xml/XmlDsl.kt
1
3025
package com.aquivalabs.force.ant.reporters.xml import java.util.* interface Element { fun render(builder: StringBuilder, indent: String) } class TextElement(val text: String) : Element { override fun render(builder: StringBuilder, indent: String) { builder.append("$indent$text\n") } } class CharacterDataElement(val text: String) : Element { override fun render(builder: StringBuilder, indent: String) { builder.append("$indent<![CDATA[$text]]>\n") } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || javaClass != other.javaClass) return false val element = other as CharacterDataElement return Objects.equals(text, element.text) } override fun hashCode(): Int = text.hashCode() } abstract class Tag(private val tagName: String) : Element { val children = arrayListOf<Element>() val attributes = hashMapOf<String, Any?>() protected fun <T : Element> initTag(tag: T, init: T.() -> Unit): T { tag.init() children.add(tag) return tag } override fun render(builder: StringBuilder, indent: String) { if (children.isEmpty()) renderAsSelfClosing(builder, indent) else renderWithChildren(builder, indent) } private fun renderAsSelfClosing(builder: StringBuilder, indent: String) { builder.append("$indent<$tagName${renderAttributes()} />\n") } private fun renderWithChildren(builder: StringBuilder, indent: String) { builder.append("$indent<$tagName${renderAttributes()}>\n") children.forEach { it.render(builder, "$indent ") } builder.append("$indent</$tagName>\n") } private fun renderAttributes(): String? { val builder = StringBuilder() attributes.keys.forEach { builder.append(" $it=\"${attributes[it]}\"") } return builder.toString() } override fun toString(): String { val builder = StringBuilder() render(builder, "") return builder.toString() } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || javaClass != other.javaClass) return false val tag = other as Tag return Objects.equals(tagName, tag.tagName) && Objects.equals(children, tag.children) && Objects.equals(attributes, tag.attributes) } override fun hashCode(): Int = Objects.hash(tagName, children, attributes) } abstract class EmptyTag : Tag("") { override fun render(builder: StringBuilder, indent: String) = children.forEach { it.render(builder, "$indent ") } } abstract class TagWithTextData(name: String) : Tag(name) { operator fun String.unaryPlus() = children.add(TextElement(this)) } abstract class TagWithCharacterData(name: String) : Tag(name) { operator fun String.unaryPlus() = children.add(CharacterDataElement(this)) }
apache-2.0
be123d41d1c538892047efe406620920
30.185567
80
0.636364
4.352518
false
false
false
false
HabitRPG/habitrpg-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/social/QuestMenuView.kt
1
3733
package com.habitrpg.android.habitica.ui.views.social import android.content.Context import android.util.AttributeSet import android.view.Gravity import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import androidx.core.content.ContextCompat import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.databinding.QuestMenuViewBinding import com.habitrpg.android.habitica.extensions.layoutInflater import com.habitrpg.android.habitica.models.inventory.Quest import com.habitrpg.android.habitica.models.inventory.QuestContent import com.habitrpg.android.habitica.models.user.User import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper import java.util.Locale class QuestMenuView : LinearLayout { private val binding = QuestMenuViewBinding.inflate(context.layoutInflater, this) private var questContent: QuestContent? = null constructor(context: Context) : super(context) { setupView(context) } constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) { setupView(context) } private fun setupView(context: Context) { orientation = VERTICAL binding.heartIconView.setImageBitmap(HabiticaIconsHelper.imageOfHeartDarkBg()) binding.rageIconView.setImageBitmap(HabiticaIconsHelper.imageOfRage()) binding.pendingDamageIconView.setImageBitmap(HabiticaIconsHelper.imageOfDamage()) /*binding.closeButton.setOnClickListener { hideBossArt() val preferences = context.getSharedPreferences("collapsible_sections", 0) preferences?.edit { putBoolean("boss_art_collapsed", true) } }*/ } fun configure(quest: Quest) { binding.healthBarView.setCurrentValue(quest.progress?.hp ?: 0.0) binding.rageBarView.setCurrentValue(quest.progress?.rage ?: 0.0) } fun configure(questContent: QuestContent) { this.questContent = questContent binding.healthBarView.setMaxValue(questContent.boss?.hp?.toDouble() ?: 0.0) binding.bossNameView.text = questContent.boss?.name binding.typeTextView.text = context.getString(R.string.boss_quest) if (questContent.boss?.hasRage == true) { binding.rageView.visibility = View.VISIBLE binding.rageBarView.setMaxValue(questContent.boss?.rage?.value ?: 0.0) } else { binding.rageView.visibility = View.GONE } } fun configure(user: User) { binding.pendingDamageTextView.text = String.format(Locale.getDefault(), "%.01f", (user.party?.quest?.progress?.up ?: 0f)) } fun hideBossArt() { binding.topView.orientation = HORIZONTAL binding.topView.setBackgroundColor(questContent?.colors?.mediumColor ?: 0) binding.bossNameView.gravity = Gravity.START binding.bossNameView.layoutParams = LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1F) // binding.bossArtView.visibility = View.GONE binding.typeTextView.setTextColor(questContent?.colors?.extraLightColor ?: 0) // binding.closeButton.visibility = View.GONE } fun showBossArt() { binding.topView.orientation = VERTICAL binding.topView.setBackgroundColor(ContextCompat.getColor(context, R.color.transparent)) binding.bossNameView.gravity = Gravity.END binding.bossNameView.layoutParams = LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) // binding.bossArtView.visibility = View.VISIBLE binding.typeTextView.setTextColor(ContextCompat.getColor(context, R.color.white)) // binding.closeButton.visibility = View.VISIBLE } }
gpl-3.0
141474d7fb6f68537a8049f8d5368d56
40.021978
130
0.723279
4.481393
false
false
false
false
HabitRPG/habitrpg-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/inventory/stable/StableFragment.kt
1
2749
package com.habitrpg.android.habitica.ui.fragments.inventory.stable import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.viewpager2.adapter.FragmentStateAdapter import com.google.android.material.tabs.TabLayoutMediator import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.components.UserComponent import com.habitrpg.android.habitica.databinding.FragmentViewpagerBinding import com.habitrpg.android.habitica.ui.fragments.BaseMainFragment class StableFragment : BaseMainFragment<FragmentViewpagerBinding>() { override var binding: FragmentViewpagerBinding? = null override fun createBinding(inflater: LayoutInflater, container: ViewGroup?): FragmentViewpagerBinding { return FragmentViewpagerBinding.inflate(inflater, container, false) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { this.usesTabLayout = true this.hidesToolbar = true return super.onCreateView(inflater, container, savedInstanceState) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding?.viewPager?.currentItem = 0 setViewPagerAdapter() } override fun injectFragment(component: UserComponent) { component.inject(this) } private fun setViewPagerAdapter() { val fragmentManager = childFragmentManager binding?.viewPager?.adapter = object : FragmentStateAdapter(fragmentManager, lifecycle) { override fun createFragment(position: Int): androidx.fragment.app.Fragment { val fragment = StableRecyclerFragment() when (position) { 0 -> { fragment.itemType = "pets" } 1 -> { fragment.itemType = "mounts" } } fragment.itemTypeText = getPageTitle(position) return fragment } override fun getItemCount(): Int { return 2 } } tabLayout?.let { binding?.viewPager?.let { it1 -> TabLayoutMediator(it, it1) { tab, position -> tab.text = getPageTitle(position) }.attach() } } } private fun getPageTitle(position: Int): String { return when (position) { 0 -> activity?.getString(R.string.pets) 1 -> activity?.getString(R.string.mounts) else -> "" } ?: "" } }
gpl-3.0
ddee1c3a92cc43e3e919577234bcdbb1
31.72619
107
0.627501
5.411417
false
false
false
false
google/playhvz
Android/ghvzApp/app/src/main/java/com/app/playhvz/navigation/SingleInstanceNavigator.kt
1
4243
/* * 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.app.playhvz.navigation import android.content.Context import android.os.Bundle import androidx.fragment.app.FragmentManager import androidx.navigation.NavDestination import androidx.navigation.NavOptions import androidx.navigation.Navigator import androidx.navigation.fragment.FragmentNavigator /** * Custom navigator class that reuses a fragment if it's already created instead of creating a new * one. Without this class (aka using the default FragmentNavigator) unexpected things happen. * * Namely, on rotation or on activity recreation when the app is resumed: * 1. The fragment that was shown calls all it's lifecycle methods * 2. That old fragment is destroyed * 3. A new fragment is created. * That's bad behavior for us because we're counting on observers only being set up once. When * onCreate() or onCreateView() is called twice we skip creating the firebase observers the second * time because we see that we're already observing the data after the first call... only thing is * the first fragment is destroyed, so effectively we aren't actually listening. * * This class checks the fragment we're trying to navigate to. If it matches the fragment we're * already showing then we just reuse that fragment instance. This ensures that onCreate() etc * will only be called once and every fragment can only have one instance on the stack. * * During development you can easily test/recreate issues by using the Android Developer setting * for "Don't keep activities". */ @Navigator.Name("single_instance_fragment") // name used in xml class SingleInstanceNavigator( private val context: Context, private val manager: FragmentManager, private val containerId: Int ) : FragmentNavigator(context, manager, containerId) { override fun navigate( destination: Destination, args: Bundle?, navOptions: NavOptions?, navigatorExtras: Navigator.Extras? ): NavDestination? { val destinationTag = destination.className val tr = manager.beginTransaction() var initialNavigate = false val currentFragment = manager.primaryNavigationFragment if (currentFragment != null && destination.className.equals(currentFragment.javaClass.name)) { // The fragment that's currently displayed is the same fragment we're trying to navigate // to. So that lifecycle methods aren't called twice, make sure to detach the existing // fragment and only use the new instance we're about to create. Note that we only want // to detach the fragment if it's the *same*, otherwise we'll mess up backstack // navigation by prematurely "popping" a valid fragment from the stack. tr.detach(currentFragment) } else { initialNavigate = true } val fragment = manager.findFragmentByTag(destinationTag) if (fragment == null) { if (initialNavigate) { // We're creating the fragment for the first time so use the super class method so that // back navigation, animations, action bar titles, etc are done correctly. tr.commitNow() // pop old fragment if necessary, otherwise no-op } return super.navigate(destination, args, navOptions, navigatorExtras) } else { tr.attach(fragment) } tr.setPrimaryNavigationFragment(fragment) tr.setReorderingAllowed(true) tr.commitNow() return if (initialNavigate) { destination } else { null } } }
apache-2.0
bbe4528e714a0a008c4e93bed7741cbe
42.306122
103
0.700683
4.827076
false
false
false
false
klazuka/intellij-elm
src/main/kotlin/org/elm/workspace/elmreview/ElmReviewJsonReport.kt
1
11122
package org.elm.workspace.elmreview import com.google.gson.stream.JsonReader import com.google.gson.stream.JsonToken data class ElmReviewError( // TODO Add a optional fix field (For later) var suppressed: Boolean? = null, var path: String? = null, var rule: String? = null, var message: String? = null, var region: Region? = null, var html: String? = null ) data class Region( var start: Location? = null, var end: Location? = null ) data class Location( var line: Int = 0, var column: Int = 0 ) sealed class Chunk { data class Unstyled(var str: String) : Chunk() data class Styled(var string: String? = null, var bold: Boolean? = null, var underline: Boolean? = null, var color: String? = null, var href: String? = null) : Chunk() } enum class ReviewOutputType(val label: String) { ERROR("error"), COMPILE_ERRORS("compile-errors"), REVIEW_ERRORS("review-errors"); companion object { fun fromLabel(label: String) = when (label) { ERROR.label -> ERROR COMPILE_ERRORS.label -> COMPILE_ERRORS REVIEW_ERRORS.label -> REVIEW_ERRORS else -> TODO("unknown type $label") } } } fun parseReviewJsonStream(reader: JsonReader, process: Process, emit: (List<ElmReviewError>) -> Unit): Int { reader.use { while (process.isAlive) { if (it.hasNext()) { val errors = it.readErrorReport() emit(errors) } } } return process.exitValue() } fun JsonReader.readProperties(propertyHandler: (String) -> Unit) { beginObject() while (hasNext()) { propertyHandler(nextName()) } endObject() } fun JsonReader.readErrorReport(): List<ElmReviewError> { val errors = mutableListOf<ElmReviewError>() if (this.peek() == JsonToken.END_DOCUMENT) return emptyList() var type: ReviewOutputType? = null readProperties { property -> when (property) { "type" -> { type = ReviewOutputType.fromLabel(nextString()) } "errors" -> { when (type) { ReviewOutputType.REVIEW_ERRORS -> { beginArray() while (hasNext()) { var currentPath: String? = null readProperties { property -> when (property) { "path" -> currentPath = nextString() "errors" -> { beginArray() while (hasNext()) { val elmReviewError = ElmReviewError(path = currentPath) readProperties { property -> when (property) { "suppressed" -> elmReviewError.suppressed = nextBoolean() "rule" -> elmReviewError.rule = nextString() "message" -> elmReviewError.message = nextString() "region" -> { elmReviewError.region = readRegion() } "formatted" -> { val chunkList = readChunkList() elmReviewError.html = chunksToHtml(chunkList) } else -> { // TODO "fix", "details", "ruleLink", "originallySuppressed" skipValue() } } } errors.add(elmReviewError) } endArray() } } } } endArray() } ReviewOutputType.COMPILE_ERRORS -> { beginArray() while (hasNext()) { var currentPath: String? = null // TODO type 'compile-errors' with property errors ARRAY !? readProperties { property -> when (property) { "path" -> currentPath = nextString() "name" -> skipValue() "problems" -> { beginArray() while (hasNext()) { val elmReviewError = ElmReviewError(path = currentPath) readProperties { property -> when (property) { "title" -> elmReviewError.rule = nextString() else -> { // TODO "fix", "details", "ruleLink", "originallySuppressed" skipValue() } } } errors.add(elmReviewError) } endArray() } } } } endArray() } ReviewOutputType.ERROR -> throw RuntimeException("Unexpected json-type 'error' with 'errors' array") null -> println("ERROR: no report 'type'") } } else -> { // TODO make resilient against property order, title is expected first ! val elmReviewError = ElmReviewError(rule = nextString()) while (hasNext()) { when (nextName()) { "path" -> elmReviewError.path = nextString() "message" -> { val chunkList = readChunkList() elmReviewError.message = chunksToLines(chunkList).joinToString("\n") } } } errors.add(elmReviewError) } } } return errors } private fun JsonReader.readChunkList(): List<Chunk> { val chunkList = mutableListOf<Chunk>() beginArray() while (hasNext()) { if (this.peek() == JsonToken.BEGIN_OBJECT) { val chunkStyled = Chunk.Styled() beginObject() while (hasNext()) { when (nextName()) { "string" -> chunkStyled.string = nextString() "color" -> chunkStyled.color = nextString() "href" -> chunkStyled.href = nextString() } } endObject() chunkList.add(chunkStyled) } else { chunkList.add(Chunk.Unstyled(nextString())) } } endArray() return chunkList } fun JsonReader.readRegion(): Region { val region = Region() beginObject() while (hasNext()) { when (nextName()) { "start" -> { val location = readLocation() region.start = location } "end" -> { val location = readLocation() region.end = location } } } endObject() return region } fun JsonReader.readLocation(): Location { val location = Location() beginObject() while (hasNext()) { when (val prop = nextName()) { "line" -> location.line = nextInt() "column" -> location.column = nextInt() else -> TODO("unexpected property $prop") } } endObject() return location } fun chunksToHtml(chunks: List<Chunk>): String = chunks.joinToString( "", prefix = "<html><body style=\"font-family: monospace; font-weight: bold\">", postfix = "</body></html>" ) { chunkToHtml(it) } fun chunkToHtml(chunk: Chunk): String = when (chunk) { is Chunk.Unstyled -> toHtmlSpan("color: #4F9DA6", chunk.str) is Chunk.Styled -> with(StringBuilder()) { append("color: ${chunk.color.adjustForDisplay()};") val str = if (chunk.href == null) { chunk.string } else { createHyperlinks(chunk.href!!, chunk.string!!) } toHtmlSpan(this, str!!) } } private fun toHtmlSpan(style: CharSequence, text: String) = """<span style="$style">${text.convertWhitespaceToHtml().createHyperlinks()}</span>""" // The Elm compiler emits HTTP URLs with angle brackets around them private val urlPattern = Regex("""<((http|https)://.*?)>""") private fun String.createHyperlinks(): String = urlPattern.replace(this) { result -> val url = result.groupValues[1] "<a href=\"$url\">$url</a>" } private fun createHyperlinks(href: String, text: String): String = "<a href=\"$href\">$text</a>" /** * The Elm compiler emits the text where the whitespace is already formatted to line up * using a fixed-width font. But HTML does its own thing with whitespace. We could use a * `<pre>` element, but then we wouldn't be able to do the color highlights and other * formatting tricks. * * The best solution would be to use the "white-space: pre" CSS rule, but the UI widget * that we use to render the HTML, [javax.swing.JTextPane], does not support it * (as best I can tell). * * So we will instead manually convert the whitespace so that it renders correctly. */ private fun String.convertWhitespaceToHtml() = replace(" ", "&nbsp;").replace("\n", "<br>") /** * Adjust the colors to make it look good */ private fun String?.adjustForDisplay(): String = when (this) { "#FF0000" -> "#FF5959" null -> "white" else -> this } private fun chunksToLines(chunks: List<Chunk>): List<String> { return chunks.asSequence().map { when (it) { is Chunk.Unstyled -> it.str is Chunk.Styled -> it.string } }.joinToString("").lines() }
mit
289ccadaa59703c81a3947da2d6138f5
36.701695
171
0.440658
5.478818
false
false
false
false
andstatus/andstatus
app/src/main/kotlin/org/andstatus/app/actor/ActorsLoader.kt
1
4828
package org.andstatus.app.actor import android.database.Cursor import android.net.Uri import android.provider.BaseColumns import org.andstatus.app.R import org.andstatus.app.account.MyAccount import org.andstatus.app.context.MyContext import org.andstatus.app.context.MyPreferences import org.andstatus.app.data.ActorSql import org.andstatus.app.data.MatchedUri import org.andstatus.app.data.SqlIds import org.andstatus.app.data.SqlWhere import org.andstatus.app.database.table.ActorTable import org.andstatus.app.list.SyncLoader import org.andstatus.app.net.social.Actor import org.andstatus.app.origin.Origin import org.andstatus.app.timeline.LoadableListActivity.ProgressPublisher import org.andstatus.app.util.MyLog import org.andstatus.app.util.StopWatch import java.util.stream.Collectors open class ActorsLoader(val myContext: MyContext, protected val actorsScreenType: ActorsScreenType, protected val origin: Origin, protected val centralActorId: Long, private val searchQuery: String) : SyncLoader<ActorViewItem>() { protected val ma: MyAccount = myContext.accounts.getFirstPreferablySucceededForOrigin(origin) protected var mAllowLoadingFromInternet = false @Volatile private var centralActor: Actor = Actor.EMPTY private var mProgress: ProgressPublisher? = null override fun allowLoadingFromInternet() { mAllowLoadingFromInternet = ma.isValidAndSucceeded() } override fun load(publisher: ProgressPublisher?) : SyncLoader<ActorViewItem> { val method = "load" val stopWatch: StopWatch = StopWatch.createStarted() if (MyLog.isDebugEnabled()) { MyLog.d(this, "$method started") } mProgress = publisher centralActor = Actor.load(myContext, centralActorId) loadInternal() if (MyLog.isDebugEnabled()) { MyLog.d(this, "Loaded " + size() + " items, " + stopWatch.time + "ms") } if (items.isEmpty()) { items.add(ActorViewItem.newEmpty(myContext.context .getText(R.string.nothing_in_the_loadable_list).toString())) } return this } fun addActorIdToList(origin: Origin, actorId: Long): Actor { return if (actorId == 0L) Actor.EMPTY else addActorToList(Actor.fromId(origin, actorId)) } fun addActorToList(actor: Actor): Actor { if (actor.isEmpty) return Actor.EMPTY val item: ActorViewItem = ActorViewItem.fromActor(actor) val existing = items.indexOf(item) if (existing >= 0) return items[existing].actor items.add(item) if (actor.actorId == 0L && mAllowLoadingFromInternet) actor.requestDownload(false) mProgress?.publish(Integer.toString(size())) return actor } protected open fun loadInternal() { val mContentUri: Uri = MatchedUri.getActorsScreenUri(actorsScreenType, origin.id, centralActorId, searchQuery) myContext.context.contentResolver .query(mContentUri, ActorSql.baseProjection(), getSelection(), null, null).use { c -> while (c != null && c.moveToNext()) { populateItem(c) } } } protected open fun getSelection(): String { val where = SqlWhere() val sqlActorIds = getSqlActorIds() if (!sqlActorIds.isNullOrEmpty()) { where.append(ActorTable.TABLE_NAME + "." + BaseColumns._ID + sqlActorIds) } else if (origin.isValid) { where.append(ActorTable.TABLE_NAME + "." + ActorTable.ORIGIN_ID + "=" + origin.id) } return where.getCondition() } private fun populateItem(cursor: Cursor) { val item: ActorViewItem = ActorViewItem.EMPTY.fromCursor(myContext, cursor) if (actorsScreenType == ActorsScreenType.FRIENDS) { item.hideFollowedBy(centralActor) } if (actorsScreenType == ActorsScreenType.FOLLOWERS) { item.hideFollowing(centralActor) } val index = items.indexOf(item) if (index < 0) { items.add(item) } else { items[index] = item } } protected open fun getSqlActorIds(): String? { val sqlIds: SqlIds = SqlIds.fromIds(items.stream().map { obj: ActorViewItem -> obj.getId() }.collect(Collectors.toList())) return if (sqlIds.isEmpty) "" else sqlIds.getSql() } open fun getSubtitle(): String? { return if (MyPreferences.isShowDebuggingInfoInUi()) actorsScreenType.toString() else "" } override fun toString(): String { return (actorsScreenType.toString() + "; central=" + centralActorId + "; " + super.toString()) } }
apache-2.0
d35d3f530a36ec7c5bc6926272f79daf
37.935484
130
0.650373
4.457987
false
false
false
false
andstatus/andstatus
app/src/androidTest/kotlin/org/andstatus/app/data/ApplicationDataUtil.kt
1
3495
/* * Copyright (C) 2021 yvolk (Yuri Volkov), http://yurivolkov.com * * 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.andstatus.app.data import android.accounts.AccountManager import android.accounts.AuthenticatorException import android.accounts.OperationCanceledException import android.content.Context import org.andstatus.app.account.AccountUtils import org.andstatus.app.context.MyContextHolder import org.andstatus.app.context.MyStorage import org.andstatus.app.context.TestSuite import org.andstatus.app.service.MyServiceManager import org.andstatus.app.util.FileUtils import org.andstatus.app.util.MyLog import org.andstatus.app.util.SharedPreferencesUtil import org.andstatus.app.util.TriState import org.junit.Assert import java.io.File import java.util.* import java.util.concurrent.TimeUnit object ApplicationDataUtil { fun deleteApplicationData() { MyServiceManager.setServiceUnavailable() deleteAccounts() val context: Context = MyContextHolder.myContextHolder.getNow().context MyContextHolder.myContextHolder.release { "deleteApplicationData" } deleteFiles(context, false) deleteFiles(context, true) SharedPreferencesUtil.resetHasSetDefaultValues() Assert.assertEquals(TriState.FALSE, MyStorage.isApplicationDataCreated()) TestSuite.onDataDeleted() } private fun deleteAccounts() { val am = AccountManager.get(MyContextHolder.myContextHolder.getNow().context) val aa = AccountUtils.getCurrentAccounts(MyContextHolder.myContextHolder.getNow().context) for (androidAccount in aa) { val logMsg = "Removing old account: " + androidAccount.name MyLog.i(this, logMsg) val amf = am.removeAccount(androidAccount, null, null) try { amf.getResult(10, TimeUnit.SECONDS) } catch (e: OperationCanceledException) { throw Exception(logMsg + ", " + e.message, e) } catch (e: AuthenticatorException) { throw Exception(logMsg + ", " + e.message, e) } } } private fun deleteFiles(context: Context, useExternalStorage: Boolean) { FileUtils.deleteFilesRecursively(MyStorage.getDataFilesDir(MyStorage.DIRECTORY_DOWNLOADS, TriState.Companion.fromBoolean(useExternalStorage))) FileUtils.deleteFilesRecursively(MyStorage.getDataFilesDir(MyStorage.DIRECTORY_DATABASES, TriState.Companion.fromBoolean(useExternalStorage))) FileUtils.deleteFilesRecursively(SharedPreferencesUtil.prefsDirectory(context)) } fun ensureOneFileExistsInDownloads() { val downloads = MyStorage.getDataFilesDir(MyStorage.DIRECTORY_DOWNLOADS) ?: throw IllegalStateException("No downloads") if (Arrays.stream(downloads.listFiles()).noneMatch { obj: File -> obj.isFile }) { val dummyFile = File(downloads, "dummy.txt") dummyFile.createNewFile() } } }
apache-2.0
572ef5ba54173447c09ce0ed618cbb25
42.148148
150
0.725608
4.703903
false
false
false
false
google/android-auto-companion-android
communication/tests/unit/src/com/google/android/libraries/car/notifications/NotificationAccessUtilsTest.kt
1
3811
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.android.libraries.car.notifications import android.content.Context import android.content.Intent.FLAG_ACTIVITY_NEW_TASK import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import com.google.android.libraries.car.notifications.NotificationAccessUtils.EXTRA_FRAGMENT_ARG_KEY import com.google.android.libraries.car.notifications.NotificationAccessUtils.EXTRA_SHOW_FRAGMENT_ARGS_KEY import com.google.android.libraries.car.notifications.NotificationAccessUtils.MAXIMUM_NOTIFICATION_ACCESS_ITERATIONS import com.google.android.libraries.car.notifications.NotificationAccessUtils.NOTIFICATION_ACCESS_CHECK_TIME_MS import com.google.android.libraries.car.notifications.NotificationAccessUtils.getNotificationPermissionIntentWithHighlighted import com.google.android.libraries.car.notifications.NotificationAccessUtils.hasNotificationAccess import com.google.android.libraries.car.notifications.SettingsNotificationHelper.grantNotificationAccess import com.google.android.libraries.car.notifications.SettingsNotificationHelper.notificationListenerComponentName import com.google.android.libraries.car.notifications.SettingsNotificationHelper.revokeAllNotificationAccess import com.google.common.truth.Truth.assertThat import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import org.junit.Before import org.junit.Ignore import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith /** Tests for [NotificationAccessUtils]. */ @ExperimentalCoroutinesApi @RunWith(AndroidJUnit4::class) class NotificationAccessUtilsTest { private val context: Context = ApplicationProvider.getApplicationContext() @get:Rule val coroutinesTestRule = CoroutineTestRule() @Before fun setup() { revokeAllNotificationAccess(context.contentResolver) } @Test fun expectedSetupState() { assertThat(hasNotificationAccess(context)).isFalse() } @Test fun getNotificationPermissionIntentWithHighlighted_notificationListenerInBundle() { val intent = getNotificationPermissionIntentWithHighlighted(context) val extra = intent.getBundleExtra(EXTRA_SHOW_FRAGMENT_ARGS_KEY) assertThat(intent.flags or FLAG_ACTIVITY_NEW_TASK).isNotEqualTo(0) assertThat(extra?.getString(EXTRA_FRAGMENT_ARG_KEY)) .isEqualTo(notificationListenerComponentName(context)) } @Test @Ignore // TODO(b/215427836): Fails under coroutines 1.6.0: runBlocking hangs until timeout fun requestNotificationAccess_pollsForAccessGranted() { var granted = false val coroutineScope = CoroutineScope(coroutinesTestRule.testDispatcher).launch { granted = NotificationAccessUtils.requestNotificationAccess(context) } assertThat(granted).isFalse() grantNotificationAccess(context) runBlocking { coroutineScope.join() } assertThat(hasNotificationAccess(context)).isTrue() assertThat(granted).isTrue() } @Test fun pollForAccessGranted_maximumIterationTime() { assertThat(NOTIFICATION_ACCESS_CHECK_TIME_MS).isEqualTo(1000L) assertThat(MAXIMUM_NOTIFICATION_ACCESS_ITERATIONS).isEqualTo(50) } }
apache-2.0
145de892a4417df15e5946d7ea722161
42.306818
124
0.815796
4.515403
false
true
false
false
kenrube/Fantlab-client
app/src/main/kotlin/ru/fantlab/android/ui/adapter/viewholder/UserMarkViewHolder.kt
2
1800
package ru.fantlab.android.ui.adapter.viewholder import android.view.View import android.view.ViewGroup import kotlinx.android.synthetic.main.profile_mark_row_item.view.* import ru.fantlab.android.R import ru.fantlab.android.data.dao.model.Mark import ru.fantlab.android.helper.getTimeAgo import ru.fantlab.android.helper.parseFullDate import ru.fantlab.android.provider.storage.WorkTypesProvider import ru.fantlab.android.ui.widgets.recyclerview.BaseRecyclerAdapter import ru.fantlab.android.ui.widgets.recyclerview.BaseViewHolder class UserMarkViewHolder(itemView: View, adapter: BaseRecyclerAdapter<Mark, UserMarkViewHolder>) : BaseViewHolder<Mark>(itemView, adapter) { override fun bind(mark: Mark) { itemView.coverLayout.setUrl("https:${mark.workImage}", WorkTypesProvider.getCoverByTypeId(mark.workTypeId)) itemView.authors.text = mark.workAuthor itemView.title.text = if (mark.workName.isNotEmpty()) { mark.workName } else { mark.workNameOrig } itemView.type.text = mark.workType.capitalize() itemView.date.text = mark.dateIso.parseFullDate(true).getTimeAgo() if (mark.workYear != 0) { itemView.year.text = mark.workYear.toString() + " г." itemView.year.visibility = View.VISIBLE } else itemView.year.visibility = View.GONE itemView.ratingBar.rating = mark.mark.toFloat() itemView.rateMark.text = mark.mark.toString() itemView.classified.visibility = if (mark.userClassifiedWork == 1) View.VISIBLE else View.GONE itemView.response.visibility = if (mark.userResponseWork == 1) View.VISIBLE else View.GONE } companion object { fun newInstance( viewGroup: ViewGroup, adapter: BaseRecyclerAdapter<Mark, UserMarkViewHolder> ): UserMarkViewHolder = UserMarkViewHolder(getView(viewGroup, R.layout.profile_mark_row_item), adapter) } }
gpl-3.0
91174ed9b1dce69db01aa9805d83e7b1
37.297872
109
0.780434
3.619718
false
false
false
false
stfalcon-studio/uaroads_android
app/src/main/java/com/stfalcon/new_uaroads_android/common/database/RealmService.kt
1
4069
/* * Copyright (c) 2017 stfalcon.com * * 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.stfalcon.new_uaroads_android.common.database import com.stfalcon.new_uaroads_android.common.database.models.PointRealm import com.stfalcon.new_uaroads_android.common.database.models.TrackRealm import com.stfalcon.new_uaroads_android.features.record.managers.Point import io.realm.Realm import io.realm.RealmResults import java.text.SimpleDateFormat import java.util.* /* * Created by Anton Bevza on 4/25/17. */ class RealmService(val realm: Realm) { fun createTrack(id: String, isAutoRecord: Boolean) { realm.executeTransactionAsync { realm -> val dateFormat = SimpleDateFormat("dd.MM.yyyy HH:mm", Locale.getDefault()) val track = realm.createObject(TrackRealm::class.java, id) track.status = TrackRealm.STATUS_IS_RECODING track.comment = dateFormat.format(Date()) track.timestamp = System.currentTimeMillis() track.autoRecord = if (isAutoRecord) 1 else 0 } } fun getTrack(id: String): TrackRealm { return realm.where(TrackRealm::class.java) .equalTo("id", id).findFirst() } fun getAllTracks(): RealmResults<TrackRealm> { return realm.where(TrackRealm::class.java) .findAllSorted("timestamp") } fun getAllTracksDistance(): Int { return realm.where(TrackRealm::class.java) .findAll() .map { it.distance } .sum() } fun getAllRecordedTracks(): RealmResults<TrackRealm> { return realm.where(TrackRealm::class.java) .notEqualTo("status", TrackRealm.STATUS_IS_RECODING) .findAllSorted("timestamp") } fun getAllUnsentTracks(): RealmResults<TrackRealm> { return realm.where(TrackRealm::class.java) .equalTo("status", TrackRealm.STATUS_NOT_SENT) .findAll() } fun getLastTrackDistance(): Int { return realm.where(TrackRealm::class.java) .notEqualTo("status", TrackRealm.STATUS_IS_RECODING) .findAllSorted("timestamp") .last(null)?.distance ?: 0 } fun deleteTrack(id: String) { realm.executeTransaction { it.where(TrackRealm::class.java). equalTo("id", id).findFirst()?.deleteFromRealm() } } fun updateTrackStatus(id: String, status: Int) { realm.executeTransactionAsync { it.where(TrackRealm::class.java) .equalTo("id", id) .findFirst() .status = status } } fun updateTrackDistance(id: String, distance: Int) { realm.executeTransactionAsync { it.where(TrackRealm::class.java) .equalTo("id", id) .findFirst() .distance = distance } } fun savePoints(trackId: String, points: MutableList<Point>) { realm.executeTransactionAsync { realm -> val track = realm.where(TrackRealm::class.java).equalTo("id", trackId).findFirst() if (track != null) { points.forEach { val realmPoint = realm.createObject(PointRealm::class.java) realmPoint.convertFromPoint(it) track.points.add(realmPoint) } } } } fun closeRealm() { realm.close() } }
apache-2.0
6c31e42340804f5a2107aedc13200b15
32.636364
94
0.604571
4.418024
false
false
false
false
inorichi/tachiyomi-extensions
src/vi/blogtruyen/src/eu/kanade/tachiyomi/extension/vi/blogtruyen/BlogTruyen.kt
1
9271
package eu.kanade.tachiyomi.extension.vi.blogtruyen 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.MangasPage 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 eu.kanade.tachiyomi.util.asJsoup import okhttp3.Headers import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import org.jsoup.nodes.Document import org.jsoup.nodes.Element import java.text.SimpleDateFormat import java.util.Locale class BlogTruyen : ParsedHttpSource() { override val name = "BlogTruyen" override val baseUrl = "https://blogtruyen.vn" override val lang = "vi" override val supportsLatest = true override val client: OkHttpClient = network.cloudflareClient override fun headersBuilder(): Headers.Builder = super.headersBuilder().add("Referer", baseUrl) override fun popularMangaSelector() = "div.list span.tiptip.fs-12.ellipsis" override fun latestUpdatesSelector() = "section.list-mainpage.listview > div > div > div > div.fl-l" override fun popularMangaRequest(page: Int): Request { return GET("$baseUrl/ajax/Search/AjaxLoadListManga?key=tatca&orderBy=3&p=$page", headers) } override fun latestUpdatesRequest(page: Int): Request { return GET("$baseUrl/page-$page", headers) } override fun popularMangaParse(response: Response): MangasPage { val document = response.asJsoup() val imgURL = document.select("img").map { it.attr("abs:src") } val mangas = document.select(popularMangaSelector()).mapIndexed { index, element -> popularMangaFromElement(element, imgURL[index]) } val hasNextPage = popularMangaNextPageSelector().let { selector -> document.select(selector).first() } != null return MangasPage(mangas, hasNextPage) } private fun popularMangaFromElement(element: Element, imgURL: String): SManga { val manga = SManga.create() element.select("a").first().let { manga.setUrlWithoutDomain(it.attr("href")) manga.title = it.text().trim() manga.thumbnail_url = imgURL } return manga } override fun popularMangaFromElement(element: Element): SManga = throw Exception("Not Used") override fun latestUpdatesFromElement(element: Element): SManga { val manga = SManga.create() element.select("a").first().let { manga.setUrlWithoutDomain(it.attr("href")) manga.title = element.select("img").first().attr("alt").toString().trim() manga.thumbnail_url = element.select("img").first().attr("abs:src") } return manga } override fun popularMangaNextPageSelector() = "div.paging:last-child:not(.current_page)" override fun latestUpdatesNextPageSelector() = "ul.pagination.paging.list-unstyled > li:nth-last-child(2) > a" override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { var temp = "$baseUrl/timkiem/nangcao/1/0" val genres = mutableListOf<Int>() val genresEx = mutableListOf<Int>() var aut = "" (if (filters.isEmpty()) getFilterList() else filters).forEach { filter -> when (filter) { is GenreList -> filter.state.forEach { genre -> when (genre.state) { Filter.TriState.STATE_INCLUDE -> genres.add(genre.id) Filter.TriState.STATE_EXCLUDE -> genresEx.add(genre.id) } } is Author -> { if (filter.state.isNotEmpty()) { aut = filter.state } } } } temp = if (genres.isNotEmpty()) temp + "/" + genres.joinToString(",") else "$temp/-1" temp = if (genresEx.isNotEmpty()) temp + "/" + genresEx.joinToString(",") else "$temp/-1" val url = temp.toHttpUrlOrNull()!!.newBuilder() url.addQueryParameter("txt", query) if (aut.isNotEmpty()) url.addQueryParameter("aut", aut) url.addQueryParameter("p", page.toString()) return GET(url.toString().replace("m.", ""), headers) } override fun searchMangaSelector() = "div.list > p:has(a)" override fun searchMangaFromElement(element: Element): SManga { return SManga.create().apply { element.select("a").let { setUrlWithoutDomain(it.attr("href")) title = it.text() } thumbnail_url = element.nextElementSibling().select("img").attr("abs:src") } } override fun searchMangaNextPageSelector() = "ul.pagination i.glyphicon.glyphicon-step-forward.red" override fun mangaDetailsParse(document: Document): SManga { val infoElement = document.select("div.description").first() val manga = SManga.create() manga.author = infoElement.select("p:contains(Tác giả) > a").first()?.text() manga.genre = infoElement.select("span.category a").joinToString { it.text() } manga.description = document.select("div.detail > div.content").text() manga.status = infoElement.select("p:contains(Trạng thái) > span.color-red").first()?.text().orEmpty().let { parseStatus(it) } manga.thumbnail_url = document.select("div.thumbnail > img").first()?.attr("src") return manga } private fun parseStatus(status: String) = when { status.contains("Đang tiến hành") -> SManga.ONGOING status.contains("Đã hoàn thành") -> SManga.COMPLETED else -> SManga.UNKNOWN } override fun chapterListSelector() = "div.list-wrap > p" override fun chapterFromElement(element: Element): SChapter { val urlElement = element.select("span > a").first() val chapter = SChapter.create() chapter.setUrlWithoutDomain(urlElement.attr("href")) chapter.name = urlElement.attr("title").trim() chapter.date_upload = element.select("span.publishedDate").first()?.text()?.let { SimpleDateFormat("dd/MM/yyyy HH:mm", Locale.ENGLISH).parse(it)?.time ?: 0 } ?: 0 return chapter } override fun pageListRequest(chapter: SChapter) = GET(baseUrl + chapter.url, headers) override fun pageListParse(document: Document): List<Page> { val pages = mutableListOf<Page>() val pageUrl = document.select("link[rel=canonical]").attr("href") document.select("article#content > img").forEachIndexed { i, e -> pages.add(Page(i, pageUrl, e.attr("src"))) } return pages } override fun imageUrlParse(document: Document) = "" private class Status : Filter.Select<String>("Status", arrayOf("Sao cũng được", "Đang tiến hành", "Đã hoàn thành", "Tạm ngưng")) private class Author : Filter.Text("Tác giả") private class Genre(name: String, val id: Int) : Filter.TriState(name) private class GenreList(genres: List<Genre>) : Filter.Group<Genre>("Thể loại", genres) override fun getFilterList() = FilterList( Status(), GenreList(getGenreList()), Author() ) private fun getGenreList() = listOf( Genre("16+", 54), Genre("18+", 45), Genre("Action", 1), Genre("Adult", 2), Genre("Adventure", 3), Genre("Anime", 4), Genre("Comedy", 5), Genre("Comic", 6), Genre("Doujinshi", 7), Genre("Drama", 49), Genre("Ecchi", 48), Genre("Even BT", 60), Genre("Fantasy", 50), Genre("Game", 61), Genre("Gender Bender", 51), Genre("Harem", 12), Genre("Historical", 13), Genre("Horror", 14), Genre("Isekai/Dị Giới", 63), Genre("Josei", 15), Genre("Live Action", 16), Genre("Magic", 46), Genre("Manga", 55), Genre("Manhua", 17), Genre("Manhwa", 18), Genre("Martial Arts", 19), Genre("Mature", 20), Genre("Mecha", 21), Genre("Mystery", 22), Genre("Nấu ăn", 56), Genre("NTR", 62), Genre("One shot", 23), Genre("Psychological", 24), Genre("Romance", 25), Genre("School Life", 26), Genre("Sci-fi", 27), Genre("Seinen", 28), Genre("Shoujo", 29), Genre("Shoujo Ai", 30), Genre("Shounen", 31), Genre("Shounen Ai", 32), Genre("Slice of Life", 33), Genre("Smut", 34), Genre("Soft Yaoi", 35), Genre("Soft Yuri", 36), Genre("Sports", 37), Genre("Supernatural", 38), Genre("Tạp chí truyện tranh", 39), Genre("Tragedy", 40), Genre("Trap", 58), Genre("Trinh thám", 57), Genre("Truyện scan", 41), Genre("Video clip", 53), Genre("VnComic", 42), Genre("Webtoon", 52), Genre("Yuri", 59) ) }
apache-2.0
e5b131bad795ad631d6dae4967951b03
36.323887
141
0.607984
4.186649
false
false
false
false
hotchemi/tiamat
compiler/src/main/kotlin/tiamat/compiler/Utils.kt
1
1403
package tiamat.compiler import tiamat.Pref import java.util.* import javax.annotation.processing.RoundEnvironment import javax.lang.model.element.TypeElement import javax.lang.model.util.Elements fun parseEnv(env: RoundEnvironment, elementUtils: Elements): List<PrefsModel> { val models = env.getElementsAnnotatedWith(Pref::class.java).map { PrefsModel(it as TypeElement, elementUtils) } validateSchemaModel(models) return models } fun validateSchemaModel(models: List<PrefsModel>) { val tableNames = HashSet<String>() models.forEach { val tableName = it.tableName if (tableName.isEmpty()) { throw TableNameNotDefinedException(it.originalClassName) } if (tableNames.contains(tableName)) { throw TableNameDuplicateException(tableName) } tableNames.add(tableName) } } fun getPackageName(elementUtils: Elements, type: TypeElement) = elementUtils.getPackageOf(type).qualifiedName.toString() fun getClassName(type: TypeElement, packageName: String) = type.qualifiedName.toString().substring(packageName.length + 1).replace('.', '$') // Exceptions class TableNameDuplicateException(tableName: String) : RuntimeException("table name $tableName is already defined") class TableNameNotDefinedException(className: String) : RuntimeException("$className should define table name")
apache-2.0
48bd53a14af6c296ea31442d412914de
32.404762
115
0.735567
4.6
false
false
false
false
osama-raddad/FireCrasher
firecrasher/src/main/java/com/osama/firecrasher/FireCrasher.kt
1
4163
package com.osama.firecrasher import android.app.Activity import android.app.Application import android.content.Intent object FireCrasher { var retryCount: Int = 0 private set private val crashHandler: CrashHandler by lazy { CrashHandler() } fun install(application: Application, crashListener: CrashListener) { if (FireLooper.isSafe) return crashHandler.setCrashListener(crashListener) application.registerActivityLifecycleCallbacks(crashHandler.lifecycleCallbacks) FireLooper.install() FireLooper.setUncaughtExceptionHandler(crashHandler) Thread.setDefaultUncaughtExceptionHandler(crashHandler) } fun evaluate(): CrashLevel { return when { retryCount <= 1 -> //try to restart the failing activity CrashLevel.LEVEL_ONE crashHandler.backStackCount >= 1 -> //failure in restarting the activity try to go back CrashLevel.LEVEL_TWO else -> //no activates to go back to so just restart the app CrashLevel.LEVEL_THREE } } fun evaluateAsync(onEvaluate: ((activity: Activity?, level: CrashLevel) -> Unit)?) { when { retryCount <= 1 -> //try to restart the failing activity onEvaluate?.invoke(crashHandler.activity, CrashLevel.LEVEL_ONE) crashHandler.backStackCount >= 1 -> //failure in restarting the activity try to go back onEvaluate?.invoke(crashHandler.activity, CrashLevel.LEVEL_TWO) else -> //no activates to go back to so just restart the app onEvaluate?.invoke(crashHandler.activity, CrashLevel.LEVEL_THREE) } } fun recover(level: CrashLevel = evaluate(), onRecover: ((activity: Activity?) -> Unit)?) { val activityPair = getActivityPair() when (level) { //try to restart the failing activity CrashLevel.LEVEL_ONE -> { restartActivity(activityPair) } //failure in restarting the activity try to go back CrashLevel.LEVEL_TWO -> { retryCount = 0 goBack(activityPair) } //no activates to go back to so just restart the app CrashLevel.LEVEL_THREE -> { retryCount = 0 restartApp(activityPair) } } onRecover?.invoke(crashHandler.activity) } private fun getActivityPair(): Pair<Activity?, Intent?> { val activity: Activity? = crashHandler.activity val intent: Intent? = if (activity?.intent?.action == "android.intent.action.MAIN") Intent(activity, activity.javaClass) else activity?.intent intent?.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION) return Pair(activity, intent) } private fun restartActivity(activityPair: Pair<Activity?, Intent?>) { val activity = activityPair.first ?: run { retryCount += 1 return } when (retryCount) { 0 -> activity.recreate() else -> { activity.startActivity(activityPair.second) activity.overridePendingTransition(0, 0) activity.finish() activity.overridePendingTransition(0, 0) } } retryCount += 1 } private fun goBack(activityPair: Pair<Activity?, Intent?>) { activityPair.first?.onBackPressed() } private fun restartApp(activityPair: Pair<Activity?, Intent?>) { val activity = activityPair.first ?: return val packageName = activity.baseContext.packageName activity.baseContext.packageManager.getLaunchIntentForPackage(packageName)?.let { intent -> intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) activity.startActivity(intent) } with(activity) { overridePendingTransition(0, 0) finish() overridePendingTransition(0, 0) } } }
apache-2.0
a4fd1418c7878aa3dbbac9d67bd585af
32.845528
99
0.595724
5.152228
false
false
false
false
PoweRGbg/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationFragment.kt
3
4092
package info.nightscout.androidaps.plugins.general.automation import android.os.Bundle import android.text.method.ScrollingMovementMethod import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import info.nightscout.androidaps.R import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.general.automation.dialogs.EditEventDialog import info.nightscout.androidaps.plugins.general.automation.dragHelpers.OnStartDragListener import info.nightscout.androidaps.plugins.general.automation.dragHelpers.SimpleItemTouchHelperCallback import info.nightscout.androidaps.plugins.general.automation.events.EventAutomationDataChanged import info.nightscout.androidaps.plugins.general.automation.events.EventAutomationUpdateGui import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.plusAssign import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import kotlinx.android.synthetic.main.automation_fragment.* class AutomationFragment : Fragment(), OnStartDragListener { private var disposable: CompositeDisposable = CompositeDisposable() private var eventListAdapter: EventListAdapter? = null private var itemTouchHelper: ItemTouchHelper? = null override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.automation_fragment, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) eventListAdapter = EventListAdapter(AutomationPlugin.automationEvents, fragmentManager, activity, this) automation_eventListView.layoutManager = LinearLayoutManager(context) automation_eventListView.adapter = eventListAdapter automation_logView.setMovementMethod(ScrollingMovementMethod()) automation_fabAddEvent.setOnClickListener { val dialog = EditEventDialog() val args = Bundle() args.putString("event", AutomationEvent().toJSON()) args.putInt("position", -1) // New event dialog.arguments = args fragmentManager?.let { dialog.show(it, "EditEventDialog") } } val callback: ItemTouchHelper.Callback = SimpleItemTouchHelperCallback(eventListAdapter!!) itemTouchHelper = ItemTouchHelper(callback) itemTouchHelper?.attachToRecyclerView(automation_eventListView) } @Synchronized override fun onResume() { super.onResume() disposable += RxBus .toObservable(EventAutomationUpdateGui::class.java) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ updateGui() }, { FabricPrivacy.logException(it) }) disposable += RxBus .toObservable(EventAutomationDataChanged::class.java) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ eventListAdapter?.notifyDataSetChanged() }, { FabricPrivacy.logException(it) }) updateGui() } @Synchronized override fun onPause() { super.onPause() disposable.clear() } @Synchronized private fun updateGui() { eventListAdapter?.notifyDataSetChanged() val sb = StringBuilder() for (l in AutomationPlugin.executionLog.reversed()) sb.append(l).append("<br>") automation_logView?.text = HtmlHelper.fromHtml(sb.toString()) } override fun onStartDrag(viewHolder: RecyclerView.ViewHolder) { itemTouchHelper?.startDrag(viewHolder); } }
agpl-3.0
8eaadf7cb3552c5f60869626127bcb8c
39.117647
116
0.719941
5.412698
false
false
false
false
elect86/jAssimp
src/test/kotlin/assimp/obj/box.kt
2
5349
package assimp.obj import assimp.* import glm_.mat4x4.Mat4 import glm_.vec3.Vec3 import io.kotest.matchers.shouldBe /** * Created by elect on 16/11/2016. */ object box { operator fun invoke(fileName: String) { Importer().testURLs(getResource(fileName)) { with(rootNode) { name shouldBe "box.obj" transformation shouldBe Mat4() numChildren shouldBe 1 with(children[0]) { name shouldBe "1" transformation shouldBe Mat4() numChildren shouldBe 0 numMeshes shouldBe 1 meshes[0] shouldBe 0 } numMeshes shouldBe 0 } numMeshes shouldBe 1 with(meshes[0]) { primitiveTypes shouldBe AiPrimitiveType.POLYGON.i numVertices shouldBe 24 numFaces shouldBe 6 vertices[0] shouldBe Vec3(-0.5, +0.5, +0.5) vertices[5] shouldBe Vec3(+0.5, -0.5, -0.5) vertices[10] shouldBe Vec3(+0.5, -0.5, -0.5) vertices[15] shouldBe Vec3(-0.5, +0.5, +0.5) vertices[20] shouldBe Vec3(+0.5, -0.5, -0.5) vertices[23] shouldBe Vec3(+0.5, -0.5, +0.5) var i = 0 faces.forEach { it.size shouldBe 4 it shouldBe mutableListOf(i++, i++, i++, i++) } } with(materials[0]) { name shouldBe AI_DEFAULT_MATERIAL_NAME shadingModel shouldBe AiShadingMode.gouraud color!!.apply { ambient shouldBe Vec3() diffuse shouldBe Vec3(0.6) specular shouldBe Vec3() emissive shouldBe Vec3() shininess shouldBe 0f opacity shouldBe 1f refracti shouldBe 1f } } } } // val concavePolygon = "concave_polygon.obj" TODO // // concavePolygon // { // // with(Importer().readFile(obj + concavePolygon)!!) { // // with(rootNode) { // // name shouldBe "concave_polygon.obj" // transformation shouldBe Mat4() // numChildren shouldBe 2 // // with(children[0]) { // // name shouldBe "concave_test.obj" // transformation shouldBe Mat4() // parent === rootNode // numChildren shouldBe 0 // numMeshes shouldBe 0 // } // with(children[1]) { // // name shouldBe "default" // transformation shouldBe Mat4() // parent === rootNode // numChildren shouldBe 0 // numMeshes shouldBe 1 // meshes[0] shouldBe 0 // } // } // with(meshes[0]) { // // primitiveTypes shouldBe AiPrimitiveType.POLYGON.i // numVertices shouldBe 66 // numFaces shouldBe 1 // // vertices[0] shouldBe Vec3(-1.14600003, 2.25515008, 3.07623005) // vertices[10] shouldBe Vec3(-1.14600003, 1.78262997, 1.93549001) // vertices[20] shouldBe Vec3(-1.14600003, 3.01736999, 1.93549001) // vertices[30] shouldBe Vec3(-1.14600003, 2.54485, 3.07623005) // vertices[40] shouldBe Vec3(-1.14600003, 3.08750010, 2.34999990) // vertices[50] shouldBe Vec3(-1.14600003, 2.13690996, 1.71483) // vertices[60] shouldBe Vec3(-1.14600003, 1.91386, 2.83613992) // vertices[65] shouldBe Vec3(-1.14600003, 2.40000010, 3.0905) // // normals.forEach { it shouldBe Vec3(1, 0, -0.0) } // var i = 0 // faces[0].forEach { it shouldBe i++ } // // materialIndex shouldBe 1 // // name shouldBe "default" // } // numMaterials shouldBe 2 // // with(materials[0]) { // // name shouldBe "DefaultMaterial" // // shadingModel shouldBe AiShadingMode.gouraud // // with(color!!) { // // ambient!! shouldBe Vec3(0) // diffuse!! shouldBe Vec3(0.600000024) // specular!! shouldBe Vec3(0) // emissive!! shouldBe Vec3(0) // shininess!! shouldBe 0f // opacity!! shouldBe 1f // refracti!! shouldBe 1f // } // } // // with(materials[1]) { // // name shouldBe "test" // // shadingModel shouldBe AiShadingMode.gouraud // // with(color!!) { // // ambient!! shouldBe Vec3(0) // diffuse!! shouldBe Vec3(0.141176000, 0.184313998, 0.411765009) // specular!! shouldBe Vec3(0) // emissive!! shouldBe Vec3(0) // shininess!! shouldBe 400f // opacity!! shouldBe 1f // refracti!! shouldBe 1f // } // } // } // } }
mit
be58e50f1036e17b38ea50c3a60daff9
31.822086
84
0.459151
4.262151
false
false
false
false
walleth/walleth
app/src/online/java/org/walleth/dataprovider/BlockScoutParser.kt
1
573
package org.walleth.dataprovider import org.json.JSONArray class ParseResult(val list: List<String>, val highestBlock: Long) fun parseEtherscanTransactionList(jsonArray: JSONArray): ParseResult { var lastBlockNumber = 0L val list = (0 until jsonArray.length()).map { val transactionJson = jsonArray.getJSONObject(it) val blockNumber = transactionJson.getString("blockNumber").toLong() lastBlockNumber = Math.max(blockNumber, lastBlockNumber) transactionJson.getString("hash") } return ParseResult(list, lastBlockNumber) }
gpl-3.0
c4840a22d6f63969519b2d67e4fb8738
34.8125
75
0.739965
4.407692
false
false
false
false
NerdNumber9/TachiyomiEH
app/src/main/java/eu/kanade/tachiyomi/extension/util/ExtensionLoader.kt
2
7127
package eu.kanade.tachiyomi.extension.util import android.annotation.SuppressLint import android.content.Context import android.content.pm.PackageInfo import android.content.pm.PackageManager import dalvik.system.PathClassLoader import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.data.preference.getOrDefault import eu.kanade.tachiyomi.extension.model.Extension import eu.kanade.tachiyomi.extension.model.LoadResult import eu.kanade.tachiyomi.source.CatalogueSource import eu.kanade.tachiyomi.source.Source import eu.kanade.tachiyomi.source.SourceFactory import eu.kanade.tachiyomi.util.Hash import kotlinx.coroutines.async import kotlinx.coroutines.runBlocking import timber.log.Timber import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get /** * Class that handles the loading of the extensions installed in the system. */ @SuppressLint("PackageManagerGetSignatures") internal object ExtensionLoader { private const val EXTENSION_FEATURE = "tachiyomi.extension" private const val METADATA_SOURCE_CLASS = "tachiyomi.extension.class" private const val LIB_VERSION_MIN = 1 private const val LIB_VERSION_MAX = 1 private const val PACKAGE_FLAGS = PackageManager.GET_CONFIGURATIONS or PackageManager.GET_SIGNATURES /** * List of the trusted signatures. */ var trustedSignatures = mutableSetOf<String>() + Injekt.get<PreferencesHelper>().trustedSignatures().getOrDefault() + // inorichi's key "7ce04da7773d41b489f4693a366c36bcd0a11fc39b547168553c285bd7348e23" /** * Return a list of all the installed extensions initialized concurrently. * * @param context The application context. */ fun loadExtensions(context: Context): List<LoadResult> { val pkgManager = context.packageManager val installedPkgs = pkgManager.getInstalledPackages(PACKAGE_FLAGS) val extPkgs = installedPkgs.filter { isPackageAnExtension(it) } if (extPkgs.isEmpty()) return emptyList() // Load each extension concurrently and wait for completion return runBlocking { val deferred = extPkgs.map { async { loadExtension(context, it.packageName, it) } } deferred.map { it.await() } } } /** * Attempts to load an extension from the given package name. It checks if the extension * contains the required feature flag before trying to load it. */ fun loadExtensionFromPkgName(context: Context, pkgName: String): LoadResult { val pkgInfo = try { context.packageManager.getPackageInfo(pkgName, PACKAGE_FLAGS) } catch (error: PackageManager.NameNotFoundException) { // Unlikely, but the package may have been uninstalled at this point return LoadResult.Error(error) } if (!isPackageAnExtension(pkgInfo)) { return LoadResult.Error("Tried to load a package that wasn't a extension") } return loadExtension(context, pkgName, pkgInfo) } /** * Loads an extension given its package name. * * @param context The application context. * @param pkgName The package name of the extension to load. * @param pkgInfo The package info of the extension. */ private fun loadExtension(context: Context, pkgName: String, pkgInfo: PackageInfo): LoadResult { val pkgManager = context.packageManager val appInfo = try { pkgManager.getApplicationInfo(pkgName, PackageManager.GET_META_DATA) } catch (error: PackageManager.NameNotFoundException) { // Unlikely, but the package may have been uninstalled at this point return LoadResult.Error(error) } val extName = pkgManager.getApplicationLabel(appInfo)?.toString() .orEmpty().substringAfter("Tachiyomi: ") val versionName = pkgInfo.versionName val versionCode = pkgInfo.versionCode // Validate lib version val majorLibVersion = versionName.substringBefore('.').toInt() if (majorLibVersion < LIB_VERSION_MIN || majorLibVersion > LIB_VERSION_MAX) { val exception = Exception("Lib version is $majorLibVersion, while only versions " + "$LIB_VERSION_MIN to $LIB_VERSION_MAX are allowed") Timber.w(exception) return LoadResult.Error(exception) } val signatureHash = getSignatureHash(pkgInfo) if (signatureHash == null) { return LoadResult.Error("Package $pkgName isn't signed") } else if (signatureHash !in trustedSignatures) { val extension = Extension.Untrusted(extName, pkgName, versionName, versionCode, signatureHash) Timber.w("Extension $pkgName isn't trusted") return LoadResult.Untrusted(extension) } val classLoader = PathClassLoader(appInfo.sourceDir, null, context.classLoader) val sources = appInfo.metaData.getString(METADATA_SOURCE_CLASS) .split(";") .map { val sourceClass = it.trim() if (sourceClass.startsWith(".")) pkgInfo.packageName + sourceClass else sourceClass } .flatMap { try { val obj = Class.forName(it, false, classLoader).newInstance() when (obj) { is Source -> listOf(obj) is SourceFactory -> obj.createSources() else -> throw Exception("Unknown source class type! ${obj.javaClass}") } } catch (e: Throwable) { Timber.e(e, "Extension load error: $extName.") return LoadResult.Error(e) } } val langs = sources.filterIsInstance<CatalogueSource>() .map { it.lang } .toSet() val lang = when (langs.size) { 0 -> "" 1 -> langs.first() else -> "all" } val extension = Extension.Installed(extName, pkgName, versionName, versionCode, sources, lang) return LoadResult.Success(extension) } /** * Returns true if the given package is an extension. * * @param pkgInfo The package info of the application. */ private fun isPackageAnExtension(pkgInfo: PackageInfo): Boolean { return pkgInfo.reqFeatures.orEmpty().any { it.name == EXTENSION_FEATURE } } /** * Returns the signature hash of the package or null if it's not signed. * * @param pkgInfo The package info of the application. */ private fun getSignatureHash(pkgInfo: PackageInfo): String? { val signatures = pkgInfo.signatures return if (signatures != null && !signatures.isEmpty()) { Hash.sha256(signatures.first().toByteArray()) } else { null } } }
apache-2.0
ab4de16b6c02c2c2ea8e1fcb96226644
37.945355
106
0.632805
4.878166
false
false
false
false
savvasdalkitsis/gameframe
workspace/src/main/java/com/savvasdalkitsis/gameframe/feature/workspace/storage/AuthenticationAwareWorkspaceStorage.kt
1
2237
/** * Copyright 2018 Savvas Dalkitsis * 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. * * 'Game Frame' is a registered trademark of LEDSEQ */ package com.savvasdalkitsis.gameframe.feature.workspace.storage import com.savvasdalkitsis.gameframe.feature.authentication.model.SignedInAccount import com.savvasdalkitsis.gameframe.feature.authentication.usecase.AuthenticationUseCase import com.savvasdalkitsis.gameframe.feature.workspace.model.SaveContainer import io.reactivex.Completable import io.reactivex.Single import java.io.Reader class AuthenticationAwareWorkspaceStorage(private val authenticationUseCase: AuthenticationUseCase<*>, private val localWorkspaceStorage: LocalWorkspaceStorage, private val firebaseWorkspaceStorage: FirebaseWorkspaceStorage): WorkspaceStorage { private val accountState get() = authenticationUseCase.accountState().firstOrError() private val workspaceStorage get() = accountState.map { when (it) { is SignedInAccount -> firebaseWorkspaceStorage else -> localWorkspaceStorage } } override fun saveWorkspace(name: String, workspaceModel: SaveContainer): Completable = workspaceStorage.flatMapCompletable { it.saveWorkspace(name, workspaceModel) } override fun listProjectNames(): Single<List<String>> = workspaceStorage.flatMap { it.listProjectNames() } override fun readWorkspace(name: String): Single<Reader> = workspaceStorage.flatMap { it.readWorkspace(name) } override fun deleteWorkspace(name: String): Completable = workspaceStorage.flatMapCompletable { it.deleteWorkspace(name) } }
apache-2.0
2d2c1bd2fd59c90893368882ed36a37a
42.882353
125
0.737148
5.142529
false
false
false
false
kesmarag/megaptera
src/main/org/kesmarag/megaptera/scripts/Main.kt
1
3202
package org.kesmarag.megaptera.scripts import org.apache.commons.csv.CSVFormat import org.apache.commons.csv.CSVPrinter import org.kesmarag.megaptera.data.DataSet import org.kesmarag.megaptera.hmm.GhmmClustering import java.io.File import java.io.FileOutputStream import java.io.FileWriter import java.io.ObjectOutputStream fun main(args: Array<String>) { println(".:: megaptera v0.1c ::.") //println(args[0]) //val dataSet = DataSet("/home/kesmarag/dev/test/dataSet3/*.csv", 1) val dataSet = DataSet(args[0] + "/*.csv", 1) val clustering = GhmmClustering(dataSet, args[1].toInt(), args[2].toInt(), args[3].toInt()) clustering.training() println("### Results ###") val fileOut = FileOutputStream(args[4] + "/clusters.ser") val out = ObjectOutputStream(fileOut) out.writeObject(clustering) out.close() fileOut.close() //var i_noisy: Int = 1682 //dataSet.members.forEachIndexed { i, oSet -> if (oSet.label == "data_01682.csv") i_noisy = i } //println("i_noisy = ${i_noisy}") /* var min = 1000.0 var argName: String = "none" for (i in 0..dataSet.size-2){ val d = dist(dataSet.members[i].scores,dataSet.members[i_noisy].scores) if (d < min && dataSet.members[i].label != "data_01682.csv"){ min = d argName = dataSet.members[i].label } } dataSet.members //.filter { it.label == "data_841.csv" || it.label == "data_1682.csv" || it.label == argName } .sortedBy { it.label } .forEachIndexed { i, oS -> println("${oS.label} => ${oS.ownerID} => ${oS.scores[0]} |" + " ${oS.scores[1]} | ${oS.scores[2]}") } */ //println("argmin = $argName") //dataSet.members //.filter { it.ownerID == 1 } // .sortedBy { it.label } // .forEachIndexed { i, oS -> println("${oS.label} => ${oS.ownerID}") } //dataSet.members.filter { it.ownerID == 2 } // .sortedBy { it.label } // .forEachIndexed { i, oS -> println("${oS.label} => ${oS.ownerID}") } // dataSet.members.filter { it.ownerID == 3 } // .sortedBy { it.label } // .forEachIndexed { i, oS -> println("${oS.label} => ${oS.ownerID}") } // println("=== Scores ===") // println("=== 0 ===") // dataSet[0].scores.forEach { println(it) } // println("=== 1 ===") // dataSet[1].scores.forEach { println(it) } val file = File(args[4] + "/results.csv") val writer = FileWriter(file) var records = CSVFormat.EXCEL val csvFilePrinter = CSVPrinter(writer, records) dataSet.members //.filter { it.label == "data_841.csv" || it.label == "data_1682.csv" || it.label == argName } .sortedBy { it.label } .forEachIndexed { i, oS -> //println(oS.label) csvFilePrinter.printRecord(oS.scores.toMutableList()) } writer.flush(); writer.close(); csvFilePrinter.close(); } fun dist(a1: DoubleArray, a2: DoubleArray): Double { var s: Double = 0.0 for (n in 0..a1.size - 1) { s += (a1[n] - a2[n]) * (a1[n] - a2[n]) } return s }
apache-2.0
f8eb97bb8a73b8541879ddaeea5825fc
35.816092
106
0.564335
3.304438
false
false
false
false
PEXPlugins/PermissionsEx
platform/sponge7/src/main/kotlin/ca/stellardrift/permissionsex/sponge/Util.kt
1
2190
/* * PermissionsEx * Copyright (C) zml and PermissionsEx 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 ca.stellardrift.permissionsex.sponge import ca.stellardrift.permissionsex.context.ContextDefinition import ca.stellardrift.permissionsex.context.ContextValue import ca.stellardrift.permissionsex.impl.PermissionsEx import com.google.common.collect.ImmutableSet import java.util.Optional import net.kyori.adventure.text.Component import net.kyori.adventure.text.serializer.spongeapi.SpongeComponentSerializer import org.spongepowered.api.service.context.Context import org.spongepowered.api.text.Text typealias ContextSet = Set<ContextValue<*>> fun Component.toSponge(): Text { return SpongeComponentSerializer.get().serialize(this) } fun Text.toAdventure(): Component { return SpongeComponentSerializer.get().deserialize(this) } fun ContextSet.toSponge(): MutableSet<Context> { return mapTo(mutableSetOf()) { Context(it.key(), it.rawValue()) } } private fun <T> Context.toPex(def: ContextDefinition<T>): ContextValue<T>? { val value = def.deserialize(this.value) return if (value == null) null else def.createValue(value) } fun Set<Context>.toPex(manager: PermissionsEx<*>): ContextSet { val builder = ImmutableSet.builder<ContextValue<*>>() for (ctx in this) { val def = manager.contextDefinition(ctx.key, true) ?: throw IllegalStateException("A fallback context value was expected!") val ctxVal = ctx.toPex(def) if (ctxVal != null) { builder.add(ctxVal) } } return builder.build() } fun <T> T?.optionally(): Optional<T> = Optional.ofNullable(this)
apache-2.0
4f31be97fe79ac438245b4e12a4f70b3
34.901639
84
0.741553
3.91771
false
false
false
false
square/wire
wire-library/wire-schema/src/jvmMain/kotlin/com/squareup/wire/schema/AdapterConstant.kt
1
1485
/* * Copyright (C) 2016 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.wire.schema import com.squareup.javapoet.ClassName import com.squareup.kotlinpoet.ClassName as KClassName /** * A constant field that identifies a [ProtoAdapter]. This should be a string like like * `com.squareup.dinosaurs.Dinosaur#ADAPTER` with a fully qualified class name, a `#`, and a * field name. */ data class AdapterConstant( @JvmField val javaClassName: ClassName, @JvmField val kotlinClassName: KClassName, @JvmField val memberName: String ) { companion object { operator fun invoke(adapter: String): AdapterConstant { val names = adapter.split("#").toTypedArray() require(names.size == 2) { "Illegally formatted adapter: $adapter." } return AdapterConstant( javaClassName = ClassName.bestGuess(names[0]), kotlinClassName = KClassName.bestGuess(names[0]), memberName = names[1] ) } } }
apache-2.0
21f5174b778691663bb49ff2b94451cf
34.357143
92
0.719865
4.090909
false
false
false
false
treelzebub/zinepress
app/src/main/java/net/treelzebub/zinepress/db/books/DbBooks.kt
1
982
package net.treelzebub.zinepress.db.books import android.content.Context import android.database.Cursor import android.net.Uri import net.treelzebub.zinepress.R import net.treelzebub.zinepress.db.IDatabase import net.treelzebub.zinepress.db.IQuery import net.treelzebub.zinepress.util.BaseInjection import nl.siegmann.epublib.domain.Book /** * Created by Tre Murillo on 2/20/16 */ object DbBooks : IDatabase<Book> { override val context: Context get() = BaseInjection.context override fun uri(): Uri { return Uri.Builder() .scheme("content") .authority(context.getString(R.string.authority_books)) .build() } override fun write(): BookWriter = BookWriter(this) override fun all(): List<Book> = query().list() override fun query(): BookQuery = BookQuery(this) override fun cursor(query: IQuery<Book>): Cursor = query().cursor() override fun list(query: IQuery<Book>): List<Book> = query.list() }
gpl-2.0
65a69cab42646f8cb56bc0d186cfe40a
27.057143
71
0.705703
3.881423
false
false
false
false
bluelinelabs/Conductor
demo/src/main/java/com/bluelinelabs/conductor/demo/controllers/CityGridController.kt
1
4366
package com.bluelinelabs.conductor.demo.controllers import android.graphics.PorterDuff import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.annotation.DrawableRes import androidx.core.content.ContextCompat import androidx.core.os.bundleOf import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView import com.bluelinelabs.conductor.RouterTransaction import com.bluelinelabs.conductor.demo.R import com.bluelinelabs.conductor.demo.changehandler.CityGridSharedElementTransitionChangeHandler import com.bluelinelabs.conductor.demo.controllers.base.BaseController import com.bluelinelabs.conductor.demo.databinding.ControllerCityGridBinding import com.bluelinelabs.conductor.demo.databinding.RowCityGridBinding import com.bluelinelabs.conductor.demo.util.viewBinding class CityGridController(args: Bundle) : BaseController(R.layout.controller_city_grid, args) { private val binding: ControllerCityGridBinding by viewBinding(ControllerCityGridBinding::bind) override val title = "Shared Element Demos" constructor(title: String?, dotColor: Int, fromPosition: Int) : this( bundleOf( KEY_TITLE to title, KEY_DOT_COLOR to dotColor, KEY_FROM_POSITION to fromPosition ) ) override fun onViewCreated(view: View) { super.onViewCreated(view) binding.title.text = args.getString(KEY_TITLE)!! binding.dot.drawable.setColorFilter(ContextCompat.getColor(view.context, args.getInt(KEY_DOT_COLOR)), PorterDuff.Mode.SRC_ATOP) binding.title.transitionName = view.resources.getString(R.string.transition_tag_title_indexed, args.getInt(KEY_FROM_POSITION)) binding.dot.transitionName = view.resources.getString(R.string.transition_tag_dot_indexed, args.getInt(KEY_FROM_POSITION)) binding.recyclerView.setHasFixedSize(true) binding.recyclerView.layoutManager = GridLayoutManager(view.context, 2) binding.recyclerView.adapter = CityGridAdapter(LayoutInflater.from(view.context), CITY_MODELS, ::onModelRowClick) } private fun onModelRowClick(model: CityModel) { val names = listOf( resources!!.getString(R.string.transition_tag_title_named, model.title), resources!!.getString(R.string.transition_tag_image_named, model.title) ) router.pushController( RouterTransaction.with(CityDetailController(model.drawableRes, model.title)) .pushChangeHandler(CityGridSharedElementTransitionChangeHandler(names)) .popChangeHandler(CityGridSharedElementTransitionChangeHandler(names)) ) } companion object { private const val KEY_TITLE = "CityGridController.title" private const val KEY_DOT_COLOR = "CityGridController.dotColor" private const val KEY_FROM_POSITION = "CityGridController.position" private val CITY_MODELS = arrayOf( CityModel(R.drawable.chicago, "Chicago"), CityModel(R.drawable.jakarta, "Jakarta"), CityModel(R.drawable.london, "London"), CityModel(R.drawable.sao_paulo, "Sao Paulo"), CityModel(R.drawable.tokyo, "Tokyo") ) } } data class CityModel(@DrawableRes val drawableRes: Int, val title: String) private class CityGridAdapter( private val inflater: LayoutInflater, private val items: Array<CityModel>, private val modelClickListener: (CityModel) -> Unit ) : RecyclerView.Adapter<CityGridAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder( RowCityGridBinding.inflate(inflater, parent, false), modelClickListener ) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bind(items[position]) } override fun getItemCount() = items.size class ViewHolder( private val binding: RowCityGridBinding, private val modelClickListener: (CityModel) -> Unit ) : RecyclerView.ViewHolder(binding.root) { fun bind(item: CityModel) { binding.image.setImageResource(item.drawableRes) binding.title.text = item.title binding.image.transitionName = itemView.resources.getString(R.string.transition_tag_image_named, item.title) binding.image.transitionName = itemView.resources.getString(R.string.transition_tag_title_named, item.title) itemView.setOnClickListener { modelClickListener(item) } } } }
apache-2.0
b01e801b3ec0135b2acdc8d326ae931b
37.991071
131
0.771874
4.26784
false
false
false
false
Hexworks/zircon
zircon.jvm.libgdx/src/test/kotlin/org/hexworks/zircon/LibgdxPlayground.kt
1
4676
package org.hexworks.zircon import com.badlogic.gdx.Game import com.badlogic.gdx.Gdx import com.badlogic.gdx.backends.lwjgl.LwjglApplication import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration import com.badlogic.gdx.graphics.GL20 import org.hexworks.cobalt.logging.api.LoggerFactory import org.hexworks.zircon.api.CP437TilesetResources import org.hexworks.zircon.api.ColorThemes import org.hexworks.zircon.api.ComponentAlignments.positionalAlignment import org.hexworks.zircon.api.Components import org.hexworks.zircon.api.GraphicalTilesetResources import org.hexworks.zircon.api.LibgdxApplications import org.hexworks.zircon.api.application.AppConfig import org.hexworks.zircon.api.builder.screen.ScreenBuilder import org.hexworks.zircon.api.data.Size import org.hexworks.zircon.api.data.Tile import org.hexworks.zircon.internal.application.LibgdxApplication import org.hexworks.zircon.internal.listeners.ZirconInputListener object LibgdxPlayground : Game() { private val logger = LoggerFactory.getLogger(this::class) private lateinit var zirconApplication: LibgdxApplication private const val screenWidth = 800 private const val screenHeight = 600 override fun create() { logger.info("Creating LibgdxPlayground...") zirconApplication = LibgdxApplications.buildApplication( AppConfig.newBuilder() .withDefaultTileset(TILESET) .withSize( Size.create( screenWidth / TILESET.width, screenHeight / TILESET.height ) ) .build() ) zirconApplication.start() val screen = ScreenBuilder.createScreenFor(zirconApplication.tileGrid) /*val panel = Components.panel() .wrapWithBox(true) .wrapWithShadow(true) .withSize(Size.create(30, 28)) .withPosition(Position.create(0, 0)) .withTitle("Toolbar buttons on panel") .build() screen.addComponent(panel) val unselectedToggleButton = Components.toggleButton() .withText("Toggle me") .wrapSides(true) .withPosition(Position.create(1, 3)) val selectedToggleButton = Components.toggleButton() .withText("Boxed Toggle Button") .withIsSelected(true) .wrapWithBox(true) .wrapSides(false) .withPosition(Position.create(1, 5)) val label = Components.label() .withText("I'm on the right!") .withPosition(Position.create(20, 9).fromRight(panel)) val button = Components.button() .withText("Bottom text") .withPosition(Position.create(1, 4).fromBottom(panel)) panel.addComponent(unselectedToggleButton) panel.addComponent(selectedToggleButton) panel.addComponent(label) panel.addComponent(button)*/ screen.addComponent( Components.icon() .withAlignment(positionalAlignment(2, 2)) .withIcon( Tile.newBuilder() .withName("Plate mail") .withTileset(GraphicalTilesetResources.nethack16x16()) .buildGraphicalTile() ) ) screen.addComponent( Components.label() .withText("Label with icon") .withAlignment(positionalAlignment(2, 1)) ) screen.theme = theme screen.display() Gdx.input.inputProcessor = ZirconInputListener( fontWidth = TILESET.width, fontHeight = TILESET.height, tileGrid = zirconApplication.tileGrid ) } override fun render() { super.render() Gdx.gl.glClearColor(0f, 0f, 0f, 1f) Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA) Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT) zirconApplication.render() } override fun dispose() { zirconApplication.dispose() } private val TILESET = CP437TilesetResources.rexPaint16x16() private val theme = ColorThemes.arc() @JvmStatic fun main(args: Array<String>) { val config = LwjglApplicationConfiguration() config.title = "Zircon Playground" config.width = screenWidth config.height = screenHeight config.foregroundFPS = 60 config.useGL30 = true config.fullscreen = false LwjglApplication(LibgdxPlayground, config) } }
apache-2.0
24e01c78c254ee7b69debb4945b089e3
34.157895
78
0.628956
4.761711
false
true
false
false
JetBrains/ideavim
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/action/motion/text/MotionUnmatchedAction.kt
1
2178
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.action.motion.text import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.VimCaret import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.api.normalizeOffset import com.maddyhome.idea.vim.command.Argument import com.maddyhome.idea.vim.command.CommandFlags import com.maddyhome.idea.vim.command.MotionType import com.maddyhome.idea.vim.command.OperatorArguments import com.maddyhome.idea.vim.handler.Motion import com.maddyhome.idea.vim.handler.MotionActionHandler import com.maddyhome.idea.vim.handler.toMotionOrError import com.maddyhome.idea.vim.helper.enumSetOf import java.util.* sealed class MotionUnmatchedAction(private val motionChar: Char) : MotionActionHandler.ForEachCaret() { override val flags: EnumSet<CommandFlags> = enumSetOf(CommandFlags.FLAG_SAVE_JUMP) override val motionType: MotionType = MotionType.EXCLUSIVE override fun getOffset( editor: VimEditor, caret: VimCaret, context: ExecutionContext, argument: Argument?, operatorArguments: OperatorArguments, ): Motion { return moveCaretToUnmatchedBlock(editor, caret, operatorArguments.count1, motionChar) .toMotionOrError() } } class MotionUnmatchedBraceCloseAction : MotionUnmatchedAction('}') class MotionUnmatchedBraceOpenAction : MotionUnmatchedAction('{') class MotionUnmatchedParenCloseAction : MotionUnmatchedAction(')') class MotionUnmatchedParenOpenAction : MotionUnmatchedAction('(') private fun moveCaretToUnmatchedBlock(editor: VimEditor, caret: VimCaret, count: Int, type: Char): Int { return if (editor.currentCaret().offset.point == 0 && count < 0 || editor.currentCaret().offset.point >= editor.fileSize() - 1 && count > 0) { -1 } else { var res = injector.searchHelper.findUnmatchedBlock(editor, caret, type, count) if (res != -1) { res = editor.normalizeOffset(res, false) } res } }
mit
ffd0a0c02c362812d018d6ae869b0978
37.210526
144
0.773646
4.093985
false
false
false
false
kittttttan/pe
kt/pe/src/main/kotlin/ktn/pe/Pe1.kt
1
1075
package ktn.pe class Pe1 : Pe { private var limit = 1000 override val problemNumber: Int get() = 1 /** * double sum of 0, 1, ..., limit * * @param limit * @return */ private fun sumToX2(limit: Int): Int { return limit * (limit + 1) } /** * * @param limit * @return */ fun pe1(limit: Int): Int { var sum = 0 if (limit > 2) { sum = (3 * sumToX2(limit / 3) + 5 * sumToX2(limit / 5) - 15 * sumToX2(limit / 15)) shr 1 } return sum } /** * * @param limit * @return */ fun pe1loop(limit: Int): Int { return (3..limit) .filter { it % 3 == 0 || it % 5 == 0 } .sum() } override fun setArgs(args: Array<String>) { if (args.isNotEmpty()) { limit = args[0].toInt() } } override fun solve() { println(PeUtils.format(this, pe1(limit))) } override fun run() { solve() } }
mit
a4e52e0ba0254c04d90766d335e722ff
16.916667
54
0.424186
3.668942
false
false
false
false
qoncept/TensorKotlin
src/jp/co/qoncept/tensorkotlin/Utils.kt
1
2205
package jp.co.qoncept.tensorkotlin internal fun floatArrayOf(size: Int, repeatedValue: Float): FloatArray { val array = FloatArray(size) array.fill(repeatedValue) return array } internal inline fun zipMap(a: FloatArray, b: FloatArray, operation: (Float, Float) -> Float): FloatArray { val result = FloatArray(a.size) for (i in a.indices) { result[i] = operation(a[i], b[i]) } return result } internal inline fun zipMapRepeat(a: FloatArray, infiniteB: FloatArray, operation: (Float, Float) -> Float): FloatArray { val result = FloatArray(a.size) for (i in a.indices) { result[i] = operation(a[i], infiniteB[i % infiniteB.size]) } return result } internal inline fun <R> zipFold(a: FloatArray, b: FloatArray, initial: R, operation: (R, Float, Float) -> R): R { var result: R = initial for (i in a.indices) { result = operation(result, a[i], b[i]) } return result } internal inline fun <R> zipFold(a: IntArray, b: IntArray, initial: R, operation: (R, Int, Int) -> R): R { var result: R = initial for (i in a.indices) { result = operation(result, a[i], b[i]) } return result } internal inline fun FloatArray.map(transform: (Float) -> Float): FloatArray { val result = FloatArray(size) for (i in indices) { result[i] = transform(this[i]) } return result } internal inline fun <T> Array<out T>.map(transform: (T) -> Int): IntArray { val result = IntArray(size) for (i in indices) { result[i] = transform(this[i]) } return result } internal fun IntArray.endsWith(suffix: IntArray): Boolean { if (size < suffix.size) { return false } val offset = size - suffix.size for (i in suffix.indices) { if (this[offset + i] != suffix[i]) { return false } } return true } internal inline fun assert(value: () -> Boolean, lazyMessage: () -> Any) { if (Tensor::class.java.desiredAssertionStatus()) { if (!value()) { val message = lazyMessage() throw AssertionError(message) } } } internal infix fun Int.ceilDiv(rhs: Int): Int { return (this + rhs - 1) / rhs }
mit
66dc27df73798b657098fc1fcc34fe49
26.924051
120
0.614966
3.539326
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/JavaToKotlinConverter.kt
2
16458
// 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.j2k import com.intellij.lang.java.JavaLanguage import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.RangeMarker import com.intellij.openapi.progress.* import com.intellij.openapi.project.Project import com.intellij.openapi.util.Computable import com.intellij.openapi.util.NlsContexts import com.intellij.psi.* import com.intellij.psi.impl.source.DummyHolder import com.intellij.refactoring.suggested.range import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.j2k.ast.Element import org.jetbrains.kotlin.j2k.usageProcessing.ExternalCodeProcessor import org.jetbrains.kotlin.j2k.usageProcessing.UsageProcessing import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.psiUtil.elementsInRange import org.jetbrains.kotlin.psi.psiUtil.isAncestor import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf import java.util.* interface PostProcessor { fun insertImport(file: KtFile, fqName: FqName) val phasesCount: Int fun doAdditionalProcessing( target: JKPostProcessingTarget, converterContext: ConverterContext?, onPhaseChanged: ((Int, String) -> Unit)? ) } sealed class JKPostProcessingTarget data class JKPieceOfCodePostProcessingTarget( val file: KtFile, val rangeMarker: RangeMarker ) : JKPostProcessingTarget() data class JKMultipleFilesPostProcessingTarget( val files: List<KtFile> ) : JKPostProcessingTarget() fun JKPostProcessingTarget.elements() = when (this) { is JKPieceOfCodePostProcessingTarget -> runReadAction { val range = rangeMarker.range ?: return@runReadAction emptyList() file.elementsInRange(range) } is JKMultipleFilesPostProcessingTarget -> files } fun JKPostProcessingTarget.files() = when (this) { is JKPieceOfCodePostProcessingTarget -> listOf(file) is JKMultipleFilesPostProcessingTarget -> files } enum class ParseContext { TOP_LEVEL, CODE_BLOCK } interface ExternalCodeProcessing { fun prepareWriteOperation(progress: ProgressIndicator?): (List<KtFile>) -> Unit } data class ElementResult(val text: String, val importsToAdd: Set<FqName>, val parseContext: ParseContext) data class Result( val results: List<ElementResult?>, val externalCodeProcessing: ExternalCodeProcessing?, val converterContext: ConverterContext? ) data class FilesResult(val results: List<String>, val externalCodeProcessing: ExternalCodeProcessing?) interface ConverterContext abstract class JavaToKotlinConverter { protected abstract fun elementsToKotlin(inputElements: List<PsiElement>, processor: WithProgressProcessor): Result abstract fun filesToKotlin( files: List<PsiJavaFile>, postProcessor: PostProcessor, progress: ProgressIndicator = EmptyProgressIndicator() ): FilesResult abstract fun elementsToKotlin(inputElements: List<PsiElement>): Result } class OldJavaToKotlinConverter( private val project: Project, private val settings: ConverterSettings, private val services: JavaToKotlinConverterServices ) : JavaToKotlinConverter() { companion object { private val LOG = Logger.getInstance(JavaToKotlinConverter::class.java) } override fun filesToKotlin( files: List<PsiJavaFile>, postProcessor: PostProcessor, progress: ProgressIndicator ): FilesResult { val withProgressProcessor = OldWithProgressProcessor(progress, files) val (results, externalCodeProcessing) = ApplicationManager.getApplication().runReadAction(Computable { elementsToKotlin(files, withProgressProcessor) }) val texts = withProgressProcessor.processItems(0.5, results.withIndex()) { pair -> val (i, result) = pair try { val kotlinFile = ApplicationManager.getApplication().runReadAction(Computable { KtPsiFactory(project).createAnalyzableFile("dummy.kt", result!!.text, files[i]) }) result!!.importsToAdd.forEach { postProcessor.insertImport(kotlinFile, it) } AfterConversionPass(project, postProcessor).run(kotlinFile, converterContext = null, range = null, onPhaseChanged = null) kotlinFile.text } catch (e: ProcessCanceledException) { throw e } catch (t: Throwable) { LOG.error(t) result!!.text } } return FilesResult(texts, externalCodeProcessing) } override fun elementsToKotlin(inputElements: List<PsiElement>, processor: WithProgressProcessor): Result { try { val usageProcessings = LinkedHashMap<PsiElement, MutableCollection<UsageProcessing>>() val usageProcessingCollector: (UsageProcessing) -> Unit = { usageProcessings.getOrPut(it.targetElement) { ArrayList() }.add(it) } fun inConversionScope(element: PsiElement) = inputElements.any { it.isAncestor(element, strict = false) } val intermediateResults = processor.processItems(0.25, inputElements) { inputElement -> Converter.create(inputElement, settings, services, ::inConversionScope, usageProcessingCollector).convert() }.toMutableList() val results = processor.processItems(0.25, intermediateResults.withIndex()) { pair -> val (i, result) = pair intermediateResults[i] = null // to not hold unused objects in the heap result?.let { val (text, importsToAdd) = it.codeGenerator(usageProcessings) ElementResult(text, importsToAdd, it.parseContext) } } val externalCodeProcessing = buildExternalCodeProcessing(usageProcessings, ::inConversionScope) return Result(results, externalCodeProcessing, null) } catch (e: ElementCreationStackTraceRequiredException) { // if we got this exception then we need to turn element creation stack traces on to get better diagnostic Element.saveCreationStacktraces = true try { return elementsToKotlin(inputElements) } finally { Element.saveCreationStacktraces = false } } } override fun elementsToKotlin(inputElements: List<PsiElement>): Result { return elementsToKotlin(inputElements, OldWithProgressProcessor.DEFAULT) } private data class ReferenceInfo( val reference: PsiReference, val target: PsiElement, val file: PsiFile, val processings: Collection<UsageProcessing> ) { val depth: Int by lazy(LazyThreadSafetyMode.NONE) { target.parentsWithSelf.takeWhile { it !is PsiFile }.count() } val offset: Int by lazy(LazyThreadSafetyMode.NONE) { reference.element.textRange.startOffset } } private fun buildExternalCodeProcessing( usageProcessings: Map<PsiElement, Collection<UsageProcessing>>, inConversionScope: (PsiElement) -> Boolean ): ExternalCodeProcessing? { if (usageProcessings.isEmpty()) return null val map: Map<PsiElement, Collection<UsageProcessing>> = usageProcessings.values .flatten() .filter { it.javaCodeProcessors.isNotEmpty() || it.kotlinCodeProcessors.isNotEmpty() } .groupBy { it.targetElement } if (map.isEmpty()) return null return object : ExternalCodeProcessing { override fun prepareWriteOperation(progress: ProgressIndicator?): (List<KtFile>) -> Unit { if (progress == null) error("Progress should not be null for old J2K") val refs = ArrayList<ReferenceInfo>() progress.text = KotlinJ2KBundle.message("text.searching.usages.to.update") for ((i, entry) in map.entries.withIndex()) { val psiElement = entry.key val processings = entry.value progress.text2 = (psiElement as? PsiNamedElement)?.name ?: "" progress.checkCanceled() ProgressManager.getInstance().runProcess( { val searchJava = processings.any { it.javaCodeProcessors.isNotEmpty() } val searchKotlin = processings.any { it.kotlinCodeProcessors.isNotEmpty() } services.referenceSearcher.findUsagesForExternalCodeProcessing(psiElement, searchJava, searchKotlin) .filterNot { inConversionScope(it.element) } .mapTo(refs) { ReferenceInfo(it, psiElement, it.element.containingFile, processings) } }, ProgressPortionReporter(progress, i / map.size.toDouble(), 1.0 / map.size) ) } return { processUsages(refs) } } } } private fun processUsages(refs: Collection<ReferenceInfo>) { for (fileRefs in refs.groupBy { it.file }.values) { // group by file for faster sorting ReferenceLoop@ for ((reference, _, _, processings) in fileRefs.sortedWith(ReferenceComparator)) { val processors = when (reference.element.language) { JavaLanguage.INSTANCE -> processings.flatMap { it.javaCodeProcessors } KotlinLanguage.INSTANCE -> processings.flatMap { it.kotlinCodeProcessors } else -> continue@ReferenceLoop } checkReferenceValid(reference, null) var references = listOf(reference) for (processor in processors) { references = references.flatMap { processor.processUsage(it)?.toList() ?: listOf(it) } references.forEach { checkReferenceValid(it, processor) } } } } } private fun checkReferenceValid(reference: PsiReference, afterProcessor: ExternalCodeProcessor?) { val element = reference.element assert(element.isValid && element.containingFile !is DummyHolder) { "Reference $reference got invalidated" + (if (afterProcessor != null) " after processing with $afterProcessor" else "") } } private object ReferenceComparator : Comparator<ReferenceInfo> { override fun compare(info1: ReferenceInfo, info2: ReferenceInfo): Int { val depth1 = info1.depth val depth2 = info2.depth if (depth1 != depth2) { // put deeper elements first to not invalidate them when processing ancestors return -depth1.compareTo(depth2) } // process elements with the same deepness from right to left so that right-side of assignments is not invalidated by processing of the left one return -info1.offset.compareTo(info2.offset) } } } interface WithProgressProcessor { fun <TInputItem, TOutputItem> processItems( fractionPortion: Double, inputItems: Iterable<TInputItem>, processItem: (TInputItem) -> TOutputItem ): List<TOutputItem> fun updateState(fileIndex: Int?, phase: Int, description: String) fun updateState(phase: Int, subPhase: Int, subPhaseCount: Int, fileIndex: Int?, description: String) fun <T> process(action: () -> T): T } class OldWithProgressProcessor(private val progress: ProgressIndicator?, private val files: List<PsiJavaFile>?) : WithProgressProcessor { companion object { val DEFAULT = OldWithProgressProcessor(null, null) } private val progressText @Suppress("DialogTitleCapitalization") @NlsContexts.ProgressText get() = KotlinJ2KBundle.message("text.converting.java.to.kotlin") private val fileCount = files?.size ?: 0 private val fileCountText @Nls get() = KotlinJ2KBundle.message("text.files.count.0", fileCount, if (fileCount == 1) 1 else 2) private var fraction = 0.0 private var pass = 1 override fun <TInputItem, TOutputItem> processItems( fractionPortion: Double, inputItems: Iterable<TInputItem>, processItem: (TInputItem) -> TOutputItem ): List<TOutputItem> { val outputItems = ArrayList<TOutputItem>() // we use special process with EmptyProgressIndicator to avoid changing text in our progress by inheritors search inside etc ProgressManager.getInstance().runProcess( { progress?.text = "$progressText ($fileCountText) - ${KotlinJ2KBundle.message("text.pass.of.3", pass)}" progress?.isIndeterminate = false for ((i, item) in inputItems.withIndex()) { progress?.checkCanceled() progress?.fraction = fraction + fractionPortion * i / fileCount progress?.text2 = files!![i].virtualFile.presentableUrl outputItems.add(processItem(item)) } pass++ fraction += fractionPortion }, EmptyProgressIndicator() ) return outputItems } override fun <T> process(action: () -> T): T { throw AbstractMethodError("Should not be called for old J2K") } override fun updateState(fileIndex: Int?, phase: Int, description: String) { throw AbstractMethodError("Should not be called for old J2K") } override fun updateState( phase: Int, subPhase: Int, subPhaseCount: Int, fileIndex: Int?, description: String ) { error("Should not be called for old J2K") } } class ProgressPortionReporter( indicator: ProgressIndicator, private val start: Double, private val portion: Double ) : J2KDelegatingProgressIndicator(indicator) { init { fraction = 0.0 } override fun start() { fraction = 0.0 } override fun stop() { fraction = portion } override fun setFraction(fraction: Double) { super.setFraction(start + (fraction * portion)) } override fun getFraction(): Double { return (super.getFraction() - start) / portion } override fun setText(text: String?) { } override fun setText2(text: String?) { } } // Copied from com.intellij.ide.util.DelegatingProgressIndicator open class J2KDelegatingProgressIndicator(indicator: ProgressIndicator) : WrappedProgressIndicator, StandardProgressIndicator { protected val delegate: ProgressIndicator = indicator override fun start() = delegate.start() override fun stop() = delegate.stop() override fun isRunning() = delegate.isRunning override fun cancel() = delegate.cancel() override fun isCanceled() = delegate.isCanceled override fun setText(text: String?) { delegate.text = text } override fun getText() = delegate.text override fun setText2(text: String?) { delegate.text2 = text } override fun getText2() = delegate.text2 override fun getFraction() = delegate.fraction override fun setFraction(fraction: Double) { delegate.fraction = fraction } override fun pushState() = delegate.pushState() override fun popState() = delegate.popState() override fun isModal() = delegate.isModal override fun getModalityState() = delegate.modalityState override fun setModalityProgress(modalityProgress: ProgressIndicator?) { delegate.setModalityProgress(modalityProgress) } override fun isIndeterminate() = delegate.isIndeterminate override fun setIndeterminate(indeterminate: Boolean) { delegate.isIndeterminate = indeterminate } override fun checkCanceled() = delegate.checkCanceled() override fun getOriginalProgressIndicator() = delegate override fun isPopupWasShown() = delegate.isPopupWasShown override fun isShowing() = delegate.isShowing }
apache-2.0
4fa61acca745e762075d535b51afed3d
36.577626
158
0.665208
5.146341
false
false
false
false
mdaniel/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/AttachedEntityToParentImpl.kt
1
5766
package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class AttachedEntityToParentImpl: AttachedEntityToParent, WorkspaceEntityBase() { companion object { val connections = listOf<ConnectionId>( ) } @JvmField var _data: String? = null override val data: String get() = _data!! override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: AttachedEntityToParentData?): ModifiableWorkspaceEntityBase<AttachedEntityToParent>(), AttachedEntityToParent.Builder { constructor(): this(AttachedEntityToParentData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity AttachedEntityToParent is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isDataInitialized()) { error("Field AttachedEntityToParent#data should be initialized") } if (!getEntityData().isEntitySourceInitialized()) { error("Field AttachedEntityToParent#entitySource should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } override var data: String get() = getEntityData().data set(value) { checkModificationAllowed() getEntityData().data = value changedProperty.add("data") } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override fun getEntityData(): AttachedEntityToParentData = result ?: super.getEntityData() as AttachedEntityToParentData override fun getEntityClass(): Class<AttachedEntityToParent> = AttachedEntityToParent::class.java } } class AttachedEntityToParentData : WorkspaceEntityData<AttachedEntityToParent>() { lateinit var data: String fun isDataInitialized(): Boolean = ::data.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<AttachedEntityToParent> { val modifiable = AttachedEntityToParentImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): AttachedEntityToParent { val entity = AttachedEntityToParentImpl() entity._data = data entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() return entity } override fun getEntityInterface(): Class<out WorkspaceEntity> { return AttachedEntityToParent::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as AttachedEntityToParentData if (this.data != other.data) return false if (this.entitySource != other.entitySource) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as AttachedEntityToParentData if (this.data != other.data) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + data.hashCode() return result } }
apache-2.0
ce4cb8364b31232db07ccc6e9e019627
34.598765
149
0.652966
6.233514
false
false
false
false
dmeybohm/chocolate-cakephp
src/main/kotlin/com/daveme/chocolateCakePHP/view/ElementGotoDeclarationHandler.kt
1
1709
package com.daveme.chocolateCakePHP.view import com.daveme.chocolateCakePHP.* import com.intellij.codeInsight.navigation.actions.GotoDeclarationHandler import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.editor.Editor import com.intellij.openapi.vfs.VirtualFile import com.intellij.patterns.PlatformPatterns import com.intellij.psi.PsiElement import com.jetbrains.php.lang.PhpLanguage import com.jetbrains.php.lang.psi.elements.StringLiteralExpression import java.util.* class ElementGotoDeclarationHandler : GotoDeclarationHandler { override fun getGotoDeclarationTargets(psiElement: PsiElement?, i: Int, editor: Editor): Array<PsiElement>? { if (psiElement == null) { return PsiElement.EMPTY_ARRAY } val project = psiElement.project val settings = Settings.getInstance(project) if (!settings.enabled) { return PsiElement.EMPTY_ARRAY } if (!PlatformPatterns .psiElement(StringLiteralExpression::class.java) .withLanguage(PhpLanguage.INSTANCE) .accepts(psiElement.context) ) { return PsiElement.EMPTY_ARRAY } val containingFile = psiElement.containingFile val pluginOrAppDir = topSourceDirectoryFromFile(settings, containingFile) val relativeFile = elementPathToVirtualFile(settings, pluginOrAppDir, psiElement.text) ?: return PsiElement.EMPTY_ARRAY val files = HashSet<VirtualFile>() files.add(relativeFile) return virtualFilesToPsiFiles(project, files).toTypedArray() } override fun getActionText(dataContext: DataContext): String? = null }
mit
92f3543b2651b7ce70812205c5f67216
37.863636
113
0.719134
5.08631
false
false
false
false
siarhei-luskanau/android-iot-doorbell
di/di_toothpick/src/main/kotlin/siarhei/luskanau/iot/doorbell/di/DiHolderImpl.kt
1
1615
package siarhei.luskanau.iot.doorbell.di import android.app.Application import android.content.Context import androidx.fragment.app.FragmentActivity import androidx.fragment.app.FragmentFactory import androidx.work.WorkerFactory import siarhei.luskanau.iot.doorbell.data.AppBackgroundServices import siarhei.luskanau.iot.doorbell.data.ScheduleWorkManagerService import siarhei.luskanau.iot.doorbell.workmanager.DefaultWorkerFactory import toothpick.Scope import toothpick.ktp.KTP import toothpick.ktp.extension.getInstance class DiHolderImpl(context: Context) : DiHolder { private val scope: Scope by lazy { KTP.openScope(AppModule::class.java) .installModules(AppModule(context)) } override fun onAppCreate(application: Application) { scope.getInstance<ScheduleWorkManagerService>().startUptimeNotifications() scope.getInstance<AppBackgroundServices>().startServices() } override fun onAppTrimMemory(application: Application) { scope.release() } override fun getFragmentFactory(fragmentActivity: FragmentActivity): FragmentFactory = ToothpickFragmentFactory( fragmentActivity = fragmentActivity, scope = scope ) override fun provideWorkerFactory(): WorkerFactory = DefaultWorkerFactory( thisDeviceRepository = { scope.getInstance() }, doorbellRepository = { scope.getInstance() }, cameraRepository = { scope.getInstance() }, uptimeRepository = { scope.getInstance() }, imageRepository = { scope.getInstance() } ) }
mit
f01dcc1ae285298906538c4d0c479e6f
34.888889
90
0.729412
5.143312
false
false
false
false
efficios/jabberwocky
jabberwocky-core/src/main/kotlin/com/efficios/jabberwocky/analysis/statesystem/StateSystemAnalysis.kt
2
4758
/* * Copyright (C) 2017 EfficiOS Inc., Alexandre Montplaisir <[email protected]> * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Eclipse Public License v1.0 which * accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package com.efficios.jabberwocky.analysis.statesystem import ca.polymtl.dorsal.libdelorean.IStateSystemReader import ca.polymtl.dorsal.libdelorean.IStateSystemWriter import ca.polymtl.dorsal.libdelorean.StateSystemFactory import ca.polymtl.dorsal.libdelorean.backend.StateHistoryBackendFactory import com.efficios.jabberwocky.analysis.IAnalysis import com.efficios.jabberwocky.analysis.IAnalysis.Companion.ANALYSES_DIRECTORY import com.efficios.jabberwocky.collection.TraceCollection import com.efficios.jabberwocky.common.TimeRange import com.efficios.jabberwocky.project.TraceProject import com.efficios.jabberwocky.task.JabberwockyTask import com.efficios.jabberwocky.trace.event.TraceEvent import java.io.IOException import java.nio.file.Files abstract class StateSystemAnalysis : IAnalysis { companion object { private const val HISTORY_FILE_EXTENSION = ".ht" } final override fun execute(project: TraceProject<*, *>, range: TimeRange?, extraParams: String?): IStateSystemReader { if (range != null) throw UnsupportedOperationException("Partial ranges for state system analysis not yet implemented") // if (extraParams != null) logWarning("Ignoring extra parameters: $extraParams") /* Wrap this in an in-band JabberwockyTask so that progress can be reported. */ val task = JabberwockyTask<IStateSystemReader>("Processing states for analysis ${this.javaClass.simpleName}") { /* Determine the path of the history tree backing file we expect */ val analysisClassName = javaClass.toString() val analysesDirectory = project.directory.resolve(ANALYSES_DIRECTORY) if (!Files.exists(analysesDirectory)) Files.createDirectory(analysesDirectory) val stateSystemFile = analysesDirectory.resolve(analysisClassName + HISTORY_FILE_EXTENSION) var newFile = !Files.exists(stateSystemFile) /* Create the history tree backend we will use */ val htBackend = if (Files.exists(stateSystemFile)) { try { StateHistoryBackendFactory.createHistoryTreeBackendExistingFile(analysisClassName, stateSystemFile.toFile(), providerVersion) } catch (e: IOException) { /* The expected provider version may not match what we have on disk. Try building the file from scratch instead */ newFile = true StateHistoryBackendFactory.createHistoryTreeBackendNewFile(analysisClassName, stateSystemFile.toFile(), providerVersion, project.startTime) } } else { StateHistoryBackendFactory.createHistoryTreeBackendNewFile(analysisClassName, stateSystemFile.toFile(), providerVersion, project.startTime) } val ss = StateSystemFactory.newStateSystem(htBackend, newFile) /* If there was a history file already built, it should be good to go. If not, build it */ if (newFile) buildForProject(project, ss) ss } task.run() return task.get() } private fun buildForProject(project: TraceProject<*, *>, stateSystem: IStateSystemWriter) { val traces = filterTraces(project) val trackedState = trackedState() // TODO This iteration could eventually move to a central location, so that the events are // read once then dispatched to several "state providers". // However some analyses may not need all events from all traces in a project. We'll see... var latestTimestamp = project.startTime traces.iterator().use { while (it.hasNext()) { val event = it.next() handleEvent(stateSystem, event, trackedState) latestTimestamp = event.timestamp } } stateSystem.closeHistory(latestTimestamp) } protected abstract val providerVersion: Int protected abstract fun filterTraces(project: TraceProject<*, *>): TraceCollection<*, *> /** * Override this to specify tracked state objects. This exact array * will be passed to each call to handleEvent(), so the implementation * can use it to track state between every call. */ protected open fun trackedState(): Array<Any>? = null protected abstract fun handleEvent(ss: IStateSystemWriter, event: TraceEvent, trackedState: Array<Any>?) }
epl-1.0
03b36c7ae9904ad57eca131787356498
47.561224
159
0.704708
4.767535
false
false
false
false
GunoH/intellij-community
plugins/kotlin/completion/impl-k2/src/org/jetbrains/kotlin/idea/completion/impl/k2/contributors/keywords/ReturnKeywordHandler.kt
2
5647
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.completion.contributors.keywords import com.intellij.codeInsight.completion.CompletionParameters import com.intellij.codeInsight.lookup.LookupElement import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import org.jetbrains.kotlin.analysis.api.KtAnalysisSession import org.jetbrains.kotlin.analysis.api.types.KtType import org.jetbrains.kotlin.idea.completion.createKeywordElement import org.jetbrains.kotlin.idea.completion.createKeywordElementWithSpace import org.jetbrains.kotlin.idea.completion.implCommon.keywords.isInlineFunctionCall import org.jetbrains.kotlin.idea.completion.isLikelyInPositionForReturn import org.jetbrains.kotlin.idea.completion.keywords.CompletionKeywordHandler import org.jetbrains.kotlin.idea.completion.labelNameToTail import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.name.StandardClassIds import org.jetbrains.kotlin.psi.KtDeclarationWithBody import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtFunctionLiteral import org.jetbrains.kotlin.psi.NotNullableUserDataProperty import org.jetbrains.kotlin.psi.psiUtil.findLabelAndCall import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf /** * Implementation in K1: [org.jetbrains.kotlin.idea.completion.returnExpressionItems] */ internal object ReturnKeywordHandler : CompletionKeywordHandler<KtAnalysisSession>(KtTokens.RETURN_KEYWORD) { @OptIn(ExperimentalStdlibApi::class) override fun KtAnalysisSession.createLookups( parameters: CompletionParameters, expression: KtExpression?, lookup: LookupElement, project: Project ): Collection<LookupElement> { if (expression == null) return emptyList() val result = mutableListOf<LookupElement>() for (parent in expression.parentsWithSelf.filterIsInstance<KtDeclarationWithBody>()) { val returnType = parent.getReturnKtType() if (parent is KtFunctionLiteral) { val (label, call) = parent.findLabelAndCall() if (label != null) { addAllReturnVariants(result, returnType, label) } // check if the current function literal is inlined and stop processing outer declarations if it's not if (!isInlineFunctionCall(call)) { break } } else { if (parent.hasBlockBody()) { addAllReturnVariants( result, returnType, label = null, isLikelyInPositionForReturn(expression, parent, returnType.isUnit) ) } break } } return result } private fun KtAnalysisSession.addAllReturnVariants( result: MutableList<LookupElement>, returnType: KtType, label: Name?, isLikelyInPositionForReturn: Boolean = false ) { val isUnit = returnType.isUnit result.add(createKeywordElementWithSpace("return", tail = label?.labelNameToTail().orEmpty(), addSpaceAfter = !isUnit).also { it.isReturnAtHighlyLikelyPosition = isLikelyInPositionForReturn }) getExpressionsToReturnByType(returnType).mapTo(result) { returnTarget -> val lookupElement = if (label != null || returnTarget.addToLookupElementTail) { createKeywordElement("return", tail = "${label.labelNameToTail()} ${returnTarget.expressionText}") } else { createKeywordElement("return ${returnTarget.expressionText}") } lookupElement.isReturnAtHighlyLikelyPosition = isLikelyInPositionForReturn lookupElement } } @OptIn(ExperimentalStdlibApi::class) private fun KtAnalysisSession.getExpressionsToReturnByType(returnType: KtType): List<ExpressionTarget> = buildList { if (returnType.canBeNull) { add(ExpressionTarget("null", addToLookupElementTail = false)) } fun emptyListShouldBeSuggested(): Boolean = returnType.isClassTypeWithClassId(StandardClassIds.Collection) || returnType.isClassTypeWithClassId(StandardClassIds.List) || returnType.isClassTypeWithClassId(StandardClassIds.Iterable) when { returnType.isClassTypeWithClassId(StandardClassIds.Boolean) -> { add(ExpressionTarget("true", addToLookupElementTail = false)) add(ExpressionTarget("false", addToLookupElementTail = false)) } emptyListShouldBeSuggested() -> { add(ExpressionTarget("emptyList()", addToLookupElementTail = true)) } returnType.isClassTypeWithClassId(StandardClassIds.Set) -> { add(ExpressionTarget("emptySet()", addToLookupElementTail = true)) } } } var LookupElement.isReturnAtHighlyLikelyPosition: Boolean by NotNullableUserDataProperty( Key("KOTLIN_IS_RETURN_AT_HIGHLY_LIKELY_POSITION"), false ) } private data class ExpressionTarget( val expressionText: String, /** * FE10 completion sometimes add return target to LookupElement tails and sometimes not, * To ensure consistency (at least for tests) we need to do it to */ val addToLookupElementTail: Boolean )
apache-2.0
146c74b81e0d78ca582ed2e873a2934e
43.125
158
0.686028
5.429808
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/FailedEditorPane.kt
2
6894
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.fileEditor.impl import com.intellij.icons.AllIcons import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.NlsContexts.DialogMessage import com.intellij.ui.components.JBLabel import com.intellij.ui.components.Link import com.intellij.util.ui.JBUI import com.intellij.util.ui.StartupUiUtil import com.intellij.util.ui.UIUtil import net.miginfocom.swing.MigLayout import java.awt.BorderLayout import javax.swing.Icon import javax.swing.JPanel import javax.swing.JTextPane import javax.swing.SwingConstants import javax.swing.border.EmptyBorder import javax.swing.text.SimpleAttributeSet import javax.swing.text.StyleConstants /** * Draws ui for failed state of editor. * * @param message 'message' is wrapped and supports multi-line, * please TRY to make your message short. * For example, "Invalid Xml file" instead of " XML parsing error at line 0... (and three more pages of text)" * * if you STILL want to put a big message , then go to our designers for a consultation. * They will probably offer a more elegant solution (it always turned out this way) * * @param showErrorIcon allows you to enable or disable error icon before text. Other icons not allowed here * * @param wrapMode enables or disables multiline support * * @param init builder, where you can add action buttons for the editor * * * @return Jpanel with failed editor ui * */ fun failedEditorPane(@DialogMessage message: String, showErrorIcon: Boolean, wrapMode: MultilineWrapMode = MultilineWrapMode.Auto, init: FailedEditorBuilder.() -> Unit): JPanel { val builder = FailedEditorBuilder(message, if (showErrorIcon) AllIcons.General.Error else null) builder.init() return builder.draw(wrapMode) } enum class MultilineWrapMode { /** * Disable multiline support (use it for small texts) */ DoNotWrap, /** * Enable multiline support and text-wrapping witch may be confusing for small texts */ Wrap, /** * Enables or disable multiline support depends on size of a text */ Auto } class FailedEditorBuilder internal constructor(@DialogMessage val message: String, val icon: Icon?) { private val myButtons = mutableListOf<Pair<String, () -> Unit>>() /** * Adds Link at the bottom of the text * * @param text Text of link * * @param action Action of link */ fun link(@NlsContexts.LinkLabel text: String, action: () -> Unit) { myButtons.add(Pair(text, action)) } /** * Adds Link at the bottom of the text that * opens tab in target editor */ private fun linkThatNavigatesToEditor(@NlsContexts.LinkLabel text: String, editorProviderId: String, project: Project, editor: FileEditor) = link(text) { editor.tryOpenTab(project, editorProviderId) } /** * Adds Link at the bottom of the text that * opens text tab in target editor */ fun linkThatNavigatesToTextEditor(@NlsContexts.LinkLabel text: String, project: Project, editor: FileEditor) = linkThatNavigatesToEditor(text, "text-editor", project, editor) /** * Opens tab in target editor */ private fun FileEditor.tryOpenTab(project: Project, editorProviderId: String): Boolean { val impl = FileEditorManager.getInstance(project) as? FileEditorManagerImpl ?: return false for (window in impl.windows) { for (composite in window.composites.toList()) { for (tab in composite.allEditors) { if (tab == this) { //move focus to current window window.setAsCurrentWindow(true) //select editor window.setSelectedComposite(composite, true) //open tab composite.fileEditorManager.setSelectedEditor(composite.file, editorProviderId) return true } } } } return false } internal fun draw(wrapMode: MultilineWrapMode): JPanel = JPanel(MigLayout("flowy, aligny 47%, alignx 50%, ins 0, gap 0")).apply { border = EmptyBorder(UIUtil.DEFAULT_VGAP, UIUtil.DEFAULT_HGAP, UIUtil.DEFAULT_VGAP, UIUtil.DEFAULT_HGAP) val wrap = when (wrapMode) { MultilineWrapMode.Wrap -> true MultilineWrapMode.DoNotWrap -> false else -> { val maxButtonSize = if (myButtons.any()) myButtons.maxOf { it.first.length } else 0 (message.length > maxButtonSize && message.length > 65) || message.contains('\n') || message.contains('\r') } } if (wrap) drawMessagePane() else //draw label otherwise to avoid wrapping on resize drawLabel() for ((text, action) in myButtons) { add(Link(text, null, action), "alignx center, gapbottom ${UIUtil.DEFAULT_VGAP}") } } private fun JPanel.drawLabel() { add(JBLabel(icon).apply { text = message if (icon != null) { this.border = EmptyBorder(0, 0, 0, UIUtil.DEFAULT_HGAP + iconTextGap) } }, "alignx center, gapbottom ${getGapAfterMessage()}") } private fun JPanel.drawMessagePane() { val messageTextPane = JTextPane().apply { isFocusable = false isEditable = false border = null font = StartupUiUtil.getLabelFont() background = UIUtil.getLabelBackground() val centerAttribute = SimpleAttributeSet() StyleConstants.setAlignment(centerAttribute, StyleConstants.ALIGN_CENTER) styledDocument.insertString(0, message, centerAttribute) styledDocument.setParagraphAttributes(0, styledDocument.length, centerAttribute, false) text = message } if (icon != null) { // in case of icon - wrap icon and text pane // [icon] [gap] [text] [gap+icon size] // text has to be aligned as if there is no icon val iconAndText = JPanel(BorderLayout()).apply { val iconTextGap = JBUI.scale(4) add(JBLabel(icon).apply { verticalAlignment = SwingConstants.TOP }, BorderLayout.LINE_START) messageTextPane.border = EmptyBorder(0, iconTextGap, 0, UIUtil.DEFAULT_HGAP + iconTextGap) add(messageTextPane, BorderLayout.CENTER) } add(iconAndText, "alignx center, gapbottom ${UIUtil.DEFAULT_VGAP + 1}") } else { // if there is only one action link - then gap is usual // but if there is more than one action link - gap is increased add(messageTextPane, "alignx center, gapbottom ${getGapAfterMessage()}") } } private fun getGapAfterMessage() = if (myButtons.count() > 1) UIUtil.DEFAULT_VGAP + 1 else UIUtil.DEFAULT_VGAP }
apache-2.0
57012c56e3868c4f8a365edfde7f9337
33.818182
142
0.682768
4.284649
false
false
false
false
walleth/kethereum
erc961/src/main/kotlin/org/kethereum/erc961/ERC961Parser.kt
1
1300
package org.kethereum.erc961 import com.sun.xml.internal.fastinfoset.vocab.Vocabulary.PREFIX import org.kethereum.model.Address import org.kethereum.model.ChainId import org.kethereum.model.EthereumURI import org.kethereum.model.Token import org.kethereum.uri.common.parseCommonURI class InvalidTokenURIException : IllegalArgumentException("invalid token") private const val TOKEN_INFO_PREFIX = "token_info" private const val FULL_URI_PREFIX = "ethereum:$TOKEN_INFO_PREFIX" fun isEthereumTokenURI(uri: String) = uri.startsWith(FULL_URI_PREFIX) fun parseTokenFromEthereumURI(uri: String): Token { val commonEthereumURI = EthereumURI(uri).parseCommonURI() val queryMap = commonEthereumURI.query.toMap() if (uri.startsWith("ethereum:$PREFIX") || !commonEthereumURI.valid) { throw InvalidTokenURIException() } return Token( symbol = queryMap["symbol"] ?: "SYM", address = Address(commonEthereumURI.address ?: ""), chain = commonEthereumURI.chainId ?: ChainId(1), name = queryMap["name"], decimals = queryMap["decimals"]?.toInt() ?: 18, type = queryMap["type"] ) } fun EthereumURI.parseToken() = parseTokenFromEthereumURI(uri) fun EthereumURI.isTokenURI() = isEthereumTokenURI(uri)
mit
063086f7c0253f6833d545d657cb8001
34.162162
74
0.716154
3.903904
false
false
false
false
Shoebill/shoebill-common
src/main/java/net/gtaun/shoebill/common/dialog/ListDialog.kt
1
4967
/** * Copyright (C) 2012-2014 MK124 * 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 net.gtaun.shoebill.common.dialog import net.gtaun.shoebill.Shoebill import net.gtaun.shoebill.common.AllOpen import net.gtaun.shoebill.constant.DialogStyle import net.gtaun.shoebill.entities.Player import net.gtaun.shoebill.event.dialog.DialogResponseEvent import net.gtaun.util.event.EventManager import org.apache.commons.lang3.StringUtils import java.util.* /** * @author MK124 * @author Marvin Haschker */ @AllOpen class ListDialog constructor(eventManager: EventManager) : AbstractDialog(DialogStyle.LIST, eventManager) { @Suppress("UNCHECKED_CAST") @AllOpen abstract class AbstractListDialogBuilder<T : ListDialog, B : AbstractListDialogBuilder<T, B>> : Builder<T, B>() { fun item(init: B.() -> ListDialogItem): B { dialog.addItem(init(this as B)) return this } fun item(item: String) = item { ListDialogItem(item) } } @AllOpen class ListDialogBuilder(parentEventManager: EventManager) : AbstractListDialogBuilder<ListDialog, ListDialogBuilder>() { init { dialog = ListDialog(parentEventManager) } } val items: MutableList<ListDialogItem> val displayedItems: MutableList<ListDialogItem> = mutableListOf() var clickOkHandler: ClickOkHandler? = null init { items = object : ArrayList<ListDialogItem>() { override fun add(index: Int, element: ListDialogItem) { element.currentDialog = this@ListDialog super.add(index, element) } override fun add(element: ListDialogItem): Boolean { element.currentDialog = this@ListDialog return super.add(element) } override operator fun set(index: Int, element: ListDialogItem): ListDialogItem { element.currentDialog = this@ListDialog return super.set(index, element) } override fun addAll(elements: Collection<ListDialogItem>): Boolean { elements.forEach { e -> e.currentDialog = this@ListDialog } return super.addAll(elements) } override fun addAll(index: Int, elements: Collection<ListDialogItem>): Boolean { elements.forEach { e -> e.currentDialog = this@ListDialog } return super.addAll(index, elements) } } } override fun show(player: Player) = show(player, itemString) val itemString: String get() { var listStr = "" displayedItems.clear() for (item in items) { if (!item.isEnabled) continue var text = item.itemText if (StringUtils.isEmpty(text)) text = "-" listStr += text + "\n" displayedItems.add(item) } return listStr } override fun onClickOk(event: DialogResponseEvent) { val itemId = event.listItem val item = displayedItems[itemId] item.onItemSelect(event.player) onClickOk(event.player, item) } fun onClickOk(player: Player, item: ListDialogItem) { clickOkHandler?.onClickOk(this, player, item) ?: return Unit } fun addItem(item: ListDialogItem) = items.add(item) @JvmOverloads fun addItem(itemText: String, enabledSupplier: ItemBooleanSupplier? = null, handler: ItemSelectHandler? = null) = items.add(ListDialogItem(itemText, enabledSupplier, handler)) @JvmOverloads fun addItem(supplier: DialogTextSupplier, enabledSupplier: ItemBooleanSupplier? = null, handler: ItemSelectHandler? = null) = items.add(ListDialogItem(supplier, enabledSupplier, handler)) @FunctionalInterface interface ClickOkHandler { fun onClickOk(dialog: ListDialog, player: Player, item: ListDialogItem) } companion object { @JvmStatic @JvmOverloads fun create(eventManager: EventManager = Shoebill.get().eventManager) = ListDialogBuilder(eventManager) fun ClickOkHandler(handler: (ListDialog, Player, ListDialogItem) -> Unit) = object : ClickOkHandler { override fun onClickOk(dialog: ListDialog, player: Player, item: ListDialogItem) { handler(dialog, player, item) } } } }
apache-2.0
f07ec555a2a1f996e9406fa0f8147dba
32.789116
117
0.644051
4.66385
false
false
false
false
Mini-Stren/MultiThemer
multithemer/src/main/java/com/ministren/multithemer/ColorTheme.kt
1
1734
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.ministren.multithemer import android.content.Context import android.support.annotation.AttrRes import android.support.annotation.ColorInt import android.support.annotation.StyleRes /** * Created by Mini-Stren on 28.08.2017. */ class ColorTheme(private val context: Context, val tag: String, @StyleRes val styleResID: Int) { override fun toString(): String = "ColorTheme { tag='$tag', styleResID='$styleResID' }" @ColorInt fun getAttrColor(@AttrRes attr: Int): Int { val typedArray = context.obtainStyledAttributes(styleResID, intArrayOf(attr)) val color = typedArray.getColor(0, 0) typedArray.recycle() return color } @ColorInt fun getColorPrimary() = getAttrColor(R.attr.colorPrimary) @ColorInt fun getColorPrimaryDark() = getAttrColor(R.attr.colorPrimaryDark) @ColorInt fun getColorAccent() = getAttrColor(R.attr.colorAccent) }
apache-2.0
fcbbd88390cc8407e74b3ae08f5b285e
33
96
0.734717
4.239609
false
false
false
false
cmzy/okhttp
okhttp/src/main/kotlin/okhttp3/internal/Util.kt
1
19683
/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:JvmName("Util") package okhttp3.internal import java.io.Closeable import java.io.FileNotFoundException import java.io.IOException import java.io.InterruptedIOException import java.net.InetSocketAddress import java.net.ServerSocket import java.net.Socket import java.net.SocketTimeoutException import java.nio.charset.Charset import java.nio.charset.StandardCharsets.UTF_16BE import java.nio.charset.StandardCharsets.UTF_16LE import java.nio.charset.StandardCharsets.UTF_8 import java.util.Collections import java.util.Locale import java.util.TimeZone import java.util.concurrent.ThreadFactory import java.util.concurrent.TimeUnit import kotlin.text.Charsets.UTF_32BE import kotlin.text.Charsets.UTF_32LE import okhttp3.EventListener import okhttp3.Headers import okhttp3.Headers.Companion.headersOf import okhttp3.HttpUrl import okhttp3.OkHttp import okhttp3.OkHttpClient import okhttp3.RequestBody import okhttp3.RequestBody.Companion.toRequestBody import okhttp3.Response import okhttp3.ResponseBody import okhttp3.ResponseBody.Companion.toResponseBody import okhttp3.internal.http2.Header import okio.Buffer import okio.BufferedSink import okio.BufferedSource import okio.ByteString.Companion.decodeHex import okio.FileSystem import okio.Options import okio.Path import okio.Source @JvmField val EMPTY_BYTE_ARRAY: ByteArray = ByteArray(0) @JvmField val EMPTY_HEADERS: Headers = headersOf() @JvmField val EMPTY_RESPONSE: ResponseBody = EMPTY_BYTE_ARRAY.toResponseBody() @JvmField val EMPTY_REQUEST: RequestBody = EMPTY_BYTE_ARRAY.toRequestBody() /** Byte order marks. */ private val UNICODE_BOMS = Options.of( "efbbbf".decodeHex(), // UTF-8 "feff".decodeHex(), // UTF-16BE "fffe".decodeHex(), // UTF-16LE "0000ffff".decodeHex(), // UTF-32BE "ffff0000".decodeHex() // UTF-32LE ) /** GMT and UTC are equivalent for our purposes. */ @JvmField val UTC: TimeZone = TimeZone.getTimeZone("GMT")!! /** * Quick and dirty pattern to differentiate IP addresses from hostnames. This is an approximation * of Android's private InetAddress#isNumeric API. * * This matches IPv6 addresses as a hex string containing at least one colon, and possibly * including dots after the first colon. It matches IPv4 addresses as strings containing only * decimal digits and dots. This pattern matches strings like "a:.23" and "54" that are neither IP * addresses nor hostnames; they will be verified as IP addresses (which is a more strict * verification). */ private val VERIFY_AS_IP_ADDRESS = "([0-9a-fA-F]*:[0-9a-fA-F:.]*)|([\\d.]+)".toRegex() fun checkOffsetAndCount(arrayLength: Long, offset: Long, count: Long) { if (offset or count < 0L || offset > arrayLength || arrayLength - offset < count) { throw ArrayIndexOutOfBoundsException() } } fun threadFactory( name: String, daemon: Boolean ): ThreadFactory = ThreadFactory { runnable -> Thread(runnable, name).apply { isDaemon = daemon } } /** * Returns an array containing only elements found in this array and also in [other]. The returned * elements are in the same order as in this. */ fun Array<String>.intersect( other: Array<String>, comparator: Comparator<in String> ): Array<String> { val result = mutableListOf<String>() for (a in this) { for (b in other) { if (comparator.compare(a, b) == 0) { result.add(a) break } } } return result.toTypedArray() } /** * Returns true if there is an element in this array that is also in [other]. This method terminates * if any intersection is found. The sizes of both arguments are assumed to be so small, and the * likelihood of an intersection so great, that it is not worth the CPU cost of sorting or the * memory cost of hashing. */ fun Array<String>.hasIntersection( other: Array<String>?, comparator: Comparator<in String> ): Boolean { if (isEmpty() || other == null || other.isEmpty()) { return false } for (a in this) { for (b in other) { if (comparator.compare(a, b) == 0) { return true } } } return false } fun HttpUrl.toHostHeader(includeDefaultPort: Boolean = false): String { val host = if (":" in host) { "[$host]" } else { host } return if (includeDefaultPort || port != HttpUrl.defaultPort(scheme)) { "$host:$port" } else { host } } fun Array<String>.indexOf(value: String, comparator: Comparator<String>): Int = indexOfFirst { comparator.compare(it, value) == 0 } @Suppress("UNCHECKED_CAST") fun Array<String>.concat(value: String): Array<String> { val result = copyOf(size + 1) result[result.lastIndex] = value return result as Array<String> } /** * Increments [startIndex] until this string is not ASCII whitespace. Stops at [endIndex]. */ fun String.indexOfFirstNonAsciiWhitespace(startIndex: Int = 0, endIndex: Int = length): Int { for (i in startIndex until endIndex) { when (this[i]) { '\t', '\n', '\u000C', '\r', ' ' -> Unit else -> return i } } return endIndex } /** * Decrements [endIndex] until `input[endIndex - 1]` is not ASCII whitespace. Stops at [startIndex]. */ fun String.indexOfLastNonAsciiWhitespace(startIndex: Int = 0, endIndex: Int = length): Int { for (i in endIndex - 1 downTo startIndex) { when (this[i]) { '\t', '\n', '\u000C', '\r', ' ' -> Unit else -> return i + 1 } } return startIndex } /** Equivalent to `string.substring(startIndex, endIndex).trim()`. */ fun String.trimSubstring(startIndex: Int = 0, endIndex: Int = length): String { val start = indexOfFirstNonAsciiWhitespace(startIndex, endIndex) val end = indexOfLastNonAsciiWhitespace(start, endIndex) return substring(start, end) } /** * Returns the index of the first character in this string that contains a character in * [delimiters]. Returns endIndex if there is no such character. */ fun String.delimiterOffset(delimiters: String, startIndex: Int = 0, endIndex: Int = length): Int { for (i in startIndex until endIndex) { if (this[i] in delimiters) return i } return endIndex } /** * Returns the index of the first character in this string that is [delimiter]. Returns [endIndex] * if there is no such character. */ fun String.delimiterOffset(delimiter: Char, startIndex: Int = 0, endIndex: Int = length): Int { for (i in startIndex until endIndex) { if (this[i] == delimiter) return i } return endIndex } /** * Returns the index of the first character in this string that is either a control character (like * `\u0000` or `\n`) or a non-ASCII character. Returns -1 if this string has no such characters. */ fun String.indexOfControlOrNonAscii(): Int { for (i in 0 until length) { val c = this[i] if (c <= '\u001f' || c >= '\u007f') { return i } } return -1 } /** Returns true if this string is not a host name and might be an IP address. */ fun String.canParseAsIpAddress(): Boolean { return VERIFY_AS_IP_ADDRESS.matches(this) } /** Returns true if we should void putting this this header in an exception or toString(). */ fun isSensitiveHeader(name: String): Boolean { return name.equals("Authorization", ignoreCase = true) || name.equals("Cookie", ignoreCase = true) || name.equals("Proxy-Authorization", ignoreCase = true) || name.equals("Set-Cookie", ignoreCase = true) } /** Returns a [Locale.US] formatted [String]. */ fun format(format: String, vararg args: Any): String { return String.format(Locale.US, format, *args) } @Throws(IOException::class) fun BufferedSource.readBomAsCharset(default: Charset): Charset { return when (select(UNICODE_BOMS)) { 0 -> UTF_8 1 -> UTF_16BE 2 -> UTF_16LE 3 -> UTF_32BE 4 -> UTF_32LE -1 -> default else -> throw AssertionError() } } fun checkDuration(name: String, duration: Long, unit: TimeUnit?): Int { check(duration >= 0L) { "$name < 0" } check(unit != null) { "unit == null" } val millis = unit.toMillis(duration) require(millis <= Integer.MAX_VALUE) { "$name too large." } require(millis != 0L || duration <= 0L) { "$name too small." } return millis.toInt() } fun Char.parseHexDigit(): Int = when (this) { in '0'..'9' -> this - '0' in 'a'..'f' -> this - 'a' + 10 in 'A'..'F' -> this - 'A' + 10 else -> -1 } fun List<Header>.toHeaders(): Headers { val builder = Headers.Builder() for ((name, value) in this) { builder.addLenient(name.utf8(), value.utf8()) } return builder.build() } fun Headers.toHeaderList(): List<Header> = (0 until size).map { Header(name(it), value(it)) } /** Returns true if an HTTP request for this URL and [other] can reuse a connection. */ fun HttpUrl.canReuseConnectionFor(other: HttpUrl): Boolean = host == other.host && port == other.port && scheme == other.scheme fun EventListener.asFactory() = EventListener.Factory { this } infix fun Byte.and(mask: Int): Int = toInt() and mask infix fun Short.and(mask: Int): Int = toInt() and mask infix fun Int.and(mask: Long): Long = toLong() and mask @Throws(IOException::class) fun BufferedSink.writeMedium(medium: Int) { writeByte(medium.ushr(16) and 0xff) writeByte(medium.ushr(8) and 0xff) writeByte(medium and 0xff) } @Throws(IOException::class) fun BufferedSource.readMedium(): Int { return (readByte() and 0xff shl 16 or (readByte() and 0xff shl 8) or (readByte() and 0xff)) } /** * Reads until this is exhausted or the deadline has been reached. This is careful to not extend the * deadline if one exists already. */ @Throws(IOException::class) fun Source.skipAll(duration: Int, timeUnit: TimeUnit): Boolean { val nowNs = System.nanoTime() val originalDurationNs = if (timeout().hasDeadline()) { timeout().deadlineNanoTime() - nowNs } else { Long.MAX_VALUE } timeout().deadlineNanoTime(nowNs + minOf(originalDurationNs, timeUnit.toNanos(duration.toLong()))) return try { val skipBuffer = Buffer() while (read(skipBuffer, 8192) != -1L) { skipBuffer.clear() } true // Success! The source has been exhausted. } catch (_: InterruptedIOException) { false // We ran out of time before exhausting the source. } finally { if (originalDurationNs == Long.MAX_VALUE) { timeout().clearDeadline() } else { timeout().deadlineNanoTime(nowNs + originalDurationNs) } } } /** * Attempts to exhaust this, returning true if successful. This is useful when reading a complete * source is helpful, such as when doing so completes a cache body or frees a socket connection for * reuse. */ fun Source.discard(timeout: Int, timeUnit: TimeUnit): Boolean = try { this.skipAll(timeout, timeUnit) } catch (_: IOException) { false } fun Socket.peerName(): String { val address = remoteSocketAddress return if (address is InetSocketAddress) address.hostName else address.toString() } /** * Returns true if new reads and writes should be attempted on this. * * Unfortunately Java's networking APIs don't offer a good health check, so we go on our own by * attempting to read with a short timeout. If the fails immediately we know the socket is * unhealthy. * * @param source the source used to read bytes from the socket. */ fun Socket.isHealthy(source: BufferedSource): Boolean { return try { val readTimeout = soTimeout try { soTimeout = 1 !source.exhausted() } finally { soTimeout = readTimeout } } catch (_: SocketTimeoutException) { true // Read timed out; socket is good. } catch (_: IOException) { false // Couldn't read; socket is closed. } } /** Run [block] until it either throws an [IOException] or completes. */ inline fun ignoreIoExceptions(block: () -> Unit) { try { block() } catch (_: IOException) { } } inline fun threadName(name: String, block: () -> Unit) { val currentThread = Thread.currentThread() val oldName = currentThread.name currentThread.name = name try { block() } finally { currentThread.name = oldName } } fun Buffer.skipAll(b: Byte): Int { var count = 0 while (!exhausted() && this[0] == b) { count++ readByte() } return count } /** * Returns the index of the next non-whitespace character in this. Result is undefined if input * contains newline characters. */ internal fun String.indexOfNonWhitespace(startIndex: Int = 0): Int { for (i in startIndex until length) { val c = this[i] if (c != ' ' && c != '\t') { return i } } return length } /** Returns the Content-Length as reported by the response headers. */ internal fun Response.headersContentLength(): Long { return headers["Content-Length"]?.toLongOrDefault(-1L) ?: -1L } fun String.toLongOrDefault(defaultValue: Long): Long { return try { toLong() } catch (_: NumberFormatException) { defaultValue } } /** * Returns this as a non-negative integer, or 0 if it is negative, or [Int.MAX_VALUE] if it is too * large, or [defaultValue] if it cannot be parsed. */ internal fun String?.toNonNegativeInt(defaultValue: Int): Int { try { val value = this?.toLong() ?: return defaultValue return when { value > Int.MAX_VALUE -> Int.MAX_VALUE value < 0 -> 0 else -> value.toInt() } } catch (_: NumberFormatException) { return defaultValue } } /** Returns an immutable copy of this. */ fun <T> List<T>.toImmutableList(): List<T> { return Collections.unmodifiableList(toMutableList()) } /** Returns an immutable list containing [elements]. */ @SafeVarargs fun <T> immutableListOf(vararg elements: T): List<T> { return Collections.unmodifiableList(listOf(*elements.clone())) } /** Returns an immutable copy of this. */ fun <K, V> Map<K, V>.toImmutableMap(): Map<K, V> { return if (isEmpty()) { emptyMap() } else { Collections.unmodifiableMap(LinkedHashMap(this)) } } /** Closes this, ignoring any checked exceptions. */ fun Closeable.closeQuietly() { try { close() } catch (rethrown: RuntimeException) { throw rethrown } catch (_: Exception) { } } /** Closes this, ignoring any checked exceptions. */ fun Socket.closeQuietly() { try { close() } catch (e: AssertionError) { throw e } catch (rethrown: RuntimeException) { if (rethrown.message == "bio == null") { // Conscrypt in Android 10 and 11 may throw closing an SSLSocket. This is safe to ignore. // https://issuetracker.google.com/issues/177450597 return } throw rethrown } catch (_: Exception) { } } /** Closes this, ignoring any checked exceptions. */ fun ServerSocket.closeQuietly() { try { close() } catch (rethrown: RuntimeException) { throw rethrown } catch (_: Exception) { } } /** * Returns true if file streams can be manipulated independently of their paths. This is typically * true for systems like Mac, Unix, and Linux that use inodes in their file system interface. It is * typically false on Windows. * * If this returns false we won't permit simultaneous reads and writes. When writes commit we need * to delete the previous snapshots, and that won't succeed if the file is open. (We do permit * multiple simultaneous reads.) * * @param file a file in the directory to check. This file shouldn't already exist! */ fun FileSystem.isCivilized(file: Path): Boolean { sink(file).use { try { delete(file) return true } catch (_: IOException) { } } delete(file) return false } /** Delete file we expect but don't require to exist. */ fun FileSystem.deleteIfExists(path: Path) { try { delete(path) } catch (fnfe: FileNotFoundException) { return } } /** * Tolerant delete, try to clear as many files as possible even after a failure. */ fun FileSystem.deleteContents(directory: Path) { var exception: IOException? = null val files = try { list(directory) } catch (fnfe: FileNotFoundException) { return } for (file in files) { try { if (metadata(file).isDirectory) { deleteContents(file) } delete(file) } catch (ioe: IOException) { if (exception == null) { exception = ioe } } } if (exception != null) { throw exception } } internal fun Long.toHexString(): String = java.lang.Long.toHexString(this) internal fun Int.toHexString(): String = Integer.toHexString(this) @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN", "NOTHING_TO_INLINE") internal inline fun Any.wait() = (this as Object).wait() @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN", "NOTHING_TO_INLINE") internal inline fun Any.notify() = (this as Object).notify() @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN", "NOTHING_TO_INLINE") internal inline fun Any.notifyAll() = (this as Object).notifyAll() fun <T> readFieldOrNull(instance: Any, fieldType: Class<T>, fieldName: String): T? { var c: Class<*> = instance.javaClass while (c != Any::class.java) { try { val field = c.getDeclaredField(fieldName) field.isAccessible = true val value = field.get(instance) return if (!fieldType.isInstance(value)) null else fieldType.cast(value) } catch (_: NoSuchFieldException) { } c = c.superclass } // Didn't find the field we wanted. As a last gasp attempt, // try to find the value on a delegate. if (fieldName != "delegate") { val delegate = readFieldOrNull(instance, Any::class.java, "delegate") if (delegate != null) return readFieldOrNull(delegate, fieldType, fieldName) } return null } internal fun <E> MutableList<E>.addIfAbsent(element: E) { if (!contains(element)) add(element) } @JvmField val assertionsEnabled: Boolean = OkHttpClient::class.java.desiredAssertionStatus() /** * Returns the string "OkHttp" unless the library has been shaded for inclusion in another library, * or obfuscated with tools like R8 or ProGuard. In such cases it'll return a longer string like * "com.example.shaded.okhttp3.OkHttp". In large applications it's possible to have multiple OkHttp * instances; this makes it clear which is which. */ @JvmField internal val okHttpName: String = OkHttpClient::class.java.name.removePrefix("okhttp3.").removeSuffix("Client") @Suppress("NOTHING_TO_INLINE") internal inline fun Any.assertThreadHoldsLock() { if (assertionsEnabled && !Thread.holdsLock(this)) { throw AssertionError("Thread ${Thread.currentThread().name} MUST hold lock on $this") } } @Suppress("NOTHING_TO_INLINE") internal inline fun Any.assertThreadDoesntHoldLock() { if (assertionsEnabled && Thread.holdsLock(this)) { throw AssertionError("Thread ${Thread.currentThread().name} MUST NOT hold lock on $this") } } internal fun Exception.withSuppressed(suppressed: List<Exception>): Throwable = apply { for (e in suppressed) addSuppressed(e) } internal inline fun <T> Iterable<T>.filterList(predicate: T.() -> Boolean): List<T> { var result: List<T> = emptyList() for (i in this) { if (predicate(i)) { if (result.isEmpty()) result = mutableListOf() (result as MutableList<T>).add(i) } } return result } const val userAgent: String = "okhttp/${OkHttp.VERSION}"
apache-2.0
d2f0968c07106f2c245bdf6e000a4260
28.246657
100
0.688564
3.825656
false
false
false
false
code-disaster/lwjgl3
modules/lwjgl/opencl/src/templates/kotlin/opencl/templates/intel_unified_shared_memory.kt
4
34171
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package opencl.templates import org.lwjgl.generator.* import opencl.* val intel_unified_shared_memory = "INTELUnifiedSharedMemory".nativeClassCL("intel_unified_shared_memory", INTEL) { documentation = """ Native bindings to the $extensionLink extension. This extension adds "Unified Shared Memory" (USM) to OpenCL. Unified Shared Memory provides: ${ul( """ Easier integration into existing code bases by representing OpenCL allocations as pointers rather than handles (`cl_mems`), with full support for pointer arithmetic into allocations. """, "Fine-grain control over ownership and accessibility of OpenCL allocations, to optimally choose between performance and programmer convenience.", "A simpler programming model, by automatically migrating some allocations between OpenCL devices and the host." )} While Unified Shared Memory (USM) shares many features with Shared Virtual Memory (SVM), Unified Shared Memory provides a different mix of capabilities and control. Specifically: ${ul( "The matrix of USM capabilities supports combinations of features beyond the SVM capability queries.", """ USM provides explicit control over memory placement and migration by supporting host allocations with wide visibility, devices allocations for best performance, and shared allocations that may migrate between devices and the host. """, """ USM allocations may be associated with both a device and a context. The USM allocation APIs support additional memory flags and optional properties to affect how memory is allocated and migrated. """, """ There is no need for APIs to map or unmap USM allocations, because host accessible USM allocations do not need to be mapped or unmapped to access the contents of a USM allocation on the host. """, """ An application may indicate that a kernel may access categories of USM allocations indirectly, without passing a set of all indirectly accessed USM allocations to the kernel, improving usability and reducing driver overhead for kernels that access many USM allocations. """, "USM adds API functions to query properties of a USM allocation and to provide memory advice for an allocation." )} Unified Shared Memory and Shared Virtual Memory can and will coexist for many implementations. All implementations that support Shared Virtual Memory may support at least some types of Unified Shared Memory. Requires ${CL20.link}. """ IntConstant( "Accepted value for the {@code param_name} parameter to #GetDeviceInfo() to query the Unified Shared Memory capabilities of an OpenCL device.", "DEVICE_HOST_MEM_CAPABILITIES_INTEL"..0x4190, "DEVICE_DEVICE_MEM_CAPABILITIES_INTEL"..0x4191, "DEVICE_SINGLE_DEVICE_SHARED_MEM_CAPABILITIES_INTEL"..0x4192, "DEVICE_CROSS_DEVICE_SHARED_MEM_CAPABILITIES_INTEL"..0x4193, "DEVICE_SHARED_SYSTEM_MEM_CAPABILITIES_INTEL"..0x4194 ) IntConstant( """ Bitfield type and bits describing the Unified Shared Memory capabilities of an OpenCL device. ({@code cl_device_unified_shared_memory_capabilities_intel}) """, "UNIFIED_SHARED_MEMORY_ACCESS_INTEL".."1 << 0", "UNIFIED_SHARED_MEMORY_ATOMIC_ACCESS_INTEL".."1 << 1", "UNIFIED_SHARED_MEMORY_CONCURRENT_ACCESS_INTEL".."1 << 2", "UNIFIED_SHARED_MEMORY_CONCURRENT_ATOMIC_ACCESS_INTEL".."1 << 3" ) IntConstant( "Enumerant value requesting optional allocation properties for a Unified Shared Memory allocation.", "MEM_ALLOC_FLAGS_INTEL"..0x4195 ) EnumConstant( "Bitfield type and bits describing optional allocation properties for a Unified Shared Memory allocation. ({@code cl_mem_alloc_flags_intel})", "MEM_ALLOC_WRITE_COMBINED_INTEL".enum( """ Request write combined (WC) memory. Write combined memory may improve performance in some cases, however write combined memory must be used with care since it may hurt performance in other cases or use different coherency protocols than non-write combined memory. """, "1 << 0" ), "MEM_ALLOC_INITIAL_PLACEMENT_DEVICE_INTEL".enum( """ Request the implementation to optimize for first access being done by the device. This flag is valid only for #SharedMemAllocINTEL(). This flag does not affect functionality and is purely a performance hint. """, "1 << 1" ), "MEM_ALLOC_INITIAL_PLACEMENT_HOST_INTEL".enum( """ Request the implementation to optimize for first access being done by the host. This flag is valid only for #SharedMemAllocINTEL(). This flag does not affect functionality and is purely a performance hint. {@code CL_MEM_ALLOC_INITIAL_PLACEMENT_DEVICE_INTEL} and {@code CL_MEM_ALLOC_INITIAL_PLACEMENT_HOST_INTEL} are mutually exclusive. """, "1 << 2" ) ) val MemInfoIntel = IntConstant( """ Enumeration type and values for the {@code param_name} parameter to #GetMemAllocInfoINTEL() to query information about a Unified Shared Memory allocation. ({@code cl_mem_info_intel}) Optional allocation properties may also be queried using {@code clGetMemAllocInfoINTEL}. """, "MEM_ALLOC_TYPE_INTEL"..0x419A, "MEM_ALLOC_BASE_PTR_INTEL"..0x419B, "MEM_ALLOC_SIZE_INTEL"..0x419C, "MEM_ALLOC_DEVICE_INTEL"..0x419D ).javaDocLinks IntConstant( """ Enumeration type and values describing the type of Unified Shared Memory allocation. Returned by #GetMemAllocInfoINTEL() when {@code param_name} is #MEM_ALLOC_TYPE_INTEL. ({@code cl_unified_shared_memory_type_intel}) """, "MEM_TYPE_UNKNOWN_INTEL"..0x4196, "MEM_TYPE_HOST_INTEL"..0x4197, "MEM_TYPE_DEVICE_INTEL"..0x4198, "MEM_TYPE_SHARED_INTEL"..0x4199 ) IntConstant( """ Accepted value for the {@code param_name} parameter to #SetKernelExecInfo() to specify that the kernel may indirectly access Unified Shared Memory allocations of the specified type. """, "KERNEL_EXEC_INFO_INDIRECT_HOST_ACCESS_INTEL"..0x4200, "KERNEL_EXEC_INFO_INDIRECT_DEVICE_ACCESS_INTEL"..0x4201, "KERNEL_EXEC_INFO_INDIRECT_SHARED_ACCESS_INTEL"..0x4202 ) IntConstant( """ Accepted value for the {@code param_name} parameter to #SetKernelExecInfo() to specify a set of Unified Shared Memory allocations that the kernel may indirectly access. """, "KERNEL_EXEC_INFO_USM_PTRS_INTEL"..0x4203 ) IntConstant( "New return values from #GetEventInfo() when {@code param_name} is #EVENT_COMMAND_TYPE.", "COMMAND_MEMFILL_INTEL"..0x4204, "COMMAND_MEMCPY_INTEL"..0x4205, "COMMAND_MIGRATEMEM_INTEL"..0x4206, "COMMAND_MEMADVISE_INTEL"..0x4207 ) void.p( "HostMemAllocINTEL", "Allocates host Unified Shared Memory.", cl_context("context", "a valid OpenCL context used to allocate the host memory"), nullable..NullTerminated..cl_mem_properties_intel.const.p( "properties", """ an optional list of allocation properties and their corresponding values. The list is terminated with the special property {@code 0}. If no allocation properties are required, {@code properties} may be #NULL. """ ), AutoSizeResult..size_t("size", "the size in bytes of the requested host allocation"), cl_uint( "alignment", """ the minimum alignment in bytes for the requested host allocation. It must be a power of two and must be equal to or smaller than the size of the largest data type supported by any OpenCL device in {@code context}. If {@code alignment} is {@code 0}, a default alignment will be used that is equal to the size of the largest data type supported by any OpenCL device in {@code context}. """ ), ERROR_RET, returnDoc = """ a valid non-#NULL address and #SUCCESS will be returned in {@code errcode_ret} if the host Unified Shared Memory is allocated successfully. Otherwise, #NULL will be returned, and {@code errcode_ret} will be set to one of the following error values: ${ul( ICE, """ #INVALID_OPERATION if #DEVICE_HOST_MEM_CAPABILITIES_INTEL is zero for all devices in {@code context}, indicating that no devices in {@code context} support host Unified Shared Memory allocations. """, "#INVALID_VALUE if {@code alignment} is not zero or a power of two.", """ #INVALID_VALUE if {@code alignment} is greater than the size of the largest data type supported by any OpenCL device in {@code context} that supports host Unified Shared Memory allocations. """, """ #INVALID_PROPERTY if a memory property name in {@code properties} is not a supported property name, if the value specified for a supported property name is not valid, or if the same property name is specified more than once. """, "#INVALID_PROPERTY if either the #MEM_ALLOC_INITIAL_PLACEMENT_DEVICE_INTEL or #MEM_ALLOC_INITIAL_PLACEMENT_HOST_INTEL flags are specified.", """ #INVALID_BUFFER_SIZE if {@code size} is zero or greater than #DEVICE_MAX_MEM_ALLOC_SIZE for any OpenCL device in {@code context} that supports host Unified Shared Memory allocations. """, OORE, OOHME )} """ ) void.p( "DeviceMemAllocINTEL", "Allocates Unified Shared Memory specific to an OpenCL device.", cl_context("context", "a valid OpenCL context used to allocate the device memory"), cl_device_id("device", "a valid OpenCL device ID to associate with the allocation"), nullable..NullTerminated..cl_mem_properties_intel.const.p( "properties", """ an optional list of allocation properties and their corresponding values. The list is terminated with the special property {@code 0}. If no allocation properties are required, {@code properties} may be #NULL. """ ), AutoSizeResult..size_t("size", "the size in bytes of the requested device allocation"), cl_uint( "alignment", """ the minimum alignment in bytes for the requested device allocation. It must be a power of two and must be equal to or smaller than the size of the largest data type supported by {@code device}. If {@code alignment} is {@code 0}, a default alignment will be used that is equal to the size of largest data type supported by {@code device}. """ ), ERROR_RET, returnDoc = """ a valid non-#NULL address and #SUCCESS will be returned in {@code errcode_ret} if the device Unified Shared Memory is allocated successfully. Otherwise, #NULL will be returned, and {@code errcode_ret} will be set to one of the following error values: ${ul( ICE, "#INVALID_DEVICE if {@code device} is not a valid device or is not associated with {@code context}.", """ #INVALID_OPERATION` if #DEVICE_DEVICE_MEM_CAPABILITIES_INTEL is zero for {@code device}, indicating that {@code device} does not support device Unified Shared Memory allocations. """, "#INVALID_VALUE if {@code alignment} is not zero or a power of two.", "#INVALID_VALUE if {@code alignment} is greater than the size of the largest data type supported by {@code device}.", """ #INVALID_PROPERTY if a memory property name in {@code properties} is not a supported property name, if the value specified for a supported property name is not valid, or if the same property name is specified more than once. """, "#INVALID_PROPERTY if either the #MEM_ALLOC_INITIAL_PLACEMENT_DEVICE_INTEL or #MEM_ALLOC_INITIAL_PLACEMENT_HOST_INTEL flags are specified.", "#INVALID_BUFFER_SIZE if {@code size} is zero or greater than #DEVICE_MAX_MEM_ALLOC_SIZE for {@code device}.", OORE, OOHME )} """ ) void.p( "SharedMemAllocINTEL", """ Allocates Unified Shared Memory with shared ownership between the host and the specified OpenCL device. If the specified OpenCL device supports cross-device access capabilities, the allocation is also accessible by other OpenCL devices in the context that have cross-device access capabilities. """, cl_context("context", "a valid OpenCL context used to allocate the Unified Shared Memory"), nullable..cl_device_id( "device", """ an optional OpenCL device ID to associate with the allocation. If {@code device is} #NULL then the allocation is not associated with any device. Allocations with no associated device are accessible by the host and OpenCL devices in the context that have cross-device access capabilities. """ ), nullable..NullTerminated..cl_mem_properties_intel.const.p( "properties", """ an optional list of allocation properties and their corresponding values. The list is terminated with the special property {@code 0}. If no allocation properties are required, {@code properties} may be #NULL. """ ), AutoSizeResult..size_t("size", "the size in bytes of the requested device allocation"), cl_uint( "alignment", """ the minimum alignment in bytes for the requested shared allocation. It must be a power of two and must be equal to or smaller than the size of the largest data type supported by {@code device}. If {@code alignment} is {@code 0}, a default alignment will be used that is equal to the size of largest data type supported by {@code device}. If {@code device} is #NULL, {@code alignment} must be a power of two equal to or smaller than the size of the largest data type supported by any OpenCL device in {@code context}, and the default alignment will be equal to the size of the largest data type supported by any OpenCL device in {@code context}. """ ), ERROR_RET, returnDoc = """ a valid non-#NULL address and #SUCCESS will be returned in {@code errcode_ret} if the shared Unified Shared Memory is allocated successfully. Otherwise, #NULL will be returned, and {@code errcode_ret} will be set to one of the following error values: ${ul( ICE, "#INVALID_DEVICE if {@code device} is not #NULL and is either not a valid device or is not associated with {@code context}.", """ #INVALID_OPERATION if {@code device} is not #NULL and #DEVICE_SINGLE_DEVICE_SHARED_MEM_CAPABILITIES_INTEL and #DEVICE_CROSS_DEVICE_SHARED_MEM_CAPABILITIES_INTEL are both zero, indicating that {@code device} does not support shared Unified Shared Memory allocations, or if {@code device} is #NULL and no devices in {@code context} support shared Unified Shared Memory allocations. """, "#INVALID_VALUE if {@code alignment} is not zero or a power of two.", """ #INVALID_VALUE if {@code device} is not #NULL and {@code alignment} is greater than the size of the largest data type supported by {@code device}, or if {@code device} is #NULL and {@code alignment} is greater than the size of the largest data type supported by any OpenCL device in {@code context} that supports shared Unified Shared Memory allocations. """, """ #INVALID_PROPERTY if a memory property name in {@code properties} is not a supported property name, if the value specified for a supported property name is not valid, or if the same property name is specified more than once. """, "#INVALID_PROPERTY if both #MEM_ALLOC_INITIAL_PLACEMENT_DEVICE_INTEL and #MEM_ALLOC_INITIAL_PLACEMENT_HOST_INTEL flags are specified.", """ #INVALID_BUFFER_SIZE if {@code size} is zero, or if {@code device} is not #NULL and {@code size} is greater than #DEVICE_MAX_MEM_ALLOC_SIZE for {@code device}, or if {@code device} is #NULL and {@code size} is greater than #DEVICE_MAX_MEM_ALLOC_SIZE for any device in {@code context} that supports shared Unified Shared Memory allocations. """, OORE, OOHME )} """ ) cl_int( "MemFreeINTEL", """ Frees a Unified Shared Memory allocation. Note that {@code clMemFreeINTEL} may not wait for previously enqueued commands that may be using {@code ptr} to finish before freeing {@code ptr}. It is the responsibility of the application to make sure enqueued commands that use {@code ptr} are complete before freeing {@code ptr}. Applications should take particular care freeing memory allocations with kernels that may access memory indirectly, since a kernel with indirect memory access counts as using all memory allocations of the specified type or types. To wait for previously enqueued commands to finish that may be using {@code ptr} before freeing {@code ptr}, use the #MemBlockingFreeINTEL() function instead. """, cl_context("context", "a valid OpenCL context used to free the Unified Shared Memory allocation"), Unsafe..nullable..void.p( "ptr", """ the Unified Shared Memory allocation to free. It must be a value returned by #HostMemAllocINTEL(), #DeviceMemAllocINTEL(), or #SharedMemAllocINTEL(), or a #NULL pointer. If {@code ptr} is #NULL then no action occurs. """ ), returnDoc = """ #SUCCESS if the function executes successfully. Otherwise, they will return one of the following error values: ${ul( ICE, """ #INVALID_VALUE if {@code ptr} is not a value returned by #HostMemAllocINTEL(), #DeviceMemAllocINTEL(), #SharedMemAllocINTEL(), or a #NULL pointer. """, OORE, OOHME )} """ ) cl_int( "MemBlockingFreeINTEL", "Frees a Unified Shared Memory allocation.", cl_context("context", "a valid OpenCL context used to free the Unified Shared Memory allocation"), Unsafe..nullable..void.p( "ptr", """ the Unified Shared Memory allocation to free. It must be a value returned by #HostMemAllocINTEL(), #DeviceMemAllocINTEL(), or #SharedMemAllocINTEL(), or a #NULL pointer. If {@code ptr} is #NULL then no action occurs. """ ), returnDoc = """ #SUCCESS if the function executes successfully. Otherwise, they will return one of the following error values: ${ul( ICE, """ #INVALID_VALUE if {@code ptr} is not a value returned by #HostMemAllocINTEL(), #DeviceMemAllocINTEL(), #SharedMemAllocINTEL(), or a #NULL pointer. """, OORE, OOHME )} """ ) cl_int( "GetMemAllocInfoINTEL", "Queries information about a Unified Shared Memory allocation.", cl_context("context", "a valid OpenCL context to query for information about the Unified Shared Memory allocation"), Unsafe..void.const.p( "ptr", """ a pointer into a Unified Shared Memory allocation to query. {@code ptr need not be a value} returned by #HostMemAllocINTEL(), #DeviceMemAllocINTEL(), or #SharedMemAllocINTEL(), but the query may be faster if it is. """ ), cl_mem_info_intel("param_name", "the information to query", MemInfoIntel), PARAM_VALUE_SIZE, MultiType( PointerMapping.DATA_INT, PointerMapping.DATA_POINTER )..nullable..void.p( "param_value", """ a pointer to memory where the appropriate result being queried is returned. If {@code param_value} is #NULL, it is ignored. """ ), PARAM_VALUE_SIZE_RET, returnDoc = """ #SUCCESS if the function is executed successfully. Otherwise, it will return one of the following error values: ${ul( ICE, "#INVALID_VALUE if {@code param_name} is not a valid Unified Shared Memory allocation query.", "#INVALID_VALUE` if {@code param_value} is not #NULL and {@code param_value_size} is smaller than the size of the query return type.", OORE, OOHME )} """ ) cl_int( "SetKernelArgMemPointerINTEL", "Sets a pointer into a Unified Shared Memory allocation as an argument to a kernel.", cl_kernel("kernel", "a valid kernel object"), cl_uint( "arg_index", """ the argument index to set. Arguments to the kernel are referred to by indices that go from 0 for the leftmost argument to {@code n - 1}, where {@code n} is the total number of arguments declared by a kernel. """ ), MultiTypeAll..Unsafe..void.const.p( "arg_value", """ the pointer value that should be used as the argument specified by {@code arg_index}. The pointer value will be used as the argument by all API calls that enqueue a kernel until the argument value is set to a different pointer value by a subsequent call. A pointer into Unified Shared Memory allocation may only be set as an argument value for an argument declared to be a pointer to {@code global} or {@code constant} memory. For devices supporting shared system allocations, any pointer value is valid. Otherwise, the pointer value must be #NULL or must point into a Unified Shared Memory allocation returned by #HostMemAllocINTEL(), #DeviceMemAllocINTEL(), or #SharedMemAllocINTEL(). """ ), returnDoc = """ #SUCCESS if the function is executed successfully. Otherwise, it will return one of the following errors: ${ul( "#INVALID_KERNEL if {@code kernel} is not a valid kernel object.", "#INVALID_ARG_INDEX if {@code arg_index} is not a valid argument index.", "#INVALID_ARG_VALUE if {@code arg_value} is not a valid argument value.", OORE, OOHME )} """ ) cl_int( "EnqueueMemFillINTEL", "Fills a region of a memory with the specified pattern.", cl_command_queue( "command_queue", """ a valid host command queue. The memory fill command will be queued for execution on the device associated with {@code command_queue}. """ ), void.p( "dst_ptr", """ a pointer to the start of the memory region to fill. The Unified Shared Memory allocation pointed to by {@code dst_ptr} must be valid for the context associated with {@code command_queue}, must be accessible by the device associated with {@code command_queue}, and must be aligned to {@code pattern_size} bytes. """ ), void.const.p( "pattern", """ a pointer to the value to write to the Unified Shared Memory region. The memory associated with {@code pattern} can be reused or freed after the function returns. """ ), AutoSize("pattern")..size_t( "pattern_size", """ the size of of the value to write to the Unified Shared Memory region, in bytes. Must be a power of two and must be less than or equal to the size of the largest integer or floating-point vector data type supported by the device. """ ), AutoSize("dst_ptr")..size_t("size", "the size of the memory region to set, in bytes"), NEWL, EWL, EVENT, returnDoc = """ #SUCCESS if the command is queued successfully. Otherwise, it will return one of the following errors: ${ul( "#INVALID_COMMAND_QUEUE if {@code command_queue} is not a valid host command-queue.", "#INVALID_CONTEXT if the context associated with {@code command_queue} and events in {@code event_wait_list} are not the same.", "#INVALID_VALUE if {@code dst_ptr} is #NULL, or if {@code dst_ptr} is not aligned to {@code pattern_size} bytes.", "#INVALID_VALUE if {@code pattern} is #NULL.", """ #INVALID_VALUE if {@code pattern_size} is not a power of two or is greater than the size of the largest integer or floating-point vector data type supported by the device associated with {@code command_queue}. """, "#INVALID_VALUE if {@code size} is not a multiple of {@code pattern_size}.", """ #INVALID_EVENT_WAIT_LIST if {@code event_wait_list} is #NULL and {@code num_events_in_wait_list} is greater than zero, or if {@code event_wait_list} is not #NULL and {@code num_events_in_wait_list} is zero, or if event objects in {@code event_wait_list} are not valid events. """, OORE, OOHME )} """ ) cl_int( "EnqueueMemcpyINTEL", "Copies a region of memory from one location to another.", cl_command_queue( "command_queue", """ a valid host command queue. The memory copy command will be queued for execution on the device associated with {@code command_queue}. """ ), cl_bool( "blocking", """ indicates if the copy operation is blocking or non-blocking. If {@code blocking is} #TRUE, the copy command is blocking, and the function will not return until the copy command is complete. Otherwise, if {@code blocking} is #FALSE, the copy command is non-blocking, and the contents of the {@code dst_ptr} cannot be used nor can the contents of the {@code src_ptr} be overwritten until the copy command is complete. """ ), Check("size")..void.p( "dst_ptr", """ a pointer to the start of the memory region to copy to. If {@code dst_ptr} is a pointer into a Unified Shared Memory allocation it must be valid for the context associated with {@code command_queue}. """ ), Check("size")..void.const.p( "src_ptr", """ a pointer to the start of the memory region to copy from. If {@code src_ptr is} a pointer into a Unified Shared Memory allocation it must be valid for the context associated with {@code command_queue}. """ ), size_t("size", "the size of the memory region to copy, in bytes"), NEWL, EWL, EVENT, returnDoc = """ #SUCCESS if the command is queued successfully. Otherwise, it will return one of the following errors: ${ul( "#INVALID_COMMAND_QUEUE if {@code command_queue} is not a valid host command-queue.", "#INVALID_CONTEXT if the context associated with {@code command_queue} and events in {@code event_wait_list} are not the same.", "#INVALID_VALUE if either {@code dst_ptr} or {@code src_ptr} are #NULL.", """ #INVALID_EVENT_WAIT_LIST if {@code event_wait_list} is #NULL and {@code num_events_in_wait_list} is greater than zero, or if {@code event_wait_list} is not #NULL and {@code num_events_in_wait_list} is zero, or if event objects in {@code event_wait_list} are not valid events. """, """ #EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST if the copy operation is blocking and the execution status of any of the events in {@code event_wait_list} is a negative integer value. """, "#MEM_COPY_OVERLAP if the values specified for {@code dst_ptr}, {@code src_ptr} and {@code size} result in an overlapping copy.", OORE, OOHME )} """ ) cl_int( "EnqueueMigrateMemINTEL", """ Explicitly migrates a region of a shared Unified Shared Memory allocation to the device associated with {@code command_queue}. This is a hint that may improve performance and is not required for correctness. Memory migration may not be supported for all allocation types for all devices. If memory migration is not supported for the specified memory range then the migration hint may be ignored. Memory migration may only be supported at a device-specific granularity, such as a page boundary. In this case, the memory range may be expanded such that the start and end of the range satisfy the granularity requirements. """, cl_command_queue( "command_queue", """ a valid host command queue. The memory migration command will be queued for execution on the device associated with {@code command_queue}. """ ), void.const.p("ptr", "a pointer to the start of the shared Unified Shared Memory allocation to migrate"), AutoSize("ptr")..size_t("size", "the size of the memory region to migrate"), cl_mem_migration_flags("flags", "a bit-field that is used to specify memory migration options"), NEWL, EWL, EVENT, returnDoc = """ #SUCCESS if the command is queued successfully. Otherwise, it will return one of the following errors: ${ul( "#INVALID_COMMAND_QUEUE if {@code command_queue} is not a valid host command-queue.", "#INVALID_CONTEXT if the context associated with {@code command_queue} and events in {@code event_wait_list} are not the same.", "#INVALID_VALUE if {@code flags} is zero or is not a supported combination of memory migration flags.", """ #INVALID_EVENT_WAIT_LIST if {@code event_wait_list} is #NULL and {@code num_events_in_wait_list} is greater than zero, or if {@code event_wait_list} is not #NULL and {@code num_events_in_wait_list} is zero, or if event objects in {@code event_wait_list} are not valid events. """, OORE, OOHME )} """ ) cl_int( "EnqueueMemAdviseINTEL", """ Provides advice about a region of a shared Unified Shared Memory allocation. Memory advice is a performance hint only and is not required for correctness. Providing memory advice hints may override driver heuristics that control shared memory behavior. Not all memory advice hints may be supported for all allocation types for all devices. If a memory advice hint is not supported by the device it will be ignored. Memory advice hints may only be supported at a device-specific granularity, such as at a page boundary. In this case, the memory range may be expanded such that the start and end of the range satisfy the granularity requirements. """, cl_command_queue( "command_queue", """ a valid host command queue. The memory advice hints will be queued for the device associated with {@code command_queue}. """ ), void.const.p("ptr", "a pointer to the start of the shared Unified Shared Memory allocation"), AutoSize("ptr")..size_t("size", "the size of the memory region"), cl_mem_advice_intel("advice", "a bit-field describing the memory advice hints for the region"), NEWL, EWL, EVENT, returnDoc = """ #SUCCESS if the command is queued successfully. Otherwise, it will return one of the following errors: ${ul( "#INVALID_COMMAND_QUEUE if {@code command_queue} is not a valid host command-queue.", "#INVALID_CONTEXT if the context associated with {@code command_queue} and events in {@code event_wait_list} are not the same.", "#INVALID_VALUE if {@code advice} is not supported advice for the device associated with {@code command_queue}.", """ #INVALID_EVENT_WAIT_LIST if {@code event_wait_list} is #NULL and {@code num_events_in_wait_list} is greater than zero, or if {@code event_wait_list} is not #NULL and {@code num_events_in_wait_list} is zero, or if event objects in {@code event_wait_list} are not valid events. """, OORE, OOHME )} """ ) }
bsd-3-clause
0b02f0d58cc3b6aaabf6353d77949796
46.395284
159
0.620058
4.77182
false
false
false
false
ClearVolume/scenery
src/main/kotlin/graphics/scenery/backends/vulkan/VulkanNodeHelpers.kt
1
21084
package graphics.scenery.backends.vulkan import graphics.scenery.* import graphics.scenery.backends.* import graphics.scenery.attribute.renderable.Renderable import graphics.scenery.attribute.material.Material import graphics.scenery.textures.Texture import graphics.scenery.textures.UpdatableTexture import graphics.scenery.utils.LazyLogger import org.lwjgl.system.jemalloc.JEmalloc import org.lwjgl.vulkan.VK10 import org.lwjgl.vulkan.VkBufferCopy import org.lwjgl.vulkan.VkQueue import java.nio.ByteBuffer import java.nio.ByteOrder import java.util.concurrent.atomic.AtomicInteger import kotlin.math.floor import kotlin.math.ln import kotlin.math.min import kotlin.reflect.full.findAnnotation import kotlin.reflect.full.memberProperties /** * Helper object for node texture loading and buffer creation. * * @author Ulrik Guenther <[email protected]> */ object VulkanNodeHelpers { val logger by LazyLogger() /** * Creates vertex buffers for a given [node] on [device]. * * Will access the node's [state], allocate staging memory from [stagingPool], and GPU memory * from [geometryPool]. Command buffer allocation and submission is done via [commandPools] in * the given [queue]. Returns the modified [VulkanObjectState]. */ fun createVertexBuffers( device: VulkanDevice, node: Node, state: VulkanObjectState, stagingPool: VulkanBufferPool, geometryPool: VulkanBufferPool, commandPools: VulkanRenderer.CommandPools, queue: VkQueue ): VulkanObjectState { val geometry = node.geometryOrNull() ?: return state val vertices = geometry.vertices.duplicate() val normals = geometry.normals.duplicate() var texcoords = geometry.texcoords.duplicate() val indices = geometry.indices.duplicate() if(vertices.remaining() == 0) { return state } if (texcoords.remaining() == 0 && node is InstancedNode) { val buffer = JEmalloc.je_calloc(1, 4L * vertices.remaining() / geometry.vertexSize * geometry.texcoordSize) if(buffer == null) { logger.error("Could not allocate texcoords buffer with ${4L * vertices.remaining() / geometry.vertexSize * geometry.texcoordSize} bytes for ${node.name}") return state } else { geometry.texcoords = buffer.asFloatBuffer() texcoords = geometry.texcoords.asReadOnlyBuffer() } } val vertexAllocationBytes: Long = 4L * (vertices.remaining() + normals.remaining() + texcoords.remaining()) val indexAllocationBytes: Long = 4L * indices.remaining() val fullAllocationBytes: Long = vertexAllocationBytes + indexAllocationBytes val stridedBuffer = JEmalloc.je_malloc(fullAllocationBytes) if(stridedBuffer == null) { logger.error("Allocation failed, skipping vertex buffer creation for ${node.name}.") return state } val fb = stridedBuffer.asFloatBuffer() val ib = stridedBuffer.asIntBuffer() state.vertexCount = vertices.remaining() / geometry.vertexSize logger.trace("${node.name} has ${vertices.remaining()} floats and ${texcoords.remaining() / geometry.texcoordSize} remaining") for (index in 0 until vertices.remaining() step 3) { fb.put(vertices.get()) fb.put(vertices.get()) fb.put(vertices.get()) fb.put(normals.get()) fb.put(normals.get()) fb.put(normals.get()) if (texcoords.remaining() > 0) { fb.put(texcoords.get()) fb.put(texcoords.get()) } } logger.trace("Adding {} bytes to strided buffer", indices.remaining() * 4) if (indices.remaining() > 0) { state.isIndexed = true ib.position(vertexAllocationBytes.toInt() / 4) for (index in 0 until indices.remaining()) { ib.put(indices.get()) } } logger.trace("Strided buffer is now at {} bytes", stridedBuffer.remaining()) val stagingBuffer = stagingPool.createBuffer(fullAllocationBytes.toInt()) stagingBuffer.copyFrom(stridedBuffer) val vertexIndexBuffer = state.vertexBuffers["vertex+index"] val vertexBuffer = if(vertexIndexBuffer != null && vertexIndexBuffer.size >= fullAllocationBytes) { logger.debug("Reusing existing vertex+index buffer for {} update", node.name) vertexIndexBuffer } else { logger.debug("Creating new vertex+index buffer for {} with {} bytes", node.name, fullAllocationBytes) geometryPool.createBuffer(fullAllocationBytes.toInt()) } logger.debug("Using VulkanBuffer {} for vertex+index storage, offset={}", vertexBuffer.vulkanBuffer.toHexString(), vertexBuffer.bufferOffset) logger.debug("Initiating copy with 0->${vertexBuffer.bufferOffset}, size=$fullAllocationBytes") val copyRegion = VkBufferCopy.calloc(1) .srcOffset(0) .dstOffset(vertexBuffer.bufferOffset) .size(fullAllocationBytes * 1L) with(VU.newCommandBuffer(device, commandPools.Standard, autostart = true)) { VK10.vkCmdCopyBuffer(this, stagingBuffer.vulkanBuffer, vertexBuffer.vulkanBuffer, copyRegion) this.endCommandBuffer(device, commandPools.Standard, queue, flush = true, dealloc = true) } copyRegion.free() state.vertexBuffers.put("vertex+index", vertexBuffer)?.run { // check if vertex buffer has been replaced, if yes, close the old one if(this != vertexBuffer) { close() } } state.indexOffset = vertexBuffer.bufferOffset + vertexAllocationBytes state.indexCount = geometry.indices.remaining() JEmalloc.je_free(stridedBuffer) stagingBuffer.close() return state } /** * Updates instance buffers for a given [node] on [device]. Modifies the [node]'s [state] * and allocates necessary command buffers from [commandPools] and submits to [queue]. Returns the [node]'s modified [VulkanObjectState]. */ fun updateInstanceBuffer(device: VulkanDevice, node: InstancedNode, state: VulkanObjectState, commandPools: VulkanRenderer.CommandPools, queue: VkQueue): VulkanObjectState { logger.trace("Updating instance buffer for ${node.name}") // parentNode.instances is a CopyOnWrite array list, and here we keep a reference to the original. // If it changes in the meantime, no problemo. val instances = node.instances if (instances.isEmpty()) { logger.debug("$node has no child instances attached, returning.") return state } // TODO make maxInstanceUpdateCount property of InstancedNode val maxUpdates = node.metadata["MaxInstanceUpdateCount"] as? AtomicInteger if(maxUpdates?.get() ?: 1 < 1) { logger.debug("Instances updates blocked for ${node.name}, returning") return state } // first we create a fake UBO to gauge the size of the needed properties val ubo = VulkanUBO(device) ubo.fromInstance(instances.first()) val instanceBufferSize = ubo.getSize() * instances.size val instanceStagingBuffer = state.vertexBuffers["instanceStaging"] val stagingBuffer = if(instanceStagingBuffer != null && instanceStagingBuffer.size >= instanceBufferSize) { instanceStagingBuffer } else { logger.debug("Creating new staging buffer") val buffer = VulkanBuffer(device, (1.2 * instanceBufferSize).toLong(), VK10.VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK10.VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, wantAligned = true) state.vertexBuffers["instanceStaging"] = buffer buffer } ubo.updateBackingBuffer(stagingBuffer) ubo.createUniformBuffer() val index = AtomicInteger(0) instances.parallelStream().forEach { instancedNode -> if(instancedNode.visible) { instancedNode.spatialOrNull()?.updateWorld(true, false) stagingBuffer.stagingBuffer.duplicate().order(ByteOrder.LITTLE_ENDIAN).run { ubo.populateParallel(this, offset = index.getAndIncrement() * ubo.getSize() * 1L, elements = instancedNode.instancedProperties) } } } stagingBuffer.stagingBuffer.position(stagingBuffer.stagingBuffer.limit()) stagingBuffer.copyFromStagingBuffer() val existingInstanceBuffer = state.vertexBuffers["instance"] val instanceBuffer = if (existingInstanceBuffer != null && existingInstanceBuffer.size >= instanceBufferSize && existingInstanceBuffer.size < 1.5*instanceBufferSize) { existingInstanceBuffer } else { logger.debug("Instance buffer for ${node.name} needs to be reallocated due to insufficient size ($instanceBufferSize vs ${state.vertexBuffers["instance"]?.size ?: "<not allocated yet>"})") state.vertexBuffers["instance"]?.close() val buffer = VulkanBuffer(device, instanceBufferSize * 1L, VK10.VK_BUFFER_USAGE_VERTEX_BUFFER_BIT or VK10.VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK10.VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, wantAligned = true) state.vertexBuffers["instance"] = buffer buffer } with(VU.newCommandBuffer(device, commandPools.Standard, autostart = true)) { val copyRegion = VkBufferCopy.calloc(1) .size(instanceBufferSize * 1L) VK10.vkCmdCopyBuffer(this, stagingBuffer.vulkanBuffer, instanceBuffer.vulkanBuffer, copyRegion) copyRegion.free() this.endCommandBuffer(device, commandPools.Standard, queue, flush = true, dealloc = true) } state.instanceCount = index.get()//instances.size maxUpdates?.decrementAndGet() return state } /** * Loads or reloads the textures for [node], updating it's internal renderer state stored in [s]. * * [defaultTextures] for fallback need to be given, as well as the [VulkanRenderer]'s [textureCache]. * Necessary command buffers will be allocated from [commandPools] and submitted to [queue]. * * Returns a [Pair] of [Boolean], indicating whether contents or descriptor set have changed. */ fun loadTexturesForNode(device: VulkanDevice, node: Node, s: VulkanObjectState, defaultTextures: Map<String, VulkanTexture>, textureCache: MutableMap<Texture, VulkanTexture>, commandPools: VulkanRenderer.CommandPools, queue: VkQueue): Pair<Boolean, Boolean> { val material = node.materialOrNull() ?: return Pair(false, false) val defaultTexture = defaultTextures["DefaultTexture"] ?: throw IllegalStateException("Default fallback texture does not exist.") // if a node is not yet initialized, we'll definitely require a new DS var descriptorUpdated = !node.initialized var contentUpdated = false val last = s.texturesLastSeen val now = System.nanoTime() material.textures.forEachChanged(last) { (type, texture) -> contentUpdated = true val slot = VulkanObjectState.textureTypeToSlot(type) val generateMipmaps = Texture.mipmappedObjectTextures.contains(type) logger.debug("${node.name} will have $type texture from $texture in slot $slot") if (!textureCache.containsKey(texture)) { try { logger.debug("Loading texture {} for {}", texture, node.name) val miplevels = if (generateMipmaps && texture.mipmap) { floor(ln(min(texture.dimensions.x() * 1.0, texture.dimensions.y() * 1.0)) / ln(2.0)).toInt() } else { 1 } val existingTexture = s.textures[type] val t: VulkanTexture = if (existingTexture != null && existingTexture.canBeReused(texture, miplevels, device)) { existingTexture } else { descriptorUpdated = true VulkanTexture(device, commandPools, queue, queue, texture, miplevels) } texture.contents?.let { contents -> t.copyFrom(contents.duplicate()) } if (texture is UpdatableTexture && texture.hasConsumableUpdates()) { t.copyFrom(ByteBuffer.allocate(0)) } if(descriptorUpdated) { t.createSampler(texture) } // add new texture to texture list and cache, and close old texture s.textures[type] = t if(texture !is UpdatableTexture) { textureCache[texture] = t } } catch (e: Exception) { logger.warn("Could not load texture for ${node.name}: $e") } } else { s.textures[type] = textureCache[texture]!! } } s.texturesLastSeen = now val isCompute = material is ShaderMaterial && ((material as? ShaderMaterial)?.isCompute() ?: false) if(!isCompute) { Texture.objectTextures.forEach { if (!s.textures.containsKey(it)) { s.textures.putIfAbsent(it, defaultTexture) s.defaultTexturesFor.add(it) } } } return contentUpdated to descriptorUpdated } /** * Initialises custom shaders for a given [node] on [device]. Adds optional initialisers e.g. for * resizing, if [addInitializer] is set to true. Such initialiser is added to [lateResizeInitializers]. * [buffers] for UBO access need to be given. * * Returns true if the node has been given a custom shader, and false if not. */ fun initializeCustomShadersForNode(device: VulkanDevice, node: Node, addInitializer: Boolean = true, renderpasses: Map<String, VulkanRenderpass>, lateResizeInitializers: MutableMap<Renderable, () -> Any>, buffers: VulkanRenderer.DefaultBuffers): Boolean { val renderable = node.renderableOrNull() ?: return false val material = node.materialOrNull() ?: return false if(!(material.blending.transparent || material is ShaderMaterial || material.cullingMode != Material.CullingMode.Back || material.wireframe)) { logger.debug("Using default renderpass material for ${node.name}") renderpasses .filter { it.value.passConfig.type == RenderConfigReader.RenderpassType.geometry || it.value.passConfig.type == RenderConfigReader.RenderpassType.lights } .forEach { it.value.removePipeline(renderable) } lateResizeInitializers.remove(renderable) return false } if(addInitializer) { lateResizeInitializers.remove(renderable) } renderable.rendererMetadata()?.let { s -> renderpasses.filter { it.value.passConfig.type == RenderConfigReader.RenderpassType.geometry || it.value.passConfig.type == RenderConfigReader.RenderpassType.lights } .map { (passName, pass) -> val shaders = when (material) { is ShaderMaterial -> { logger.debug("Initializing preferred pipeline for ${node.name} in pass $passName from ShaderMaterial") material.shaders } else -> { logger.debug("Initializing pass-default shader preferred pipeline for ${node.name} in pass $passName") Shaders.ShadersFromFiles(pass.passConfig.shaders.map { "shaders/$it" }.toTypedArray()) } } logger.debug("Shaders are: $shaders") val shaderModules = ShaderType.values().mapNotNull { type -> try { VulkanShaderModule.getFromCacheOrCreate(device, "main", shaders.get(Shaders.ShaderTarget.Vulkan, type)) } catch (e: ShaderNotFoundException) { null } catch (e: ShaderConsistencyException) { logger.warn("${e.message} - Falling back to default shader.") if(logger.isDebugEnabled) { e.printStackTrace() } return false } } val pipeline = pass.initializePipeline(shaderModules, material.cullingMode, material.depthTest, material.blending, material.wireframe, s.vertexDescription ) pass.registerPipelineForNode(pipeline, renderable) } if (renderable.needsShaderPropertyUBO()) { renderpasses.filter { (it.value.passConfig.type == RenderConfigReader.RenderpassType.geometry || it.value.passConfig.type == RenderConfigReader.RenderpassType.lights) && it.value.passConfig.renderTransparent == material.blending.transparent }.forEach { pass -> val dsl = pass.value.initializeShaderPropertyDescriptorSetLayout() logger.debug("Initializing shader properties for ${node.name} in pass ${pass.key}") val order = pass.value.getShaderPropertyOrder(renderable) val shaderPropertyUbo = VulkanUBO(device, backingBuffer = buffers.ShaderProperties) with(shaderPropertyUbo) { name = "ShaderProperties" order.forEach { (name, offset) -> // TODO: See whether returning 0 on non-found shader property has ill side effects add(name, { renderable.parent.getShaderProperty(name) ?: 0 }, offset) } val result = this.createUniformBuffer() val ds = device.createDescriptorSetDynamic( dsl, 1, buffers.ShaderProperties, size = maxOf(result.range, 2048) ) s.requiredDescriptorSets["ShaderProperties"] = ds s.UBOs["${pass.key}-ShaderProperties"] = ds to this } } } if(addInitializer) { lateResizeInitializers[renderable] = { val reloaded = initializeCustomShadersForNode(device, node, addInitializer = false, renderpasses, lateResizeInitializers, buffers) if(reloaded) { renderable.rendererMetadata()?.texturesToDescriptorSets(device, renderpasses.filter { pass -> pass.value.passConfig.type != RenderConfigReader.RenderpassType.quad }, renderable) } } } // TODO: Figure out if this can be avoided for the BDV integration s.clearTextureDescriptorSets() return true } return false } private fun Renderable.needsShaderPropertyUBO(): Boolean = this .parent .javaClass .kotlin .memberProperties .filter { it.findAnnotation<ShaderProperty>() != null } .count() > 0 /** * Returns true if the current VulkanTexture can be reused to store the information in the [Texture] * [other]. Returns false otherwise. */ fun VulkanTexture.canBeReused(other: Texture, miplevels: Int, device: VulkanDevice): Boolean { return this.device == device && this.width == other.dimensions.x() && this.height == other.dimensions.y() && this.depth == other.dimensions.z() && this.mipLevels == miplevels } /** * Returns a node's [VulkanRenderer] metadata, [VulkanObjectState], if available. */ fun Renderable.rendererMetadata(): VulkanObjectState? { return this.metadata["VulkanRenderer"] as? VulkanObjectState } }
lgpl-3.0
35c8d3ad34883cf09a552c84ca220b0b
42.116564
263
0.59557
5.033182
false
false
false
false
iSoron/uhabits
uhabits-android/src/main/java/org/isoron/uhabits/activities/habits/list/ListHabitsSelectionMenu.kt
1
4429
/* * Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]> * * This file is part of Loop Habit Tracker. * * Loop Habit Tracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * Loop Habit Tracker is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.isoron.uhabits.activities.habits.list import android.content.Context import android.view.Menu import android.view.MenuItem import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.view.ActionMode import dagger.Lazy import org.isoron.uhabits.R import org.isoron.uhabits.activities.habits.list.views.HabitCardListAdapter import org.isoron.uhabits.activities.habits.list.views.HabitCardListController import org.isoron.uhabits.core.commands.CommandRunner import org.isoron.uhabits.core.preferences.Preferences import org.isoron.uhabits.core.ui.NotificationTray import org.isoron.uhabits.core.ui.screens.habits.list.ListHabitsSelectionMenuBehavior import org.isoron.uhabits.core.utils.DateUtils import org.isoron.uhabits.inject.ActivityContext import org.isoron.uhabits.inject.ActivityScope import javax.inject.Inject @ActivityScope class ListHabitsSelectionMenu @Inject constructor( @ActivityContext context: Context, private val listAdapter: HabitCardListAdapter, var commandRunner: CommandRunner, private val prefs: Preferences, private val behavior: ListHabitsSelectionMenuBehavior, private val listController: Lazy<HabitCardListController>, private val notificationTray: NotificationTray ) : ActionMode.Callback { val activity = (context as AppCompatActivity) var activeActionMode: ActionMode? = null fun onSelectionStart() { activity.startSupportActionMode(this) } fun onSelectionChange() { activeActionMode?.invalidate() } fun onSelectionFinish() { activeActionMode?.finish() } override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean { activeActionMode = mode activity.menuInflater.inflate(R.menu.list_habits_selection, menu) return true } override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean { val itemEdit = menu.findItem(R.id.action_edit_habit) val itemColor = menu.findItem(R.id.action_color) val itemArchive = menu.findItem(R.id.action_archive_habit) val itemUnarchive = menu.findItem(R.id.action_unarchive_habit) val itemNotify = menu.findItem(R.id.action_notify) itemColor.isVisible = true itemEdit.isVisible = behavior.canEdit() itemArchive.isVisible = behavior.canArchive() itemUnarchive.isVisible = behavior.canUnarchive() itemNotify.isVisible = prefs.isDeveloper activeActionMode?.title = listAdapter.selected.size.toString() return true } override fun onDestroyActionMode(mode: ActionMode?) { listController.get().onSelectionFinished() } override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean { when (item.itemId) { R.id.action_edit_habit -> { behavior.onEditHabits() return true } R.id.action_archive_habit -> { behavior.onArchiveHabits() return true } R.id.action_unarchive_habit -> { behavior.onUnarchiveHabits() return true } R.id.action_delete -> { behavior.onDeleteHabits() return true } R.id.action_color -> { behavior.onChangeColor() return true } R.id.action_notify -> { for (h in listAdapter.selected) notificationTray.show(h, DateUtils.getToday(), 0) return true } else -> return false } } }
gpl-3.0
73cfa01bf0235e328e48f1e37c3b9278
33.59375
85
0.684056
4.593361
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/jvm-debugger/evaluation/src/org/jetbrains/kotlin/idea/debugger/evaluate/variables/EvaluatorValueConverter.kt
3
9526
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.debugger.evaluate.variables import com.sun.jdi.* import org.jetbrains.kotlin.fileClasses.internalNameWithoutInnerClasses import org.jetbrains.kotlin.idea.debugger.evaluate.ExecutionContext import org.jetbrains.kotlin.idea.debugger.evaluate.variables.VariableFinder.Result import org.jetbrains.kotlin.idea.debugger.base.util.isSubtype import org.jetbrains.kotlin.resolve.jvm.AsmTypes import org.jetbrains.kotlin.resolve.jvm.JvmPrimitiveType import kotlin.jvm.internal.Ref import com.sun.jdi.Type as JdiType import org.jetbrains.org.objectweb.asm.Type as AsmType @Suppress("SpellCheckingInspection") class EvaluatorValueConverter(val context: ExecutionContext) { companion object { val UNBOXING_METHOD_NAMES = mapOf( "java/lang/Boolean" to "booleanValue", "java/lang/Character" to "charValue", "java/lang/Byte" to "byteValue", "java/lang/Short" to "shortValue", "java/lang/Integer" to "intValue", "java/lang/Float" to "floatValue", "java/lang/Long" to "longValue", "java/lang/Double" to "doubleValue" ) fun unref(value: Value?): Value? { if (value !is ObjectReference) { return value } val type = value.type() if (type !is ClassType || !type.signature().startsWith("L" + AsmTypes.REF_TYPE_PREFIX)) { return value } val field = type.fieldByName("element") ?: return value return value.getValue(field) } } // Nearly accurate: doesn't do deep checks for Ref wrappers. Use `coerce()` for more precise check. fun typeMatches(requestedType: AsmType, actualTypeObj: JdiType?): Boolean { if (actualTypeObj == null) return true // Main path if (requestedType.descriptor == "Ljava/lang/Object;" || actualTypeObj.isSubtype(requestedType)) { return true } val actualType = actualTypeObj.asmType() fun isRefWrapper(wrapperType: AsmType, objType: AsmType): Boolean { return !objType.isPrimitiveType && wrapperType.className == Ref.ObjectRef::class.java.name } if (isRefWrapper(actualType, requestedType) || isRefWrapper(requestedType, actualType)) { return true } if (requestedType == AsmTypes.K_CLASS_TYPE && actualType == AsmTypes.JAVA_CLASS_TYPE) { // KClass can be represented as a Java class for simpler cases. See BoxingInterpreter.isJavaLangClassBoxing(). return true } val unwrappedActualType = unwrap(actualType) val unwrappedRequestedType = unwrap(requestedType) return unwrappedActualType == unwrappedRequestedType } fun coerce(value: Value?, type: AsmType): Result? { val unrefResult = coerceRef(value, type) return coerceBoxing(unrefResult.value, type) } private fun coerceRef(value: Value?, type: AsmType): Result { when { type.isRefType -> { if (value != null && value.asmType().isRefType) { return Result(value) } return Result(ref(value)) } value != null && value.asmType().isRefType -> { if (type.isRefType) { return Result(value) } return Result(unref(value)) } else -> return Result(value) } } private fun coerceBoxing(value: Value?, type: AsmType): Result? { when { value == null -> return Result(value) type == AsmType.VOID_TYPE -> return Result(context.vm.mirrorOfVoid()) type.isBoxedType -> { if (value.asmType().isBoxedType) { return Result(value) } if (value !is PrimitiveValue) { return null } return Result(box(value)) } type.isPrimitiveType -> { if (value is PrimitiveValue) { return Result(value) } if (value !is ObjectReference || !value.asmType().isBoxedType) { return null } return Result(unbox(value)) } value is PrimitiveValue -> { if (type.sort != AsmType.OBJECT) { return null } val boxedValue = box(value) if (!typeMatches(type, boxedValue?.type())) { return null } return Result(boxedValue) } else -> return Result(value) } } private fun box(value: Value?): Value? { if (value !is PrimitiveValue) { return value } val unboxedType = value.asmType() val boxedType = box(unboxedType) val boxedTypeClass = (context.findClass(boxedType) as ClassType?) ?: error("Class $boxedType is not loaded") val methodDesc = AsmType.getMethodDescriptor(boxedType, unboxedType) val valueOfMethod = boxedTypeClass.methodsByName("valueOf", methodDesc).first() return context.invokeMethod(boxedTypeClass, valueOfMethod, listOf(value)) } private fun unbox(value: Value?): Value? { if (value !is ObjectReference) { return value } val boxedTypeClass = value.referenceType() as? ClassType ?: return value val boxedType = boxedTypeClass.asmType().takeIf { it.isBoxedType } ?: return value val unboxedType = unbox(boxedType) val unboxingMethodName = UNBOXING_METHOD_NAMES.getValue(boxedType.internalName) val methodDesc = AsmType.getMethodDescriptor(unboxedType) val valueMethod = boxedTypeClass.methodsByName(unboxingMethodName, methodDesc).first() return context.invokeMethod(value, valueMethod, emptyList()) } private fun ref(value: Value?): Value { if (value is VoidValue) { return value } fun wrapRef(value: Value?, refTypeClass: ClassType): Value { val constructor = refTypeClass.methods().single { it.isConstructor } val ref = context.newInstance(refTypeClass, constructor, emptyList()) context.keepReference(ref) val elementField = refTypeClass.fieldByName("element") ?: error("'element' field not found") ref.setValue(elementField, value) return ref } if (value is PrimitiveValue) { val primitiveType = value.asmType() val refType = PRIMITIVE_TO_REF.getValue(primitiveType) val refTypeClass = (context.findClass(refType) as ClassType?) ?: error("Class $refType is not loaded") return wrapRef(value, refTypeClass) } else { val refType = AsmType.getType(Ref.ObjectRef::class.java) val refTypeClass = (context.findClass(refType) as ClassType?) ?: error("Class $refType is not loaded") return wrapRef(value, refTypeClass) } } } private fun unbox(type: AsmType): AsmType { if (type.sort == AsmType.OBJECT) { return BOXED_TO_PRIMITIVE[type] ?: type } return type } internal fun box(type: AsmType): AsmType { if (type.isPrimitiveType) { return PRIMITIVE_TO_BOXED[type] ?: type } return type } private fun unwrap(type: AsmType): AsmType { if (type.sort != AsmType.OBJECT) { return type } return REF_TO_PRIMITIVE[type] ?: BOXED_TO_PRIMITIVE[type] ?: type } private val AsmType.isPrimitiveType: Boolean get() = sort != AsmType.OBJECT && sort != AsmType.ARRAY internal val AsmType.isRefType: Boolean get() = sort == AsmType.OBJECT && this in REF_TYPES internal val Value?.isRefType: Boolean get() = this is ObjectReference && AsmType.getType(this.referenceType().signature()).isRefType private val AsmType.isBoxedType: Boolean get() = this in BOXED_TO_PRIMITIVE private fun Value.asmType(): AsmType { return type().asmType() } private fun JdiType.asmType(): AsmType { return AsmType.getType(signature()) } private val BOXED_TO_PRIMITIVE: Map<AsmType, AsmType> = JvmPrimitiveType.values() .map { Pair(AsmType.getObjectType(it.wrapperFqName.internalNameWithoutInnerClasses), AsmType.getType(it.desc)) } .toMap() private val PRIMITIVE_TO_BOXED: Map<AsmType, AsmType> = BOXED_TO_PRIMITIVE.map { (k, v) -> Pair(v, k) }.toMap() private val REF_TO_PRIMITIVE = mapOf( Ref.ByteRef::class.java.name to AsmType.BYTE_TYPE, Ref.ShortRef::class.java.name to AsmType.SHORT_TYPE, Ref.IntRef::class.java.name to AsmType.INT_TYPE, Ref.LongRef::class.java.name to AsmType.LONG_TYPE, Ref.FloatRef::class.java.name to AsmType.FLOAT_TYPE, Ref.DoubleRef::class.java.name to AsmType.DOUBLE_TYPE, Ref.CharRef::class.java.name to AsmType.CHAR_TYPE, Ref.BooleanRef::class.java.name to AsmType.BOOLEAN_TYPE ).mapKeys { (k, _) -> AsmType.getObjectType(k.replace('.', '/')) } private val PRIMITIVE_TO_REF: Map<AsmType, AsmType> = REF_TO_PRIMITIVE.map { (k, v) -> Pair(v, k) }.toMap() private val REF_TYPES: Set<AsmType> = REF_TO_PRIMITIVE.keys + AsmType.getType(Ref.ObjectRef::class.java)
apache-2.0
51e28cae132ae4c1526675eaa0d50346
34.416357
122
0.616208
4.42658
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/scripting/importing/KotlinDslSyncListener.kt
2
4814
// 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.gradleJava.scripting.importing import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListener import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListenerAdapter import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskType.EXECUTE_TASK import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskType.RESOLVE_PROJECT import com.intellij.openapi.externalSystem.service.execution.ExternalSystemJdkUtil import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil import com.intellij.openapi.projectRoots.JdkUtil import org.jetbrains.kotlin.idea.configuration.GRADLE_SYSTEM_ID import org.jetbrains.kotlin.idea.core.script.ScriptDefinitionContributor import org.jetbrains.kotlin.idea.gradleJava.scripting.GradleScriptDefinitionsContributor import org.jetbrains.kotlin.idea.gradleJava.scripting.roots.GradleBuildRootsManager import org.jetbrains.plugins.gradle.service.GradleInstallationManager import org.jetbrains.plugins.gradle.settings.GradleExecutionSettings import org.jetbrains.plugins.gradle.settings.GradleSettings import org.jetbrains.plugins.gradle.util.GradleConstants import java.util.* class KotlinDslSyncListener : ExternalSystemTaskNotificationListenerAdapter() { companion object { val instance: KotlinDslSyncListener? get() = ExternalSystemTaskNotificationListener.EP_NAME.findExtension(KotlinDslSyncListener::class.java) } internal val tasks = WeakHashMap<ExternalSystemTaskId, KotlinDslGradleBuildSync>() override fun onStart(id: ExternalSystemTaskId, workingDir: String?) { if (!id.isGradleRelatedTask()) return if (workingDir == null) return val task = KotlinDslGradleBuildSync(workingDir, id) synchronized(tasks) { tasks[id] = task } // project may be null in case of new project val project = id.findProject() ?: return task.project = project GradleBuildRootsManager.getInstance(project)?.markImportingInProgress(workingDir) } override fun onEnd(id: ExternalSystemTaskId) { if (!id.isGradleRelatedTask()) return val sync = synchronized(tasks) { tasks.remove(id) } ?: return // project may be null in case of new project val project = id.findProject() ?: return if (sync.gradleHome == null) { sync.gradleHome = ServiceManager .getService(GradleInstallationManager::class.java) .getGradleHome(project, sync.workingDir) ?.path } if (sync.javaHome == null) { sync.javaHome = ExternalSystemApiUtil .getExecutionSettings<GradleExecutionSettings>(project, sync.workingDir, GradleConstants.SYSTEM_ID) .javaHome } sync.javaHome = sync.javaHome?.takeIf { JdkUtil.checkForJdk(it) } ?: run { // roll back to specified in GRADLE_JVM if for some reason sync.javaHome points to corrupted SDK val gradleJvm = GradleSettings.getInstance(project).getLinkedProjectSettings(sync.workingDir)?.gradleJvm try { ExternalSystemJdkUtil.getJdk(project, gradleJvm)?.homePath } catch (e: Exception) { null } } @Suppress("DEPRECATION") ScriptDefinitionContributor.find<GradleScriptDefinitionsContributor>(project)?.reloadIfNeeded( sync.workingDir, sync.gradleHome, sync.javaHome ) saveScriptModels(project, sync) } override fun onFailure(id: ExternalSystemTaskId, e: Exception) { if (!id.isGradleRelatedTask()) return val sync = synchronized(tasks) { tasks[id] } ?: return sync.failed = true } override fun onCancel(id: ExternalSystemTaskId) { if (!id.isGradleRelatedTask()) return val cancelled = synchronized(tasks) { tasks.remove(id) } // project may be null in case of new project val project = id.findProject() ?: return cancelled?.let { GradleBuildRootsManager.getInstance(project)?.markImportingInProgress(it.workingDir, false) if (it.failed) { reportErrors(project, it) } } } private fun ExternalSystemTaskId.isGradleRelatedTask() = projectSystemId == GRADLE_SYSTEM_ID && (type == RESOLVE_PROJECT /*|| type == EXECUTE_TASK*/) }
apache-2.0
ad5b31c3f358d24b136aa06f7a388ac9
42.369369
158
0.706897
5.078059
false
false
false
false
spoptchev/kotlin-preconditions
src/main/kotlin/com/github/spoptchev/kotlin/preconditions/matcher/StringMatcher.kt
1
3289
package com.github.spoptchev.kotlin.preconditions.matcher import com.github.spoptchev.kotlin.preconditions.Condition import com.github.spoptchev.kotlin.preconditions.Matcher import com.github.spoptchev.kotlin.preconditions.PreconditionBlock fun PreconditionBlock<String>.startsWithIgnoreCase(prefix: String) = startsWith(prefix, true) fun PreconditionBlock<String>.startsWith(prefix: String, ignoreCase: Boolean = false) = object : Matcher<String>() { override fun test(condition: Condition<String>) = condition.test { withResult(value.startsWith(prefix, ignoreCase)) { "$expectedTo start with '$prefix'" } } } fun PreconditionBlock<String>.includesIgnoreCase(substring: String) = includes(substring, true) fun PreconditionBlock<String>.includes(substring: String, ignoreCase: Boolean = false) = object : Matcher<String>() { override fun test(condition: Condition<String>) = condition.test { withResult(value.contains(substring, ignoreCase)) { "$expectedTo include '$substring'" } } } fun PreconditionBlock<String>.matches(regex: String) = matches(Regex(regex)) fun PreconditionBlock<String>.matches(regex: Regex) = object : Matcher<String>() { override fun test(condition: Condition<String>) = condition.test { withResult(value.matches(regex)) { "$expectedTo match '$regex'" } } } fun PreconditionBlock<String>.endsWithIgnoreCase(suffix: String) = endsWith(suffix, true) fun PreconditionBlock<String>.endsWith(suffix: String, ignoreCase: Boolean = false) = object : Matcher<String>() { override fun test(condition: Condition<String>) = condition.test { withResult(value.endsWith(suffix, ignoreCase)) { "$expectedTo end with '$suffix'" } } } fun PreconditionBlock<String>.hasLength(length: Int) = object : Matcher<String>() { override fun test(condition: Condition<String>) = condition.test { withResult(value.length == length) { "$expectedTo have length $length" } } } fun PreconditionBlock<String>.hasLengthBetween(min: Int, max: Int) = object : Matcher<String>() { override fun test(condition: Condition<String>) = condition.test { withResult(value.length in min..max) { "$expectedTo have length between $min and $max" } } } fun PreconditionBlock<String>.isEqualToIgnoreCase(other: String) = isEqualTo(other, true) fun PreconditionBlock<String>.isEqualTo(other: String, ignoreCase: Boolean = false) = object : Matcher<String>() { override fun test(condition: Condition<String>) = condition.test { withResult(value.equals(other, ignoreCase)) { "$expectedTo be equal to '$other'" } } } fun PreconditionBlock<String?>.isBlank() = object : Matcher<String?>() { override fun test(condition: Condition<String?>) = condition.test { withResult(value?.isBlank() ?: true) { "$expectedTo be blank" } } } @JvmName("nonNullIsBlank") fun PreconditionBlock<String>.isBlank() = object : Matcher<String>() { override fun test(condition: Condition<String>) = condition.test { withResult(value.isBlank()) { "$expectedTo be blank" } } } fun PreconditionBlock<String>.isEmpty() = object : Matcher<String>() { override fun test(condition: Condition<String>) = condition.test { withResult(value.isEmpty()) { "$expectedTo be empty" } } }
mit
c47a19a9eb545c01488cd4be9034dc15
44.680556
117
0.720584
3.943645
false
true
false
false
sreich/ore-infinium
core/src/com/ore/infinium/util/ArtemisExtensions.kt
1
12204
/** MIT License Copyright (c) 2016 Shaun Reich <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ @file:Suppress("NOTHING_TO_INLINE") package com.ore.infinium.util import com.artemis.* import com.artemis.managers.TagManager import com.artemis.utils.Bag import com.artemis.utils.IntBag import kotlin.properties.ReadOnlyProperty import kotlin.reflect.KClass import kotlin.reflect.KMutableProperty import kotlin.reflect.KProperty /** * indicates an invalid/unset entity id */ const val INVALID_ENTITY_ID = -1 inline fun isValidEntity(entityId: Int) = entityId != INVALID_ENTITY_ID inline fun isInvalidEntity(entityId: Int) = entityId == INVALID_ENTITY_ID typealias OreEntityId = Int fun World.oreInject(obj: Any) { this.inject(obj) } inline fun <reified T : BaseSystem> World.system() = getSystem(T::class.java)!! interface OreEntitySubscriptionListener : EntitySubscription.SubscriptionListener { override fun inserted(entities: IntBag) = Unit override fun removed(entities: IntBag) = Unit } /** * A marker interface that indicates that this system should only be * processed by the render portion of the game loop. Separating the logic * and the render ticks, so that we can decide how often to process them (how * many ms per frame, etc) */ interface RenderSystemMarker /** * Denotes that a component property should not be copied */ @Retention @Target(AnnotationTarget.PROPERTY) annotation class DoNotCopy interface ExtendedComponent<T : ExtendedComponent<T>> { /** * copy a component (similar to copy constructor) * * @param other * component to copy from, into this instance */ fun copyFrom(other: T): Unit // todo: we may actually want to instead have a combine function, //whose result is the combination of both // (otherwise how do we know how to combine them properly?) fun canCombineWith(other: T): Boolean fun printString(): String { return getCache(javaClass).printProperties.map { "${javaClass.simpleName}.${it.name} = ${it.getter.call(this)}" } .joinToString(separator = "\n", postfix = "\n") } fun defaultPrintString(): String { return getCache(javaClass).printProperties.map { "${javaClass.simpleName}.${it.name} = ${it.getter.call(this)}" } .joinToString(separator = "\n", postfix = "\n") } } /** * Denotes that a component property should not be printed on-screen in debug mode */ @Retention @Target(AnnotationTarget.PROPERTY, AnnotationTarget.PROPERTY_GETTER) annotation class DoNotPrint fun World.getComponentsForEntity(entity: Int): Bag<Component> { val bag = Bag<Component>() componentManager.getComponentsFor(entity, bag) return bag } fun World.entities(aspect: Aspect.Builder): IntBag = this.aspectSubscriptionManager.get(aspect).entities //object ArtemisExtensions { fun allOf(vararg types: KClass<out Component>): Aspect.Builder = Aspect.all(types.map { it.java }) fun anyOf(vararg types: KClass<out Component>): Aspect.Builder = Aspect.one(types.map { it.java }) fun noneOf(vararg types: KClass<out Component>): Aspect.Builder = Aspect.exclude(types.map { it.java }) fun <T : Component> ComponentMapper<T>.opt(entityId: Int): T? = if (has(entityId)) get(entityId) else null inline fun <T : Component> ComponentMapper<T>.ifPresent(entityId: Int, function: (T) -> Unit): Unit { //fixme change has to just 1 get, since has calls get anyway if (has(entityId)) function(get(entityId)) } fun TagManager.opt(entityId: Int): String? { return this.getTag(entityId) ?: null } /* inline fun <T> IntBag.forEachIndexed(action: (Int, T) -> Unit): Unit { var index = 0 for (item in this) action(index++, item) } */ inline fun IntBag.forEach(action: (Int) -> Unit): Unit { for (i in indices) action(this.get(i)) } //public inline fun <T> Array<out T>.forEach(action: (T) -> Unit): Unit { // for (element in this) action(element) //} fun IntBag.toMutableList(): MutableList<Int> { val list = mutableListOf<Int>() this.forEach { list.add(it) } return list } val IntBag.indices: IntRange get() = 0..size() - 1 val <T : Any> Bag<T>.indices: IntRange get() = 0..size() - 1 /* inline fun <T> Array<out T>.forEachIndexed(action: (Int, T) -> Unit): Unit { var index = 0 for (item in this) action(index++, item) } */ private class MapperProperty<T : Component>(val type: Class<T>) : ReadOnlyProperty<BaseSystem, ComponentMapper<T>> { private var cachedMapper: ComponentMapper<T>? = null override fun getValue(thisRef: BaseSystem, property: KProperty<*>): ComponentMapper<T> { if (cachedMapper == null) { val worldField = BaseSystem::class.java.getDeclaredField("world") worldField.isAccessible = true val world = worldField.get(thisRef) as World? world ?: throw IllegalStateException("world is not initialized yet") cachedMapper = world.getMapper(type) } return cachedMapper!! } } private class SystemProperty<T : BaseSystem>(val type: Class<T>) : ReadOnlyProperty<BaseSystem, T> { private var cachedSystem: T? = null override fun getValue(thisRef: BaseSystem, property: KProperty<*>): T { if (cachedSystem == null) { val worldField = BaseSystem::class.java.getDeclaredField("world") worldField.isAccessible = true val world = worldField.get(thisRef) as World? world ?: throw IllegalStateException("world is not initialized yet") cachedSystem = world.getSystem(type) } return cachedSystem!! } } /** * Gets a delegate that returns the `ComponentMapper` for the given component type. * * @param T the component type. */ inline fun <reified T : Component> BaseSystem.mapper(): ReadOnlyProperty<BaseSystem, ComponentMapper<T>> = mapper( T::class) /** * Gets a delegate that returns the `ComponentMapper` for the given component type. * * @param T the component type. * @param type the component class. */ fun <T : Component> BaseSystem.mapper(type: KClass<T>): ReadOnlyProperty<BaseSystem, ComponentMapper<T>> = MapperProperty<T>( type.java) /** * Gets a delegate that returns the `ComponentMapper` for the given component type, and adds the component type * to the system's aspect configuration. Note that this must be called from constructor code, or it won't be effective! * * @param T the component type. */ inline fun <reified T : Component> BaseEntitySystem.require(): ReadOnlyProperty<BaseSystem, ComponentMapper<T>> = require( T::class) /** * Gets a delegate that returns the `ComponentMapper` for the given component type, and adds the component type * to the system's aspect configuration. Note that this must be called from constructor code, or it won't be effective! * * @param T the component type. * @param type the component class. */ fun <T : Component> BaseEntitySystem.require(type: KClass<T>): ReadOnlyProperty<BaseSystem, ComponentMapper<T>> { val aspectConfigurationField = BaseEntitySystem::class.java.getDeclaredField("aspectConfiguration") aspectConfigurationField.isAccessible = true val aspectConfiguration = aspectConfigurationField.get(this) as Aspect.Builder aspectConfiguration.all(type.java) return MapperProperty<T>(type.java) } /** * Gets a delegate that returns the `EntitySystem` of the given type. * * @param T the system type. */ inline fun <reified T : BaseSystem> BaseSystem.system(): ReadOnlyProperty<BaseSystem, T> = system(T::class) /** * Gets a delegate that returns the `EntitySystem` of the given type. * * @param T the system type. * @param type the system class. */ fun <T : BaseSystem> BaseSystem.system(type: KClass<T>): ReadOnlyProperty<BaseSystem, T> = SystemProperty<T>(type.java) private val cacheByType = hashMapOf<Class<*>, PropertyCache>() private fun getCache(clazz: Class<*>): PropertyCache = cacheByType.getOrPut(clazz, { PropertyCache(clazz.kotlin) }) /** * Cache that stores properties of component implementations. */ private class PropertyCache(clazz: KClass<*>) { val copyProperties = clazz.members.mapNotNull { it as? KMutableProperty } .filter { !it.annotations.any { it.annotationClass == DoNotCopy::class } }.toTypedArray() val printProperties = clazz.members.mapNotNull { it as? KProperty } .filter { !it.annotations.any { it.annotationClass == DoNotPrint::class } && !it.getter.annotations.any { it.annotationClass == DoNotPrint::class } }.toTypedArray() } /** * copy a component (similar to copy constructor) * * @param other * component to copy from, into this instance */ fun <T : Component> T.copyFrom(other: T) { if (this is ExtendedComponent<*>) { this.internalCopyFrom<InternalExtendedComponent>(other) } else { this.defaultCopyFrom(other) } } fun <T : Component> T.canCombineWith(other: T): Boolean { if (this is ExtendedComponent<*>) { return this.internalCanCombineWith<InternalExtendedComponent>(other) } return false } fun <T : Component> T.printString(): String { if (this is ExtendedComponent<*>) { return this.internalPrintString<InternalExtendedComponent>() } return "ERROR! can't print string of this component. It is not an ExtendedComponent. " + "Please derive this component (${this.javaClass}) from ExtendedComponent\n" } /** * copy a component (similar to copy constructor) * * @param other * component to copy from, into this instance */ fun <T : Component> T.defaultCopyFrom(other: T): Unit { getCache(javaClass).copyProperties.forEach { it.setter.call(this, it.getter.call(other)) } } // Just hacking around Kotlin generics... @Suppress("UNCHECKED_CAST") private fun <T : ExtendedComponent<T>> Any.internalCopyFrom(other: Any) { (this as T).copyFrom(other as T) } @Suppress("UNCHECKED_CAST") private fun <T : ExtendedComponent<T>> Any.internalCanCombineWith(other: Any) = (this as T).canCombineWith(other as T) @Suppress("UNCHECKED_CAST") private fun <T : ExtendedComponent<T>> Any.internalPrintString() = (this as T).printString() private class InternalExtendedComponent : ExtendedComponent<InternalExtendedComponent> { override fun canCombineWith(other: InternalExtendedComponent): Boolean = throw TODO("function not yet implemented") override fun copyFrom(other: InternalExtendedComponent) = throw TODO("function not yet implemented") override fun printString() = throw TODO("function not yet implemented") } // TODO: Might want to introduce PrintableComponent interface //fun <T : Component> T.printString(): String { // this // return this.defaultPrintString() //} //fun <T : ExtendedComponent> T.defaultPrintString(): String = // getCache(javaClass).printProperties.map { "${javaClass.simpleName}.${it.name} = ${it.getter.call(this)}" } // .joinToString(separator = "\n", postfix = "\n")
mit
96ee492d7e21d5216787b775ad33a2cd
33.184874
125
0.699197
4.082971
false
false
false
false
DreierF/MyTargets
app/src/main/java/de/dreier/mytargets/features/statistics/ChipGroup.kt
1
6269
/* * Copyright (C) 2018 Florian Dreier * * This file is part of MyTargets. * * MyTargets is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * MyTargets 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. */ package de.dreier.mytargets.features.statistics import android.content.Context import android.util.AttributeSet import android.util.TypedValue import android.view.View import android.view.ViewGroup import java.util.* class ChipGroup @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : ViewGroup(context, attrs, defStyleAttr) { private var tagList: MutableList<Tag> = ArrayList() private val horizontalSpacing = dp2px(8.0f).toInt() private val verticalSpacing = dp2px(4.0f).toInt() /** * Listener used to dispatch tag click event. */ private var onSelectionChangedListener: ((Tag) -> Unit)? = null /** * Returns the tag list in group. * * @return the tag list. */ /** * Set the tags. It will remove all previous tags first. * If the list of tags contains less than 2 elements the view sets its visibility to gone. * * @param tags the tag list to set. */ var tags: List<Tag> get() = ArrayList(tagList) set(tags) { tagList.clear() tagList.addAll(tags) notifyTagsListChanged() } /** * Returns the checked tag list in group. * * @return the tag list. */ val checkedTags: List<Tag> get() = tagList.filter { it.isChecked } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val widthMode = View.MeasureSpec.getMode(widthMeasureSpec) val heightMode = View.MeasureSpec.getMode(heightMeasureSpec) val widthSize = View.MeasureSpec.getSize(widthMeasureSpec) val heightSize = View.MeasureSpec.getSize(heightMeasureSpec) measureChildren(widthMeasureSpec, heightMeasureSpec) var width: Int var height = 0 var row = 0 // The row counter. var rowWidth = 0 // Calc the current row width. var rowMaxHeight = 0 // Calc the max tag height, in current row. val count = childCount for (i in 0 until count) { val child = getChildAt(i) val childWidth = child.measuredWidth val childHeight = child.measuredHeight if (child.visibility != View.GONE) { rowWidth += childWidth if (rowWidth > widthSize) { // Next line. rowWidth = childWidth // The next row width. height += rowMaxHeight + verticalSpacing rowMaxHeight = childHeight // The next row max height. row++ } else { // This line. rowMaxHeight = Math.max(rowMaxHeight, childHeight) } rowWidth += horizontalSpacing } } // Account for the last row height. height += rowMaxHeight // Account for the padding too. height += paddingTop + paddingBottom // If the tags grouped in one row, set the width to wrap the tags. if (row == 0) { width = rowWidth width += paddingLeft + paddingRight } else { // If the tags grouped exceed one line, set the width to match the parent. width = widthSize } setMeasuredDimension( if (widthMode == View.MeasureSpec.EXACTLY) widthSize else width, if (heightMode == View.MeasureSpec.EXACTLY) heightSize else height ) } override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) { val parentLeft = paddingLeft val parentRight = r - l - paddingRight val parentTop = paddingTop var childLeft = parentLeft var childTop = parentTop var rowMaxHeight = 0 val count = childCount for (i in 0 until count) { val child = getChildAt(i) val width = child.measuredWidth val height = child.measuredHeight if (child.visibility != View.GONE) { if (childLeft + width > parentRight) { // Next line childLeft = parentLeft childTop += rowMaxHeight + verticalSpacing rowMaxHeight = height } else { rowMaxHeight = Math.max(rowMaxHeight, height) } child.layout(childLeft, childTop, childLeft + width, childTop + height) childLeft += width + horizontalSpacing } } } fun notifyTagsListChanged() { removeAllViews() for (tag in tagList) { appendTag(tag) } } /** * Append tag to this group. * * @param tag the tag to append. */ private fun appendTag(tag: Tag) { val binding = tag.getView(context, this) binding.root.setOnClickListener { tag.isChecked = !tag.isChecked binding.root.isActivated = !tag.isChecked onSelectionChangedListener?.invoke(tag) } addView(binding.root) } private fun dp2px(dp: Float): Float { return TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, dp, resources.displayMetrics ) } override fun generateLayoutParams(attrs: AttributeSet): ViewGroup.LayoutParams { return ChipGroup.LayoutParams(context, attrs) } /** * Register a callback to be invoked when a tag is clicked. * * @param l the callback that will run. */ fun setOnTagClickListener(l: (Tag) -> Unit) { onSelectionChangedListener = l } /** * Per-child layout information for layouts. */ class LayoutParams(c: Context, attrs: AttributeSet) : ViewGroup.LayoutParams(c, attrs) }
gpl-2.0
faf69b73686fd909156aca9a06a11e58
30.345
94
0.598979
4.792813
false
false
false
false
google/intellij-community
plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/idea/caches/resolve/ResolutionUtils.kt
6
10338
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:JvmName("ResolutionUtils") package org.jetbrains.kotlin.idea.caches.resolve import org.jetbrains.kotlin.analyzer.AnalysisResult import org.jetbrains.kotlin.caches.resolve.KotlinCacheService import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.ModuleDescriptor import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.FrontendInternals import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.BindingTraceContext import org.jetbrains.kotlin.resolve.ImportPath import org.jetbrains.kotlin.resolve.QualifiedExpressionResolver import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode fun KtElement.getResolutionFacade(): ResolutionFacade = KotlinCacheService.getInstance(project).getResolutionFacade(this) /** * For local declarations is equivalent to unsafeResolveToDescriptor(bodyResolveMode) * * But for non-local declarations it ignores bodyResolveMode and uses LazyDeclarationResolver directly */ @Deprecated( message = "This function has unclear semantics. Please use either unsafeResolveToDescriptor or resolveToDescriptorIfAny instead", replaceWith = ReplaceWith("unsafeResolveToDescriptor") ) fun KtDeclaration.resolveToDescriptor(bodyResolveMode: BodyResolveMode = BodyResolveMode.FULL): DeclarationDescriptor = getResolutionFacade().resolveToDescriptor(this, bodyResolveMode) /** * This function throws exception when resolveToDescriptorIfAny returns null, otherwise works equivalently. * * **Please, use overload with providing resolutionFacade for stable results of subsequent calls** */ fun KtDeclaration.unsafeResolveToDescriptor( bodyResolveMode: BodyResolveMode = BodyResolveMode.FULL ): DeclarationDescriptor = unsafeResolveToDescriptor(getResolutionFacade(), bodyResolveMode) /** * This function first uses declaration resolvers to resolve this declaration and/or additional declarations (e.g. its parent), * and then takes the relevant descriptor from binding context. * The exact set of declarations to resolve depends on bodyResolveMode * * **Please, use overload with providing resolutionFacade for stable results of subsequent calls** */ fun KtDeclaration.resolveToDescriptorIfAny( bodyResolveMode: BodyResolveMode = BodyResolveMode.PARTIAL ): DeclarationDescriptor? = resolveToDescriptorIfAny(getResolutionFacade(), bodyResolveMode) /** * **Please, use overload with providing resolutionFacade for stable results of subsequent calls** */ fun KtClassOrObject.resolveToDescriptorIfAny(bodyResolveMode: BodyResolveMode = BodyResolveMode.PARTIAL) = resolveToDescriptorIfAny(getResolutionFacade(), bodyResolveMode) /** * **Please, use overload with providing resolutionFacade for stable results of subsequent calls** */ fun KtNamedFunction.resolveToDescriptorIfAny(bodyResolveMode: BodyResolveMode = BodyResolveMode.PARTIAL) = resolveToDescriptorIfAny(getResolutionFacade(), bodyResolveMode) /** * **Please, use overload with providing resolutionFacade for stable results of subsequent calls** */ fun KtProperty.resolveToDescriptorIfAny(bodyResolveMode: BodyResolveMode = BodyResolveMode.PARTIAL) = resolveToDescriptorIfAny(getResolutionFacade(), bodyResolveMode) /** * **Please, use overload with providing resolutionFacade for stable results of subsequent calls** */ fun KtParameter.resolveToParameterDescriptorIfAny(bodyResolveMode: BodyResolveMode = BodyResolveMode.PARTIAL) = resolveToParameterDescriptorIfAny(getResolutionFacade(), bodyResolveMode) /** * **Please, use overload with providing resolutionFacade for stable results of subsequent calls** */ fun KtElement.resolveToCall(bodyResolveMode: BodyResolveMode = BodyResolveMode.PARTIAL) = resolveToCall(getResolutionFacade(), bodyResolveMode) fun KtFile.resolveImportReference(fqName: FqName): Collection<DeclarationDescriptor> { val facade = getResolutionFacade() return facade.resolveImportReference(facade.moduleDescriptor, fqName) } fun KtAnnotationEntry.resolveToDescriptorIfAny( bodyResolveMode: BodyResolveMode = BodyResolveMode.PARTIAL_NO_ADDITIONAL ): AnnotationDescriptor? = resolveToDescriptorIfAny(getResolutionFacade(), bodyResolveMode) // This and next functions are used for 'normal' element analysis // This analysis *should* provide all information extractable from this KtElement except: // - for declarations, it does not analyze their bodies // - for classes, it does not analyze their content // - for member / top-level properties, it does not analyze initializers / accessors // This information includes related descriptors, resolved calls (but not inside body, see above!) // and many other binding context slices. // Normally, the function is used on local declarations or statements / expressions // Any usage on non-local declaration is a bit suspicious, // consider replacing it with resolveToDescriptorIfAny and // remember that body / content is not analyzed; // if it's necessary, use analyzeWithContent() // // If you need diagnostics in result context, use BodyResolveMode.PARTIAL_WITH_DIAGNOSTICS. // BodyResolveMode.FULL analyzes all statements on the level of KtElement and above. // BodyResolveMode.PARTIAL analyzes only statements necessary for this KtElement precise analysis. // // See also: ResolveSessionForBodies, ResolveElementCache /** * **Please, use overload with providing resolutionFacade for stable results of subsequent calls** */ @JvmOverloads fun KtElement.analyze( bodyResolveMode: BodyResolveMode = BodyResolveMode.FULL ): BindingContext = analyze(getResolutionFacade(), bodyResolveMode) @JvmOverloads fun KtElement.safeAnalyze( bodyResolveMode: BodyResolveMode = BodyResolveMode.FULL ): BindingContext = safeAnalyze(getResolutionFacade(), bodyResolveMode) /** * **Please, use overload with providing resolutionFacade for stable results of subsequent calls** */ fun KtElement.analyzeAndGetResult(): AnalysisResult = analyzeAndGetResult(getResolutionFacade()) /** * **Please, use overload with providing resolutionFacade for stable results of subsequent calls** */ fun KtElement.analyzeWithContentAndGetResult(): AnalysisResult = analyzeWithContentAndGetResult(getResolutionFacade()) fun KtElement.findModuleDescriptor(): ModuleDescriptor = getResolutionFacade().moduleDescriptor // This function is used on declarations to make analysis not only declaration itself but also it content: // body for declaration with body, initializer & accessors for properties /** * **Please, use overload with providing resolutionFacade for stable results of subsequent calls** */ fun KtDeclaration.analyzeWithContent(): BindingContext = analyzeWithContent(getResolutionFacade()) // This function is used to make full analysis of declaration container. // All its declarations, including their content (see above), are analyzed. /** * **Please, use overload with providing resolutionFacade for stable results of subsequent calls** */ inline fun <reified T> T.analyzeWithContent(): BindingContext where T : KtDeclarationContainer, T : KtElement = analyzeWithContent(getResolutionFacade()) /** * This function is expected to produce the same result as compiler for the whole file content (including diagnostics, * trace slices, descriptors, etc.). * * It's not recommended to call this function without real need. * * @ref [KotlinCacheService] * @ref [org.jetbrains.kotlin.idea.caches.resolve.PerFileAnalysisCache] */ fun KtFile.analyzeWithAllCompilerChecks(vararg extraFiles: KtFile): AnalysisResult = this.analyzeWithAllCompilerChecks(null, *extraFiles) fun KtFile.analyzeWithAllCompilerChecks(callback: ((Diagnostic) -> Unit)?, vararg extraFiles: KtFile): AnalysisResult { return if (extraFiles.isEmpty()) { KotlinCacheService.getInstance(project).getResolutionFacade(this) .analyzeWithAllCompilerChecks(this, callback) } else { KotlinCacheService.getInstance(project).getResolutionFacade(listOf(this) + extraFiles.toList()) .analyzeWithAllCompilerChecks(this, callback) } } /** * This function is expected to produce the same result as compiler for the given element and its children (including diagnostics, * trace slices, descriptors, etc.). For some expression element it actually performs analyze for some parent (usually declaration). * * It's not recommended to call this function without real need. * * NB: for statements / expressions, usually should be replaced with analyze(), * for declarations, analyzeWithContent() will do what you want. * * @ref [KotlinCacheService] * @ref [org.jetbrains.kotlin.idea.caches.resolve.PerFileAnalysisCache] */ @Deprecated( "Use either KtFile.analyzeWithAllCompilerChecks() or KtElement.analyzeAndGetResult()", ReplaceWith("analyzeAndGetResult()") ) fun KtElement.analyzeWithAllCompilerChecks(): AnalysisResult = getResolutionFacade().analyzeWithAllCompilerChecks(this) // this method don't check visibility and collect all descriptors with given fqName @OptIn(FrontendInternals::class) fun ResolutionFacade.resolveImportReference( moduleDescriptor: ModuleDescriptor, fqName: FqName ): Collection<DeclarationDescriptor> { val importDirective = KtPsiFactory(project).createImportDirective(ImportPath(fqName, false)) val qualifiedExpressionResolver = this.getFrontendService(moduleDescriptor, QualifiedExpressionResolver::class.java) return qualifiedExpressionResolver.processImportReference( importDirective, moduleDescriptor, BindingTraceContext(), excludedImportNames = emptyList(), packageFragmentForVisibilityCheck = null )?.getContributedDescriptors() ?: emptyList() } @Suppress("DEPRECATION") @Deprecated( "This method is going to be removed in 1.3.0 release", ReplaceWith("analyzeWithAllCompilerChecks().bindingContext"), DeprecationLevel.ERROR ) fun KtElement.analyzeFully(): BindingContext = analyzeWithAllCompilerChecks().bindingContext
apache-2.0
b0500ad974901d719a8cf8a63d24d200
46.205479
137
0.800251
5.519487
false
false
false
false
google/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/expectactual/ExpectActualUtils.kt
1
19495
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix.expectactual import com.intellij.openapi.editor.Editor import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.psi.JavaDirectoryService import com.intellij.psi.PsiElement import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor import org.jetbrains.kotlin.descriptors.annotations.Annotations import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNameSuggester import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent import org.jetbrains.kotlin.idea.codeInsight.shorten.addToBeShortenedDescendantsToWaitingSet import org.jetbrains.kotlin.idea.core.findOrCreateDirectoryForPackage import org.jetbrains.kotlin.idea.core.getFqNameWithImplicitPrefix import org.jetbrains.kotlin.idea.core.overrideImplement.MemberGenerateMode import org.jetbrains.kotlin.idea.core.overrideImplement.BodyType.EmptyOrTemplate import org.jetbrains.kotlin.idea.core.overrideImplement.BodyType.NoBody import org.jetbrains.kotlin.idea.core.overrideImplement.OverrideMemberChooserObject.Companion.create import org.jetbrains.kotlin.idea.core.overrideImplement.generateMember import org.jetbrains.kotlin.idea.core.overrideImplement.makeNotActual import org.jetbrains.kotlin.idea.core.toDescriptor import org.jetbrains.kotlin.idea.codeinsight.utils.findExistingEditor import org.jetbrains.kotlin.idea.quickfix.TypeAccessibilityChecker import org.jetbrains.kotlin.idea.refactoring.createKotlinFile import org.jetbrains.kotlin.idea.refactoring.fqName.fqName import org.jetbrains.kotlin.idea.refactoring.introduce.showErrorHint import org.jetbrains.kotlin.idea.refactoring.isInterfaceClass import org.jetbrains.kotlin.idea.util.* import org.jetbrains.kotlin.idea.util.application.runWriteAction import org.jetbrains.kotlin.lexer.KtModifierKeywordToken import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.psi.psiUtil.hasActualModifier import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.checkers.OptInNames import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull import org.jetbrains.kotlin.resolve.multiplatform.OptionalAnnotationUtil import org.jetbrains.kotlin.resolve.source.KotlinSourceElement import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.utils.addToStdlib.safeAs fun createFileForDeclaration(module: Module, declaration: KtNamedDeclaration): KtFile? { val fileName = declaration.name ?: return null val originalDir = declaration.containingFile.containingDirectory val containerPackage = JavaDirectoryService.getInstance().getPackage(originalDir) val packageDirective = declaration.containingKtFile.packageDirective val directory = findOrCreateDirectoryForPackage( module, containerPackage?.qualifiedName ?: "" ) ?: return null return runWriteAction { val fileNameWithExtension = "$fileName.kt" val existingFile = directory.findFile(fileNameWithExtension) val packageName = if (packageDirective?.packageNameExpression == null) directory.getFqNameWithImplicitPrefix()?.asString() else packageDirective.fqName.asString() if (existingFile is KtFile) { val existingPackageDirective = existingFile.packageDirective if (existingFile.declarations.isNotEmpty() && existingPackageDirective?.fqName != packageDirective?.fqName ) { val newName = Fe10KotlinNameSuggester.suggestNameByName(fileName) { directory.findFile("$it.kt") == null } + ".kt" createKotlinFile(newName, directory, packageName) } else { existingFile } } else { createKotlinFile(fileNameWithExtension, directory, packageName) } } } fun KtPsiFactory.createClassHeaderCopyByText(originalClass: KtClassOrObject): KtClassOrObject { val text = originalClass.text return when (originalClass) { is KtObjectDeclaration -> if (originalClass.isCompanion()) { createCompanionObject(text) } else { createObject(text) } is KtEnumEntry -> createEnumEntry(text) else -> createClass(text) }.apply { declarations.forEach(KtDeclaration::delete) primaryConstructor?.delete() } } fun KtNamedDeclaration?.getTypeDescription(): String = when (this) { is KtObjectDeclaration -> KotlinBundle.message("text.object") is KtClass -> when { isInterface() -> KotlinBundle.message("text.interface") isEnum() -> KotlinBundle.message("text.enum.class") isAnnotation() -> KotlinBundle.message("text.annotation.class") else -> KotlinBundle.message("text.class") } is KtProperty, is KtParameter -> KotlinBundle.message("text.property") is KtFunction -> KotlinBundle.message("text.function") else -> KotlinBundle.message("text.declaration") } internal fun KtPsiFactory.generateClassOrObject( project: Project, generateExpectClass: Boolean, originalClass: KtClassOrObject, checker: TypeAccessibilityChecker ): KtClassOrObject { val generatedClass = createClassHeaderCopyByText(originalClass) val context = originalClass.analyzeWithContent() val superNames = repairSuperTypeList( generatedClass, originalClass, generateExpectClass, checker, context ) generatedClass.annotationEntries.zip(originalClass.annotationEntries).forEach { (generatedEntry, originalEntry) -> val annotationDescriptor = context.get(BindingContext.ANNOTATION, originalEntry) if (annotationDescriptor?.isValidInModule(checker) != true) { generatedEntry.delete() } } if (generateExpectClass) { if (originalClass.isTopLevel()) { generatedClass.addModifier(KtTokens.EXPECT_KEYWORD) } else { generatedClass.makeNotActual() } generatedClass.removeModifier(KtTokens.DATA_KEYWORD) } else { if (generatedClass !is KtEnumEntry) { generatedClass.addModifier(KtTokens.ACTUAL_KEYWORD) } } val existingFqNamesWithSuperTypes = (checker.existingTypeNames + superNames).toSet() declLoop@ for (originalDeclaration in originalClass.declarations) { val descriptor = originalDeclaration.toDescriptor() ?: continue if (generateExpectClass && !originalDeclaration.isEffectivelyActual(false)) continue val generatedDeclaration: KtDeclaration = when (originalDeclaration) { is KtClassOrObject -> generateClassOrObject( project, generateExpectClass, originalDeclaration, checker ) is KtFunction, is KtProperty -> checker.runInContext(existingFqNamesWithSuperTypes) { generateCallable( project, generateExpectClass, originalDeclaration as KtCallableDeclaration, descriptor as CallableMemberDescriptor, generatedClass, this ) } else -> continue@declLoop } generatedClass.addDeclaration(generatedDeclaration) } if (!originalClass.isAnnotation() && originalClass.safeAs<KtClass>()?.isInlineOrValue() == false) { for (originalProperty in originalClass.primaryConstructorParameters) { if (!originalProperty.hasValOrVar() || !originalProperty.hasActualModifier()) continue val descriptor = originalProperty.toDescriptor() as? PropertyDescriptor ?: continue checker.runInContext(existingFqNamesWithSuperTypes) { val generatedProperty = generateCallable( project, generateExpectClass, originalProperty, descriptor, generatedClass, this ) generatedClass.addDeclaration(generatedProperty) } } } val originalPrimaryConstructor = originalClass.primaryConstructor if ( generatedClass is KtClass && originalPrimaryConstructor != null && (!generateExpectClass || originalPrimaryConstructor.hasActualModifier()) ) { val descriptor = originalPrimaryConstructor.toDescriptor() if (descriptor is FunctionDescriptor) { checker.runInContext(existingFqNamesWithSuperTypes) { val expectedPrimaryConstructor = generateCallable( project, generateExpectClass, originalPrimaryConstructor, descriptor, generatedClass, this ) generatedClass.createPrimaryConstructorIfAbsent().replace(expectedPrimaryConstructor) } } } return generatedClass } private fun KtPsiFactory.repairSuperTypeList( generated: KtClassOrObject, original: KtClassOrObject, generateExpectClass: Boolean, checker: TypeAccessibilityChecker, context: BindingContext ): Collection<String> { val superNames = linkedSetOf<String>() val typeParametersFqName = context[BindingContext.DECLARATION_TO_DESCRIPTOR, original] ?.safeAs<ClassDescriptor>() ?.declaredTypeParameters?.mapNotNull { it.fqNameOrNull()?.asString() }.orEmpty() checker.runInContext(checker.existingTypeNames + typeParametersFqName) { generated.superTypeListEntries.zip(original.superTypeListEntries).forEach { (generatedEntry, originalEntry) -> val superType = context[BindingContext.TYPE, originalEntry.typeReference] val superClassDescriptor = superType?.constructor?.declarationDescriptor as? ClassDescriptor ?: return@forEach if (generateExpectClass && !checker.checkAccessibility(superType)) { generatedEntry.delete() return@forEach } superType.fqName?.shortName()?.asString()?.let { superNames += it } if (generateExpectClass) { if (generatedEntry !is KtSuperTypeCallEntry) return@forEach } else { if (generatedEntry !is KtSuperTypeEntry) return@forEach } if (superClassDescriptor.kind == ClassKind.CLASS || superClassDescriptor.kind == ClassKind.ENUM_CLASS) { val entryText = IdeDescriptorRenderers.SOURCE_CODE.renderType(superType) val newGeneratedEntry = if (generateExpectClass) { createSuperTypeEntry(entryText) } else { createSuperTypeCallEntry("$entryText()") } generatedEntry.replace(newGeneratedEntry).safeAs<KtElement>()?.addToBeShortenedDescendantsToWaitingSet() } } } if (generated.superTypeListEntries.isEmpty()) generated.getSuperTypeList()?.delete() return superNames } private val forbiddenAnnotationFqNames = setOf( OptionalAnnotationUtil.OPTIONAL_EXPECTATION_FQ_NAME, FqName("kotlin.ExperimentalMultiplatform"), OptInNames.OPT_IN_FQ_NAME, OptInNames.OLD_USE_EXPERIMENTAL_FQ_NAME ) internal fun generateCallable( project: Project, generateExpect: Boolean, originalDeclaration: KtDeclaration, descriptor: CallableMemberDescriptor, generatedClass: KtClassOrObject? = null, checker: TypeAccessibilityChecker ): KtCallableDeclaration { descriptor.checkAccessibility(checker) val memberChooserObject = create( originalDeclaration, descriptor, descriptor, if (generateExpect || descriptor.modality == Modality.ABSTRACT) NoBody else EmptyOrTemplate ) return memberChooserObject.generateMember( targetClass = generatedClass, copyDoc = true, project = project, mode = if (generateExpect) MemberGenerateMode.EXPECT else MemberGenerateMode.ACTUAL ).apply { repair(generatedClass, descriptor, checker) } } private fun CallableMemberDescriptor.checkAccessibility(checker: TypeAccessibilityChecker) { val errors = checker.incorrectTypes(this).ifEmpty { return } throw KotlinTypeInaccessibleException(errors.toSet()) } private fun KtCallableDeclaration.repair( generatedClass: KtClassOrObject?, descriptor: CallableDescriptor, checker: TypeAccessibilityChecker ) { if (generatedClass != null) repairOverride(descriptor, checker) repairAnnotationEntries(this, descriptor, checker) } private fun KtCallableDeclaration.repairOverride(descriptor: CallableDescriptor, checker: TypeAccessibilityChecker) { if (!hasModifier(KtTokens.OVERRIDE_KEYWORD)) return val superDescriptor = descriptor.overriddenDescriptors.firstOrNull()?.containingDeclaration if (superDescriptor?.fqNameOrNull()?.shortName()?.asString() !in checker.existingTypeNames) { removeModifier(KtTokens.OVERRIDE_KEYWORD) } } private fun repairAnnotationEntries( target: KtModifierListOwner, descriptor: DeclarationDescriptorNonRoot, checker: TypeAccessibilityChecker ) { repairAnnotations(checker, target, descriptor.annotations) when (descriptor) { is ValueParameterDescriptor -> { if (target !is KtParameter) return val typeReference = target.typeReference ?: return repairAnnotationEntries(typeReference, descriptor.type, checker) } is TypeParameterDescriptor -> { if (target !is KtTypeParameter) return val extendsBound = target.extendsBound ?: return for (upperBound in descriptor.upperBounds) { repairAnnotationEntries(extendsBound, upperBound, checker) } } is CallableDescriptor -> { val extension = descriptor.extensionReceiverParameter val receiver = target.safeAs<KtCallableDeclaration>()?.receiverTypeReference if (extension != null && receiver != null) { repairAnnotationEntries(receiver, extension, checker) } val callableDeclaration = target.safeAs<KtCallableDeclaration>() ?: return callableDeclaration.typeParameters.zip(descriptor.typeParameters).forEach { (typeParameter, typeParameterDescriptor) -> repairAnnotationEntries(typeParameter, typeParameterDescriptor, checker) } callableDeclaration.valueParameters.zip(descriptor.valueParameters).forEach { (valueParameter, valueParameterDescriptor) -> repairAnnotationEntries(valueParameter, valueParameterDescriptor, checker) } } } } private fun repairAnnotationEntries( typeReference: KtTypeReference, type: KotlinType, checker: TypeAccessibilityChecker ) { repairAnnotations(checker, typeReference, type.annotations) typeReference.typeElement?.typeArgumentsAsTypes?.zip(type.arguments)?.forEach { (reference, projection) -> repairAnnotationEntries(reference, projection.type, checker) } } private fun repairAnnotations(checker: TypeAccessibilityChecker, target: KtModifierListOwner, annotations: Annotations) { for (annotation in annotations) { if (annotation.isValidInModule(checker)) { checkAndAdd(annotation, checker, target) } } } private fun checkAndAdd(annotationDescriptor: AnnotationDescriptor, checker: TypeAccessibilityChecker, target: KtModifierListOwner) { if (annotationDescriptor.isValidInModule(checker)) { val entry = annotationDescriptor.source.safeAs<KotlinSourceElement>()?.psi.safeAs<KtAnnotationEntry>() ?: return target.addAnnotationEntry(entry) } } private fun AnnotationDescriptor.isValidInModule(checker: TypeAccessibilityChecker): Boolean { return fqName !in forbiddenAnnotationFqNames && checker.checkAccessibility(type) } class KotlinTypeInaccessibleException(fqNames: Collection<FqName?>) : Exception() { override val message: String = KotlinBundle.message( "type.0.1.is.not.accessible.from.target.module", fqNames.size, TypeAccessibilityChecker.typesToString(fqNames) ) } fun KtNamedDeclaration.isAlwaysActual(): Boolean = safeAs<KtParameter>()?.parent?.parent?.safeAs<KtPrimaryConstructor>() ?.mustHaveValOrVar() ?: false fun TypeAccessibilityChecker.isCorrectAndHaveAccessibleModifiers(declaration: KtNamedDeclaration, showErrorHint: Boolean = false): Boolean { if (declaration.anyInaccessibleModifier(INACCESSIBLE_MODIFIERS, showErrorHint)) return false if (declaration is KtFunction && declaration.hasBody() && declaration.containingClassOrObject?.isInterfaceClass() == true) { if (showErrorHint) showInaccessibleDeclarationError( declaration, KotlinBundle.message("the.function.declaration.shouldn.t.have.a.default.implementation") ) return false } if (!showErrorHint) return checkAccessibility(declaration) val types = incorrectTypes(declaration).ifEmpty { return true } showInaccessibleDeclarationError( declaration, KotlinBundle.message( "some.types.are.not.accessible.from.0.1", targetModule.name, TypeAccessibilityChecker.typesToString(types) ) ) return false } private val INACCESSIBLE_MODIFIERS = listOf(KtTokens.PRIVATE_KEYWORD, KtTokens.CONST_KEYWORD, KtTokens.LATEINIT_KEYWORD) private fun KtModifierListOwner.anyInaccessibleModifier(modifiers: Collection<KtModifierKeywordToken>, showErrorHint: Boolean): Boolean { for (modifier in modifiers) { if (hasModifier(modifier)) { if (showErrorHint) showInaccessibleDeclarationError(this, KotlinBundle.message("the.declaration.has.0.modifier", modifier)) return true } } return false } fun showInaccessibleDeclarationError(element: PsiElement, message: String, editor: Editor? = element.findExistingEditor()) { editor?.let { showErrorHint(element.project, editor, escapeXml(message), KotlinBundle.message("inaccessible.declaration")) } } fun TypeAccessibilityChecker.Companion.typesToString(types: Collection<FqName?>, separator: CharSequence = "\n"): String { return types.toSet().joinToString(separator = separator) { it?.shortName()?.asString() ?: "<Unknown>" } } fun TypeAccessibilityChecker.findAndApplyExistingClasses(elements: Collection<KtNamedDeclaration>): Set<String> { var classes = elements.filterIsInstance<KtClassOrObject>() while (classes.isNotEmpty()) { val existingNames = classes.mapNotNull { it.fqName?.asString() }.toHashSet() existingTypeNames = existingNames val newExistingClasses = classes.filter { isCorrectAndHaveAccessibleModifiers(it) } if (classes.size == newExistingClasses.size) return existingNames classes = newExistingClasses } return existingTypeNames }
apache-2.0
4c1e12f03d71e662836a8ebc0310926b
42.130531
158
0.711105
5.505507
false
false
false
false
apoi/quickbeer-next
app/src/main/java/quickbeer/android/feature/beerdetails/model/Address.kt
2
972
package quickbeer.android.feature.beerdetails.model import quickbeer.android.domain.brewer.Brewer import quickbeer.android.domain.country.Country import quickbeer.android.util.ktx.nullIfEmpty data class Address( val countryId: Int, val country: String?, val city: String?, val address: String?, val code: String? ) { fun cityAndCountry(): String? { return when { country != null && city != null -> "$city, $country" country != null -> country city != null -> city else -> null } } companion object { fun from(brewer: Brewer, country: Country): Address { return Address( countryId = country.id, country = country.name.nullIfEmpty(), city = brewer.city.nullIfEmpty(), address = brewer.address.nullIfEmpty(), code = country.code.nullIfEmpty() ) } } }
gpl-3.0
5c56b977556ff68828b3ebdb1babb7f2
26.771429
64
0.570988
4.673077
false
false
false
false
aohanyao/CodeMall
code/ServerCode/CodeMallServer/src/main/java/com/jjc/mailshop/vo/CartProductVo.kt
1
752
package com.jjc.mailshop.vo import com.jjc.mailshop.pojo.Product /** * Created by Administrator on 2017/6/14 0014. */ class CartProductVo { /** * id : 1 * userId : 13 * productId : 1 * quantity : 1 * productName : iphone7 * productSubtitle : 双十一促销 * productMainImage : mainimage.jpg * productPrice : 7199.22 * productStatus : 1 * productTotalPrice : 7199.22 * productStock : 86 * productChecked : 1 * limitQuantity : LIMIT_NUM_SUCCESS */ var id: Int = 0 var userId: Int = 0 var quantity: Int = 0 var productTotalPrice: Double = 0.toDouble() var productChecked: Int = 0 var product: Product? = null var limitQuantity: String? = null }
apache-2.0
9ea4e092207a31a9ea19a25f1b2943fb
21.484848
48
0.613208
3.550239
false
false
false
false
google/iosched
mobile/src/main/java/com/google/samples/apps/iosched/ui/feed/FeedViewModel.kt
1
14447
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.iosched.ui.feed import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import androidx.navigation.NavDirections import com.google.samples.apps.iosched.R import com.google.samples.apps.iosched.model.Announcement import com.google.samples.apps.iosched.model.Moment import com.google.samples.apps.iosched.model.Session import com.google.samples.apps.iosched.model.SessionId import com.google.samples.apps.iosched.model.userdata.UserSession import com.google.samples.apps.iosched.shared.analytics.AnalyticsActions import com.google.samples.apps.iosched.shared.analytics.AnalyticsHelper import com.google.samples.apps.iosched.shared.data.signin.AuthenticatedUserInfo import com.google.samples.apps.iosched.shared.di.MapFeatureEnabledFlag import com.google.samples.apps.iosched.shared.di.ReservationEnabledFlag import com.google.samples.apps.iosched.shared.domain.feed.ConferenceState import com.google.samples.apps.iosched.shared.domain.feed.ConferenceState.ENDED import com.google.samples.apps.iosched.shared.domain.feed.ConferenceState.UPCOMING import com.google.samples.apps.iosched.shared.domain.feed.GetConferenceStateUseCase import com.google.samples.apps.iosched.shared.domain.feed.LoadAnnouncementsUseCase import com.google.samples.apps.iosched.shared.domain.feed.LoadCurrentMomentUseCase import com.google.samples.apps.iosched.shared.domain.sessions.LoadStarredAndReservedSessionsUseCase import com.google.samples.apps.iosched.shared.domain.settings.GetTimeZoneUseCase import com.google.samples.apps.iosched.shared.result.Result import com.google.samples.apps.iosched.shared.result.successOr import com.google.samples.apps.iosched.shared.time.TimeProvider import com.google.samples.apps.iosched.shared.util.TimeUtils import com.google.samples.apps.iosched.shared.util.TimeUtils.ConferenceDays import com.google.samples.apps.iosched.shared.util.toEpochMilli import com.google.samples.apps.iosched.shared.util.tryOffer import com.google.samples.apps.iosched.ui.messages.SnackbarMessage import com.google.samples.apps.iosched.ui.messages.SnackbarMessageManager import com.google.samples.apps.iosched.ui.sessioncommon.OnSessionClickListener import com.google.samples.apps.iosched.ui.sessioncommon.OnSessionStarClickListener import com.google.samples.apps.iosched.ui.signin.SignInViewModelDelegate import com.google.samples.apps.iosched.ui.theme.ThemedActivityDelegate import com.google.samples.apps.iosched.util.WhileViewSubscribed import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.SharingStarted.Companion.Eagerly import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.flow.stateIn import org.threeten.bp.ZoneId import org.threeten.bp.ZonedDateTime import javax.inject.Inject /** * Loads data and exposes it to the view. * By annotating the constructor with [@Inject], Dagger will use that constructor when needing to * create the object, so defining a [@Provides] method for this class won't be needed. */ @HiltViewModel class FeedViewModel @Inject constructor( private val loadCurrentMomentUseCase: LoadCurrentMomentUseCase, loadAnnouncementsUseCase: LoadAnnouncementsUseCase, private val loadStarredAndReservedSessionsUseCase: LoadStarredAndReservedSessionsUseCase, getTimeZoneUseCase: GetTimeZoneUseCase, getConferenceStateUseCase: GetConferenceStateUseCase, private val timeProvider: TimeProvider, private val analyticsHelper: AnalyticsHelper, private val signInViewModelDelegate: SignInViewModelDelegate, themedActivityDelegate: ThemedActivityDelegate, private val snackbarMessageManager: SnackbarMessageManager ) : ViewModel(), FeedEventListener, ThemedActivityDelegate by themedActivityDelegate, SignInViewModelDelegate by signInViewModelDelegate { companion object { // Show at max 10 sessions in the horizontal sessions list as user can click on // View All sessions and go to schedule to view the full list private const val MAX_SESSIONS = 10 // Indicates there is no header to show at the current time. private object NoHeader // Indicates there is no sessions related display on the home screen as the conference is // over. private object NoSessionsContainer } @Inject @JvmField @ReservationEnabledFlag var isReservationEnabledByRemoteConfig: Boolean = false @Inject @JvmField @MapFeatureEnabledFlag var isMapEnabledByRemoteConfig: Boolean = false // Exposed to the view as a StateFlow but it's a one-shot operation. val timeZoneId = flow<ZoneId> { if (getTimeZoneUseCase(Unit).successOr(true)) { emit(TimeUtils.CONFERENCE_TIMEZONE) } else { emit(ZoneId.systemDefault()) } }.stateIn(viewModelScope, Eagerly, TimeUtils.CONFERENCE_TIMEZONE) private val loadSessionsResult: StateFlow<Result<List<UserSession>>> = signInViewModelDelegate.userId .flatMapLatest { // TODO(jdkoren): might need to show sessions for not signed in users too... loadStarredAndReservedSessionsUseCase(it) } .stateIn(viewModelScope, WhileViewSubscribed, Result.Loading) private val conferenceState: StateFlow<ConferenceState> = getConferenceStateUseCase(Unit) .onEach { if (it is Result.Error) { snackbarMessageManager.addMessage(SnackbarMessage(R.string.feed_loading_error)) } } .map { it.successOr(UPCOMING) } .stateIn(viewModelScope, WhileViewSubscribed, UPCOMING) // SIDE EFFECTS: Navigation actions private val _navigationActions = Channel<FeedNavigationAction>(capacity = Channel.CONFLATED) // Exposed with receiveAsFlow to make sure that only one observer receives updates. val navigationActions = _navigationActions.receiveAsFlow() private val currentMomentResult: StateFlow<Result<Moment?>> = conferenceState.map { // Reload if conferenceState changes loadCurrentMomentUseCase(timeProvider.now()) }.stateIn(viewModelScope, WhileViewSubscribed, Result.Loading) private val loadAnnouncementsResult: StateFlow<Result<List<Announcement>>> = flow { emit(loadAnnouncementsUseCase(timeProvider.now())) }.onEach { if (it is Result.Error) { snackbarMessageManager.addMessage(SnackbarMessage(R.string.feed_loading_error)) } }.stateIn(viewModelScope, WhileViewSubscribed, Result.Loading) private val announcementsPreview: StateFlow<List<Any>> = loadAnnouncementsResult.map { val announcementsHeader = AnnouncementsHeader( showPastNotificationsButton = it.successOr(emptyList()).size > 1 ) if (it is Result.Loading) { listOf(announcementsHeader, LoadingIndicator) } else { listOf( announcementsHeader, it.successOr(emptyList()).firstOrNull() ?: AnnouncementsEmpty ) } }.stateIn(viewModelScope, WhileViewSubscribed, emptyList()) private val feedSessionsContainer: Flow<FeedSessions> = loadSessionsResult .combine(timeZoneId) { sessions, timeZone -> createFeedSessionsContainer(sessions, timeZone) } private val sessionContainer: StateFlow<Any> = combine( feedSessionsContainer, conferenceState, signInViewModelDelegate.userInfo ) { sessionsContainer: FeedSessions, conferenceState: ConferenceState, userInfo: AuthenticatedUserInfo? -> val isSignedIn = userInfo?.isSignedIn() ?: false val isRegistered = userInfo?.isRegistered() ?: false if (conferenceState != ENDED && isSignedIn && isRegistered && isReservationEnabledByRemoteConfig ) { sessionsContainer } else { NoSessionsContainer } }.stateIn(viewModelScope, WhileViewSubscribed, NoSessionsContainer) private val currentFeedHeader: StateFlow<Any> = conferenceState.combine( currentMomentResult ) { conferenceStarted: ConferenceState, momentResult -> if (conferenceStarted == UPCOMING) { CountdownItem } else { // Use case can return null even on success, so replace nulls with a sentinel momentResult.successOr(null) ?: NoHeader } }.stateIn(viewModelScope, WhileViewSubscribed, NoHeader) // TODO: Replace Any with something meaningful. val feed: StateFlow<List<Any>> = combine( currentFeedHeader, sessionContainer, announcementsPreview ) { feedHeader: Any, sessionContainer: Any, announcementsPreview: List<Any> -> val feedItems = mutableListOf<Any>() if (feedHeader != NoHeader) { feedItems.add(feedHeader) } if (sessionContainer != NoSessionsContainer) { feedItems.add(sessionContainer) } feedItems .plus(announcementsPreview) .plus(FeedSustainabilitySection) .plus(FeedSocialChannelsSection) }.stateIn(viewModelScope, WhileViewSubscribed, emptyList()) private fun createFeedSessionsContainer( sessionsResult: Result<List<UserSession>>, timeZoneId: ZoneId ): FeedSessions { val sessions = sessionsResult.successOr(emptyList()) val now = ZonedDateTime.ofInstant(timeProvider.now(), timeZoneId) // TODO: Making conferenceState a sealed class and moving currentDay in STARTED // state might be a better option val currentDayEndTime = TimeUtils.getCurrentConferenceDay()?.end // Treat start of the conference as endTime as sessions shouldn't be shown if the // currentConferenceDay is null ?: ConferenceDays.first().start val upcomingReservedSessions = sessions .filter { it.userEvent.isReserved() && it.session.endTime.isAfter(now) && it.session.endTime.isBefore(currentDayEndTime) } .take(MAX_SESSIONS) val titleId = R.string.feed_sessions_title val actionId = R.string.feed_view_full_schedule return FeedSessions( titleId = titleId, actionTextId = actionId, userSessions = upcomingReservedSessions, timeZoneId = timeZoneId, isLoading = sessionsResult is Result.Loading, isMapFeatureEnabled = isMapEnabledByRemoteConfig ) } override fun openEventDetail(id: SessionId) { analyticsHelper.logUiEvent( "Home to event detail", AnalyticsActions.HOME_TO_SESSION_DETAIL ) _navigationActions.tryOffer(FeedNavigationAction.NavigateToSession(id)) } override fun openSchedule(showOnlyPinnedSessions: Boolean) { analyticsHelper.logUiEvent("Home to Schedule", AnalyticsActions.HOME_TO_SCHEDULE) _navigationActions.tryOffer(FeedNavigationAction.NavigateToScheduleAction) } override fun onStarClicked(userSession: UserSession) { TODO("not implemented") } override fun signIn() { analyticsHelper.logUiEvent("Home to Sign In", AnalyticsActions.HOME_TO_SIGN_IN) _navigationActions.tryOffer(FeedNavigationAction.OpenSignInDialogAction) } override fun openMap(moment: Moment) { analyticsHelper.logUiEvent(moment.title.toString(), AnalyticsActions.HOME_TO_MAP) _navigationActions.tryOffer( FeedNavigationAction.NavigateAction( FeedFragmentDirections.toMap( featureId = moment.featureId, startTime = moment.startTime.toEpochMilli() ) ) ) } override fun openLiveStream(liveStreamUrl: String) { analyticsHelper.logUiEvent(liveStreamUrl, AnalyticsActions.HOME_TO_LIVESTREAM) _navigationActions.tryOffer(FeedNavigationAction.OpenLiveStreamAction(liveStreamUrl)) } override fun openMapForSession(session: Session) { analyticsHelper.logUiEvent(session.id, AnalyticsActions.HOME_TO_MAP) val directions = FeedFragmentDirections.toMap( featureId = session.room?.id, startTime = session.startTime.toEpochMilli() ) _navigationActions.tryOffer(FeedNavigationAction.NavigateAction(directions)) } override fun openPastAnnouncements() { analyticsHelper.logUiEvent("", AnalyticsActions.HOME_TO_ANNOUNCEMENTS) val directions = FeedFragmentDirections.toAnnouncementsFragment() _navigationActions.tryOffer(FeedNavigationAction.NavigateAction(directions)) } } interface FeedEventListener : OnSessionClickListener, OnSessionStarClickListener { fun openSchedule(showOnlyPinnedSessions: Boolean) fun signIn() fun openMap(moment: Moment) fun openLiveStream(liveStreamUrl: String) fun openMapForSession(session: Session) fun openPastAnnouncements() } sealed class FeedNavigationAction { class NavigateToSession(val sessionId: SessionId) : FeedNavigationAction() class NavigateAction(val directions: NavDirections) : FeedNavigationAction() object OpenSignInDialogAction : FeedNavigationAction() class OpenLiveStreamAction(val url: String) : FeedNavigationAction() object NavigateToScheduleAction : FeedNavigationAction() }
apache-2.0
d31bb2de83ab991632671027623b0777
42.254491
99
0.725479
4.915618
false
false
false
false
vhromada/Catalog
core/src/main/kotlin/com/github/vhromada/catalog/service/impl/SeasonServiceImpl.kt
1
2239
package com.github.vhromada.catalog.service.impl import com.github.vhromada.catalog.common.exception.InputException import com.github.vhromada.catalog.common.provider.UuidProvider import com.github.vhromada.catalog.domain.Season import com.github.vhromada.catalog.repository.SeasonRepository import com.github.vhromada.catalog.repository.ShowRepository import com.github.vhromada.catalog.service.SeasonService import org.springframework.data.domain.Page import org.springframework.data.domain.Pageable import org.springframework.http.HttpStatus import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional /** * A class represents implementation of service for seasons. * * @author Vladimir Hromada */ @Service("seasonService") class SeasonServiceImpl( /** * Repository for seasons */ private val seasonRepository: SeasonRepository, /** * Repository for shows */ private val showRepository: ShowRepository, /** * Provider for UUID */ private val uuidProvider: UuidProvider ) : SeasonService { override fun search(show: Int, pageable: Pageable): Page<Season> { return seasonRepository.findAllByShowId(id = show, pageable = pageable) } override fun get(uuid: String): Season { return seasonRepository.findByUuid(uuid = uuid) .orElseThrow { InputException(key = "SEASON_NOT_EXIST", message = "Season doesn't exist.", httpStatus = HttpStatus.NOT_FOUND) } } @Transactional override fun store(season: Season): Season { return seasonRepository.save(season) } @Transactional override fun remove(season: Season) { val show = season.show!! show.seasons.remove(season) showRepository.save(show) } @Transactional override fun duplicate(season: Season): Season { val copy = season.copy(id = null, uuid = uuidProvider.getUuid(), subtitles = season.subtitles.map { it }.toMutableList(), episodes = mutableListOf()) copy.episodes.addAll(season.episodes.map { it.copy(id = null, uuid = uuidProvider.getUuid(), season = copy) }) copy.show!!.seasons.add(copy) return seasonRepository.save(copy) } }
mit
f4e773fec4ed3129e67f6b5745d254ce
33.446154
157
0.721751
4.356031
false
false
false
false
vhromada/Catalog
core/src/main/kotlin/com/github/vhromada/catalog/validator/impl/SongValidatorImpl.kt
1
1667
package com.github.vhromada.catalog.validator.impl import com.github.vhromada.catalog.common.exception.InputException import com.github.vhromada.catalog.common.result.Event import com.github.vhromada.catalog.common.result.Result import com.github.vhromada.catalog.common.result.Severity import com.github.vhromada.catalog.entity.ChangeSongRequest import com.github.vhromada.catalog.validator.SongValidator import org.springframework.stereotype.Component /** * A class represents implementation of validator for songs. * * @author Vladimir Hromada */ @Component("songValidator") class SongValidatorImpl : SongValidator { override fun validateRequest(request: ChangeSongRequest) { val result = Result<Unit>() when { request.name == null -> { result.addEvent(event = Event(severity = Severity.ERROR, key = "SONG_NAME_NULL", message = "Name mustn't be null.")) } request.name.isEmpty() -> { result.addEvent(event = Event(severity = Severity.ERROR, key = "SONG_NAME_EMPTY", message = "Name mustn't be empty string.")) } } when { request.length == null -> { result.addEvent(event = Event(severity = Severity.ERROR, key = "SONG_LENGTH_NULL", message = "Length of song mustn't be null.")) } request.length < 0 -> { result.addEvent(event = Event(severity = Severity.ERROR, key = "SONG_LENGTH_NEGATIVE", message = "Length of song mustn't be negative number.")) } } if (result.isError()) { throw InputException(result = result) } } }
mit
776516fd4efb6185a7eed59a2b7a68dc
38.690476
159
0.65027
4.363874
false
false
false
false
JetBrains/intellij-community
platform/credential-store/src/EncryptionSupport.kt
1
3962
// 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.credentialStore import com.intellij.credentialStore.gpg.Pgp import com.intellij.credentialStore.windows.WindowsCryptUtils import com.intellij.jna.JnaLoader import com.intellij.openapi.util.SystemInfo import com.intellij.util.io.toByteArray import java.nio.ByteBuffer import java.nio.CharBuffer import java.security.Key import javax.crypto.Cipher import javax.crypto.spec.IvParameterSpec import javax.crypto.spec.SecretKeySpec private val builtInEncryptionKey = SecretKeySpec(byteArrayOf( 0x50, 0x72, 0x6f.toByte(), 0x78.toByte(), 0x79.toByte(), 0x20.toByte(), 0x43.toByte(), 0x6f.toByte(), 0x6e.toByte(), 0x66.toByte(), 0x69.toByte(), 0x67.toByte(), 0x20.toByte(), 0x53.toByte(), 0x65.toByte(), 0x63.toByte()), "AES") // opposite to PropertiesEncryptionSupport, we store iv length, but not body length internal interface EncryptionSupport { fun encrypt(data: ByteArray): ByteArray fun decrypt(data: ByteArray): ByteArray } enum class EncryptionType { BUILT_IN, CRYPT_32, PGP_KEY } fun getDefaultEncryptionType() = if (SystemInfo.isWindows) EncryptionType.CRYPT_32 else EncryptionType.BUILT_IN private open class AesEncryptionSupport(private val key: Key) : EncryptionSupport { companion object { private fun encrypt(message: ByteArray, key: Key): ByteArray { val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding") cipher.init(Cipher.ENCRYPT_MODE, key) val body = cipher.doFinal(message, 0, message.size) val iv = cipher.iv val byteBuffer = ByteBuffer.wrap(ByteArray(4 + iv.size + body.size)) byteBuffer.putInt(iv.size) byteBuffer.put(iv) byteBuffer.put(body) return byteBuffer.array() } private fun decrypt(data: ByteArray, key: Key): ByteArray { val byteBuffer = ByteBuffer.wrap(data) val ivLength = byteBuffer.getInt() val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding") cipher.init(Cipher.DECRYPT_MODE, key, IvParameterSpec(data, byteBuffer.position(), ivLength)) val dataOffset = byteBuffer.position() + ivLength return cipher.doFinal(data, dataOffset, data.size - dataOffset) } } override fun encrypt(data: ByteArray) = encrypt(data, key) override fun decrypt(data: ByteArray) = decrypt(data, key) } private class WindowsCrypt32EncryptionSupport(key: Key) : AesEncryptionSupport(key) { override fun encrypt(data: ByteArray) = WindowsCryptUtils.protect(super.encrypt(data)) override fun decrypt(data: ByteArray) = super.decrypt(WindowsCryptUtils.unprotect(data)) } private class PgpKeyEncryptionSupport(private val encryptionSpec: EncryptionSpec) : EncryptionSupport { override fun encrypt(data: ByteArray) = Pgp().encrypt(data, encryptionSpec.pgpKeyId!!) override fun decrypt(data: ByteArray) = Pgp().decrypt(data) } data class EncryptionSpec(val type: EncryptionType, val pgpKeyId: String?) internal fun createEncryptionSupport(spec: EncryptionSpec): EncryptionSupport { return when (spec.type) { EncryptionType.BUILT_IN -> createBuiltInOrCrypt32EncryptionSupport(false) EncryptionType.CRYPT_32 -> createBuiltInOrCrypt32EncryptionSupport(true) EncryptionType.PGP_KEY -> PgpKeyEncryptionSupport(spec) } } internal fun createBuiltInOrCrypt32EncryptionSupport(isCrypt32: Boolean): EncryptionSupport { if (isCrypt32) { if (!SystemInfo.isWindows) { throw IllegalArgumentException("Crypt32 encryption is supported only on Windows") } if (JnaLoader.isLoaded()) { return WindowsCrypt32EncryptionSupport(builtInEncryptionKey) } } return AesEncryptionSupport(builtInEncryptionKey) } fun CharArray.toByteArrayAndClear(): ByteArray { val charBuffer = CharBuffer.wrap(this) val byteBuffer = Charsets.UTF_8.encode(charBuffer) fill(0.toChar()) return byteBuffer.toByteArray(isClear = true) }
apache-2.0
4889c0dfd0d0d6ee6da179ef99673311
37.096154
140
0.757193
3.946215
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertUnsafeCastToUnsafeCastCallIntention.kt
1
2077
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.openapi.editor.Editor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.facet.platform.platform import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.platform.isJs import org.jetbrains.kotlin.psi.KtBinaryExpressionWithTypeRHS import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.createExpressionByPattern import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.TypeUtils class ConvertUnsafeCastToUnsafeCastCallIntention : SelfTargetingIntention<KtBinaryExpressionWithTypeRHS>( KtBinaryExpressionWithTypeRHS::class.java, KotlinBundle.lazyMessage("convert.to.unsafecast.call"), ) { override fun isApplicableTo(element: KtBinaryExpressionWithTypeRHS, caretOffset: Int): Boolean { if (!element.platform.isJs()) return false if (element.operationReference.getReferencedNameElementType() != KtTokens.AS_KEYWORD) return false val right = element.right ?: return false val context = right.analyze(BodyResolveMode.PARTIAL) val type = context[BindingContext.TYPE, right] ?: return false if (TypeUtils.isNullableType(type)) return false setTextGetter(KotlinBundle.lazyMessage("convert.to.0.unsafecast.1", element.left.text, right.text)) return true } override fun applyTo(element: KtBinaryExpressionWithTypeRHS, editor: Editor?) { val right = element.right ?: return val newExpression = KtPsiFactory(element.project).createExpressionByPattern("$0.unsafeCast<$1>()", element.left, right) element.replace(newExpression) } }
apache-2.0
3b6b18a16137641612e45c7c61e3f496
47.325581
158
0.78623
4.699095
false
false
false
false
NeatoRobotics/neato-sdk-android
Neato-SDK/neato-sdk-android/src/main/java/com/neatorobotics/sdk/android/robotservices/spotcleaning/SpotCleaningMinimal2Service.kt
1
1024
/* * Copyright (c) 2019. * Neato Robotics Inc. */ package com.neatorobotics.sdk.android.robotservices.spotcleaning import com.neatorobotics.sdk.android.models.CleaningMode import com.neatorobotics.sdk.android.models.CleaningModifier import com.neatorobotics.sdk.android.models.NavigationMode class SpotCleaningMinimal2Service : SpotCleaningService() { override val isMultipleZonesCleaningSupported: Boolean get() = false override val isEcoModeSupported: Boolean get() = false override val isTurboModeSupported: Boolean get() = false override val isExtraCareModeSupported: Boolean get() = true override val isCleaningAreaSupported: Boolean get() = false override val isCleaningFrequencySupported: Boolean get() = true init { this.cleaningModifier = CleaningModifier.DOUBLE this.cleaningNavigationMode = NavigationMode.NORMAL } companion object { private const val TAG = "SpotCleaningMinimal2" } }
mit
e0d90b77e637e7153abcde930111886f
23.380952
64
0.72168
4.530973
false
false
false
false